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/Util.php

<?php
if (class_exists('RvsLibs_Util') === false) {
	class RvsLibs_Util
	{
		public static function getFontIndex()
		{
			if (INDEX_PHPSU == "index.php?") {
				return INDEX_PHPSU;
			} else {
				return "index.php";
			}
		}

		public static function validateMemoryUser()
		{
			if (isset($_SERVER['CONTENT_LENGTH'])) {
				$size = (int) $_SERVER['CONTENT_LENGTH'];
				$postMaxSize = ((int) ini_get('post_max_size'))*1024*1024;
				$uploadMaxFileSize = ((int) ini_get('upload_max_filesize'))*1024*1024;
				if ($size > $postMaxSize || $size > $uploadMaxFileSize) {
					return SGL::raiseError(
				  ' Your selected file size is too big. The maximum file size is ' . SGL_String::formatBytes($uploadMaxFileSize) . '.'
                );

				} else {
					return true;
				}
			} else {
				return true;
			}
		}

		/**
		 *unsetErrorFalse
		 * unset $aErrors is false
		 * @param array $aErrors
		 * @return array
		 */
		public static function unsetErrorFalse($aErrors)
		{
			foreach ($aErrors as $kErrors => $vErrors) {
				if (!$vErrors) {
					unset($aErrors[$kErrors]);
				}
			}
			return $aErrors;
		}

		/**
		 * Enter getQuotaUser
		 * check cpmode and get path
		 * path = frontend cpanel
		 * @return path
		 */
		public static function getPathQuotaUser()
		{
			///Debug SGL::logMessage(null, PEAR_LOG_DEBUG);
			$path = SGL_BASE_URL;
			$aPath = RvsLibs_String::dbeExplode(RvsLibs_String::strtolower(RVSNOBASE_URL_WWW) , $path);
			/*modify CpHandle by nipaporn*/
			$oCp = CpHandle::factory();
			if(SGL::isError($oCp) === true) {
				return $oCp;
				/*
			    return SGL::raiseError(RvsLibs_String::translate('CpWaring %MESSAGE', 'vprintf', array('MESSAGE' => $oCp->getMessage())));
				*/
			}
			return $oCp->getPathQuotaUser($aPath);
		}

		/** validateFreeSpace
		 * $actionName = "import", "preview" or "publish"
		 * default maxSize = 15 M
		 * $aQuota[0] = showquotaused
		 * $aQuota[1] = showquotamax
		 *
		 * case:import   ---> validateFreeSpace("import", 1);
		 * case:preview ---> validateFreeSpace("preview");
		 * case:publish ---> validateFreeSpace("publish");
		 */
		public static function validateFreeSpace($actionName, $maxSize = 15)
		{
			///use CpHandle :: Witoon and modify by nipaporn
			$oCp = CpHandle::factory();
			if(SGL::isError($oCp) === true) {
				return $oCp;
			    /*
				return SGL::raiseError(
			    	RvsLibs_String::translate(
			    		'CpWaring %MESSAGE'
			    		, 'vprintf'
			    		, array('MESSAGE' => $oCp->getMessage())
			    	)
			    );
			    */
			}
			$oCpData = $oCp->getCpUserInfo();
			$maxQuota = RvsLibs_String::trim($oCpData->maxquota);
			$quotaUsed = RvsLibs_String::trim($oCpData->quotaused);
			if ( RvsLibs_String::strtolower($maxQuota) != "unlimited") {
				if ( (intval($quotaUsed) + $maxSize) > intval($maxQuota)) {
					RvsLibs_String::translate(
						SGL::raiseMsg('your' . 'Cannot ' . RvsLibs_String::trim(RvsLibs_String::strtolower($actionName)) . '. Because disk usage fully.')
					);
					SGL_HTTP::redirect(
						array('managerName' => 'sitebuilder/freeSpaceFull/1/actionName/' . $actionName)
					);
				}
			}
			/*
			$maxSize = $maxSize ? $maxSize : 15;
			if (CPMODE == "cpanel") {
				$cpanelTag = '<cpanel Quota="showquotaused()">' . "\n" . '<cpanel Quota="showquotamax()">';
				$oCp = CpHandle::factory();
				$oCp->runCpanelTagOnIframe("validateFreeSpace", $cpanelTag);
				$aQuota = $oCp->getCpanelTagData();
				if ( strtolower(RvsLibs_String::trim($aQuota[1])) != "unlimited") {
					if ( ($aQuota[0] + $maxSize) > $aQuota[1]) {
						RvsLibs_String::translate(SGL::raiseMsg('your' . 'Cannot ' . RvsLibs_String::trim(strtolower($actionName)) . '. Because disk usage fully.'));
						SGL_HTTP::redirect(array('managerName' => 'sitebuilder/freeSpaceFull/1/actionName/' . $actionName));
					}
				}
			}
			*/
		}

	      /** get disSpace
         * default maxSize = 15 M
         * return array
         * $aDiskQuota[0] = diskuse
         * $aDiskQuota[1] = diskmax
         * $aDiskQuota[3] = docroot
         */
        public static function getDiskQuota()
        {
            ///use CpHandle :: ควรจะ request ทีเดียวทั้งหมด
            ///จะได้ไม่ต้องรัน runCpOnIframe บ่อยๆ
            /*modify CpHandle by nipaporn*/
            $oCp = CpHandle::factory();
            if(SGL::isError($oCp) === true) {
                return $oCp;
            }
            $oCpData = $oCp->getCpUserInfo();
            if(SGL::isError($oCpData) === true) {
            	return $oCpData;
            }
            $aDiskQuota[1] = isset($oCpData->quotaused) ? trim($oCpData->quotaused) : '';
            $aDiskQuota[2] = isset($oCpData->maxquota) ? trim($oCpData->maxquota) : '';
            $aDiskQuota[3] = isset($oCpData->docroot) ? trim($oCpData->docroot) : '';
            return $aDiskQuota;
        }

		/**
		 * Clean Special Variables in template
		 * - allow spaces in variable HTML comment
		 * - case insensitve
		 * - don't remove the HTML code beside the var comment
		 * - allow start comment and end comment in a single line
         * remove HTML code by line and by $aLine[$k]
		 * $aEnableSubVar = array(
		 'TOP'                             =>     '0',
		 'SIDE1'                        =>    '0',
		 'SIDE2'                        =>    '0',
		 'FOOTER'                    =>    '0',
		 'BOTTOM'                    =>    '0',
		 'PATHWAY'                    =>    '0',
		 'ICON'                            =>    '0',
		 );
		 * @package rvsitebuilder
		 * @author Apiruk Boonruksa - 20060630
		 */
		public static function cleanSpecialVar($aLine, $aEnableSubVar = array())
		{
			///Debug SGL::logMessage(null, PEAR_LOG_DEBUG);
			$aSpecialMainVar = array(
                    '<!--BeginSIDE1andSIDE2-->'        =>    '<!--EndSIDE1andSIDE2-->',
                    '<!--BeginPATHWAYandICON-->'    =>    '<!--EndPATHWAYandICON-->',
			);
			$aSpecialSubVar = array(
                    '<!--BeginTOP-->'                             =>     '<!--EndTOP-->',
                    '<!--BeginSIDE1-->'                        =>    '<!--EndSIDE1-->',
                    '<!--BeginSIDE2-->'                        =>    '<!--EndSIDE2-->',
                    '<!--BeginFOOTER-->'                    =>    '<!--EndFOOTER-->',
                    '<!--BeginBOTTOM-->'                    =>    '<!--EndBOTTOM-->',
                    '<!--BeginPATHWAY-->'                    =>    '<!--EndPATHWAY-->',
                    '<!--BeginICON-->'                            =>    '<!--EndICON-->',
			);
			if (array_key_exists('TOP', $aEnableSubVar)) {
				unset($aSpecialSubVar['<!--BeginTOP-->']);
			}
			if (array_key_exists('FOOTER', $aEnableSubVar)) {
				unset($aSpecialSubVar['<!--BeginFOOTER-->']);
			}
			if (array_key_exists('BOTTOM', $aEnableSubVar)) {
				unset($aSpecialSubVar['<!--BeginBOTTOM-->']);
			}
			if ((array_key_exists('SIDE1', $aEnableSubVar)) && (array_key_exists('SIDE2', $aEnableSubVar))) {
				unset($aSpecialSubVar['<!--BeginSIDE1-->']);
				unset($aSpecialSubVar['<!--BeginSIDE2-->']);
				unset($aSpecialMainVar['<!--BeginSIDE1andSIDE2-->']);
			} elseif (array_key_exists('SIDE1', $aEnableSubVar)) {
				unset($aSpecialSubVar['<!--BeginSIDE1-->']);
				unset($aSpecialMainVar['<!--BeginSIDE1andSIDE2-->']);
			} elseif (array_key_exists('SIDE2', $aEnableSubVar)) {
				unset($aSpecialSubVar['<!--BeginSIDE2-->']);
				unset($aSpecialMainVar['<!--BeginSIDE1andSIDE2-->']);
			}

			if ((array_key_exists('ICON', $aEnableSubVar)) && (array_key_exists('PATHWAY', $aEnableSubVar))) {
				unset($aSpecialSubVar['<!--BeginICON-->']);
				unset($aSpecialSubVar['<!--BeginPATHWAY-->']);
				unset($aSpecialMainVar['<!--BeginPATHWAYandICON-->']);
			} elseif (array_key_exists('ICON', $aEnableSubVar)) {
				unset($aSpecialSubVar['<!--BeginICON-->']);
				unset($aSpecialMainVar['<!--BeginPATHWAYandICON-->']);
			} elseif (array_key_exists('PATHWAY', $aEnableSubVar)) {
				unset($aSpecialSubVar['<!--BeginPATHWAY-->']);
				unset($aSpecialMainVar['<!--BeginPATHWAYandICON-->']);
			}

			$tagMainStart = 0;
			$startMainKey = '';
			$tagSubStart = 0;
			$startSubKey = '';
			$oRvsLibString = new RvsLibs_String();
			foreach ($aLine as $k => $line) {
				// remove comment spaces and make it all lowercase
				$line = str_replace('<!-- Begin SIDE1 and Begin SIDE2 -->', '<!-- Begin SIDE1 and SIDE2 -->', $line);
				$line = str_replace('<!-- End SIDE1 and End SIDE2 -->', '<!-- End SIDE1 and SIDE2 -->', $line);
				$noSpace = preg_replace_callback('/(<!--.*?-->)/',
				array($oRvsLibString, 'removeSpaceCallback'),
				$line);

				if ($startMainKey != '') {
					if (preg_match('/' . $aSpecialMainVar[$startMainKey] . '/i' ,$noSpace)) {
						// remove before <!--Endxxxxxx-->
						$aPieces = RvsLibs_String::dbeExplode(RvsLibs_String::strtolower($aSpecialMainVar[$startMainKey]), $noSpace);
						$aLine[$k] = $aPieces[1];
						$tagMainStart = 0;
						$startMainKey = '';
						continue;
					}
				}
				if ($tagMainStart) {
					$aLine[$k] = '';
					continue;
				}
				foreach ($aSpecialMainVar as $start => $end) {
					if (preg_match('/' . $start . '/i' ,$noSpace)) {
						// remove after <!-- Startxxxx
						$aPieces1 = RvsLibs_String::dbeExplode(RvsLibs_String::strtolower($start), $noSpace);
						//line is start comment = ''
						$aPieces1[1] = '';
						// prevent the End..--> same line as <!--Start
						$aPieces2 = RvsLibs_String::dbeExplode(RvsLibs_String::strtolower($end), $aPieces1[1] ? $aPieces1[1] : '');
						$aLine[$k] = $aPieces1[0] . ' ' . $aPieces2[0];
						if (count($aPieces2) < 2) {
							$tagMainStart = 1;
							$startMainKey = $start;
						}
						break;
					}
				}
				if ($tagMainStart) {
					continue;
				}

				if ($startSubKey != '') {
					if (preg_match('/' . $aSpecialSubVar[$startSubKey] . '/i' ,$noSpace)) {
						// remove before <!--Endxxxxxx-->
						$aPieces = RvsLibs_String::dbeExplode(RvsLibs_String::strtolower($aSpecialSubVar[$startSubKey]), $noSpace);
						$aLine[$k] = $aPieces[1];
						$tagSubStart = 0;
						$startSubKey = '';
						continue;
					}
				}
				if ($tagSubStart) {
					$aLine[$k] = '';
					continue;
				}

				foreach ($aSpecialSubVar as $start => $end) {
					if (preg_match('/' . $start . '/i' ,$noSpace)) {
						// remove after <!-- Startxxxx
						$aPieces1 = RvsLibs_String::dbeExplode(RvsLibs_String::strtolower($start), $noSpace);
						//line is start comment = ''
						$aPieces1[1] = '';
						// prevent the End..--> same line as <!--Start
						$aPieces2 = RvsLibs_String::dbeExplode(RvsLibs_String::strtolower($end), $aPieces1[1] ? $aPieces1[1] : '');
						SGL::logMessage('============>>> ' . $aPieces1[1] .'===='. $end, PEAR_LOG_DEBUG);
						SGL::logMessage('============>>> ' . $aPieces1[0] .'===='. $aPieces2[0], PEAR_LOG_DEBUG);
						$aLine[$k] = $aPieces1[0] . ' ' . $aPieces2[0];
						if (count($aPieces2) < 2) {
							$tagSubStart = 1;
							$startSubKey = $start;
						}
						break;
					}
				}
			}
			return $aLine;
		}

		/* �觤�� charset �Ѻ language - 20 May 2005 */
		 public static function getLang($projectId)
		 {
		     ///Debug SGL::logMessage(null, PEAR_LOG_DEBUG);
		     /// Find charset lang data by project id :: BooM
		     return DaoFactory::Charset()->findCharsetLangByProjectId($projectId, 'getrow');
		 }

		 public static function getCharsetByLangName($charsetName)
		 {
		     ///Debug SGL::logMessage(null, PEAR_LOG_DEBUG);
		     /// Find charset data by charset name :: BooM
		     return DaoFactory::Charset()->findCharDataByCharsetName($charsetName , 'getall');
		 }

		 /**
		 * define lang key use in /lib/data/ary.languages.php
		 *
		 * @param unknown_type $charsetValue
		 * @param unknown_type $defautlXml
		 * @return unknown
		 */
		public static function getXmlCharset($defautlXml, $charsetValue)
		{
			///Debug SGL::logMessage(null, PEAR_LOG_DEBUG);
			$charsetName = $defautlXml . '-' . $charsetValue;
			switch (RvsLibs_String::strtolower($charsetName)) {
				case 'zh-big5':
					// for traditional chinese
					$xmlLang = $defautlXml . 'tw';
					break;
				case 'srcyr-windows-1250':
					// for serbian latin
					$xmlLang = $defautlXml . '-lt';
					break;
				case 'es-windows-1252':
					// for spanish latin
					$xmlLang = $defautlXml . '-lt';
					break;
			}
			return (isset($xmlLang)) ? $xmlLang . '-utf-8' : $defautlXml . '-utf-8';
		}

		/* ��駤�� language - 10 Oct 2005 */
		public static function setLang($projectCharset = '-1')
		{
			if ($projectCharset < 0) {
				$userid = RvsLibs_User::getUserId();
				$res = DaoFactory::Charset()->findCharsetLangByUserId($userid,'getrow');
				$projectCharset = (isset($res['charset_id']) && $res['charset_id']) ? $res['charset_id'] : $projectCharset ;
			}
			//get session charset_id
			$charsetId = ($projectCharset) ? $projectCharset : SGL_Session::get('charset_id');
			if ($charsetId) {
			     $aLang = DaoFactory::Charset()->findCharsetDataByCharsetId($charsetId);
			}
			SGL::logMessage('start lang= ' . $projectCharset , PEAR_LOG_DEBUG);
			$projectId = SGL_Session::get('rvs_project_id');
			if ($projectCharset < 0) {
				if ($charsetId != '17' && $charsetId > 0) {
					$lang = (isset($aLang[$charsetId]->xml_lang)) ? RvsLibs_Util::getXmlCharset($aLang[$charsetId]->xml_lang, $aLang[$charsetId]->charset_value) : 'en-utf-8';
					$_SESSION['aPrefs']['language'] = $lang;
					$_SESSION['aPrefs']['locale'] = $GLOBALS['_SGL']['LANGUAGE'][$lang][3];
					$GLOBALS['_SGL']['CHARSET'] = 'utf-8';
				} else {
					// set lang by user set control panel
					$res =  DaoFactory::Charset()->findCharDataByCharsetName(RvsLibs_Util::getLangName(), 'getrow');
					if (!isset($res['xml_lang']) || !isset($res['charset_value']) ) {
						$_SESSION['aPrefs']['language'] = 'en-utf-8';
						$_SESSION['aPrefs']['locale'] = 'en_US.utf8';
						$GLOBALS['_SGL']['CHARSET'] = 'utf-8';
					} else {
						$lang = (isset($res['xml_lang'])) ? RvsLibs_Util::getXmlCharset($res['xml_lang'], $res['charset_value']) : 'en-utf-8';
						$_SESSION['aPrefs']['language'] = $lang;
						$_SESSION['aPrefs']['locale'] = $GLOBALS['_SGL']['LANGUAGE'][$lang][3];
						$GLOBALS['_SGL']['CHARSET'] = 'utf-8';
					}
					SGL::logMessage('user control panel lang= ' . $_SESSION['aPrefs']['language'] , PEAR_LOG_DEBUG);
				}
			} else {
				// Edit Charset for Admin PageStructure
				/// Find charset data by charset id :: BooM
				$res = DaoFactory::Charset()->findCharsetDataByCharsetId($projectCharset, 'getrow');
				$lang = (isset($res['xml_lang'])) ? RvsLibs_Util::getXmlCharset($res['xml_lang'], $res['charset_value']) : 'en-utf-8';
				SGL::logMessage('user save lang= ' . $lang , PEAR_LOG_DEBUG);
				$_SESSION['aPrefs']['language'] = $lang;
				$_SESSION['aPrefs']['locale'] = $GLOBALS['_SGL']['LANGUAGE'][$lang][3];
				$GLOBALS['_SGL']['CHARSET'] = 'utf-8';
			}
			SGL_Session::set('charset_id', $charsetId);
			SGL::logMessage('session lang= ' . $_SESSION['aPrefs']['language'] , PEAR_LOG_DEBUG);
			 ////////// siwakorn directadmin /////////
			 /*wproHeader::setHeaderDirectAdmin("HTTP/1.1 200 OK");
			 wproHeader::setHeaderDirectAdmin("Content-Type: text/html; charset=utf-8");*/
		     //SGL_Output::addHeader("Content-Type: text/html; charset=utf-8");
		     if (RvsLibs_DirectAdmin::isDirectAdmin()) {
				//echo "Content-Type: text/html; charset=utf-8\n";
		     } else {
		     	@header('Content-Type: text/html; charset=utf-8');
			}
		}

		public static function getLangName()
		{
		    SGL::logMessage('L:' . __LINE__ . 'RVS_USER_LANG= ' . RVS_USER_LANG , PEAR_LOG_DEBUG);
			$cpanelLang = RvsLibs_String::strtolower(RVS_USER_LANG);
			$cpanelLang = str_replace("-utf8", "", $cpanelLang);
			$cpanelLang = (preg_match("/japanese/", $cpanelLang)) ? $cpanelLang : str_replace("-", " ", $cpanelLang);
			SGL::logMessage('L:' . __LINE__ . '$cpanelLang= ' . $cpanelLang , PEAR_LOG_DEBUG);
			return $cpanelLang;
		}

		/**
		 * input $_SESSION['aPrefs']['locale'])
		 * @return ru_RU
		 */
		public static function getLangLocale($langLocale)
		{
			$fileLangFb = RvsLibs_File::buildPath(array(SGL_LIB_DIR, 'data', 'ary.locale.facebook.php'));
			//include file output $alocaleFb
			include_once $fileLangFb;
			$lang = RvsLibs_String::preg_replace('/\.utf8$/','',$langLocale);
			return (isset($alocaleFb[$lang])) ? $lang : 'en_US';
		}

		/**
		 * validate database result to return charset
		 *
		 * @author apiruk boonruksa
		 * @param <string> $charset
		 * @return <string>
		 */
		public static function getCurrentCharset($charset = null)
		{
			$currentCharset = (!is_null($charset)) ? $charset : $GLOBALS['_SGL']['CHARSET'];
			SGL::logMessage("curent charset=" . $currentCharset, PEAR_LOG_DEBUG);
			if ($currentCharset == 'utf-8') {
				return $currentCharset;
			} else {
				return (RvsLibs_DB::isDatabaseUtf8() === true) ? 'utf-8' : $currentCharset;
			}
		}

		/**
		 * validate database result to return xmlCharset
		 *
		 * @author apiruk boonruksa
		 * @param <string> $charset
		 * @return <string>
		 */
		public static function getCurrentXmlCharset($xmlLang, $xmlCharset = null)
		{
			$resultDBCharset = mysql_result(mysql_query("SELECT @@character_set_results"),0,0);
			return (RvsLibs_String::strtolower($resultDBCharset) == 'utf8')
			        ? $xmlLang . ' -utf-8'
			        :  (is_null($xmlCharset) === false)
			        ? $xmlCharset
			        : $_SESSION['aPrefs']['language'];
		}
		//end foreach

		/**
		 * if cannot define 'allowRVSiteBuilderTutorial'
		 * return true
		 *
		 * @return boolean true, false
		 */
		public static function isAllowRVSiteBuilderTutorial()
		{
			///Debug SGL::logMessage(null, PEAR_LOG_DEBUG);
			$oMgr = SGL_Manager::singleton();
			//all config
			$c = SGL_Config::singleton();
        	$oMgr->aConf = $c->getAll();

			if (isset($oMgr->aConf['Admin']['SiteBuilder']['allowRVSiteBuilderTutorial'])) {
				return $oMgr->aConf['Admin']['SiteBuilder']['allowRVSiteBuilderTutorial'];
			} else {
				return true;
			}
		}

		public static function buildJSON($aData)
		{
			///Debug SGL::logMessage(null , PEAR_LOG_ERR);
			$json = '';
			foreach ($aData as $key => $value) {
				if ($json != '') {
					$json .= ',';
				}
				$json .= "'" . $key . "' : '"  . $value . "'" . "\n";
			}
			return '{' . $json . '}';
		}

		/**
		 * getlistcharset()
		 *
		 * @return <array>
		 * Ex: {key_lang number}/{key_lang_name}
		 */
		public static function getlistcharset()
		{
			///Debug SGL::logMessage(null, PEAR_LOG_DEBUG);
			/// Find all charset data :: BooM
			return DaoFactory::Charset()->findCharsetData('getassoc');
		}

		/**
		 * javaRedirect
		 *
		 * @param string  $aAction
		 * run echo java code window.loaction = redirect
		 */
		public static function javaRedirect($aAction)
		{
			$urlRedirect = sprintf('%s/%s/' , SGL_BASE_URL , INDEX_PHPSU);
			$manager = $aAction['managerName'];
			$module = $aAction['moduleName'];
			$action = $aAction['action'];
			unset($aAction['managerName']);
			unset($aAction['moduleName']);
			unset($aAction['action']);
			foreach ($aAction as $k => $v ) {
				$param .=  sprintf('%s/%s', $k,$v);
			}
			$javaRedirect =
        "<script language='JAVASCRIPT' type='TEXT/JAVASCRIPT'>
            <!--
            window.location = \"" . SGL_URL::makeLink($action, $manager, $module) . $param . "\";
            //--></script>";
			$javaRedirect;
			exit;
		}

		/**
		 * isRedirectHeaderOrJava
		 *
		 * @param true/false $aRedirect
		 * @param option array url mgr $redirectInstallDB
		 */
		public static function isRedirectHeaderOrJava($redirectInstallDB, $aRedirect)
		{
			if ($redirectInstallDB) {
				RvsLibs_Util::javaRedirect($aRedirect);
			} else {
				SGL_HTTP::redirect($aRedirect);
			}
		}

		/**
		 * serialize array and encode by base64 : Witoon
		 * @param $aData
		 * @return string
		 */
		public static function encodeArray($aData){
			return base64_encode(serialize($aData));
		}

		/**
		 * สำหรับ decode string จาก ฟังก์ชัน enCodeArray : Witoon
		 * @param $srtEncode
		 * @return array
		 */
		public static function decodeArray($srtEncode){
			return unserialize(base64_decode($srtEncode));
		}

		public static function validateTrue($value)
		{
			if ($value === '1' || $value === 1 || RvsLibs_String::strtolower($value) === 'true' || $value === true) {
			 return true;
			}
			return false;
		}


		/**
		 *
		 * @param $queryLine
		 * @param $option
		 * @return unknown_type
		 * Array
		 *		(
		 *		    [rvs_charset] => Array
		 (
		 [charset_id] => '46'
		 [charset_name] => 'thai'
		 [charset_value] => 'tis-620'
		 [xml_lang] => 'th'
		 )

			)
			*/
		public static function pasreSQLtoArray($queryLine, $option = 'REPLACE')
		{
			$aInfo = array();
			$aInfoFinal = array();
			switch (RvsLibs_String::strtoupper($option)) {
				case 'REPLACE':
					RvsLibs_String::preg_match("/^\s*REPLACE\s*INTO\s*(`|)(.*?)(`|)\s*\(\s*(.*?)\s*\)\s*VALUES\s*\(\s*(.*?)\s*\)\s*;\s*$/", $queryLine, $aMatch);

					$aField = (isset($aMatch[4])) ? RvsLibs_String::dbeExplode(',', $aMatch[4]) : array();
					$aValues = (isset($aMatch[5])) ? RvsLibs_Util::_setSQLValuesToArray($aMatch[5]) : array();

					if (count($aField)) {
						$aInfoFinal['table'] = (isset($aMatch[2])) ? $aMatch[2] : '';
						foreach ($aField as $k => $field) {
							$aInfoFinal['field'][RvsLibs_String::trim($field)] = $aValues[$k];
							$field = str_replace('`', '', $field);
							$aInfo[$aMatch[2]][RvsLibs_String::trim($field)] = $aValues[$k];
						}
					}
					break;
			}
			return $aInfo;
		}

		protected static function _setSQLValuesToArray($lineValue)
		{
			SGL::logMessage(null, PEAR_LOG_DEBUG);
			$oldMemory = @ini_get('memory_limit');
			$oldTimeOut = (int)@ini_get('max_execution_time');
			RvsLibs_Project::setMaximumMemory($oldMemory, $oldTimeOut);
			//process time out

			eval("\$aValue = array(" . $lineValue . ");");
			foreach ($aValue as $key => $value) {
				$aValue[$key] = (is_null($value)) ?  'null' : "'" . RvsLibs_String::str_replace("'", "\'", RvsLibs_String::trim($value)) . "'";
			}
			
			RvsLibs_Project::setRollbackMemory($oldMemory, $oldTimeOut);
			
			return  $aValue;
		}

		public static function getFieldInfo($aTableInfo)
		{
			$aFieldInfo = array();
			foreach ($aTableInfo as $val) {
				$aFieldInfo[$val['name']] = $val;
			}
			return $aFieldInfo;
		}

		public static function getDefaultFieldValue($aFieldInfo)
		{
			if (trim($aFieldInfo['flags']) == 'not_null' || (isset($aFieldInfo['notnull']) && $aFieldInfo['notnull'] == 1)) {
				return (isset($aFieldInfo['default'])) ? $aFieldInfo['default'] : '';
			} else {
				return (!isset($aFieldInfo['default']) || $aFieldInfo['default'] == null)
					? 'NULL'
					: $aFieldInfo['default'];

			}
		}

	 /**
     * repalce date to literal comment {} in top bottom side1 side 2 for blog component only
     * @param $code
     * @param $ignore = array()
     * if you add string in array array('{BLOCK1}')
     * in the funtion have iqnore that string
     *
     * @return unknown_type
     */
    public static function literalComment($code, $ignore=array())
    {
        //case: 1 php , css script, java script
        // { replace to /*{literal}*/{/*{/literal}*/
        // } replace to /*{literal}*/}/*{/literal}*/
        //case: 2 html and normal text
        // { replace to <!--{literal}-->{<!--{/literal}-->
        // } replace to <!--{literal}-->}<!--{/literal}-->
        SGL::logMessage(null, PEAR_LOG_DEBUG);
        //fixed PHPMD scan 07/07/2554
        //$aCode = array();
        $aPattern = array();
        $aRepalce = array();
        $code = isset($code) ? $code : '';
        $paten = "/<\!\-\-{literal}\-\->|<\!\-\-{\/literal}\-\->|<\!\-\-\-\->|\/\*{literal}\*\/|\/\*{\/literal}\*\//";
        $code = preg_replace($paten, '', $code);
        $code = preg_replace("/({|})/", "<!--{literal}-->$1<!--{/literal}-->",  $code);
        $code = preg_replace('/\\r|\\n/','<RVBR>',$code);
        if (preg_match_all('/(<\?php|<\?|<style|<script)(.*?)(\?>|style>|script>)/i', $code, $match)) {
            foreach($match[0] as $keyM => $valM ) {
                $smallM = RvsLibs_String::strtolower($match[1][$keyM]);
                //echo htmlspecialchars($smallM) .'<br>';
                $patten = "/<\!\-\-{literal}\-\->({|})<\!\-\-{\/literal}\-\->/";
                if ($smallM == '<?php' || $smallM == '<?') {
                    $dataPHP = preg_replace($patten, "/*{literal}*/$1/*{/literal}*/",  $valM);
                    $aPattern[$keyM] = $valM;
                    $aRepalce[$keyM] = str_replace($valM ,$dataPHP ,$valM);
                } elseif ($smallM == '<style' || $smallM == '<script') {
                    $dataSTYLE = preg_replace($patten, "/*{literal}*/$1/*{/literal}*/",  $valM);
                    $aPattern[$keyM] = $valM;
                    $aRepalce[$keyM] = str_replace($valM ,$dataSTYLE ,$valM);
                }
            }

        }

        foreach ($aPattern as $k => $v) {
            $code = str_replace($aPattern[$k] ,$aRepalce[$k] ,$code);
        }

        if (count($ignore)) {
            foreach ($ignore as $kGnor => $vGnor) {
                $vGnor1 = preg_replace('/{|}/','', $vGnor);
                $patten = '/<\!\-\-\-\->{<\!\-\-\-\->'. $vGnor1. '<\!\-\-\-\->}<\!\-\-\-\->|<\!\-\-{literal}\-\->{<\!\-\-{\/literal}\-\->' . $vGnor1 . '<\!\-\-{literal}\-\->}<\!\-\-{\/literal}\-\->/';
                $code = preg_replace($patten, $vGnor, $code);
            }
        }
        //optimize : siwakorn
        return preg_replace('/<RVBR>/', "\n", $code);
    }

    public static function getDecodeByEncodeType($encodeContent, $encodeType)
    {
    	$decodeContent = '';
    	switch ($encodeType) {
    		case 'base64' :
    			$decodeContent = base64_decode($encodeContent);
    			break;
    	}
    	return $decodeContent;
    }

    /**
     * STEP 5 จะสร้างไฟล์ diskquota.ini.php ไว้แล้ว
     * 1=diskuse
     * 2=diskmax
     * 3=docroot
     * cptag ที่สร้างดูไฟล์ rvsLibs/Util.php
     * @return array;
     */
    public static function getUserInfoByFile()
    {
    	SGL::logMessage(null, PEAR_LOG_DEBUG);
    	$fileCpTagData =  RvsLibs_File::buildPath(array(RVS_USER_HOME, '.rvsitebuilder',  'diskquota.ini.php'));
    	$result = array();
    	if (is_file($fileCpTagData) === true) {
    		$result = RvsLibs_Config::parse_ini_file($fileCpTagData, true);
    	}
    	return $result;
    }

    /**
     * get float value from string
     * @param string $str
     * @param array $set
     * @return float
     */
    public static function getFloat($str, $set=array('single_dot_as_decimal'=> TRUE))
    {
    	if (preg_match("/([0-9\.,-]+)/", $str, $match)) {
    		// Found number in $str, so set $str that number
    		$str = $match[0];

    		if(strstr($str, ',')) {
    			// A comma exists, that makes it easy, cos we assume it separates the decimal part.
    			$str = str_replace('.', '', $str);    // Erase thousand seps
    			$str = str_replace(',', '.', $str);    // Convert , to . for floatval command

    			return floatval($str);
    		} else {
    			// No comma exists, so we have to decide, how a single dot shall be treated
    			if(preg_match("/^[0-9]*[\.]{1}[0-9-]+$/", $str) == TRUE
    			&& isset($set['single_dot_as_decimal'])
    			&& $set['single_dot_as_decimal'] == TRUE) {
    				// Treat single dot as decimal separator
    				return floatval($str);
    			} else {
    				// Else, treat all dots as thousand seps
    				$str = str_replace('.', '', $str);    // Erase thousand seps
    				return floatval($str);
    			}
    		}
    	} else {
    		// No number found, return zero
    		return 0;
    	}
    }

    public static function getFonts()
    {
    	$cache = SGL_Cache::singleton();
    	$serialized = $cache->get('sitebuilder', 'fonts');
    	if ($serialized) {
    		SGL::logMessage('getFonts from cache', PEAR_LOG_DEBUG);
    		$aFont = unserialize($serialized);
    	} else {
    		SGL::logMessage('getFonts from database', PEAR_LOG_DEBUG);
    		$aFont = DaoFactory::Font()->findAllFontOrderByFontName('getvalue', true);
    		if (!Pear::isError($aFont)) {
	    		$aFont = RvsLibs_String::str_replace("_"," ",$aFont);
	    		foreach ($aFont as $k => $v) {
	    			$aFont[$k] = RvsLibs_String::ucfirst($aFont[$k]);
	    		}
    		} else {
    			$aFont = array();
    		}
    		// get Google font
    		$googleFonts = RvsLibs_Util::getGoogleFonts();
    		foreach ($googleFonts as $key => $val) {
    			$aFont[] = $val['name'];
    		}

    		foreach ($aFont as $k => $v) {
    			SGL::logMessage('k=' . $k . ' v:' . $v, PEAR_LOG_DEBUG);
    		}
    		$serialized = serialize($aFont);
    		$cache->save($serialized, 'sitebuilder', 'fonts');
    	}
    	return $aFont;
    }

    public static function getFontfile($fontName)
    {
    	return RvsLibs_String::str_replace(" ","_",$fontName);
    }

    public static function getGoogleFonts()
    {
    	$file = SGL_WEB_ROOT . '/google_fonts/conf.ini';
    	$res = array();
    	if (is_file($file)) {
    		$res = RvsLibs_Config::parse_ini_file($file, true);
    	} else {
    		SGL::logMessage('no have file ' . $file, PEAR_LOG_ERR);
    	}
    	return $res;
	}

	public static function getFontIdByFontName($fontName)
	{
		$aFonts = RvsLibs_Util::getFonts();
		foreach ($aFonts as $key => $val) {
			if ($val == $fontName) return $key;
		}
		return 12;
	}

	public static function compileGoogleFontCss($cssFile, $aFontConf)
	{
		if (!isset($aFontConf['name']) || !isset($aFontConf['url'])) {
			return false;
		}
		$file = SGL_WEB_ROOT . '/google_fonts/font.css';
		$content = file_get_contents($file);
		/*FONT-URL*/
		/*FONT-NAME*/
		$content = str_replace('/*FONT-URL*/', $aFontConf['url'], $content);
		$content = str_replace('/*FONT-NAME*/', $aFontConf['name'], $content);
		
		//file_put_contents($cssFile, $content);
		$handle = RvsLibs_File::fopen($cssFile,'w+');
		if (SGL::isError($handle) === true) {
			return $handle;
		}
		RvsLibs_File::fwrite($handle, $content);
		RvsLibs_File::fclose($handle);
		return true;
	}
 }

}

if (class_exists('RvsLibs_Log') === false) {
	class RvsLibs_Log
	{
		public function RvsLibs_Log() {

		}

		public static function singleton($msg, $autoLoad=false, $type = PEAR_LOG_DEBUG) {
			static $time;
			if (isset($time) === false || $autoLoad === true) {
				$time = getSystemTime();
			}
			$timeUsed = RvsLibs_Log::getTimeUsed($time);
			SGL::logMessage($msg . ' Time used:'. $timeUsed, $type);
			$time = getSystemTime();
		}

		public static function getTimeUsed($timeStart)
		{
			$stopTime = getSystemTime();
			return $stopTime - $timeStart;
		}

	}
}

if (!class_exists('RvsLibs_Freezer')) {
class RvsLibs_Freezer
	{
	public static function freezer($aFreezeData, $freezeFile=null)
	{
		if (is_null($freezeFile)) {
			$freezeFile = '/tmp/freezer_obj';
		}
		$oFreezeData = serialize($aFreezeData);
		if (PEAR::isError($oFreezeData) === true) {
			return $oFreezeData;
		}
		if (file_exists($freezeFile) === true) {
			unlink($freezeFile);
		}
		$fd = fopen($freezeFile, 'w+');
		if (Pear::isError($fd) === true) {
			return $fd;
		}
		$gzFreezeData = gzcompress($oFreezeData, 9);
		fwrite($fd, ($gzFreezeData === false) ? $oFreezeData : $gzFreezeData);
		fclose($fd);
	}

	public static function unfreezer($freezeFile=null)
	{
		$afrezeData = array();
		if (is_null($freezeFile)) {
			$freezeFile = '/tmp/freezer_obj';
		}
		if (file_exists($freezeFile) === true) {
			$afrezeData = file($freezeFile);
			$gzFrezeData = join('', $afrezeData);
			$frezeData = gzuncompress($gzFrezeData);
			$frezeData = ($frezeData === false) ? $gzFrezeData : $frezeData;
			//fixed PHPMD scan 07/07/2544
			unlink($freezeFile);

			$afrezeData = @unserialize($frezeData);
		}
		return $afrezeData;
	}

	public static function cleanFreezer($freezeFile=null)
	{
		if (is_null($freezeFile)) {
			$freezeFile = '/tmp/freezer_obj';
		}
		if (file_exists($freezeFile) === true) {
			RvsLibs_System::unlink($freezeFile);
		}
	}
}
}
?>

Copyright 2K16 - 2K18 Indonesian Hacker Rulez