CHips L MINI SHELL

CHips L pro

Current Path : /opt/cpanel/ea-php54/root/usr/share/pear/RVSeagullMod/lib/RVSGL/rvsLibs/
Upload File :
Current File : //opt/cpanel/ea-php54/root/usr/share/pear/RVSeagullMod/lib/RVSGL/rvsLibs/File.php

<?php
/* Reminder: always indent with 4 spaces (no tabs). */
// +---------------------------------------------------------------------------+
// WebSite:  http://www.rvglobalsoft.com
// Unauthorized copying is strictly forbidden and may result in severe legal action.
// Copyright (c) 2006 RV Global Soft Co.,Ltd. All rights reserved.
//
// =====YOU MUST KEEP THIS COPYRIGHTS NOTICE INTACT AND CAN NOT BE REMOVE =======
// Copyright (c) 2006 RV Global Soft Co.,Ltd. All rights reserved.
// This Agreement is a legal contract, which specifies the terms of the license
// and warranty limitation between you and RV Global Soft Co.,Ltd. and RV Site Builder.
// You should carefully read the following terms and conditions before
// installing or using this software.  Unless you have a different license
// agreement obtained from RV Global Soft Co.,Ltd., installation or use of this software
// indicates your acceptance of the license and warranty limitation terms
// contained in this Agreement. If you do not agree to the terms of this
// Agreement, promptly delete and destroy all copies of the Software.
//
// =====  Grant of License =======
// The Software may only be installed and used on a single host machine.
//
// =====  Disclaimer of Warranty =======
// THIS SOFTWARE AND ACCOMPANYING DOCUMENTATION ARE PROVIDED "AS IS" AND
// WITHOUT WARRANTIES AS TO PERFORMANCE OF MERCHANTABILITY OR ANY OTHER
// WARRANTIES WHETHER EXPRESSED OR IMPLIED.   BECAUSE OF THE VARIOUS HARDWARE
// AND SOFTWARE ENVIRONMENTS INTO WHICH RV SITE BUILDER MAY BE USED, NO WARRANTY OF
// FITNESS FOR A PARTICULAR PURPOSE IS OFFERED.  THE USER MUST ASSUME THE
// ENTIRE RISK OF USING THIS PROGRAM.  ANY LIABILITY OF RV GLOBAL SOFT CO.,LTD. WILL BE
// LIMITED EXCLUSIVELY TO PRODUCT REPLACEMENT OR REFUND OF PURCHASE PRICE.
// IN NO CASE SHALL RV GLOBAL SOFT CO.,LTD. BE LIABLE FOR ANY INCIDENTAL, SPECIAL OR
// CONSEQUENTIAL DAMAGES OR LOSS, INCLUDING, WITHOUT LIMITATION, LOST PROFITS
// OR THE INABILITY TO USE EQUIPMENT OR ACCESS DATA, WHETHER SUCH DAMAGES ARE
// BASED UPON A BREACH OF EXPRESS OR IMPLIED WARRANTIES, BREACH OF CONTRACT,
// NEGLIGENCE, STRICT TORT, OR ANY OTHER LEGAL THEORY. THIS IS TRUE EVEN IF
// RV GLOBAL SOFT CO.,LTD. IS ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. IN NO CASE WILL
// RV GLOBAL SOFT CO.,LTD.'S LIABILITY EXCEED THE AMOUNT OF THE LICENSE FEE ACTUALLY PAID
// BY LICENSEE TO RV GLOBAL SOFT CO.,LTD.
// +---------------------------------------------------------------------------+
// $Id$
// +---------------------------------------------------------------------------+

/**
 * RvSiteBuilder files libary
 *
 * @package RvsLibs
 * @author  Pairote Manunphol <pairote@rvglobalsoft.com>
 * @version $Revision$
 * @since   PHP 5.1
 */
if (class_exists('RvsLibs_File') === false) {
	class RvsLibs_File
	{
		/**
		 * Builder path
		 * @author Parinya Chaipetch <parinya@rvglobalsoft.com>
		 *
		 * @param array $parts
		 * @param string $separator
		 * @return string
		 */

		public static function buildPath($parts, $separator = DIRECTORY_SEPARATOR)
		{
			if (is_file(SGL_LIB_PEAR_DIR . '/File/Util.php') === true) {
				if (class_exists('File_Util') === false) {
					require_once SGL_LIB_PEAR_DIR . '/File/Util.php' ;
				}
				return File_Util::buildPath($parts, $separator);
			} else {
				return File_Util::customBuildPath($separator, $parts);
			}
		}

		public static function customBuildPath($parts, $separator = DIRECTORY_SEPARATOR)
		{
			$qs = '/^'. preg_quote($separator, '/') .'+$/';
			//optimize:pharadol
			$c = count($parts);
			for ($i = 0, $max = $c; $i < $max; $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);
		}

		/**
		 * Opens file or URL
		 * @author Parinya Chaipetch <parinya@rvglobalsoft.com>
		 *
		 * @param string $filename
		 * @param string $mode
		 * @return resource ;Returns a file pointer resource on success, or PEAR_Error on error.
		 */
		public static function fopen($filename, $mode='r')
		{
			if (empty($filename)) {
		        return SGL::raiseError(
				    RvsLibs_String::translate('Filename cannot be empty')
				);
		    }
		    
		    if (is_dir($filename) == true) {
		    	SGL::logMessage('Cannot fopen is dir: ' . $filename, PEAR_LOG_ERR);
		    	return false;
		    }

		    $isHardLink = false;
		    if (function_exists('stat') == true && is_file($filename) == true) {
		    	$fileStat = @stat($filename);
		    	$isHardLink = (isset($fileStat['nlink']) && $fileStat['nlink'] == '2') ? true : false;
		    	
		    }
		    //RVSB case: Privilege is not root and file is hard link return error
		    if (strtolower(RvsLibs_User::getPrivilege()) != 'root' && $isHardLink == true) {
		    	SGL::logMessage('File name cannot be hard link: ' . $filename, PEAR_LOG_ERR);
		    	return SGL::raiseError('File name cannot be hard link: ' . $filename);
		    }
		    
		    //RVSB case: Privilege is not root and file is symlink return error
		    if (strtolower(RvsLibs_User::getPrivilege()) != 'root' && is_link($filename) == true) {
		    	SGL::logMessage('File name cannot be symlink: ' . $filename, PEAR_LOG_ERR);
		    	return SGL::raiseError('File name cannot be symlink: ' . $filename);
		    }
		    
			switch ($mode) {
				case 'r' :
				default:
					$doAction = RvsLibs_String::translate('open');
					$doEvent = RvsLibs_String::translate('reading only');
					break;
				case 'r+':
				case 'w+' :
					$doAction = RvsLibs_String::translate('open');
					$doEvent = RvsLibs_String::translate('reading and writing');
					break;
				case 'w':
				case 'a':
					$doAction = RvsLibs_String::translate('open');
					$doEvent = RvsLibs_String::translate('writing only');
					break;
				case 'x' :
					$doAction = RvsLibs_String::translate('create and open');
					$doEvent = RvsLibs_String::translate('writing only');
					break;
				case 'x+' :
					$doAction = RvsLibs_String::translate('create and open');
					$doEvent = RvsLibs_String::translate('writing only');
					break;
			}
			$fh = @fopen($filename,$mode);
			if($fh === FALSE){
				return SGL::raiseError(
				RvsLibs_String::translate('Failed to %ACTION file for %EVENT file %FILE'
				, 'vprintf'
				, array('ACTION' => $doAction, 'EVENT' => $doEvent, 'FILE' => $filename))
				);
			} else {
				return $fh;
			}
		}

		/**
		 * Binary-safe file write
		 * @author Parinya Chaipetch <parinya@rvglobalsoft.com>
		 *
		 * @param resource $handle
		 * @param string $content
		 * @return bool ;returns true if can written, or PEAR error on error.
		 */
		public static function fwrite($handle, $content)
		{
			if (!is_resource($handle)) {
				return SGL::raiseError('fwrite() expects parameter 1 to be resource.');
			}
			if (fwrite($handle, $content) === FALSE) {
				return SGL::raiseError(
					RvsLibs_String::translate('Failed write to file.')
				);
			}
			return true;
		}

		/**
		 * Binary-safe file read
		 * @author Parinya Chaipetch <parinya@rvglobalsoft.com>
		 *
		 * @param resource $handle
		 * @return array ;returns true if can written, or PEAR error on error.
		 */
		public static function fread($handle)
		{
			if (!is_resource($handle)) {
				return SGL::raiseError('fread() expects parameter 1 to be resource.');
			}
			$content = '';
			while (!feof($handle)) {
				$content .= fread($handle, 8192);
			}
			return $content;
		}

		/**
		 * Closes an open file pointer
		 * @author Parinya Chaipetch <parinya@rvglobalsoft.com>
		 *
		 * @param resource $handle
		 * @return bool ;returns true if can close, or PEAR error on error.
		 */
		public static function fclose($handle)
		{
			if (!is_resource($handle)) {
				return SGL::raiseError('fclose() expects parameter 1 to be resource.');
			}
			if (fclose ( $handle ) === FALSE) {
				return SGL::raiseError ( RvsLibs_String::translate ( 'Failed to close file.' ) );
			}
			return true;
		}

		/**
		 * Get file size
		 * @author Parinya Chaipetch <parinya@rvglobalsoft.com>
		 *
		 * @param string $filename
		 * @return int
		 */
		public static function filesize($filename)
		{
			return filesize($filename);
		}

		/**
		 * return memory usage
		 * @return unknown_type
		 */
		public static function memoryusage()
		{
			$unit = array('b','kb','mb','gb','tb','pb');
            $size = memory_get_usage(true);
            $memory = @round($size/pow(1024,($i=floor(log($size,1024)))),2) . ' ' . $unit[$i];
			return $memory;
		}

		/**
		 *
		 * @author Martin Sweeny
		 * @version 2010.0617
		 *
		 * returns formatted number of bytes.
		 * two parameters: the bytes and the precision (optional).
		 * if no precision is set, function will determine clean
		 * result automatically.
		 *
		 **/
		public static function getformatFileSize($sizeByte, $p = null)
		{
			//$sizeByte = RvsLibs_File::filesize($filename);
			$units = array("B","kB","MB","GB","TB","PB","EB","ZB","YB");
			$c=0;
			if(!$p && $p !== 0) {
				foreach($units as $k => $u) {
					if(($sizeByte / pow(1024,$k)) >= 1) {
						$r["bytes"] = $sizeByte / pow(1024,$k);
						$r["units"] = $u;
						$c++;
					}
				}
				return number_format($r["bytes"],2) . " " . $r["units"];
			} else {
				$key = array_search($p, $units);
				return number_format($sizeByte / pow(1024,$key),2) . " " . $p;
			}
		}

		/**
		 * Reads entire file into an array
		 * @author Parinya Chaipetch <parinya@rvglobalsoft.com>
		 *
		 * @param string $filename
		 * @param int $flags
		 *
		 * @return array; Returns the file in an array.
		 *  Each element of the array corresponds to a line in the file,
		 *  with the newline still attached.
		 *  Upon failure, file() returns SGL::raiseError
		 */
		public static function file($filename, $flags=0)
		{
			$filename = realpath($filename);
			if (is_file($filename) === false) {
				return SGL::raiseError(
				RvsLibs_String::translate('File %FILE not found.'
				, 'vprintf'
				, array('FILE' => $filename))
				);
			}
			if (is_readable($filename) === false) {
				return SGL::raiseError(
				RvsLibs_String::translate('The file %FILE not readable.'
				, 'vprintf'
				, array('FILE' => $filename))
				);
			}
			if (RvsLibs_System::function_exists('file') === true) {
				$aContent = @file($filename, $flags);
				if (SGL::isError($aContent) === true || $aContent === false) {
					return SGL::raiseError(
					RvsLibs_String::translate('cannot get file content.')
					);
				}
				return $aContent;
			} else {
				///TODO : ใช้ fread แทน แล้วปรับให้เป็น array return ออกไป
				return SGL::raiseError(
				RvsLibs_String::translate('Function file are not allow on this server.')
				);
			}
		}

		/**
		 *
		 * @param $path = fullpath
		 * @param $aData = array
		 * @param $option
		 * @return unknown_type
		 */
		public static function writeFileSerialData($path = null, $aData = array(), $mode = 'w+')
		{
			SGL::logMessage(null, PEAR_LOG_DEBUG);
			$handle = RvsLibs_File::fopen($path, $mode);
			if (SGL::isError($handle) === true) {
				return $handle;
			}
			RvsLibs_File::fwrite($handle, serialize($aData));
			RvsLibs_File::fclose($handle);
			return true;
		}

		/**
		 *
		 * @param $path = full path
		 * @return array
		 */
		public static function getFileSerialData($path)
		{
		      $fileContent = (is_file($path))
                    ? file_get_contents($path)
                    : array();
              $aData = !empty($fileContent) ? unserialize($fileContent) : array();
              return $aData;
		}

		public static function getJsonDecodeFile($path, $assoc)
		{
			$fileContent = (is_file($path))
			? file_get_contents($path)
			: '';
			$aData = !empty($fileContent) ? json_decode($fileContent, $assoc) : array();
			return $aData;
		}

		public static function writeJsonEncodeFile($path, $aData)
		{
			//@file_put_contents($path, json_encode($aData));
			$handle = RvsLibs_File::fopen($path,'w+');
			if (SGL::isError($handle) === true) {
				return $handle;
			}
			RvsLibs_File::fwrite($handle, json_encode($aData));
			RvsLibs_File::fclose($handle);
		}

		public static function getHeaderBannerData($path, $isUikit=false)
		{
			SGL::logMessage('SB==isUikit:' . $isUikit, PEAR_LOG_DEBUG);
			if ($isUikit) {
				$aData = RvsLibs_File::getJsonDecodeFile($path, true);
				//fixed uikit banner height fix 520
				$aData['height'] = 520;
			} else {
				$aData = RvsLibs_File::getFileSerialData($path);
				$i = 1;
				if (count($aData)) {
					foreach ($aData as $k => $v) {
						$v['headernum'] = $i;
						$aData[$k] = $v;
						$i++;
					}
				}
			}
			return $aData;
		}

		public static function getFileExtension($fileName = null)
		{
			$fileExtension = '';
			if (is_null($fileName) === false && $fileName != '' ) {
			    //fixed PHPMD scan 30/06/2544
				$fileName = RvsLibs_String::strtolower($fileName);
                if (preg_match('#\.tar\.gz$#', $fileName)) {
					$fileExtension = 'tar.gz';
				} else {
					//$fileName = RvsLibs_String::strtolower($fileName);
					$fileName = preg_replace('/\/$/','', $fileName);
					$afileExtension = preg_split("#[/\\.]#", $fileName) ;
					$n = count($afileExtension)-1;
					$fileExtension = $afileExtension[$n];
				}
			}
			return $fileExtension;
		}

		public static function getPageExtension($component, $pageId, $confAllowPHP)
		{
			if ($component != '0' && $component != '') {
				$extension = 'php';
			} else {
				if ($confAllowPHP == 1 || isset($_SESSION['onlineform_' . $pageId])) {
					$extension = 'php';
				} else {
					$extension = 'html';
				}
			}
			return $extension;
		}

		/**
		 * 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
		 */
		public static function convertCharsetFile($nativeEncoding = null, $path = null, $toFilePattern = '', $ignoreDir = array(), $skipBackup = false)
		{
			//set list filename convert charset on success
			$listFileConvert = '';
			if (is_null($nativeEncoding) || $nativeEncoding == '') {
				return SGL::raiseError(
				RvsLibs_String::translate('nativeEncoding invalid')
				);
			}
			if (is_null($path) || $path == '') {
				return SGL::raiseError(
				RvsLibs_String::translate('path to convert invalid')
				);
			}
			$filePattern = "*.html,*.php,*.js,*.htm,*.htpl,*.shtml,*.shtml1,*.whl,*.inc,*.css,*.php3,*.php4,*.php5,*.phphtml,*.xml,*.xmlhtml,*.sql";
			$filePattern = ($toFilePattern != '') ? $toFilePattern : $filePattern;
			$aPathConvertCharsetComplete = array();
			//path file complate
			$pathFileComplete = RvsLibs_File::buildPath(array($path, 'rvsUtf8Config' ));
			$fileComplete = RvsLibs_File::buildPath(array($path, 'rvsUtf8Config' , 'complete.txt'));
			// path back project
			$backupPath = RvsLibs_File::buildPath(array($path, 'rvsUtf8Backup' ));
			// 1. make folder
			if (file_exists($pathFileComplete) === false) {
				$res = RvsLibs_System::mkDir(array('-p', '-m', '0755', $pathFileComplete));
				if (SGL::isError($res)) {
					SGL::logMessage('Cannot create folder ' . $pathFileComplete , PEAR_LOG_ERR);
					SGL_Error::pop();
					return false;
				}
			}
			//check file complete
			if (is_file($fileComplete)) {
				$aPathConvertCharsetComplete = RvsLibs_File::file($fileComplete);
			}
			if (file_exists($backupPath) === false) {
				$res = RvsLibs_System::mkDir(array('-p', '-m', '0755', $backupPath));
				if (SGL::isError($res)) {
					SGL::logMessage('Cannot create folder ' . $backupPath , PEAR_LOG_ERR);
					SGL_Error::pop();
					return false;
				}
			}
			//2. List file or folder
			//'-a' = show hidden file
			$aPathFileProjectAll = RvsLibs_System::ls(array('-a', '-R', $path), $ignoreDir);
			//3. List file by pattern format
			foreach ($aPathFileProjectAll['dirs'] as $dirname) {
				$adir = RvsLibs_File::_listDirs($dirname, $filePattern);
			}
			//fix notice undefind $adir
			if (isset($adir) && is_array($adir)) {
				//4. loop all file
				foreach ($adir as $fullPath) {
					// 5. START make {$path}/rvsUtf8Backup
					if ( !RvsLibs_String::preg_match("/\/rvsUtf8Backup/", $fullPath)) {
						$fullPathBackup = RvsLibs_String::str_replace($path, $backupPath, $fullPath);
						if ($fullPathBackup == $fullPath) {
							$path2 = realpath($path);
							$fullPathBackup = RvsLibs_String::str_replace($path2, $backupPath, $fullPath);
						}
						$fileName = end(RvsLibs_String::dbeExplode('/', $fullPath));
						$fullPathBackupMakeDir = RvsLibs_String::str_replace('/' . $fileName, '', $fullPathBackup);
						if (is_dir($fullPathBackupMakeDir) === false) {
							RvsLibs_System::mkDir(array('-p', '-m', '0755', $fullPathBackupMakeDir ));
						}
						//END make {$path}/rvsUtf8Backup
						// 6. go to copy file to backup
						if (is_file($fullPath) === true && $skipBackup == false) {
							RvsLibs_System::copy(array($fullPath, $fullPathBackup));
						}
					}
					// 7. validate ว่า เคยตรวจสอบว่าเป็น utf-8 หรือไม่ check ในไฟล์ complete.tx
					// 7.2 ถ้ามีแล้ว continue;
					if (RvsLibs_String::preg_match("/\.utf8\./i", $fullPath)
					|| count($aPathConvertCharsetComplete)
					&& in_array($fullPath, RvsLibs_String::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 = RvsLibs_File::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, RvsLibs_String::preg_replace("/\\r\\n/", "", $aPathConvertCharsetComplete))
					) && !RvsLibs_String::preg_match("/rvsUtf8Backup|RvSitebuilderPreview/", $fullPath)) {

						RvsLibs_File::writeDataAppendToFile($fullPath, $fileComplete);
						//set list filename convert charset on success
						$listFileConvert .= $fullPath . "\r\n";
					}
					// 9. if utf-8 go to continue;
					if (isset($type) && RvsLibs_String::preg_match("/utf-8/i", $type)) {
						continue;
					}
					// 10. if not utf-8 go to convrt by iconv
					if ((RvsLibs_String::strtolower($type) != 'utf-8')) {
						RvsLibs_String::iconvFile($fullPath, $fullPath, $nativeEncoding, 'UTF-8');
					}
				}
			}
			return $listFileConvert;
		}

		public static function _listDirs($dir, $filePattern = "*") {
			static $alldirs = array();
			$dirs = glob( sprintf("%s/{%s}", $dir, $filePattern), GLOB_BRACE);
			if (is_array($dirs) && count($dirs) > 0) {
				foreach ($dirs as $d) {
					$alldirs[] = $d;
				}
			}
			return $alldirs;
		}

		public static function _listDirs1($dir, $ignoreDir = array())
		{
			$aPathFileProjectAll = RvsLibs_System::ls(array('-a', '-R', $dir), $ignoreDir);
			return $aPathFileProjectAll['files'];
		}

		/**
		 * scandir และ sort filemtime ด้วย
		 * @param unknown $path
		 */
		public static function scanDir($dir, $ignored = array())
		{
			//'.project','.svn','.','..','wpThumbnails', 'thumbnails', 'Thumbs.db'
			if (count($ignored) == 0) {
				$ignored = array('.', '..', '.svn', '.htaccess', 'thumbnails', 'wpThumbnails', '.project');
			}
			$files = array();
			foreach (scandir($dir) as $file) {
				if (in_array($file, $ignored)) continue;
				$files[$file] = filemtime($dir . '/' . $file);
			}
			//sort folder
			arsort($files);
			$files = array_keys($files);
			return ($files) ? $files : false;
		}

		/**
		 * Write data to file
		 *
		 * @param string $strData
		 * @param stiing $fileName
		 * @return <bool>
		 */
		public static function writeDataAppendToFile($strData, $fileName)
		{
			///Debug SGL::logMessage(null, PEAR_LOG_DEBUG);
			$strData = $strData . "\r\n";
			$handle = RvsLibs_File::fopen($fileName, "a");
			if (SGL::isError($handle) === true) {
			    return $handle;
			}
			RvsLibs_File::fwrite($handle, $strData);
			RvsLibs_File::fclose($handle);
			return true;
		}

	 /**
	  * get Type File Encode
	  *
	  * @param string $fileName
	  * @return string; type file encode
	  */
		public static function getTypeFileEncode($fileName)
		{
		    /* modify CpHendle by nipaporn*/
		    $oCp = CpHandle::factory();
		    if(SGL::isError($oCp) === true) {
		    	SGL_Error::pop();
		        return false;
		    }
		    return $oCp->getTypeFileEncode($fileName);
		}

		public static function _getFileEncode($path)
		{
			if (is_file($path)) {
				$data = RvsLibs_File::file($path);
				return (isset($data[0])) ? trim($data[0]) : "";
			}
			return "";
		}

		public static function _getXmlCharsetByLangName($langName, $defautlXml)
		{
			switch (RvsLibs_String::strtolower($langName)) {
				case 'chinese-big5':
					// for traditional chinese
					$xmlLang = 'zhtw';
					break;
				case 'serbian-latin-windows-1250':
					// for serbian latin
					$xmlLang = 'srcyr-lt';
					break;
				case 'spanish_latin-windows-1252':
					// for spanish latin
					$xmlLang = 'es-lt';
					break;
			}
			return (isset($xmlLang)) ? $xmlLang . '-utf-8' : $defautlXml . '-utf-8';
		}


		// convert wysiwy
		public static function convertCharsetWysiwy($nativeEncoding, $pathWysiwygLang, $toFilePattern = '', $ignoreDir = array())
		{
			//TODO: move to function
			$aLangFile = array();
			$globalLang = $GLOBALS['_SGL']['LANGUAGE'];
			foreach ($globalLang as $kLang => $aVLanf) {
				$id = $aVLanf[1];
				$aLangFile[$id] = $aVLanf[2];
			}
			$backupPath = RvsLibs_File::buildPath(array($pathWysiwygLang, 'rvsUtf8Backup'));
			$pathFileComplete = RvsLibs_File::buildPath(array($pathWysiwygLang, 'rvsUtf8Config' ));
			$filePattern = "*.html,*.php,*.js,*.htm,*.htpl,*.shtml,*.shtml1,*.whl,*.inc,*.css,*.php3,*.php4,*.php5,*.phphtml,*.xml,*.xmlhtml";
            $aPathFileProjectAll = RvsLibs_System::ls(array('-a', '-R', $pathWysiwygLang), $ignoreDir);
			//lop ls
			$adir = array();
			foreach ($aPathFileProjectAll['dirs'] as $dirname) {
			//fixed PHPMD scan 30/06/2544
			$adir = RvsLibs_File::_listDirs1($dirname);
			}
			//make folder utf8
			if (file_exists($pathFileComplete) === false) {
				RvsLibs_System::mkDir(array('-p', $pathFileComplete));
			}
			//make folder backup
			if (file_exists($backupPath) === false) {
				RvsLibs_System::mkDir(array('-p', $backupPath));
			}
			//lop glop
			foreach($adir as $fullPath)
			{
				if (!RvsLibs_String::preg_match("/rvsUtf8Backup/", $fullPath)) {
					$fullPathBackup = RvsLibs_String::str_replace($pathWysiwygLang, $backupPath, $fullPath);
				}
				//TODO: START move to function rename file utf8
				$keyLang = null;
				$langFolder = null;
				if (RvsLibs_String::preg_match('/\/wysiwyglang\/(.*?)\/wysiwygpr/', $fullPath, $match)) {
					$keyLang = (isset($match[1])) ? $match[1] : null;
					$langID = RvsLibs_File::_getXmlCharsetByLangName($keyLang, RvsLibs_String::strtolower($aLangFile[$keyLang]));
					$langFolder = (isset($GLOBALS['_SGL']['LANGUAGE'][$langID][1])) ? $GLOBALS['_SGL']['LANGUAGE'][$langID][1] : null;
					$pathFile = RvsLibs_String::str_replace($keyLang, $langFolder, $fullPath);
				}
				/*if (is_null($keyLang) || is_null($langFolder)) {
				 continue;
				 }*/
				//TODO: END move to function rename file utf8
				$fileName = end(RvsLibs_String::dbeExplode('/', $fullPath));
				$fullPathBackupMakeDir = (isset($pathFile)) ? RvsLibs_String::str_replace('/' . $fileName, '', $pathFile) : null;
				if (is_dir($fullPathBackupMakeDir) === false) {
					RvsLibs_System::mkDir(array('-p', $fullPathBackupMakeDir));
				}
				//check file complete
				$fileComplete = RvsLibs_File::buildPath(array($pathWysiwygLang, 'rvsUtf8Config' , 'complete.txt'));
				if (is_file($fileComplete)) {
					$aPathConvertCharsetComplete = RvsLibs_File::file($fileComplete);
				}
				//make path backup
				if (!RvsLibs_String::preg_match("/\-utf\-8/", $fullPathBackup)) {
					$fullPathBackupMakeDir = RvsLibs_String::str_replace('/' . $fileName, '', $fullPathBackup);
					if (is_dir($fullPathBackupMakeDir) === false) {
						RvsLibs_System::mkDir(array('-p', $fullPathBackupMakeDir ));
					}
				}
				//backup folder and file old
				if (!file_exists($fullPath)) {
					copy($fullPath, $fullPathBackup);
				}
				//check file complete
				if (RvsLibs_String::preg_match("/\.utf8\./i", $fullPath)
				|| count($aPathConvertCharsetComplete)
				&& in_array($fullPath, RvsLibs_String::preg_replace("/\\r\\n/", "", $aPathConvertCharsetComplete))) {
					continue;
				}
				// copy path new
				$pathNew = RvsLibs_File::buildPath(array($fullPathBackupMakeDir, $fileName));
				if (file_exists($pathNew)) {
					copy($fullPath, $pathNew);
				}
				if (!in_array($fullPath, RvsLibs_String::preg_replace("/\\r\\n/", "", $aPathConvertCharsetComplete))) {
					if (!RvsLibs_String::preg_match("/rvsUtf8Backup/", $fullPath)
					&& !RvsLibs_String::preg_match("/\-utf\-8/", $fullPath)) {
						RvsLibs_File::writeDataAppendToFile($fullPath, $fileComplete);
					}
				}
				$type = 'utf-8';
				// finfo_open require PHP version >= 5.3
				$type = RvsLibs_File::getTypeFileEncode($fullPath);
				// 9. if utf-8 go to continue;
				if (isset($type) && RvsLibs_String::preg_match("/utf-8/i", $type)) {
					continue;
				}
				// 10. if not utf-8 go to convert by iconv
				if ((RvsLibs_String::strtolower($type) != 'utf-8')) {
					if (!RvsLibs_String::preg_match("/rvsUtf8Backup/", $fullPath)
					&& !RvsLibs_String::preg_match("/\-utf\-8/", $fullPath)) {
						RvsLibs_String::iconvFile($original = $fullPath, $newfile = $pathFile, 'UTF-8', $nativeEncoding);
					}
				}
			}
		}

		/**
		 * make Ini Unreadable. add first line ';<?php die("Unreadable"); ?>'
		 *
		 * @param unknown_type $file
		 * full path = /home/{user}/.rvsitebuilder/.myconf.ini.php
		 */
		public static function makeIniUnreadable($file)
		{
			SGL::logMessage('file: ' . $file, PEAR_LOG_DEBUG);
			if (is_dir($file) == true) {
				SGL::logMessage('Error is dir: ' . $datasrc, PEAR_LOG_ERR);
				return false;
			}
			
			$iniFle = file($file);
			$string = ';<?php die("Unreadable"); ?>' . "\n";
			array_unshift($iniFle, $string);
			
			//@file_put_contents($file, implode("", $iniFle));
			$handle = RvsLibs_File::fopen($file,'w+');
			if (SGL::isError($handle) === true) {
				return $handle;
			}
			RvsLibs_File::fwrite($handle, implode("", $iniFle));
			RvsLibs_File::fclose($handle);
		}

		/**
		 * Enter description here...
		 *
		 * @param unknown_type $aColorConfig
		 * @param unknown_type $pathFileSource
		 * @param unknown_type $pathFileDest
		 */
		public static function writeFileCssCenter($aColorConfig, $pathFileSource, $pathFileDest)
		{
			$aCode = (is_file($pathFileSource)) ? RvsLibs_File::file($pathFileSource) : array();
			$strLine = "";
			if ($aCode && is_array($aColorConfig) && count($aColorConfig)) {
				foreach ($aCode as $line) {
					if (preg_match_all('/\/\s*\*\s*\*\s*\$\s*(.*?)\s*\$\s*\*\s*\*\s*\//', $line, $aMatch) ) {
						$pattern = RvsLibs_String::trim($aMatch[0][0]);
						$replace = (isset($aColorConfig['c'][$aMatch[1][0]])) ? RvsLibs_String::trim($aColorConfig['c'][$aMatch[1][0]]) : '';
						$line = str_replace($pattern, $replace, $line);
					}
					$strLine .= $line;
				}
				//appen css hidden block login
				$strLine .= self::_getStyleHiddenBlockLogin();
				//rewrite file
				$cssPathFile = $pathFileDest;
				$handle = RvsLibs_File::fopen($cssPathFile, 'w+');
				if (SGL::isError($handle) === true) {
					return $handle;
				}
				RvsLibs_File::fwrite($handle, $strLine);
				RvsLibs_File::fclose($handle);
			}
		}

		/**
		 * get style sheet for normal page to hidden block login
		 * @return unknown_type
		 */
		public static function _getStyleHiddenBlockLogin()
		{
			$tag = <<< EOF

/******** Hidden block login **********/
#RVS_hideblock {
    display:none!important;
}
EOF;
            return $tag;
		}

		public static function compileToUTF8($iniPath)
		{
			include_once SGL_LIB_DIR . '/SGL/Task/ExecuteAjaxAction.php';
			//fixed PHPMD scan 30/06/2544
            //$oExecuteAjaxAction = new SGL_Task_ExecuteAjaxAction();
			$charset = $GLOBALS['_SGL']['CHARSET'];

			if (is_dir($iniPath) || is_file($iniPath)) {
				$folder = opendir($iniPath);
				while ( $file = readdir($folder) ) {
					if (is_file($iniPath . '/' . $file)) {
						$handle = @fopen($iniPath . '/' . $file, "r");
						$contents = @fread($handle, filesize($iniPath . '/' . $file));
						@fclose($handle);
						$codeToUTF8 = RvsLibs_String::iconv($charset, $outCharset = "UTF-8", $contents);
						//fixed PHPMD scan 30/06/2544
						if (preg_match('/utf-8/',$file)) {
							continue;
						} else {
							$fileName = str_replace('.','-utf-8.',$file);
						}
						
						$file = $iniPath . '/' . $fileName;
						$handle = RvsLibs_File::fopen($file,'w');
						if (SGL::isError($handle) === true) {
							return $handle;
						}
						RvsLibs_File::fwrite($handle, $codeToUTF8);
						RvsLibs_File::fclose($handle);
					}
				}
			}
		}

		/*
		 *
		 RewriteEngine on
		 RewriteCond %{HTTP_HOST} ^.*$
		 RewriteRule ^Order.php$ /htacc/Links.php [R=301,L]
		 ##RewriteRule ^index.php$ /htacc/Links.php [R=301,L]
		 ##RewriteRule ^%B4%D9%C3%D9%BB.php$ /htacc/index.php [R=301,L]
		 */
		public static function appendHtaccess($publishPath, $publishFolder, $fileName, $nativeLang, $fileHtaccess=null)
		{
			SGL::logMessage('run task =>' , PEAR_LOG_DEBUG);
			$fileName = preg_replace('/\.php$|\.html$/i', '', $fileName);
			//is not english
			if (!preg_match_all('/^[\w\s~`!@#\$%\^&\*\(\)\+=\|\{\}\[\]:;\'\"<>,\.\\\?\/* -]{0,}$/i', $fileName, $aMatch)) {
				$publishFolder = ($publishFolder != '') ? $publishFolder . '/' : '';
				$fileNameV4 = RvsLibs_Url::url_encode($fileName);
				if (RvsLibs_String::strtolower($nativeLang) != 'utf-8') {
			        //fixed PHPMD scan 30/06/2544
					$fileNameV3iconv = RvsLibs_String::iconv('UTF-8', $nativeLang, $fileName);
					$fileNameV3 = RvsLibs_Url::url_encode($fileNameV3iconv);
					$fileNameV3 = RvsLibs_String::str_replace('%', '\x', $fileNameV3);
					$fileNameV4 = RvsLibs_String::str_replace('%', '\%', $fileNameV4);
					$content = sprintf('RewriteRule ^%s\.(.*)$ %s%s.$1 [R=301,NC,NE,QSA,L]', $fileNameV3, $publishFolder, $fileNameV4);
				} else {
					$content = '';
				}
				$fileHtaccess = is_null($fileHtaccess) === false
				? $publishPath . '/' . $fileHtaccess
				: $publishPath . '/.htaccess';
				$str = "\n";
				$str .= <<<EOF

<IfModule mod_rewrite.c>
  RewriteEngine  on
  RewriteBase /

EOF;
				$str .= $content . "\n" . "#rvs append";
				$str .= <<<EOF

   # http://httpd.apache.org/docs/2.2/mod/mod_rewrite.html#rewriterule
   # R - redirect with response code
   # NE - (no URI escaping of output) will not convert \% to %25 but will show as %
   # QSA - query string append, for photo album, guestbook
   # L - last, stop and not processs other rules
</IfModule>
EOF;
				if (is_file($fileHtaccess)) {
					if (is_writable($fileHtaccess)) {
						$fileContent = file_get_contents($fileHtaccess);
						if (!preg_match_all('/\#rvs append/', $fileContent, $aMatch)) {
							$contentFinal = $fileContent . $str;
						} else {
							$contentFinal = preg_replace('/\<IfModule mod_rewrite\.c\>(.*?)\<\/IfModule\>(.*?)EOF;/', $str, $fileContent);
						}
					}
				} else {
					$contentFinal = $str;
				}
				$h = fopen($fileHtaccess, 'w+');
				fwrite($h,$contentFinal);
				fclose($h);
			}
		}

		/**
		 * return Calculates the md5 hash of a given file
		 * @param $filePath
		 * @return unknown_type
		 */
		public static function getMd5File($filePath)
		{
			$md5Content = '';
			if (is_file($filePath) === true) {
				if (function_exists('md5_file')) {
					$md5Content = md5_file($filePath);
				} else {
					$hd = RvsLibs_File::fopen($filePath);
					if (SGL::isError($hd) === true) {
						return $hd;
					}
					$contentFile = RvsLibs_File::fread($hd);
					RvsLibs_File::fclose($hd);
					$md5Content = md5($contentFile);
				}
			}
			return $md5Content;
		}

		/**
		 *  write file and check error
		 * @param $filePath
		 * @param $content
		 * @param $option
		 * @return True on success or pear error in failure
		 */
		public static function writeFile($filePath, $content=null, $option=null)
		{
			$hd = is_null($option) ? RvsLibs_File::fopen($filePath) : RvsLibs_File::fopen($filePath, $option);
			if (SGL::isError($hd) === true) {
				return $hd;
			}
			if (is_null($content) === false) {
				$res = RvsLibs_File::fwrite($hd, $content);
				if (SGL::isError($res) === true) {
					return $res;
				}
			}
			$resClose = RvsLibs_File::fclose($hd);
			if (SGL::isError($resClose) === true) {
				return $resClose;
			}
			return true;
		}

		public static function disk_total_space($directory)
		{
			if (RvsLibs_System::function_exists('disk_total_space') === true) {
				return disk_total_space($directory);
			} else {
				return SGL::raiseError(
				RvsLibs_String::translate(
                      'Function %FUNCTION is undefine'
                      , 'vprintf'
                      , array('FUNCTION' => 'disk_total_space')
                      )
                      );
			}
		}

  	public static function _isEncode($name)
    {
        return (preg_match('/(.*?)\%(.*?)+/i', $name)) ? true : false;
    }

    public static function _isImgEncode($name)
    {
        return (preg_match('/(.*?)\%(.*?)(\.gif$|\.png$|\.jpg$|\.jpeg$)/i', $name)) ? true : false;
    }

    public static function makeImageLink($fullPath, $filename)
    {
    	if (RvsLibs_File::_isImgEncode($filename) === false) {
    		$FName = urlencode($filename);
			//fixed PHPMD scan 30/06/2544
    		$fullPath = (!preg_match('/\/$/',$fullPath)) ? $fullPath .'/' : $fullPath;
    		$oCp = CpHandle::factory();
    		if (SGL::isError($oCp) === true) {
    			$aErrors['cpwarning'] = RvsLibs_String::translate('CpWaring %MESSAGE', 'vprintf', array('MESSAGE' => $oCp->getMessage()));
    			SGL_Error::pop();
    		}
    		if (RvsLibs_File::_isImgEncode($FName) === true && is_link($fullPath . $FName) === false) {
    			SGL::logMessage("To:" . $fullPath . $filename . ' From: ' . $fullPath . $FName , PEAR_LOG_DEBUG);
    				$oCp->makeLink($fullPath . $filename, $fullPath . $FName);
    		}
    	}
    }

    public static function makeFolderLink($fullPath, $folderName)
    {
        if (RvsLibs_File::_isEncode($folderName) === false) {
            $FName = urlencode($folderName);
            if (is_link($fullPath . $FName) === false && RvsLibs_File::_isEncode($FName) === true) {
                SGL::logMessage("To:" . $fullPath . $folderName . ' From: ' . $fullPath . $FName , PEAR_LOG_DEBUG);
                RvsLibs_System::ln(array('-s', $fullPath . $folderName, $fullPath . $FName));
            }
        }
    }

    /**
     * symlink check exists
     * @param unknown_type $target
     * @param unknown_type $link
     * @return True on success or pear error in failure
     * @auther : nipaporn
     */
    public static function symlink($target, $link)
    {
    	if (function_exists('symlink')) {
    		if (is_link($link)) {
    			return SGL::raiseError(
    			RvsLibs_String::translate('Is Symlink Exists.')
    			);
    		} else {
    			if (symlink($target, $link)) {
    				return true;
    			} else {
    				return SGL::raiseError(
    				RvsLibs_String::translate('Failed create symlink.')
    				);
    			}
    		}
    	} else {
    		return SGL::raiseError(
    		RvsLibs_String::translate('Not open function symlink.')
    		);
    	}
    }

    public static function phpFileType(){
    	return (isset($_SERVER['SERVER_SOFTWARE']) && $_SERVER['SERVER_SOFTWARE'] == 'DirectAdmin') ? 'raw' : 'php';
    }


    public static function setTempFileUpload($fileTmp)
    {
    	$aFile = array();
    	if (is_array($fileTmp)) {
    		foreach($fileTmp as $kFileTmp => $vFileTmp) {
    			$aPathInfoLogo = pathinfo($vFileTmp);
    			$aFile['type'][$kFileTmp] = RvsLibs_File::returnMIMEType($vFileTmp);
    			$aFile['tmp_name'][$kFileTmp] = $vFileTmp;
    			$aFile['size'][$kFileTmp] = filesize($vFileTmp);
    			$aFile['name'][$kFileTmp] = $aPathInfoLogo['basename'];
    			$aFile['error'][$kFileTmp] = 0;
    		}
    		return $aFile;

    	} else {
    		if (is_file($fileTmp)) {
    			$aPathInfoLogo = pathinfo($fileTmp);
    			$aFile['type'] = RvsLibs_File::returnMIMEType($fileTmp);
    			$aFile['tmp_name'] = $fileTmp;
    			$aFile['size'] = filesize($fileTmp);
    			$aFile['name'] = $aPathInfoLogo['basename'];
    			return $aFile;
    		} else {
    			return SGL::raiseError(
    				RvsLibs_String::translate('File Not Found.' . $fileTmp)
    			);
    		}

    	}
    }

	public static function returnMIMEType($filename)
    {
        preg_match("|\.([a-z0-9]{2,4})$|i", $filename, $fileSuffix);
		$type = RvsLibs_String::strtolower($fileSuffix[1]);
        SGL::logMessage(" file type:" . $type, PEAR_LOG_DEBUG);
        switch($type)
        {
            case "js" :
                return "application/x-javascript";

            case "json" :
                return "application/json";

            case "jpg" :
            case "jpeg" :
            case "jpe" :
                return "image/jpeg";

            case "png" :
            case "gif" :
            case "bmp" :
            case "tiff" :
                return "image/" . $type;

            case "css" :
                return "text/css";

            case "xml" :
                return "application/xml";

            case "doc" :
            case "docx" :
                return "application/msword";

            case "xls" :
            case "xlt" :
            case "xlm" :
            case "xld" :
            case "xla" :
            case "xlc" :
            case "xlw" :
            case "xll" :
                return "application/vnd.ms-excel";

            case "ppt" :
            case "pps" :
                return "application/vnd.ms-powerpoint";

            case "rtf" :
                return "application/rtf";

            case "pdf" :
                return "application/pdf";

            case "html" :
            case "htm" :
            case "php" :
                return "text/html";

            case "txt" :
                return "text/plain";

            case "mpeg" :
            case "mpg" :
            case "mpe" :
                return "video/mpeg";

            case "mp3" :
                return "audio/mpeg3";

            case "wav" :
                return "audio/wav";

            case "aiff" :
            case "aif" :
                return "audio/aiff";

            case "avi" :
                return "video/msvideo";

            case "wmv" :
                return "video/x-ms-wmv";

            case "mov" :
                return "video/quicktime";

            case "zip" :
                return "application/zip";

            case "tar" :
                return "application/x-tar";

            case "gz" :
                return"application/x-gzip";

            case "swf" :
                return "application/x-shockwave-flash";

            default :
            if(function_exists("mime_content_type"))
            {
                $fileSuffix = mime_content_type($filename);
            }

            return "unknown/" . trim($fileSuffix[0], ".");
        }
    }

    /**
     * detect upload file destination cannot be symlink
     * 
     * @param unknown $tempFile
     * @param unknown $destination
     * @return object|string|boolean
     */
    public static function moveUploadedFile($tempFile, $destination)
    {
    	$isHardLink = false;
    	if (function_exists('stat') == true && is_file($destination) == true) {
    		$fileStat = @stat($destination);
    		$isHardLink = (isset($fileStat['nlink']) && $fileStat['nlink'] == '2') ? true : false;
    	}
    	//RVSB case: Privilege is not root and upload file destination cannot be hard link return error
    	if (strtolower(RvsLibs_User::getPrivilege()) != 'root' && $isHardLink == true) {
    		SGL::logMessage('File name cannot be hard link: ' . $destination, PEAR_LOG_ERR);
    		return SGL::raiseError('File name cannot be hard link: ' . $destination);
    	}
    	
    	//RVSB case: Privilege is not root and upload file destination cannot be symlink return error
    	if (strtolower(RvsLibs_User::getPrivilege()) != 'root' && is_link($destination) == true) {
    		SGL::logMessage('upload file destination cannot be symlink: ' . $destination, PEAR_LOG_ERR);
    		return SGL::raiseError('upload file destination canot be symlink: ' . $destination);
    	}
    	
    	return (move_uploaded_file($tempFile, $destination)) ? true : false;
    }

    public static function isUploadedFile($tempFile)
    {
    	return (is_uploaded_file($tempFile)) ? true : false;
    }


    /**
     redirect to memberpage
     * @param $conttentHtaccMemberPage
     * @param $publishUrl
     * @param $frontScriptName
     * @param $fileName
     * @return unknown_type
     */
    /*function appendHtaccessRedirec($conttentHtaccMemberPage, $publishUrl,$frontScriptName, $fileName)
    {
    	$filenameDef = $fileName;
    	$filenameDef = RvsLibs_Url::url_encode($filenameDef);
    	$filenameDir = $publishUrl . '/' . $frontScriptName . '/default/memberpage/page/' . $fileName;
    	//$filenameDir = RvsLibs_Url::url_encode($filenameDir);
    	$filenameDef = RvsLibs_String::str_replace('%', '\x', $filenameDef);
    	$filenameDir = RvsLibs_String::str_replace('%', '\%', $filenameDir);
    	$content = sprintf('RewriteRule ^%s$ %s [R=301,NC,NE,QSA,L]', $filenameDef, $filenameDir);
    	return $conttentHtaccMemberPage . "\n" . $content;
    }*/

    /**
     * $newFileName, $oldFileName ไม่ต้อง encode อีก
     * ถ้า filename เก่า มี * ให้ใส่ \* ให้
     * @param $newFileName
     * @param $oldFileName
     * @param $publishFolder
     * @return string
     */
    public static function appendHtaccessRedirecPage($newFileName, $oldFileName, $publishFolder)
    {
    	$newFileName = RvsLibs_String::str_replace('(', '\(', $newFileName);
    	$newFileName = RvsLibs_String::str_replace(')', '\)', $newFileName);
    	$newFileName = RvsLibs_String::str_replace(',', '\,', $newFileName);
    	$newFileName = RvsLibs_String::str_replace('.', '\.', $newFileName);
    	$newFileName = RvsLibs_String::str_replace('"', '\"', $newFileName);
    	$newFileName = RvsLibs_String::str_replace("'", "\'", $newFileName);
    	$newFileName = RvsLibs_String::str_replace("-", "\-", $newFileName);

    	$newFileName = RvsLibs_String::str_replace('%', '\x', $newFileName);
    	$newFileName = RvsLibs_String::preg_replace('/\*/' , '\*', $newFileName);
    	$newFileName = RvsLibs_String::preg_replace('/\|/' , '\|', $newFileName);

    	$oldFileName = RvsLibs_String::str_replace('(', '\(', $oldFileName);
    	$oldFileName = RvsLibs_String::str_replace(')', '\)', $oldFileName);
    	$oldFileName = RvsLibs_String::str_replace(',', '\,', $oldFileName);
    	$oldFileName = RvsLibs_String::str_replace('.', '\.', $oldFileName);
    	$oldFileName = RvsLibs_String::str_replace('"', '\"', $oldFileName);
    	$oldFileName = RvsLibs_String::str_replace("'", "\'", $oldFileName);
        $oldFileName = RvsLibs_String::str_replace("-", "\-", $oldFileName);

    	$oldFileName = RvsLibs_String::str_replace('%', '\%', $oldFileName);
    	$oldFileName = RvsLibs_String::preg_replace('/\*/' , '\*', $oldFileName);
    	$oldFileName = RvsLibs_String::preg_replace('/\|/' , '\|', $oldFileName);

    	$newPathFileName = (isset($publishFolder) && $publishFolder)
    						? $publishFolder . '/' . $newFileName
    						: $newFileName;
    	$content = sprintf('RewriteRule ^%s$ %s [R=301,NE,QSA,L]', $oldFileName, $newPathFileName);
    	return  "\n" . $content;
    }


   public static function fixFileHtaccess($fileHtaccess)
    {
        if (is_file($fileHtaccess) === true) {
            $fileContent = RvsLibs_File::file($fileHtaccess);
            $hd = RvsLibs_File::fopen($fileHtaccess, 'w');
            if(SGL::isError($hd) === true) {
            	return $hd;
            }
            foreach ($fileContent as $line) {
                $line = str_replace('\n', '', $line);
                $line = preg_replace("/\s+\<IfModule/", '<IfModule' , $line);
                RvsLibs_File::fwrite($hd, $line);
            }
            RvsLibs_File::fclose($hd);
        }
       return true;
    }

    public static function backupFileHtaccessFile($path)
    {
        $filePath = RvsLibs_File::buildPath(array($path, '.htaccess'));
        $newFile = RvsLibs_File::buildPath(array($path, 'rvsBackup.htaccess'));
        if(file_exists($filePath)) {
            $res = RvsLibs_System::rename($filePath, $newFile);
            if (SGL::isError($res) === true) {
                return SGL::raiseError(
                    RvsLibs_String::translate(
                        'เราต้องการที่จะแบคอัพไฟล์ %FILE เพื่อนให้สามารถทำการ publish เว็บไซต์ แต่ไม่สามารถทำได้ เพราะ %MSG'
                        , 'vprintf'
                        , array(
                            'FILE' => $filePath
                            , 'MSG' => $res->getMessage()
                        )
                    )
                );
            }
        }
    }

    public static function restoreFileHtaccessFile($path)
    {
    	$filePath = RvsLibs_File::buildPath(array($path, 'rvsBackup.htaccess'));
    	$newFile = RvsLibs_File::buildPath(array($path, '.htaccess'));
    	if(file_exists($filePath)) {
    		return RvsLibs_System::rename($filePath, $newFile);
    	}
    	return true;
    }

    public static function appendHtaccessFile($pathDir)
    {
    	if (is_dir($pathDir)) {
    		$pathFile = RvsLibs_File::buildPath(array($pathDir, '.htaccess'));
    		$handleHta = RvsLibs_File::fopen($pathFile, 'w');
    		if (SGL::isError($handleHta) === true) {
    			SGL::logMessage('cannot open file. ' . $handleHta->getMessage() , PEAR_LOG_ERR);
    			SGL_Error::pop();
    			return false;
    		}
    		$data = 'RewriteEngine off';
    		RvsLibs_File::fwrite($handleHta, $data);
    		RvsLibs_File::fclose($handleHta);
    		RvsLibs_System::chmod($pathFile, '0755');
    	}
    }

    public static function appendImagesDa($dirPath)
    {
            $filePath = $dirPath . '/.htaccess';
            $port = (isset($_SERVER['SERVER_PORT'])) ? $_SERVER['SERVER_PORT'] : 2222;
            $htaccessData = <<< EOF
Options -Indexes

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /

RewriteCond %{HTTP_REFERER} .css|_temp [NC]
RewriteCond %{HTTP_REFERER} !^$
RewriteRule (.*) $1 [L]

RewriteCond %{HTTP_REFERER} !:$port/ [NC]
RewriteCond %{HTTP_REFERER} !^$
RewriteRule .*$ /error.gif [L]
</IfModule>
EOF;

            $handle = RvsLibs_File::fopen($filePath,'w+');
            if (SGL::isError($handleHta) === true) {
            	SGL::logMessage('cannot open file. ' . $handleHta->getMessage() , PEAR_LOG_ERR);
            	SGL_Error::pop();
            	return false;
            }
            RvsLibs_File::fwrite($handle, $htaccessData);
            RvsLibs_File::fclose($handle);
    }

    /**
     * rename file from upper name to lower name
     * @param $projectId
     * @param $action
     * @return unknown_type
     */
    public static function renameFileUpperToLower($projectId)
    {
    	SGL::logMessage(null, PEAR_LOG_DEBUG);
    	$aFolder = array('media', 'images', 'documents', 'tmp');
    	foreach ($aFolder as $foldername) {
    		$path = REAL_PROJECT_PATH . '/'. $projectId . '/' . $foldername;
    		$imgFile = RvsLibs_System::ls(array('-a', '-R', $path));
    		foreach ($imgFile['files'] as $key => $val) {
    			$newFile = preg_replace_callback(
    		'/([A-Z1-9]*)$/',
    			create_function(
	            '$match',
	            'return strtolower($match[0]);'
	            ),
	            $val
	            );
	            if ($val != $newFile) {
	            	@rename($val, $newFile);
	            }
	            //replace ค่าว่าง
	            $new = str_replace(' ', '_', $val);
	            if ($val != $new) {
	            	@rename($val, $new);
	            }
    		}
    	}
    }

    /**
     * 60*60*24 = 8400 second default = 1 day
     * 60 แรก วินาที 60 ตัวที่2คือ นาที 24 คือ 1 วัน
     * numeric is second (วินาที)
     * @param $time
     * @return unknown_type
     */
    public static function &rvsCache($time = 86400)
    {
    	$cache = SGL_Cache::singleton('function', array(
         'dontCacheWhenTheResultIsFalse' => true,
         'dontCacheWhenTheResultIsNull'  => true,
         'lifeTime'                      => $time,
         'debugCacheLiteFunction'        => true,
        ));
        return $cache;
    }

    public static function replaceDataJsOn($match)
    {
    	$GLOBALS ['deleteJSonMyImage'] {$match [1]} = true;
    	return '';
    }

    /**
     * clean json data
     * @param unknown $data
     */
    public static function  defacementMyImageJSontoArray($data) {

    	// case remove file myimage
    	$pat = '/delete[^;](?:(?:myimages)|(?:storeimages))\[\"([^;]*)\"\];/is';
    	$data = preg_replace_callback ( $pat, RvsLibs_File::replaceDataJsOn($match), $data );

    	//unsupport php5.2
    	/*$data = preg_replace_callback ( $pat, function ($match) {
    		$GLOBALS ['deleteJSonMyImage'] {$match [1]} = true;
    		return '';
    	}, $data );*/

    		$pat = '/null/is';
    		$data = preg_replace ( $pat, '{}', $data );
    		// case add image file
    		$pat = '/\}\}\;/is';
    		$data = preg_replace ( $pat, '},', $data );
    		//echo $data;
    		$pat = '/\}\;/is';
    		$data = preg_replace ( $pat, '},', $data );

    		$pat = '/(?:(?:myimages)|(?:storeimages)|(?:tagfolder))\[(.*?)\]/is';
    		$data = preg_replace ( $pat, '$1:', $data );
    		//echo $data;
    		$pat = '/\,$/is';
    		$data = preg_replace ( $pat, '};', $data );
    		//echo $data;exit;
    		$pat = '/(?:var ((?:myimages)|(?:storeimages)|(?:tagfolder)) =)|(?:\;)|[\=]/is';
    		$data = preg_replace ( $pat, '', $data );
    		//echo $data;
    		// 		$pat = '/\;$/';
    		// 		if (!preg_match ( $pat, $data)) {
    		// 		//$data .= ';';

    		// 		}

    		$pat = '/\"\{\}\"/is';
    		$data = preg_replace ( $pat, '{', $data );

    		$data = SGL_AjaxProvider::jsonDecode ( $data );

    		if (isset ( $GLOBALS ['deleteJSonMyImage'] )) {
    			foreach ( $GLOBALS ['deleteJSonMyImage'] as $key => $val ) {
    				unset ( $data [$key] );
    			}
    		}
    		unset ( $GLOBALS ['deleteJSonMyImage'] );
    		return $data;
    }

    /**
     *
     * @param $medthodName
     * @param $source file, string,path
     * @return unknown_type
     */
    public static function isNotMd5Change($medthodName, $source, $tmpDir=null)
    {
    	SGL::logMessage(null, PEAR_LOG_DEBUG);
    	$tmpPath = ($tmpDir === null) ? SGL_TMP_DIR . '/md5file' : $tmpDir;
    	$source = (is_array($source)) ? serialize($source) : $source;

    	if (is_file($source)) {
    		$md5File = RvsLibs_File::getMd5File($source);
    	} else {
    		$md5File = md5($source);
    	}

    	$fileMd5 = $medthodName . '_' . $md5File .'.md5';
    	$makeFileMd5 = $tmpPath . '/' . $fileMd5;
    	if (is_file($makeFileMd5)) {
    		return true;
    	} else {
    		if (is_dir($tmpPath)) {
    			$aFiles = System::find(array($tmpPath, "-name", sprintf("%s_*.md5", $medthodName)));
    			@System::rm($aFiles);
    		} else {
    			RvsLibs_System::mkDir(array($tmpPath));
    		}
    		if(!file_exists($makeFileMd5)) {
    			$res = RvsLibs_File::fopen($makeFileMd5,'w+');
    		}
    		RvsLibs_File::fclose($res);
    		return false;
    	}
    }

    public static function userClearCache($cacheDir=null)
    {
        $resTmp = ($cacheDir === null) ? SGL_TMP_DIR : $cacheDir;
        SGL::logMessage('rvdebug:: ' . $resTmp, PEAR_LOG_DEBUG);

        if (is_dir($resTmp)) {
        	$aTmpFiles = System::find("$resTmp -name cache_* -name js_* -name css_* -name md5file*");
        	@System::rm($aTmpFiles);
        }

        /*
        //$lastTimeTmp = filemtime($resTmp);
        $day = (24*60*60*1000);
        //if((time() - $lastTimeTmp) >= $day) {
        if (is_dir($resTmp)) {
        	$aTmpFiles = System::find("$resTmp -name *");
        	foreach ($aTmpFiles as $fileTmp) {
        		$lastTimeTmp = filemtime($fileTmp);
        		SGL::logMessage('L: ' . __LINE__ . ' : *********' . time() - $lastTimeTmp .'>'. $day , PEAR_LOG_ERR);
        		if ((time() - $lastTimeTmp) >= $day) {
        			@System::rm($fileTmp);
        		}
        	}
        }
        //}
        */

        $resCache = ($cacheDir === null) ? SGL_CACHE_DIR : $cacheDir;
        SGL::logMessage($resCache, PEAR_LOG_DEBUG);
        if (is_link($resCache)) {
        	@System::rm(array('-f', $resCache));
        } elseif (is_dir($resCache)) {
        	$aTmpFiles = System::find("$resCache -name *");
        	@System::rm($aTmpFiles);
        }

        /*
        //$lastTimeCache = filemtime($resCache);
        //if((time() - $lastTimeCache) >= $day) {
        if (is_dir($resCache)) {
        	$aTmpFiles = System::find("$resCache -name *");
        	foreach ($aTmpFiles as $fileTmp) {
        		$lastTimeTmp = filemtime($fileTmp);
        		SGL::logMessage('L: ' . __LINE__ . ' : *********' . time() - $lastTimeTmp .'>'. $day , PEAR_LOG_ERR);
        		if ((time() - $lastTimeTmp) >= $day) {
        			@System::rm($fileTmp);
        		}
        	}
        }
        //}
         */
    }

    }//end class
}//end check class_exists
?>

Copyright 2K16 - 2K18 Indonesian Hacker Rulez