File: //opt/cpanel/ea-php54/root/usr/share/pear/RVSeagullMod/lib/SGL/RVConvertFIleUtf8.php
<?php
require_once SGL_LIB_PEAR_DIR . '/System.php';
class RVConvertFileUtf8
{
function RVConvertFileUtf8()
{
}
public static function singleton($autoLoad = false)
{
static $instance;
if (!isset($instance) || $autoLoad) {
$class = __CLASS__;
$instance = new $class($autoLoad);
}
return $instance;
}
/**
* Builder path
* @author Parinya Chaipetch <parinya@rvglobalsoft.com>
*
* @param array $parts
* @param string $separator
* @return string
*/
function buildPath($parts, $separator = DIRECTORY_SEPARATOR)
{
SGL::logMessage(null, PEAR_LOG_DEBUG);
if (class_exists('File_Util')) {
return File_Util::buildPath($parts, $separator);
} else {
$qs = '/^'. preg_quote($separator, '/') .'+$/';
for ($i = 0, $c = count($parts); $i < $c; $i++) {
if (!strlen($parts[$i]) || preg_match($qs, $parts[$i])) {
unset($parts[$i]);
} elseif (0 == $i) {
$parts[$i] = rtrim($parts[$i], $separator);
} elseif ($c - 1 == $i) {
$parts[$i] = ltrim($parts[$i], $separator);
} else {
$parts[$i] = trim($parts[$i], $separator);
}
}
return implode($separator, $parts);
}
}
/**
* recusive convert file from $nativeEncoding to UTF-8
*
* @param string $nativeEncoding
* @param string $path
* @param string $toFilePattern
* @return Returns String list filename convert charset on Success.
* or mixed PEAR_Error
*/
function convertCharsetFile($nativeEncoding = null, $path = null, $toFilePattern = '', $ignoreDir = array())
{
SGL::logMessage('L: ' . __LINE__ , PEAR_LOG_DEBUG);
//set list filename convert charset on success
$listFileConvert = '';
if (is_null($nativeEncoding) || $nativeEncoding == '') {
return SGL::raiseError(
SGL_String::translate('nativeEncoding invalid')
);
}
if (is_null($path) || $path == '') {
return SGL::raiseError(
SGL_String::translate('path to convert invalid')
);
}
$filePattern = ".*.ini,*.html,*.php,*.js,*.htm,*.htpl,*.shtml,*.shtml1,*.whl,*.inc,*.ini,*.php3,*.php4,*.php5,*.phphtml,*.xml,*.xmlhtml";
$filePattern = ($toFilePattern != '') ? $toFilePattern : $filePattern;
$aPathConvertCharsetComplete = array();
//path file complate
$pathFileComplete = RVConvertFileUtf8::buildPath(array($path, 'rvsUtf8Config' ));
$fileComplete = RVConvertFileUtf8::buildPath(array($path, 'rvsUtf8Config' , 'complete.txt'));
// path back project
$backupPath = RVConvertFileUtf8::buildPath(array($path, 'rvsUtf8Backup' ));
//check file complete
if (is_file($fileComplete)) {
$aPathConvertCharsetComplete = file($fileComplete);
}
// 1. make folder
if (file_exists($pathFileComplete) === false) {
System::mkDir(array('-p', $pathFileComplete));
}
if (file_exists($backupPath) === false) {
System::mkDir(array('-p', $backupPath));
}
//2. List file or folder
//'-a' = show hidden file
$aPathFileProjectAll = RVConvertFileUtf8::ls(array('-a', '-R', $path), $ignoreDir);
//3. List file by pattern format
foreach ($aPathFileProjectAll['dirs'] as $dirname) {
$adir = RVConvertFileUtf8::_listDirs($dirname, $filePattern);
}
//4. loop all file
foreach ($adir as $fullPath) {
// 5. START make {$path}/rvsUtf8Backup
if ( !preg_match("/rvsUtf8Backup/", $fullPath)) {
$fullPathBackup = str_replace($path, $backupPath, $fullPath);
}
$fileName = end(explode('/', $fullPath));
$fullPathBackupMakeDir = str_replace('/' . $fileName, '', $fullPathBackup);
if (is_dir($fullPathBackupMakeDir) === false) {
System::mkDir(array('-p', $fullPathBackupMakeDir ));
}
//END make {$path}/rvsUtf8Backup
// 6. go to copy file to backup
if (file_exists($fullPath) === true) {
//RvsLibs_System::copy(array($fullPath, $fullPathBackup));
@copy($fullPath, $fullPathBackup);
}
// 7. validate ว่า เคยตรวจสอบว่าเป็น utf-8 หรือไม่ check ในไฟล์ complete.tx
// 7.2 ถ้ามีแล้ว continue;
if (preg_match("/\.utf8\./i", $fullPath)
|| count($aPathConvertCharsetComplete)
&& in_array($fullPath, preg_replace("/\\r\\n/", "", $aPathConvertCharsetComplete))) {
continue;
}
// 7.3 ถ้ายัง ก็ get file encoding check utf-8
//$type = 'utf-8';
// finfo_open require PHP version >= 5.3
$type = RVConvertFileUtf8::getTypeFileEncode($fullPath);
// 8. after get encong file type to write file complete.txt
//TODO: input array folder ignore to donot write to complete.txt
if ((count($aPathConvertCharsetComplete) == 0
|| !in_array($fullPath, preg_replace("/\\r\\n/", "", $aPathConvertCharsetComplete))
) && !preg_match("/rvsUtf8Backup|RvSitebuilderPreview/", $fullPath)) {
RVConvertFileUtf8::writeDataAppendToFile($fullPath, $fileComplete);
//set list filename convert charset on success
$listFileConvert .= $fullPath . "\r\n";
}
// 9. if utf-8 go to continue;
if (isset($type) && preg_match("/utf-8/i", $type)) {
continue;
}
// 10. if not utf-8 go to convrt by iconv
if ((strtolower($type) != 'utf-8')) {
RVConvertFileUtf8::iconvFile($fullPath, $nativeEncoding, 'UTF-8//IGNORE');
}
}
return $listFileConvert;
}
function _listDirs($dir, $filePattern = "*")
{
static $alldirs = array();
$dirs = glob( sprintf("%s/{%s}", $dir, $filePattern), GLOB_BRACE);
if (count($dirs) > 0) {
foreach ($dirs as $d) {
$alldirs[] = $d;
}
}
return $alldirs;
}
/**
* Iconv File
*
* @param string $fileName
* @param string $inCharset
* @param string $outCharset
*/
function iconvFile($fileOriginal, $fileNew, $inCharset, $outCharset)
{
SGL::logMessage('iconvFile : ' . $fileOriginal .' ' . $fileNew, PEAR_LOG_DEBUG);
$iconv = '';
if (is_file($fileOriginal)) {
$handle = fopen($fileOriginal, 'r');
if ($handle) {
while (!feof($handle)) {
$buffer = fgets($handle, 4096);
$iconv .= RVConvertFileUtf8::iconv($inCharset, $outCharset, $buffer);
}
}
$finaldata = $iconv;
fclose($handle);
$handle = fopen($fileNew, "w+");
fwrite($handle, $finaldata);
fclose($handle);
} elseif (is_file($fileNew) === false) {
return SGL::raiseError(
SGL_String::translate(
'The file %FILE is not exists and not regular file.'
, 'vprintf'
, array('FILE' => $fileNew)
)
);
}
}
/**
* Convert string to requested character encoding
*
* @param string $in_charset : The input charset.
* @param string $out_charset : The output charset. If you append the string //TRANSLIT to out_charset transliteration is activated.
* This means that when a character can't be represented in the target charset
* , it can be approximated through one or several similarly looking characters.
* If you append the string //IGNORE, characters that cannot be represented in the target charset are silently discarded.
* Otherwise, str is cut from the first illegal character and an E_NOTICE is generated.
*
* @param string $str
* @param bool $flagTestErrorMode; Flag for test mode error
* @return Returns the converted string or FALSE on failure
* if have error return raiseError
*/
function iconv($in_charset, $out_charset, $str, $flagTestErrorMode = false)
{
$convertValue = '';
if (function_exists('iconv') === true
&& $flagTestErrorMode === false) {
$convertValue = @iconv($in_charset, $out_charset, $str);
} elseif (function_exists('mb_convert_encoding') === true && function_exists('mb_internal_encoding') === true) {
mb_internal_encoding($in_charset);
$convertValue = mb_convert_encoding($str, $out_charset, $in_charset);
} elseif (function_exists('utf8_decode') === true) {
$convertValue = utf8_decode($str);
} else {
return SGL::raiseError(
SGL_String::translate(
'Function %FUNCTION is undefine.'
, 'vprintf'
, array('FUNCTION' => 'iconv')
)
);
}
return $convertValue;
}
/**
* Write data to file
*
* @param string $strData
* @param stiing $fileName
* @return <bool>
*/
function writeDataAppendToFile($strData, $fileName)
{
SGL::logMessage(null, PEAR_LOG_DEBUG);
$strData = $strData . "\r\n";
$handle = fopen($fileName, "a");
fwrite($handle, $strData);
fclose($handle);
return true;
}
/**
* get Type File Encode
*
* @param string $fileName
* @return string; type file encode
*/
function getTypeFileEncode($fileName)
{
SGL::logMessage(null, PEAR_LOG_DEBUG);
$TypeFileEncode = '';
if (function_exists('finfo_open') && function_exists('finfo_file')) {
$finfo = finfo_open(FILEINFO_MIME_ENCODING);
}
return $TypeFileEncode;
}
/**
* list directory contents
*
* Usage:
* 1) $aList = RvsLibs_System::ls('/home');
* 2) $aList = RvsLibs_System::ls(array('-a', '-R', '/home'));
* The -a option will do not ignore entries starting with .
* The -R option will list subdirectories recursively
* The -C option will auto-ignore files in the same way CVS/SVN does
* 3) $aList = RvsLibs_System::ls(array('-a', '-R', '/home'), array('dirnameToignore'));
* @param string $args the name of the director(y|ies) to create
*
* @return array
*
* ex: array(
* 'dirs' => array(...),
* 'files' => array(...),
* 'links' => array(...),
* )
*/
function ls($args, $aDirIgnore = array())
{
$opts = System::_parseArgs($args, 'aRC');
if (SGL::isError($opts)) {
return $opts;
}
$recursive = false;
$showHidden = false;
$cvsExclude = false;
foreach ($opts[0] as $opt) {
switch ($opt[0]) {
case 'R':
$recursive = true; break;
case 'a':
$showHidden = true; break;
case 'C':
$cvsExclude = true;
}
}
return RVConvertFileUtf8::_multipleToStruct($opts[1], $recursive, $showHidden, $cvsExclude, $aDirIgnore);
}
function _multipleToStruct($files, $recursive = false, $showHidden = false, $cvsExclude = false, $aDirIgnore = array())
{
$struct = array('dirs' => array(), 'files' => array(), 'links' => array());
settype($files, 'array');
foreach ($files as $file) {
if (is_dir($file) && !is_link($file)) {
$tmp = RVConvertFileUtf8::_dirToStruct($file, $recursive, $showHidden, $cvsExclude, 0, 0, $aDirIgnore);
$struct = array_merge_recursive($tmp, $struct);
} else if (is_link($file) === true) {
$struct['links'][] = $file;
} else {
$struct['files'][] = $file;
}
}
return $struct;
}
function _dirToStruct($sPath, $recursive = false, $showHidden = false, $cvsExclude = false, $maxinst, $aktinst = 0, $aDirIgnore = array())
{
$struct = array('dirs' => array(), 'files' => array(), 'links' => array());
if (($dir = @opendir($sPath)) === false) {
return SGL::raiseError(
SGL_String::translate(
'Could not open dir %FORDER'
, 'vprintf'
, $sPath
)
); // XXX could not open error
}
$struct['dirs'][] = $sPath = realpath($sPath); // XXX don't add if '.' or '..' ?
$list = array();
while (false !== ($file = readdir($dir))) {
if ($file === '.' || $file === '..' || (count($aDirIgnore) && in_array($file, $aDirIgnore)) ) {
/// Continue if file is dot(.) or dot dot(..) ::BooM
continue;
} else if ($showHidden === false && substr($file, 0, 1) === '.') {
/// Continue if set option show hidden is fasle and file name is start with dot(.) ::BooM
continue;
} else if ($cvsExclude === true && is_dir($sPath . DIRECTORY_SEPARATOR . $file)
&& ($file === '.svn' || $file === '.cvs')) {
/// Continue if set option auto-ignore files in the same way CVS/SVN is true
/// and it is a folder, and folder name is start with .svn or .cvs ::BooM
continue;
} else {
$list[] = $file;
}
}
closedir($dir);
sort($list);
foreach ($list as $val) {
$path = $sPath . DIRECTORY_SEPARATOR . $val;
if (is_dir($path) && !is_link($path)) {
if ($recursive === true) {
$tmp = RVConvertFileUtf8::_dirToStruct($path, $recursive, $showHidden, $cvsExclude, $maxinst, $aktinst+1, $aDirIgnore);
$struct = array_merge_recursive($tmp, $struct);
} else {
$struct['dirs'][] = realpath($path);
}
} else if (is_link($path) === true) {
$struct['links'][] = $path;
} else {
$struct['files'][] = $path;
}
}
return $struct;
}
}
?>