CHips L MINI SHELL

CHips L pro

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

<?php

require_once dirname(__FILE__) . '/InterfaceForUser.php';
require_once dirname(__FILE__) . '/CpanelLibs.php';

class CpHandle_CpanelUser extends CpHandle_CpanelLibs implements CpHandle_InterfaceForUser
{

	public function CpHandle_CpanelUser() {
		parent::SGL_Manager();
	}

	public function init()
	{
		SGL::logMessage(null, PEAR_LOG_DEBUG);
	}

	public function getLogoutUrl()
	{
		SGL::logMessage(null, PEAR_LOG_DEBUG);
		return '/logout';
	}

	/**
	 * defind path file config name
	 * @see sitebuilder/classes/CpHandle/CpHandle_InterfaceForUser#definedModulePathConfig($moduleName)
	 */
	public function definedModulePathConfig($moduleName)
	{
		SGL::logMessage(null, PEAR_LOG_DEBUG);
		return  SGL_VAR_DIR . '/config/' . $moduleName .'.ini';
	}

    public function setCookieAndRedirect()
    {
        SGL::logMessage(null, PEAR_LOG_DEBUG);
        return false;
    }

    public function detectPathPHP()
    {
        if (!function_exists('get_cfg_var')) {
            return false;
        }

        $pathPHPini = get_cfg_var('cfg_file_path');
        $pathPHPini = trim($pathPHPini);
        return ($pathPHPini == '/usr/local/lib/php.ini' || $pathPHPini == '/usr/lib/php.ini') ? true : false;

        /*
        if (CPMODE == 'cpanel') {
            $pathPHPini = get_cfg_var('cfg_file_path');
            $pathPHPini = trim($pathPHPini);
            $checkphpini = ($pathPHPini == '/usr/local/lib/php.ini' || $pathPHPini == '/usr/lib/php.ini') ? false : true;
            if ($checkphpini === false) {
                $output->warningMakecpphp = true;
            }
        }
        */
    }

    public function isValidBuyAccountUrl()
    {
        SGL::logMessage(null, PEAR_LOG_DEBUG);
        return false;
    }

    public function getUrlBackToTryout()
    {
        SGL::logMessage(null, PEAR_LOG_DEBUG);
         return false;
    }

    public function isValidClearCacheAndRVSiteFIX()
    {
        SGL::logMessage(null, PEAR_LOG_DEBUG);
        return true;
    }

    public function isValidIncludeFileLang($aConfTemplateList)
    {
        return  false;
    }

	public function isNotTryout()
	{
		//log loop SGL::logMessage(null, PEAR_LOG_DEBUG);
	    return true;
	}

	public function isVaildTemplatePrivate()
	{
		//SGL::logMessage(null, PEAR_LOG_DEBUG);
	    return false;
	}

	public function doAddCronJob()
	{
		//TODO :: ยัง Add cronjob ไม่ได้
$cptage = <<< EOF
<cronjob>
<![CDATA[
    <cpanel Rvsitebuilder="addCronJob()">
]]>
</cronjob>
EOF;
		$addCronUtl = $this->runCpOnIframe("addCronJob", $cptage);
        if(SGL::isError($addCronUtl) === true) {
            return $addCronUtl;
        } else {
        	SGL::logMessage('*********Data cronjob' . trim($addCronUtl->cronjob), PEAR_LOG_DEBUG);
			return  true;
        }
	}

	public function isValidDataHomeReplace($data)
	{
		SGL::logMessage(null, PEAR_LOG_DEBUG);
	    return preg_match('/3rdparty/', $data) ? true :false;
	}


	public function actionAJExternal($url)
	{
		SGL::logMessage(null, PEAR_LOG_DEBUG);
	   return 'actionAJExternal("' . $url. '")';
	}
	/**
    * no process in nocp
    * cpanel return true
    */
    public function isRecordPublishProject()
    {
    	SGL::logMessage(null, PEAR_LOG_DEBUG);
        return true;
    }

    //cp is process
	public function isValidTemplateItemPath($templateUserId, $templateItemFolder)
	{
		SGL::logMessage(null, PEAR_LOG_DEBUG);
	    return RvsLibs_Template::isValidTemplate($templateUserId, $templateItemFolder);
	}

	/**
    * no process in cpanel
    */
	public function getPathPHPsuexec()
	{
		SGL::logMessage(null, PEAR_LOG_DEBUG);
	    return false;
	}

    public function getProjectDbMissing($userID)
    {
    	SGL::logMessage(null, PEAR_LOG_DEBUG);
        require_once dirname(dirname(__FILE__)) . '/RestoreProjectDbMissingMgr.php';
        $oRestorePj = new RestoreProjectDbMissingMgr();
        $aProjectNotInDb = $oRestorePj->getProjectNotInDbByUserId($userID, REAL_PROJECT_PATH);
        return $aProjectNotInDb;
    }

    public function isAllowExportProject()
    {
        return (isset($this->conf['Admin']['Owner']['AllowExportProject']))
        	? $this->conf['Admin']['Owner']['AllowExportProject']
        	: '0';
    }

    public function isAllowImportProject()
    {
    	SGL::logMessage(null, PEAR_LOG_DEBUG);
        return (isset($this->conf['Admin']['Owner']['AllowImportProject']))
        	? $this->conf['Admin']['Owner']['AllowImportProject']
        	: '0';
    }

    public function getHomeDir($username=RVS_USER_NAME)
    {
    	SGL::logMessage(null, PEAR_LOG_DEBUG);
        $homeDir = @posix_getpwnam($username);
        if (empty($homeDir['dir']) === true) {
            $homeDir['dir'] = '/home/' . $username;
        }
        return $homeDir['dir'];
    }

	/// User Information Functions
	public function getCPDATA($username=RVS_USER_NAME)
	{
		SGL::logMessage(null, PEAR_LOG_DEBUG);
        $aCpLine = RvsLibs_File::file('/var/cpanel/users/' . $username);
        $aCpdata = array();
        foreach ($aCpLine as $cpLine) {
            $cpLine = RvsLibs_String::preg_replace("/\r|\n/","",$cpLine);
            list($cpKey, $cpValue) = RvsLibs_String::dbeExplode("=", $cpLine);
            if (isset($cpKey)) {
                $aCpdata[$cpKey] =  $cpValue;
            }
        }
        return $aCpdata;
	}

	public function getUserDNS($all = 0)
	{
		SGL::logMessage(null, PEAR_LOG_DEBUG);
		$aUserDNS = array();
		if ($all == 1) {
			foreach ($GLOBALS['CPANEL']['CPDATA'] as $key => $val) {
				if (RvsLibs_String::preg_match('/^DNS/', $key, $match)) {
					SGL::logMessage($key . "=" . $val, PEAR_LOG_DEBUG);
					array_push($aUserDNS, $val);
				}
			}
		} else {
			$aUserDNS = isset($GLOBALS['CPANEL']['CPDATA']['DNS']) ? $GLOBALS['CPANEL']['CPDATA']['DNS'] : '';
		}
		return $aUserDNS;
	}

	public function getRealDIRbyDomain($domain)
	{
		SGL::logMessage(null, PEAR_LOG_DEBUG);
		$foundInDNS = 0;
		$aUserDnsList = $this->getUserDNS(1);

		if (in_array(trim($domain), $aUserDnsList) === false) {
			SGL::logMessage("Cannot find domain: " . $domain . " in \$GLOBALS['CPANEL']['CPDATA']", PEAR_LOG_ERR);
			//return SGL::raiseError(RvsLibs_String::translate('Invalid your domain.'));
		}

		$path = $this->_getPathByDomain($domain);
		$result = ($path != false) ? $path : $this->_subDomainPath($domain);

		if (SGL::isError($result) === true) {
            return $result;
		} else {
			SGL::logMessage("Domain: " . $domain . " Path: " . $result, PEAR_LOG_DEBUG);
			$subDomainPath['DIR'] = $result;
		}
		return $subDomainPath;
	}


	public function getDatabaseInfomation()
	{
        SGL::logMessage(null, PEAR_LOG_DEBUG);
        $cpTag = <<<EOF
<!-- <cpanel Mysql="initcache()"> -->
<countdb>
<![CDATA[
    <cpanel Mysql="countdbs()">
]]>
</countdb>
<maxdb>
<![CDATA[
    <cpanel print="\$CPDATA{'MAXSQL'}">
]]>
</maxdb>
<listdbs>
<![CDATA[
    <?cp MysqlFE::listdbs(%\{comma},db)?>
]]>
</listdbs>
<listusers>
<![CDATA[
    <?cp MysqlFE::listusers(%\{comma},user)?>
]]>
</listusers>

EOF;
        $oXmlRes = $this->runCpOnIframe(__FUNCTION__, $cpTag);
        if (SGL::isError($oXmlRes) === true){
        	return $oXmlRes;
        } else {
        	return $this->_fetchOxmlDBInfoToArray($oXmlRes);
        }
	}

	public function doCreateDatabase($dbname)
	{
		SGL::logMessage(null, PEAR_LOG_DEBUG);
		$cpTag = <<<EOF
<processlog>
<![CDATA[
Call Mysql::adddb('$dbname').
<cpanel Mysql="adddb('$dbname')">
Call Mysql::updateprivs().
<cpanel Mysql="updateprivs()">
Call Mysql::initcache().
<cpanel Mysql="initcache()">
]]>
</processlog>
<cpanelif \$CPERROR{'mysql'}>
<status>
<![CDATA[
    <cpanel print="\$CPERROR{'mysql'}">
]]>
</status>
</cpanelif>
<cpanelif !\$CPERROR{'mysql'}>
<status>ok</status>
</cpanelif>
EOF;

        $oXmlRes = $this->runCpOnIframe(__FUNCTION__, $cpTag);
        return $this->_validateDBFunctionStatus($oXmlRes);
	}

	public function doCreateDatabaseUser($username, $passwd)
	{
        SGL::logMessage(null, PEAR_LOG_DEBUG);
        $cpTag = <<<EOF
<processlog>
<![CDATA[
Call Mysql::adduser('$username','$passwd')
<cpanel Mysql="adduser('$username','$passwd')">
Call Mysql::updateprivs()
<cpanel Mysql="updateprivs()">
Call Mysql::initcache()
<cpanel Mysql="initcache()">
]]>
</processlog>
<cpanelif \$CPERROR{'mysql'}>
<status>
<![CDATA[
    <cpanel print="\$CPERROR{'mysql'}">
]]>
</status>
</cpanelif>
<cpanelif !\$CPERROR{'mysql'}>
<status>ok</status>
</cpanelif>
EOF;

        $oXmlRes = $this->runCpOnIframe(__FUNCTION__, $cpTag);
        return $this->_validateDBFunctionStatus($oXmlRes);
	}

	public function doAddDBUser($dbname, $username)
	{
        SGL::logMessage(null, PEAR_LOG_DEBUG);
        $cpTag = <<<EOF
<processlog>
<![CDATA[
Call Mysql::adduserdb('$dbname','$username', 'ALTER CREATEROUTINE CREATETEMPORARYTABLES CREATE DELETE DROP SELECT INSERT UPDATE REFERENCES INDEX LOCKTABLES ALL')
<cpanel Mysql="adduserdb('$dbname','$username', 'ALTER CREATEROUTINE CREATETEMPORARYTABLES CREATE DELETE DROP SELECT INSERT UPDATE REFERENCES INDEX LOCKTABLES ALL')">
Call Mysql::updateprivs()
<cpanel Mysql="updateprivs()">
Call Mysql::initcache()
<cpanel Mysql="initcache()">
]]>
</processlog>
<cpanelif \$CPERROR{'mysql'}>
<status>
<![CDATA[
    <cpanel print="\$CPERROR{'mysql'}">
]]>
</status>
</cpanelif>
<cpanelif !\$CPERROR{'mysql'}>
    <status>ok</status>
</cpanelif>
EOF;

        $oXmlRes = $this->runCpOnIframe(__FUNCTION__, $cpTag);
        return $this->_validateDBFunctionStatus($oXmlRes);
	}

	public function doDeleteDatabase($dbname)
	{
		SGL::logMessage(null, PEAR_LOG_DEBUG);
        $cpTag = <<<EOF
<processlog>
<![CDATA[
Call Mysql::deldb('$dbname')
<cpanel Mysql="deldb('$dbname')">
Call Mysql::updateprivs()
<cpanel Mysql="updateprivs()">
Call Mysql::initcache()
<cpanel Mysql="initcache()">
]]>
</processlog>
<cpanelif \$CPERROR{'mysql'}>
<status>
<![CDATA[
    <cpanel print="\$CPERROR{'mysql'}">
]]>
</status>
</cpanelif>
<cpanelif !\$CPERROR{'mysql'}>
    <status>ok</status>
</cpanelif>
EOF;

        $oXmlRes = $this->runCpOnIframe(__FUNCTION__, $cpTag);
        return $this->_validateDBFunctionStatus($oXmlRes);
	}

	public function doDeleteDatabaseUser($username)
	{
        SGL::logMessage(null, PEAR_LOG_DEBUG);
        $cpTag = <<<EOF
<processlog>
<![CDATA[
Call Mysql::deluser('$username')
<cpanel Mysql="deluser('$username')">
Call Mysql::updateprivs()
<cpanel Mysql="updateprivs()">
Call Mysql::initcache()
<cpanel Mysql="initcache()">
]]>
</processlog>
<cpanelif \$CPERROR{'mysql'}>
<status>
<![CDATA[
    <cpanel print="\$CPERROR{'mysql'}">
]]>
</status>
</cpanelif>
<cpanelif !\$CPERROR{'mysql'}>
    <status>ok</status>
</cpanelif>
EOF;
        $oXmlRes = $this->runCpOnIframe(__FUNCTION__, $cpTag);
        return $this->_validateDBFunctionStatus($oXmlRes);
	}

    /**
     * input $dbname
     * check prefix and add prefix , return new dbname have prefix
     */
    public function getRealFormatDBName($dbName)
    {
    	SGL::logMessage(null, PEAR_LOG_DEBUG);
    	$db_prefix = CpHandle_CpanelLibs::getDbprefix();
    	return (defined('DATABASE_PREFIX') && DATABASE_PREFIX === false)
    		? $db_prefix . $dbName
            : $db_prefix . '_' . $dbName;
    }

	public function getMaxUserQuota()
	{
        SGL::logMessage(null, PEAR_LOG_DEBUG);
        $res = $this->getServerSoftwareInfo();
        if (strtolower($res['version']) != 'unknow' && $res['version'] >= '11.54') {
        	//get quotamax from file
        	$res = RvsLibs_Util::getUserInfoByFile();
        	$obj = new stdClass();
        	$obj->maxquota = $res[2];
        	return $obj;
        }

        $cpTag = <<<EOF
<maxquota>
<![CDATA[
<cpanel Quota="showquotamax()">
]]>
</maxquota>
EOF;

        $oXmlRes = $this->runCpOnIframe(__FUNCTION__, $cpTag);
        if (SGL::isError($oXmlRes) === true) {
            return $oXmlRes;
        } else {
            return ($oXmlRes->maxquota) ? trim($oXmlRes->maxquota) : 'no data';
        }
	}

	public function getUserQuota()
	{
        SGL::logMessage(null, PEAR_LOG_DEBUG);
        $res = $this->getServerSoftwareInfo();
        if (strtolower($res['version']) != 'unknow' && $res['version'] >= '11.54') {
        	//get quotaused from file
        	$res = RvsLibs_Util::getUserInfoByFile();
        	$obj = new stdClass();
        	$obj->quotaused = $res[1];
        	return $obj;
        }
        $cpTag = <<<EOF
<quotaused>
<![CDATA[
<cpanel Quota="showquotaused()">
]]>
</quotaused>
EOF;

        $oXmlRes = $this->runCpOnIframe(__FUNCTION__, $cpTag);
        if (SGL::isError($oXmlRes) === true) {
            return $oXmlRes;
        } else {
            return ($oXmlRes->quotaused) ? trim($oXmlRes->quotaused) : 'no data';
        }
	}

	public function getDocroot()
	{
        SGL::logMessage(null, PEAR_LOG_DEBUG);
        $res = $this->getServerSoftwareInfo();
        if (strtolower($res['version']) != 'unknow' && $res['version'] >= '11.54') {
        	//get docroot from file
        	$res = RvsLibs_Util::getUserInfoByFile();
        	$obj = new stdClass();
        	$obj->docroot = $res[3];
        	return $obj;
        }
        $cpTag = <<<EOF
<docroot>
<![CDATA[
<cpanel PHP="loaddocroots()">
]]>
</docroot>
EOF;

        $oXmlRes = $this->runCpOnIframe(__FUNCTION__, $cpTag);
        if (SGL::isError($oXmlRes) === true) {
            return $oXmlRes;
        } else {
            return ($oXmlRes->docroot) ? trim($oXmlRes->docroot) : 'no data';
        }
	}

	/**
	*get user info
	* return object
	* $obj->quotaused
	* $obj->maxquota
	* $obj->docroot
	 */
	public function getCpUserInfo()
	{
	    SGL::logMessage(null, PEAR_LOG_DEBUG);
	    $res = $this->getServerSoftwareInfo();
	    if (strtolower($res['version']) != 'unknow' && $res['version'] >= '11.54') {
	    	//get docroot from file
	    	$res = RvsLibs_Util::getUserInfoByFile();
	    	$obj = new stdClass();
	    	$obj->quotaused = $res[1];
	    	$obj->maxquota = $res[2];
	    	$obj->docroot = $res[3];
	    	return $obj;

	    }
        $cpTag = <<<EOF
<quotaused>
<![CDATA[
<cpanel Quota="showquotaused()">
]]>
</quotaused>
<maxquota>
<![CDATA[
<cpanel Quota="showquotamax()">
]]>
</maxquota>
<docroot>
<![CDATA[
<cpanel PHP="loaddocroots()">
]]>
</docroot>
EOF;
        return $this->runCpOnIframe(__FUNCTION__, $cpTag);
	}

    public function registerButtonOnlineCounter()
    {
        SGL::logMessage(null, PEAR_LOG_DEBUG);
       /* $oEditor->registerButton('onlineCounterButton', 'OnlineCounter', 'WPro.editors[\'##originalName##\'].openDialogPlugin(\'OnlineCounter&action=1&projectPageId=' . $projectPageId . '&projectId=' . $projectId . '\', 710, 520)', '##directory##images/online_counter.gif', 22, 22);
        $oEditor->addRegisteredButton('onlineCounterButton', 'after:specialchar');
        $oEditor->addContextMenuItem('onlineCounterButton', 'after:pastecleanup');
        return $oEditor;*/
        return true;
    }

    /**
     * This function process in tryout mode.
     * @author siwakorn@rvglobalsoft.com
     * @param $isPhpSuExec ( 0/1 )
     * @return <true>/<false>
     */
    public function changePermissionRVSPreview($isPhpSuExec)
    {
        SGL::logMessage(null, PEAR_LOG_DEBUG);
        return false;
    }

    /**
     * Make folder component in scripts project path.
     *
     * @author Puttipong <puttipong@rvglobalsoft.com>
     * @param String $pathComponentName
     * @return mix PEAR error or Boolean True
     */
    public function makeFolderComponent($pathComponentName = null)
    {
        SGL::logMessage(null, PEAR_LOG_DEBUG);

        if (isset($pathComponentName) === true && is_dir($pathComponentName) === false) {
            $resMkdir = RvsLibs_System::mkDir(array('-p', $pathComponentName));
            if (SGL::isError($resMkdir) === true) {
                return $resMkdir;
            }
        }
        return true;
    }

    /**
     * validate license
     * @see sitebuilder/classes/CpHandle/CpHandle_InterfaceForUser#isDisableBlogComponent()
     */
    public function isDisableBlogComponent($aTestOption = array())
    {
    	SGL::logMessage(null, PEAR_LOG_DEBUG);
    	$license = isset($aTestOption['license'])
    		? $aTestOption['license']
    		: RvsLibs_License::getSitebuilderLicense();
    	$isOwnerAllowComponent = isset($aTestOption['isOwnerAllowBlog'])
    		? $aTestOption['isOwnerAllowBlog']
    		: RvsLibs_Component::isOwnerAllowComponent(RvsLibs_User::getOwnerId(), 'Blog');
    	if (strtolower($license) != 'pro') {
    		return 2;
    	} elseif ($isOwnerAllowComponent === false) {
    		return 3;
    	} else {
    		return 0;
    	}
    }

    /**
     * theme is dir or is symlink
     * for rvskin theme only use managedbs.html but theme x, x3 use index.html
     * @see sitebuilder/classes/CpHandle/CpHandle_InterfaceForUser#getDatabaseEditURL()
     */
    public function getDatabaseEditURL()
    {
    	SGL::logMessage(null, PEAR_LOG_DEBUG);
    	if (isset($_ENV['CPSESSIONTHEME']) && $_ENV['CPSESSIONTHEME'] != "") {
    		$cpanelTheme = $_ENV['CPSESSIONTHEME'];
    	} else {
    		$cpanelTheme = $GLOBALS['CPANEL']['CPDATA']['RS'];
    	}
    	//theme is dir or is symlink
    	$cpanelThemePath = '/usr/local/cpanel/base/frontend/' . $cpanelTheme;
    	$cpanelTheme = (is_dir($cpanelThemePath) || is_link($cpanelThemePath))
    	                   ? $cpanelTheme
    	                   : 'x3';

    	//for rvskin theme only use managedbs.html but theme x, x3 use index.html
    	$fileName = (preg_match("/^rv/", $cpanelTheme)) ? 'managedbs.html' : 'index.html';
    	$url = INDEX_URL . '/frontend/' . $cpanelTheme . '/sql/' . $fileName;
    	$aSetOutput = array('UrlManageDatabase' => $url);
    	return RvsLibs_String::translate('prepare your database','vprintf', $aSetOutput);
    }

    public function getTmpPath()
    {
    	SGL::logMessage(null, PEAR_LOG_DEBUG);
    	return RvsLibs_File::buildPath(array(RVS_USER_HOME, 'tmp'));
    	/*
    	 return (RVS_USER_NAME == 'root')
    		? RvsLibs_File::buildPath(array(RVS_USER_HOME, '.rvsitebuilder', 'tmp'))
    		: RvsLibs_File::buildPath(array(RVS_USER_HOME, 'tmp'));;
    	 */
    }

	public function getTemplatePathUrl($action='edit', $aTemplateOption=array())
    {
    	SGL::logMessage(null, PEAR_LOG_DEBUG);
        if (count($aTemplateOption)
        && (RvsLibs_Template::isValidTemplate($aTemplateOption['templateUserId'], $aTemplateOption['templateItemFolder']) )) {
            $aTemplatePathUrl = ($action == 'edit')
                               ? RvsLibs_Template::getImportedTemplatePathUrlAdmin()
                               : RvsLibs_Template::getImportedTemplatePathUrlUser($aTemplateOption['templateUserId']);
        } else {
            $aTemplatePathUrl['path'] = TEMPLATE_PATH;
            $aTemplatePathUrl['url'] = TEMPLATE_URL;
        }
        return $aTemplatePathUrl;
    }

    public function skipValidTemplate()
    {
    	SGL::logMessage('RETURN FALSE', PEAR_LOG_DEBUG);
    	return false;
    }

    /**
     * get file encode .txt
     * @see sitebuilder/classes/CpHandle/CpHandle_InterfaceForUser#getTypeFileEncode($fileName)
     */
    public function getTypeFileEncode($fileName)
    {
    	SGL::logMessage(null, PEAR_LOG_DEBUG);
    	$TypeFileEncode = '';
    	if (RvsLibs_System::function_exists('finfo_open') && RvsLibs_System::function_exists('finfo_file')) {
    		$finfo = @finfo_open(FILEINFO_MIME_ENCODING);
    		$TypeFileEncode = @finfo_file($finfo, $fileName);
    	} elseif (RvsLibs_System::function_exists('system')) {
				$store = RVS_USER_HOME . '/.rvsitebuilder/fileencode.txt';
				$command = "/usr/local/cpanel/bin/guess_file_encoding " . $fileName . " > " . $store;
				@system($command);
				SGL::logMessage('command : ' . $command, PEAR_LOG_DEBUG);
				$TypeFileEncode = RvsLibs_File::_getFileEncode($store);
		}
    	return $TypeFileEncode;
    }

    function validateCounterNameExisting($counterName)
    {
        SGL::logMessage(null, PEAR_LOG_DEBUG);
        return $this->_checkCounterFileNameExisting($counterName) ? true : false;
    }

    function validateChangeCounterName($counterName)
    {
        SGL::logMessage(null, PEAR_LOG_DEBUG);
        return $this->_checkCounterFileNameExisting($counterName) ? true : false;
    }

    /**
     * For process in cp mode
     * check counter is existing and make new counter.
     * @param $defCounterName <string> counter name
     * @author pharadol@rvglobalsoft.com
     */
    public function getNewCounterExisting($counterName)
    {
        SGL::logMessage(null, PEAR_LOG_DEBUG);
        if ($this->_checkCounterFileNameExisting($counterName)) {
            $aNewCounter = RvsLibs_File::file('/var/cpanel/Counters/' . $counterName . '.dat');
            return RvsLibs_String::preg_replace('/\$/', '', $aNewCounter[0]);
        } else {
            //IF file is not have in path , return '',
            return '';
        }
    }

    public function whmRequest($request,$host,$user,$accesshash,$usessl)
    {
       SGL::logMessage(null, PEAR_LOG_DEBUG);
       return '';
    }

    public function isLicenseValid()
    {
    	return true;
    }

   /**
     * function isMinRvsOK($versionExport)
     *
     * @author Puttipong <pharadol@rvglobalsoft.com>
     * @param String $versionExport version number
     * @return mix PEAR error or not error return Boolean True
     */
    public function isMinRvsOK($versionExport)
    {
        SGL::logMessage("RVSiteBuilder Export version:: " . $versionExport, PEAR_LOG_DEBUG);
        return RvsLibs_License::siteBuilderVersion($versionExport);
    }

     /**
     * No process in Cpanel
     */
    public function replaceRelativeURL()
    {
       SGL::logMessage(null, PEAR_LOG_DEBUG);
       return '';
    }

    public function replateAtOnUserName($userName)
    {
        SGL::logMessage(null, PEAR_LOG_DEBUG);
    	return $userName;
    }
    /*
    public function getHashUrl()
    {
        SGL::logMessage(null, PEAR_LOG_DEBUG);
    	$hashUrl = preg_replace(array("/:2082/", "/:2083/", "/\/\/cpanel./"), array(":2086", ":2087", "//whm."), INDEX_URL);
    	return (RVS_IS_RESELLER) ? $hashUrl : "";
    }
    */
   /**
      * ใช้กรณี output ออกไปใช้งานต่อ
      * ไม่ได้เอาไว้เช็ค CPMODE
   */
    public function isCpanel()
	{
        SGL::logMessage(null, PEAR_LOG_DEBUG);
	    return true;
	}

    public function isSkipAllowUserPerms()
    {
        SGL::logMessage(null, PEAR_LOG_DEBUG);
    	return false;
    }

    public function getPathQuotaUser($aPath)
    {
        SGL::logMessage(null, PEAR_LOG_DEBUG);
    	$myTheme = $this->_getXferTheme();
    	return $aPath[0] . '/frontend/' . $myTheme . '/rvsitebuilder/getDiskQuota.html';
    }

    public function getFileManagerUrlByUser($username)
    {
        SGL::logMessage(null, PEAR_LOG_DEBUG);
        if (isset($_ENV['CPSESSIONTHEME']) && $_ENV['CPSESSIONTHEME'] != "") {
            $cpanelTheme = $_ENV['CPSESSIONTHEME'];
        } else {
            $cpanelTheme = $GLOBALS['CPANEL']['CPDATA']['RS'];
        }
        //theme is dir or is symlink
        $cpanelThemePath = RvsLibs_File::buildPath(array('/usr', 'local', 'cpanel', 'base', 'frontend', $cpanelTheme));
        $cpanelTheme = (is_dir($cpanelThemePath) || is_link($cpanelThemePath))
                                    ? $cpanelTheme
                                    : 'x3';
        $dns = $this->getUserDNS();
        $homeUser = $this->getHomeDir($username);
        $homeUser = RvsLibs_Url::url_encode(RvsLibs_File::buildPath(array($homeUser, '.rvsitebuilder')));
        $url = INDEX_URL . '/frontend/' . $cpanelTheme . '/filemanager/index.html?dirselect=homedir&domainselect=' . $dns . '&dir=' . $homeUser . '&showhidden=1';
        SGL::logMessage('********return url:' . $url, PEAR_LOG_DEBUG);
        return $url;
    }

	public function checkFileConfigLicenseCycle($cycleNow = 0, $errorNotExit = 0, $skipMsg = 0)
	{
	    SGL::logMessage(null, PEAR_LOG_DEBUG);
	    require_once dirname(dirname(__FILE__)) . '/LicenseCycle.php';
	    $oCycle = new LicenseCycle();
	    $oCycle->FileConfigLicenseCycle($cycleNow, $errorNotExit, $skipMsg);
	    return true;
	}

    /**
     * Get path image diy in mode wysiwyg
     *
     * @author Puttipong <puttipong@rvglobalsoft.com>
     * @param String $pathImg
     * @return String Path image diy in mode wysiwyg
     */
    public function getPathImgWysDiy($pathImg = null)
    {
        SGL::logMessage(null, PEAR_LOG_DEBUG);
        return RvsLibs_File::buildPath(array(SGL_WEB_ROOT . str_replace(PROGRAM_NAME,'',strstr($pathImg, PROGRAM_NAME))));
    }

    #File:Online_CounterMgr
    /**
     * update file counter
     * (non-PHPdoc)
     */
    public function runUpdateFileCounterData($filePreview, $cpanelTagPreview, $counterName, $newCounter)
    {
    	SGL::logMessage(null, PEAR_LOG_DEBUG);
        if (!file_exists('/var/cpanel/Counters/' . $filePreview)) {
        	$this->runCpOnIframe("Counter", $cpanelTagPreview);
        }
        $this->_updateFileCounter($counterName, $newCounter);
        $aNewCounter = RvsLibs_File::file('/var/cpanel/Counters/' . $filePreview);
        if (SGL::isError($aNewCounter) === true) {
        	SGL_Error::pop();
        	return array();
        } else {
        	$aNewCounter = RvsLibs_String::preg_replace('/\$/', '', $aNewCounter[0]);
        	return $aNewCounter;
        }
    }

    #File:Online_CounterMgr
    /**
     * run update file counter
     * (non-PHPdoc)
     */
    public function runUpdateCounterData($cpanelTag, $counterName, $newCounter)
    {
    	SGL::logMessage("runCpOnIframe==> " . $cpanelTag, PEAR_LOG_DEBUG);
    	$aCounterTag = $this->runCpOnIframe("Counter", $cpanelTag);
    	if (SGL::isError($aCounterTag)) {
    		SGL_Error::pop();
    		SGL::logMessage(' Error get counter data. ' . $aCounterTag->getMessage(), PEAR_LOG_DEBUG);
    		return false;
    	} else {
    		$this->_updateFileCounter($counterName, $newCounter);
    		return (isset($aCounterTag->makecounter)) ? $aCounterTag->makecounter : false;
    	}
    }

    /**
     * tag html
     * (non-PHPdoc)
     * @see sitebuilder/classes/CpHandle/CpHandle_InterfaceForUser#cpanelHtmlTagCounter($counterTag)
     */
    public function cpanelHtmlTagCounter($counterTag)
    {
    	SGL::logMessage(null, PEAR_LOG_DEBUG);
        $cpanelCounterTag = RvsLibs_String::html_entity_decode($counterTag);
        $cpanelCounterTag = RvsLibs_String::preg_replace('/\r|\n|\t/', '', $cpanelCounterTag);
        return $cpanelCounterTag;
    }

    public function tryoutGetBuyAccountUrl()
    {
        SGL::logMessage(null, PEAR_LOG_DEBUG);
        return false;
    }

    /**
     * create new email
     * @see sitebuilder/classes/CpHandle/CpHandle_InterfaceForUser#createNewEmailcpSecurity()
     */
    public function createNewEmailcpSecurity()
    {
        SGL::logMessage(null, PEAR_LOG_DEBUG);
        $cpSecurityToken = (isset($_ENV['cp_security_token'])) ? $_ENV['cp_security_token'] : '';
        //TODO: fucntion getCpTheme()
        $cpTheme = (isset($GLOBALS['CPANEL']['CPDATA']['RS'])) ? $GLOBALS['CPANEL']['CPDATA']['RS'] : null;
        $cpTheme = (isset($_ENV['CPSESSIONTHEME'])) ? $_ENV['CPSESSIONTHEME'] :  $cpTheme;
        $createNewEmail = RvsLibs_String::translate('Online Form Step 5 Info2');
        $createNewEmail .= RvsLibs_String::sprintf(' <a href="%s/frontend/%s/mail/pops.html" target="_blank">', $cpSecurityToken, $cpTheme);
        $createNewEmail .= RvsLibs_String::translate('Online Form Step 5 Info3');
        $createNewEmail .= '</a> ';
        $createNewEmail .=  RvsLibs_String::translate('Online Form Step 5 Info4');
        return $createNewEmail;
    }

    public function runDetectPhpSuexec($dePhpSuexec)
    {
        SGL::logMessage(null, PEAR_LOG_DEBUG);
        $phpSuExec = RvsLibs_System::runDetectPhpSuexec();
        if($phpSuExec != $dePhpSuexec) {
        	RvsLibs_Config::autoUpdatePhpSuExecToMainIpConf($phpSuExec, $this->conf);
        }
        return $phpSuExec;
    }


    public function createAutoDatabase($buildDBName, $buildDBUsername, $buildDBPasswd)
    {
         SGL::logMessage(null, PEAR_LOG_DEBUG);
         $db_prefix = CpHandle_CpanelLibs::getDbprefix();
         $dbname = (defined('DATABASE_PREFIX') && DATABASE_PREFIX === false) ? $db_prefix . $buildDBName : $buildDBName;
         $isOk = $this->doCreateDatabase($dbname);
         if (SGL::isError($isOk)) {
            SGL_Error::pop();
            return false;
         }

        $username = (defined('DATABASE_PREFIX') && DATABASE_PREFIX === false) ? $db_prefix . $buildDBUsername : $buildDBUsername;
        $isOk = $this->doCreateDatabaseUser($username, $buildDBPasswd);
        if (SGL::isError($isOk)) {
            SGL_Error::pop();
            $aDatabase = $this->doDeleteDatabase($buildDBName);
            $this->getDataResponse($aDatabase);
            return false;
        }

         $isOk = $this->doAddDBUser($this->getRealFormatDBName($buildDBName), $this->getRealFormatDBName($buildDBUsername));
         if (SGL::isError($isOk)) {
            SGL_Error::pop();
            $aData = $this->doDeleteDatabase($buildDBName);
            $this->getDataResponse($aData);

            $aDatabaseUser = $this->doDeleteDatabaseUser($buildDBUsername);
            $this->getDataResponse($aDatabaseUser);
            return false;
         }
    }


    ########################## END ###########################

    /**
     * Validate create project on mode.
     *
     * @author Puttipong <puttipong@rvglobalsoft.com>
     * @return Boolean False
     */
    public function isValidCreateProject()
    {
        SGL::logMessage(null, PEAR_LOG_DEBUG);
        return false;
    }

    /**
     * Validate get html tag counter
     *
     * @author Puttipong <puttipong@rvglobalsoft.com>
     * @return Boolean True
     */
    public function isValidHtmlTagCounter()
    {
    	SGL::logMessage(null, PEAR_LOG_DEBUG);
        return true;
    }

    /**
     * Validate update rollback version
     *
     * @author Puttipong <puttipong@rvglobalsoft.com>
     * @return Boolean True
     */
   /* public function isValidUpdateRollbackVersion()
    {
    	SGL::logMessage(null, PEAR_LOG_DEBUG);
        return false;
    }
    */

    /**
     * Validate phpsu in XML
     *
     * @author Puttipong <puttipong@rvglobalsoft.com>
     * @return Boolean True
     */
    public function isValidPhpsuModeXml()
    {
    	SGL::logMessage(null, PEAR_LOG_DEBUG);
    	return true;
    }

    /**
     * Validate component db on mode
     *
     * @author Puttipong <puttipong@rvglobalsoft.com>
     * @return Boolean True
     */
    public function isValidCompoDbMode()
    {
        return true;
    }

    /**
     * Get url for edit database
     *
     * @author Puttipong <puttipong@rvglobalsoft.com>
     * @return String
     */
    public function getUrlDb()
    {
        SGL::logMessage(null, PEAR_LOG_DEBUG);
        $cpanelTheme = (isset($_ENV['CPSESSIONTHEME']) && $_ENV['CPSESSIONTHEME'] != "")
                                           ? $_ENV['CPSESSIONTHEME']
                                           : $GLOBALS['CPANEL']['CPDATA']['RS'];
        return '/frontend/' . $cpanelTheme . '/sql/managesdbs.html';
    }


    /**
     * Validate component db on flexy
     *
     * @author Puttipong <puttipong@rvglobalsoft.com>
     * @return Boolean False
     */
    public function isValidCompoDbFlexy()
    {
    	SGL::logMessage(null, PEAR_LOG_DEBUG);
        return false;
    }

    public function isTryout()
    {
        SGL::logMessage(null, PEAR_LOG_DEBUG);
        return false;
    }

    /**
     * Is mode nocp
     *
     * @author Puttipong <puttipong@rvglobalsoft.com>
     * @return Boolean False
     */
    public function isNocp()
    {
        SGL::logMessage(null, PEAR_LOG_DEBUG);
        return false;
    }

    /**
     * Make update tryout
     *
     * @author Puttipong <puttipong@rvglobalsoft.com>
     * @return Object
     */
    public function makeUpdateTryout()
    {
        SGL::logMessage(null, PEAR_LOG_DEBUG);
        require_once dirname(dirname(__FILE__)) . '/MainComponent.php';
        $rvsOwnerUsrName = RVS_OWNER_USER_NAME;
        $cpTag = <<<EOF
<copytryoutproject>
<![CDATA[
    <cpanel Rvsitebuilder="copyTryoutProjectCode('{$oMainComponent->detectPhpSuexec()}', '{$rvsOwnerUsrName}')">
]]>
</copytryoutproject>

<createsitebuilder>
<![CDATA[
    <cpanel Rvsitebuilder="createRvsitebuilderLink()">
]]>
</createsitebuilder>
EOF;
        return $this->runCpOnIframe(__FUNCTION__, $cpTag);
    }

    /**
     * Make update tryout login config
     *
     * @author Puttipong <puttipong@rvglobalsoft.com>
     * @param Boolean $isAutoApproval
     * @param String $subdomainPath
     */
    public function makeUpdateTryoutLoginConf($isAutoApproval = false, $subdomainPath = null)
    {
    	SGL::logMessage(null, PEAR_LOG_DEBUG);

        $modulesConfPath = RvsLibs_File::buildPath(array($subdomainPath, 'tryoutlogin', 'modules', 'user', 'rv_conf.ini'));
        $aModulesConf = RvsLibs_Config::parse_ini_file($modulesConfPath, true);

        $aModulesConf['ActivateEmailMgr']['autoEnable'] = ($isAutoApproval === true) ? 1 : 0;
        $res = RvsLibs_Config::writeConfigToIniFile($aModulesConf, $modulesConfPath);
        if (SGL::isError($res) === true) {
            SGL_Error::pop();
        }
    }

    /**
     * Make remove tryout
     *
     * @author Puttipong <puttipong@rvglobalsoft.com>
     * @param Array $option
     */
    public function makeRemoveTryout($option = array())
    {
    	SGL::logMessage(null, PEAR_LOG_DEBUG);

    	$fileTryoutSetting = RvsLibs_File::buildPath(array(RVS_USER_HOME, '.rvsitebuilder', 'tryout_setting.ini.php'));
    	$aSetting = (is_file($fileTryoutSetting) === true) ? RvsLibs_Config::parse_ini_file($fileTryoutSetting) : array();
    	$databaseName = (isset($aSetting['database_name']) === true)? $aSetting['database_name'] : '';
    	$databaseUser = (isset($aSetting['database_user']) === true) ? $aSetting['database_user'] : '';
    	$subdomainPath = (isset($aSetting['subdomain_path']) === true) ? $aSetting['subdomain_path'] : '';

    	$fileTryoutConf = RvsLibs_File::buildPath(array($subdomainPath, 'tryout_config.ini.php'));
    	$aConf = (is_file($fileTryoutConf) === true) ? RvsLibs_Config::parse_ini_file($fileTryoutConf) : array();
        $domain = (isset($aConfig['dns']) === true) ? $aConf['dns'] : '';

        $cpTag = '';
        if ($option['delSubdomain'] == 1) {
            $cpTag .= <<< EOF
<deletesubdomain>
<![CDATA[
    <cpanel SubDomain="delsubdomain('{$domain}')">
]]>
</deletesubdomain>
EOF;
        }

        if ($option['delUser'] == 1) {
        	$cpTag .= <<< EOF
<deleteuserdb>
<![CDATA[
    <cpanel Mysql="deluserdb('{$databaseName}', '{$databaseUser}')">
]]>
</deleteuserdb>

<deleteuser>
<![CDATA[
    <cpanel Mysql="deluser('{$databaseUser}')">
]]>
</deleteuser>
EOF;
        }

        if ($option['delDatabase'] == 1) {
        	$cpTag .= <<< EOF
<deletedatabase>
<![CDATA[
    <cpanel Mysql="deldb('{$databaseName}')">
]]>
</deletedatabase>
EOF;
        }

        $delDirectory = (isset($option['delDirectory']) === true && $option['delDirectory'] == 1) ? 1 : 0;
        $cpTag .= <<< EOF
<deletetryout>
<![CDATA[
    <cpanel Rvsitebuilder="removeTryoutProjectCode('{$subdomainPath}', '{$delDirectory}')">
]]>
</deletetryout>
EOF;
        $this->runCpOnIframe(__FUNCTION__, $cpTag);
    }


    ###################### PRIVATE ######################
    ############## function เฉพาะ เรียกภายใน class นี้ #############

    /**
     * Find real path of domain, sub domain, park domain.
     * @param <string> $domain
     * @return <string> $path;
     * Register values in $GLOBALS
     */
    private function _subDomainPath($domain)
    {
        SGL::logMessage(null, PEAR_LOG_DEBUG);
        if ($GLOBALS['CPANEL']['CPDATA']['DNS'] == $domain) {
            return RVS_USER_HOME . '/public_html';
        } else {
            if ( isset($GLOBALS['CPANEL']['DOCROOT']['PARKDOMAIN'][$domain]) === false) {
            	$oXmlRes = $this->getDocroot();
            	eval(trim($oXmlRes->loaddocroots));
            	/**
            	 * Register all sub domain and all park domain of user in $GLOBALS
            	 * $GLOBALS['CPANEL']['DOCROOT']['PARKDOMAIN']= array($domain => $path);
            	*/
            	$GLOBALS['CPANEL']['DOCROOT']['PARKDOMAIN'] = $_CPANEL['DOCROOT'];

            }
            return ($GLOBALS['CPANEL']['DOCROOT']['PARKDOMAIN'][$domain])
                ? $GLOBALS['CPANEL']['DOCROOT']['PARKDOMAIN'][$domain]
                : SGL::raiseError(RvsLibs_String::translate('Cannot get directory of domain "%domain".', 'vprintf', array('domain' => $domain)));
        }
    }


    /**
     * Fetch SimpleXMLElement object to array database infomation.
     * @param <SimpleXMLElement> $oXml
     * @return <array>
     */
    private function _fetchOxmlDBInfoToArray($oXml)
    {
        SGL::logMessage(null, PEAR_LOG_DEBUG);
        /// Explode database list
        $aSplitListDbs = RvsLibs_String::dbeExplode(',', $oXml->listdbs);
        if (count($aSplitListDbs) > 0 ) {
            foreach ($aSplitListDbs as $vd) {
                $vd = RvsLibs_String::trim($vd);
                $aListDbs[$vd] = $vd;
            }
        } else {
            $aListDbs = array();
        }

        /// Explode users list
        $aSplitUserList = RvsLibs_String::dbeExplode(',', $oXml->listusers);
        if (count($aSplitListDbs) > 0 ) {
            foreach ($aSplitListDbs as $vd) {
                $vd = RvsLibs_String::trim($vd);
                $aUserList[$vd] = $vd;
            }
        } else {
            $aUserList = array();
        }

        return array(
            'countdb' => ($oXml->countdb) ? RvsLibs_String::trim($oXml->countdb) : 0,
            'maxdb' => ($oXml->maxdb) ? RvsLibs_String::trim($oXml->maxdb) : 0,
            'listdbs' => $aListDbs,
            'listusers' => $aUserList,
        );
    }


    private function _getXferTheme()
    {
        SGL::logMessage(null, PEAR_LOG_DEBUG);
        if (isset($_ENV['CPSESSIONTHEME']) && $_ENV['CPSESSIONTHEME'] != "") {
            $cpanelTheme = $_ENV['CPSESSIONTHEME'];
        } else {
            $cpanelTheme = $GLOBALS['CPANEL']['CPDATA']['RS'];
        }
        if ((!$cpanelTheme || !is_dir('/usr/local/cpanel/base/frontend/' . $cpanelTheme)) && is_dir('/usr/local/cpanel/base/frontend/x3')) {
            $cpanelTheme = 'x3';
        } elseif (!$cpanelTheme || !is_dir('/usr/local/cpanel/base/frontend/' . $cpanelTheme)) {
            $cpanelTheme = 'x';
        }
        return $cpanelTheme;
    }

    /**
     * validate counter filename on /var/cpanel use in this class
     * @author siwakorn induang
     * @param $counterName
     * @return true / false
     */
    private function _checkCounterFileNameExisting($counterName)
    {
        SGL::logMessage(null, PEAR_LOG_DEBUG);
        return ($counterName != "" && is_file('/var/cpanel/Counters/' . $counterName . '.dat')) ? true : false;
    }


    #File: Online_CounterMgr.php
    private function _updateFileCounter($counterName, $newCounter)
    {
        SGL::logMessage(null, PEAR_LOG_DEBUG);

        $pathCounter = '';
        if (preg_match('/\.dat$/i', $counterName)) {
        	$pathCounter = '/var/cpanel/Counters/' . $counterName;
            if (is_file($pathCounter) == true) {
            } else {
                $pathCounter = '/var/cpanel/Counters/' . RvsLibs_User::getUsername() . '-' . $counterName;
            }
        } else {
        	$pathCounter = '/var/cpanel/Counters/' . $counterName . '.dat';
            if (is_file($pathCounter) == true) {
            } else {
                $pathCounter = '/var/cpanel/Counters/' . RvsLibs_User::getUsername() . '-' . $counterName . '.dat';
            }
        }


        if (is_file($pathCounter)) {
            if (is_writable($pathCounter) === false) {
                RvsLibs_String::translate(SGL::raiseMsg('preview counter premission denied'));
                return true;
            }

            if ($newCounter != '') {
                $handle = RvsLibs_File::fopen($pathCounter, 'w');
                if (SGL::isError($handle) === true) {
                    SGL::logMessage('cannot open file. ' . $handle->getMessage() , PEAR_LOG_ERR);
                    SGL_Error::pop();
                    return false;
                } else {
                	$res = RvsLibs_File::fwrite($handle, $newCounter . "$");
                	RvsLibs_File::fclose($handle);
                	if (SGL::isError($res) === true) {
                		SGL_Error::pop();
                	}
                }
            } else {
                // error : Cannot get new counter name.
                SGL::logMessage('WARNING : Cannot get new counter name for update. [function ' . __FUNCTION__ . ']' , PEAR_LOG_ERR);
            }
        } else {
            // error: Cannot get counter filename.
            SGL::logMessage('WARNING : Cannot get counter path file for update new counter.[function ' . __FUNCTION__ . ']' , PEAR_LOG_ERR);
        }
        return true;


        /*
         * ของเก่า
         * comment and change by siwakorn
         * comment date : 19/01/2011
         *
        if (is_file($pathCounter) && is_writable($pathCounter) === false) {
            RvsLibs_String::translate(SGL::raiseMsg('preview counter premission denied'));
            return true;
        }

        if ($newCounter != '' && is_file('/var/cpanel/Counters/' . $counterName . '.dat')) {
            $file = RvsLibs_File::fopen('/var/cpanel/Counters/' . $counterName . '.dat', 'w');
            if (SGL::isError($file) === true) {
                SGL::logMessage('cannot open file. ' . $file->getMessage() , PEAR_LOG_ERR);
                SGL_Error::pop();
                return false;
            }
            $res = RvsLibs_File::fwrite($file, $newCounter . "$");
            RvsLibs_File::fclose($file);
            if (SGL::isError($res) === true) {
                SGL_Error::pop();
            }
        }
        return true;
        */
    }


    /**
     * update phpSuExec auto in MainIP.conf.php
     *
     * @param <int> $phpSuExec   1 or 0 only
     * @param <array> $conf
     * @return boolean
     *
     * @author apiruk boonruksa 20/01/2009
     */
  /*
    private function _createNewSuexec($phpSuexec)
    {
        SGL::logMessage(null, PEAR_LOG_DEBUG);
        if (is_writable("/usr/local/apache/bin/suexec")) {
            $fd = RvsLibs_File::fopen ("/usr/local/apache/bin/suexec", "r");
            while (!feof ($fd)) {
                $buffer = fgets($fd, 4096);
                //optimize:pharadol
                if (preg_match('/php /i', $buffer)) {
                    $phpSuexec = 1;
                    break;
                }
            }
            RvsLibs_File::fclose ($fd);
        } else {
           //error write to log
           SGL::logMessage("warning : cannot write [bin/suexec]", PEAR_LOG_DEBUG);
        }
        return $phpSuexec;
    }*/
    /*
    private function _switchAutoUpdatePhpSu($phpSuexec, $phpConf, $conf)
    {
        SGL::logMessage(null, PEAR_LOG_DEBUG);
        switch ($phpConf['SAPI'][$phpConf['default-ver']]) {
            case 'suphp':*/
                /*  if "DEFAULT PHP" is "4" and "PHP4 SAPI" is "suphp"
                 or "DEFAULT PHP" is "5" and "PHP5 SAPI" is "suphp" */
              //  $phpSuexec = 1;
                //if root user call tark update config phpsu to 1
              /*  $this->_autoUpdatePhpSuExecToMainIpConf($phpSuexec, $conf);
                break;
            case 'fcgi':
            case 'cgi':
                if ($phpConf['suexec'] == 'enabled') {
                     if "DEFAULT PHP" is "4" and "PHP4 SAPI" is not "suphp"
                     or "DEFAULT PHP" is "5" and "PHP5 SAPI" is not "suphp"
                     and suexec is enabled
                    $phpSuexec = 1;
                    if root user call tark update config phpsu to 1
                    $this->_autoUpdatePhpSuExecToMainIpConf($phpSuexec, $conf);
                } else {
                    $phpSuexec = 0;
                    if root user call tark update config phpsu to 0
                    $this->_autoUpdatePhpSuExecToMainIpConf($phpSuexec, $conf);
                }
                break;
            case 'dso':
            case 'none':
            default:
                $phpSuexec = 0;
                if root user call tark update config phpsu to 0
                $this->_autoUpdatePhpSuExecToMainIpConf($phpSuexec, $conf);
                break;
        }
        return $phpSuexec;
    }
    */

    /**
     * STEP HOME จะสร้างไฟล์ diskquota.ini.php ไว้แล้ว
     * 1=diskuse
     * 2=diskmax
     * 3=docroot
     * cptag ที่สร้างดูไฟล์ rvsLibs/Util.php
     * @param $domain
     * @return <string>; If not found it return false;
     */
    private function _getPathByDomain($domain)
    {
        SGL::logMessage($domain, PEAR_LOG_DEBUG);
        $fileCpTagData =  RvsLibs_File::buildPath(array(RVS_USER_HOME, '.rvsitebuilder',  'diskquota.ini.php'));

        SGL::logMessage($fileCpTagData, PEAR_LOG_DEBUG);
        $result = false;
        if (is_file($fileCpTagData) === true) {
            $aData = RvsLibs_Config::parse_ini_file($fileCpTagData, true);
            if (isset($aData[3]))  {
                $cmd = RvsLibs_String::str_replace("\'", "'", $aData[3]);
                $cmd = RvsLibs_String::str_replace("\\\"", "'", $cmd);
                eval($cmd);
            }
            if (isset($_CPANEL['DOCROOT']) && isset($_CPANEL['DOCROOT'][$domain])) {
                SGL::logMessage('return path:' . $_CPANEL['DOCROOT'][$domain], PEAR_LOG_DEBUG);
                $result = $_CPANEL['DOCROOT'][$domain];
            }
        }
        return $result;
    }

     /**
     * Validate database status
     * @param <SimpleXMLElement|PEAR::Error> $oXml
     * @return <bool|PEAR::Error>
     */
    private function _validateDBFunctionStatus($oXml)
    {
        SGL::logMessage(null, PEAR_LOG_DEBUG);
        if (SGL::isError($oXml) === true) {
            return $oXml;
        } elseif (isset($oXml->status) && trim($oXml->status) == 'ok') {
            return true;
        } else {
            return SGL::raiseError($oXml->status);
        }
    }

    ################## END PRIVATE ##################
    ##############################################

    public function replacePreviewOnlineCounter($cpanelCounterTag)
    {
       SGL::logMessage(null, PEAR_LOG_DEBUG);
       $publishUrl = 'http://' . RvsLibs_User::getUserDNS();
       return RvsLibs_String::preg_replace('/\/cgi\-sys\/Count\.cgi/', $publishUrl . '/cgi-sys/Count.cgi', $cpanelCounterTag);
    }

    public function isDirectAdmin()
    {
        SGL::logMessage(null, PEAR_LOG_DEBUG);
        return false;
    }

    public function getRvBinPath()
    {
        SGL::logMessage(null, PEAR_LOG_DEBUG);
        return '/var/cpanel/rvglobalsoft/rvsitebuilder/rvbin/rvswrapper';
    }

     public function isAdmin($username = RVS_USER_NAME)
     {
        SGL::logMessage(null, PEAR_LOG_DEBUG);
        return ($username == 'root')? true : false;

     }

    public function ownerIsAdmin($ownername = RVS_OWNER_USER_NAME)
    {
    	SGL::logMessage(null, PEAR_LOG_DEBUG);
    	return ($ownername == 'root')? true : false;
    }

    public function makeUploadFolder($userUploadPath, $pathLinkUpload, $userDataPath)
    {
        SGL::logMessage(null, PEAR_LOG_DEBUG);
        if (!is_link($pathLinkUpload) && is_dir($userDataPath) ) {
            return  symlink($userUploadPath, $pathLinkUpload);
        }
        return false;
    }

   public function createUserSymlinkUserFolder($pathUserUpload, $pathUploadLink)
    {
        SGL::logMessage(null, PEAR_LOG_DEBUG);
        RvsLibs_User::createUserSymlinkUserFolder($pathUserUpload, $pathUploadLink);
    }

   public function moveUploadedFile($tempFile, $destination)
   {
    SGL::logMessage(null, PEAR_LOG_DEBUG);
    return RvsLibs_File::moveUploadedFile($tempFile, $destination);
   }

   public function isUploadedFile($tempFile)
   {
    SGL::logMessage(null, PEAR_LOG_DEBUG);
    return RvsLibs_File::isUploadedFile($tempFile);
   }

   public function makeLink($source, $des)
   {
   	SGL::logMessage('tempFile :: ' . $source, PEAR_LOG_DEBUG);
   	SGL::logMessage('destination::' . $des, PEAR_LOG_DEBUG);
   	RvsLibs_System::ln(array('-s', $source, $des));
   }

    function secureCommandMakeLinkProjectId($projectId)
    {
        $resSecure = RvsLibs_System::secureCommand('makeprojectsymlink', array('project-id' => $projectId));
        if (SGL::isError($resSecure) === true) {
            return SGL::raiseError(
                RvsLibs_String::translate(
                      'Cannot create project folder symlink, becase %MSG.'
                      , 'vprintf'
                      , array('MSG' => $resSecure->getMessage())
                )
            );
        }
        return true;
    }

    public function msgWaringOpenBaseDir()
    {
    	SGL::logMessage(null, PEAR_LOG_DEBUG);
    	return RvsLibs_String::translate('Reseller contact provider to update virtualhost');
    }

    public function buildProjectUrlForDa()
    {
    	SGL::logMessage(null, PEAR_LOG_DEBUG);
    }

     /**
          * อัพโหลด ไฟล์ zip ชื่อไฟล์ กับชื่อ โฟล์เด่อเหมือนกัน
     * @param $fullPath
     * @param $fileZip
     * @return unknown_type
     */
    public function createLinkFolder($fullPath, $fileZip)
    {
    	SGL::logMessage("createLinkFolder >>>>>>>>>>>>> " . $fullPath . $fileZip, PEAR_LOG_DEBUG);
    	$fileNameZip = preg_replace('/(\.tar\.gz$|\.gz$|\.tar$|\.zip$)/i', '', $fileZip);
    	$FName = urlencode($fileNameZip);
    	if (file_exists($fullPath . $fileNameZip)) {
    		self::makeLink($fullPath . $fileNameZip, $fullPath . $FName);
    	}
    }

    public function createLinkFileAndFolder($fullPath)
    {
    	//file image
    	$allFile = RvsLibs_System::ls($fullPath);
    	foreach ($allFile['files'] as $k => $v) {
    		$image = end(RvsLibs_String::dbeExplode('/', $v));
    		$fileName = urlencode($image);
    		if (preg_match('/\.gif$|\.png$|\.jpg$|\.jpeg$/i',$fileName, $match)) {
    			if (is_link($fullPath . $fileName) === false) {
    				self::makeLink($fullPath . $image, $fullPath . $fileName);
    			}
    		}
    	}
    	//folder
    	foreach ($allFile['dirs'] as $key => $val ) {
    		//เช็คว่าถ้าอัพโหลดไฟล์รูปจะไม่ให้เข้ามาทำงานในส่วนนี้
    		if (realpath($fullPath) != $val) {
    			$folder= end(RvsLibs_String::dbeExplode('/', $val));
    			$dirName = urlencode($folder);
    			if (RvsLibs_File::_isEncode($dirName) === true) {
    				if (is_link($fullPath . $dirName) === false) {
    					//RvsLibs_System::ln(array('-s', $fullPath . $folder, $fullPath . $dirName));
    					self::makeLink($fullPath . $folder, $fullPath . $dirName);
    					$aFile = RvsLibs_System::ls(array('-a', '-R', '-C', $fullPath . $folder));
    					foreach($aFile['files'] as $k => $v) {
    						$file= end(RvsLibs_String::dbeExplode('/', $v));
    						$fName = urlencode($file);
    						$encodeFile = str_replace($file, $fName, $v);
    						self::makeLink($v, $encodeFile);
    					}
    				}
    			}
    		}
    	}
    }


    public function makeFolderLink($fullPath, $folderName)
    {
        SGL::logMessage(null, PEAR_LOG_DEBUG);
        RvsLibs_File::makeFolderLink($fullPath, $folderName);
    }

    public function makeImageLink($fullPath, $filename)
    {
        SGL::logMessage(null, PEAR_LOG_DEBUG);
        RvsLibs_File::makeImageLink($fullPath, $filename);
    }

    public function isRealConfigUpLoadMaxFileSize()
    {
            return ini_get('upload_max_filesize');
    }

    /**
     * Make userdata path
     * @return unknown_type
     */
    function makeuserdatapath($userdataPath)
    {
        return RvsLibs_System::secureCommand('makeuserdatapath');
    }

    function replaceUrlToNobase($data) {
    	return RvsLibs_Project::replaceDaToNobase($data);
    }

    /**
    	 * Array ( [1] => 9.87 [2] => 0 [3] => $_CPANEL[\"DOCROOT\"] = array(\'yourdomain.com\'=>\'/home/youruser/public_html\'); )
    	if (key_exists($_CPANEL["DOCROOT"][$domain]) and is_dir($_CPANEL["DOCROOT"][$domain]) ){
    		pass
    	} else {

    	}
     * @see CpHandle_InterfaceForUser::makeFileQuota()
     */
    function makeFileQuota($dnsPublish)
    {
    	SGL::logMessage(null, PEAR_LOG_DEBUG);
    	$aDiskQuota = RvsLibs_Util::getUserInfoByFile();
    	if (count($aDiskQuota)) {
	    	$cmd = RvsLibs_String::str_replace("\'", "'", $aDiskQuota[3]);
	    	$cmd = RvsLibs_String::str_replace("\\\"", "'", $cmd);
    		eval($cmd);
    		$domain = $dnsPublish;
    		if (isset($_CPANEL) && isset($_CPANEL['DOCROOT'])
    			&& isset($_CPANEL['DOCROOT'][$domain])
    			&& is_dir($_CPANEL['DOCROOT'][$domain])) {
    			SGL::logMessage('Pass => '. $domain, PEAR_LOG_DEBUG);
    			SGL::logMessage('Docroot => '. $_CPANEL['DOCROOT'][$domain], PEAR_LOG_DEBUG);
    			return true;
    		}
		}

		//case: domain ที่เพิ่มเข้ามาใหม่
		//case: มี file diskquota.ini.php แต่ /home ไม่เหมือนเดิม อาจมีสาเหตุ มาจาก ย้ายเครื่อง
		//case: home dir ที่ไม่มี
		SGL::logMessage('Modify => ', PEAR_LOG_DEBUG);
		$this->_writeFilediskquota();
    }

    private function _writeFilediskquota()
    {
    	SGL::logMessage(null, PEAR_LOG_DEBUG);
    	$aDiskQuota = RvsLibs_Util::getDiskQuota();
    	if (SGL::isError($aDiskQuota) === true) {
    		SGL::logMessage('Cannot get disk quota . ' . $aDiskQuota->getMessage(), PEAR_LOG_DEBUG);
    		SGL_Error::pop();
    	} elseif (count($aDiskQuota)  > 0) {
    		$fileDiskQuota =  RvsLibs_File::buildPath(array(RVS_USER_HOME, '.rvsitebuilder',  'diskquota.ini.php'));
    		$res = RvsLibs_Config::writeConfigToIniFile($aDiskQuota, $fileDiskQuota);
    		if (SGL::isError($res)) {
    			SGL_Error::pop();
    		}
    	}
    }

    /**
     *
     * Make Restore Online Counter
     *
     * @author Puttipong <puttipong at rvglobalsoft.com>
     *
     * @param $projectId <STRING>
     * @return TRUE
     */
    public function makeRestoreOnlineCounter($projectId=null) {
        if (isset($projectId) && $projectId != '') {
            if (class_exists('Online_CounterMgr') === false) {
                require_once RvsLibs_File::buildPath(array(SGL_MOD_DIR, 'sitebuilder', 'classes', 'Online_CounterMgr.php'));
            }
            $oCounter = new Online_CounterMgr();
            $oCounter->makeRestoreOnlineCounter($projectId);

            $imgCounterProject = RvsLibs_File::buildPath(array(REAL_PROJECT_PATH, $projectId, 'images', 'counter02.gif'));
            if (file_exists($imgCounterProject) == true) {
            } else {
                $imgCounterAdmin = RvsLibs_File::buildPath(array(SGL_WEB_ROOT, 'themes', 'default', 'sitebuilder','images', 'counter02.gif'));
                if (file_exists($imgCounterAdmin) == true) {
                    RvsLibs_System::copy(array($imgCounterAdmin, $imgCounterProject));
                }
            }
        }

        return true;
    }

    public function getPublishMsgHttps($domain = '')
    {
    	$domain = ($domain != '') ? $domain : 'domain';
    	return RvsLibs_String::translate('Please make sure your %DOMAIN can be called as https://.'
    			, 'vprintf'
    			, array('DOMAIN' => $domain)
    	);
    }

    public function detectCpanelProxyMsg()
    {
    	SGL::logMessage(null, PEAR_LOG_DEBUG);
    	if (isset($_SERVER['HTTP_PROXIED'])) {
    		return SGL::raiseMsg('Do not support cPanel proxy access.', true);
    	}
    	return false;
    }

    public function getServerUserInfomation()
    {
    	static $instance;
    	if (! isset($instance)) {
    	$cpTag = <<<EOF
<version>
<?cp StatsBar::stat([\${name}]\${value}[/\${name}], name,value) display=mysqlversion|perlversion|phpversion ?>
</version>
EOF;
    		$instance = $this->runCpOnIframe(__FUNCTION__, $cpTag);
    	}
    	return $instance;
    }

    public function getMySQLVersion()
    {
    	if (! isset($_SESSION['_MySQLVersion'])) {
	    	$oVersion = $this->getServerUserInfomation();
	    	if (isset($oVersion->version) && isset($oVersion->version->mysqlversion)) {
	    		$version = trim($oVersion->version->mysqlversion);
	    	} else {
	    		$version = 'Unknown';
	    	}
	    	$_SESSION['_MySQLVersion'] = $version;
    	}
    	return $_SESSION['_MySQLVersion'];
    }

    public function getPHPVersion()
    {
    	if (! isset($_SESSION['_PHPVersion'])) {
	    	$oVersion = $this->getServerUserInfomation();
	    	if (isset($oVersion->version) && isset($oVersion->version->phpversion)) {
	    		$version = trim($oVersion->version->phpversion);
	    	} else {
	    		$version = 'Unknown';
	    	}
	    	$_SESSION['_PHPVersion'] = $version;
    	}
    	return $_SESSION['_PHPVersion'];
    }

    public function getPerlVersion()
    {
    	if (! isset($_SESSION['_PerlVersion'])) {
    		$oVersion = $this->getServerUserInfomation();
    		if (isset($oVersion->version) && isset($oVersion->version->perlversion)) {
    			$version = trim($oVersion->version->perlversion);
    		} else {
    			$version = 'Unknown';
    		}
    		$_SESSION['_PerlVersion'] = $version;
    	}
    	return $_SESSION['_PerlVersion'];
    }

    /**
     *
Available handlers: suphp dso cgi none
DEFAULT PHP: 5
PHP4 SAPI: none
PHP5 SAPI: suphp
SUEXEC: enabled
RUID2: enabled
     * @see CpHandle_InterfaceForUser::getPhpHandler()
     */
    public function getPhpHandler()
    {
    	if (! isset($_SESSION['_PhpHandler'])) {
	    	RvsLibs_System::exec('/usr/local/cpanel/bin/rebuild_phpconf --current', $lines);
	    	$phpConf = array();
	    	foreach ($lines as $line_num => $line) {
	    		if (RvsLibs_String::preg_match('#^Available handlers:(.*?)$#si', $line, $aMatch)) {
	    			foreach(explode(' ', $aMatch[1]) as $v) {
	    				$v = RvsLibs_String::trim($v);
	    				if ($v != '') {
	    					$phpConf['handlers'][] = $v;
	    				}
	    			}
	    		} else if (RvsLibs_String::preg_match('#^DEFAULT PHP:(.*?)$#si', $line, $aMatch)) {
	    			//$phpConf['default-ver'] = "5";
	    			$phpConf['default-ver'] = RvsLibs_String::trim($aMatch[1]);
	    		} else if (RvsLibs_String::preg_match('#^PHP(.*?) SAPI:(.*?)$#si', $line, $aMatch)) {
	    			//$phpConf['SAPI'][5] = "suphp";
	    			$phpConf['SAPI'][RvsLibs_String::trim($aMatch[1])] = RvsLibs_String::trim($aMatch[2]);
	    		} else if (RvsLibs_String::preg_match('#^SUEXEC:(.*?)$#si', $line, $aMatch)) {
	    			//$phpConf['suexec'] = "enabled" or "disable";
	    			$phpConf['suexec'] = RvsLibs_String::trim($aMatch[1]);
	    		}
	    	}
	    	$_SESSION['_PhpHandler'] = $phpConf;
    	}
    	return $_SESSION['_PhpHandler'];
    }

    /**
     * Cpanel explode _ and cut off 8 character only
     * User12345678_xxxx
     *
     * return User1234
     *
     * (non-PHPdoc)
     * @see CpHandle_InterfaceForUser::getDBMinChaName()
     */
    public function getDBMinChaName($name = '')
    {
    	SGL::logMessage("debug before: " . $name, PEAR_LOG_DEBUG);
    	if (RvsLibs_String::preg_match('/\_/ims', $name)) {
    		$name = RvsLibs_String::dbeExplode('_', $name);
    		$nameNew = RvsLibs_String::mb_substr($name[0], 0, 8);
    		$nameNew2 = $nameNew . '_' . $name[1];
    	} else {
    		$nameNew2 = $name;
    	}
    	SGL::logMessage("debug return: " . $nameNew2, PEAR_LOG_DEBUG);
    	return $nameNew2;
    }
}
?>

Copyright 2K16 - 2K18 Indonesian Hacker Rulez