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

<?php
class CpHandle_DaLibs extends CpHandle
{
    private $debugMode = true;

    function __construct() {
    	parent::CpHandle();
    }

    public function runCpOnCurl()
    {

    }

    public function runCpOnIframe($module, $cpanelTag)
    {
    	return array();
    }

    public function fetchStatus($res=array())
    {
        $status = 'Unknow status.';
        foreach ($res as $line) {
            if (RvsLibs_String::preg_match('/^status=(.*)$/si', RvsLibs_String::trim($line), $aMatch)) {
                $status = RvsLibs_String::trim($aMatch[1]);
                break;
            }
        }
        return $status;
    }

    public function fetchDBInfomation($aData)
    {
    	/// Set defult struct.
    	$aDbConf = array(
            'countdb' => '',
            'maxdb' => -1,
            'listdbs' => array(),
            'listusers' => array(),
    	);
    	$aDbConf['listdbs'] = $this->listDatabaseName();
    	$aDbConf['countdb'] =  count($aDbConf['listdbs']);
    	$aDbConf['maxdb'] = $this->getMaxDb();
    	$aDbConf['listusers'] = $this->listDadabaseUserName($aDbConf['listdbs']);
    	return $aDbConf;
    }

    public function listDatabaseName()
    {
    	SGL::logMessage(null, PEAR_LOG_DEBUG);
    	$res = $this->socketAPI('CMD_API_DATABASES');
    	$aDb = (isset($res['list']) && $res['list']) ? $res['list'] : array();
    	$aDbName = array();
    	foreach ($aDb as $dbN) {
    		$aDbName[$dbN] = $dbN;
    	}
    	return $aDbName;

    }

    public function getMaxDb()
    {
    	SGL::logMessage(null, PEAR_LOG_DEBUG);
        $aRes = $this->socketAPI('CMD_API_SHOW_USER_CONFIG');
        return $aRes['mysql'];
    }

    public function listDadabaseUserName($aDbName)
    {
    	SGL::logMessage(null, PEAR_LOG_DEBUG);
    	$aDbname = array();
    	foreach ($aDbName as $dbName) {
    	   $aRes = $this->socketAPI('CMD_API_DATABASES', array('action' => 'users', 'db' => $dbName));
    	   $aDbname = array_merge($aDbname, $aRes['list']);
    	}

    	//$aDbname['ning'] = 'ning';
    	foreach ($aDbname as $k => $v) {
    		unset($aDbname[$k]);
    		$aDbname[$v] = $v;
    	}
    	return $aDbname;
    }



    /**
     * Get WHM remote Accress Key
     */
    public function getCpAccessKey()
    {
        SGL::logMessage(null, PEAR_LOG_DEBUG);
        return '';
    }

    /**
     * directadmin connect API
     * default connect 127.0.0.1
     * if not work goto connect hostname
     *
     * @param unknown $api
     * @param unknown $aOpt
     * @param $fetchMode
     * @return unknown
     */
    var $aDataList = array();
    public function socketAPI($api, $aOpt = array() ,$fetchMode  = 'fetch_parsed_body')
    {
    	SGL::logMessage('api:' . $api, PEAR_LOG_DEBUG);
    	$md5 = md5(serialize($aOpt) . '_' . $fetchMode);
    	if (isset($this->aDataList[$api][$md5]) && count($this->aDataList[$api][$md5]) > 0) {
    		return $this->aDataList[$api][$md5];
    	}

    	 if (class_exists('HTTPSocket') === false) {
            require_once dirname(__FILE__) . '/DaLibs/httpsocket.php';
        }

        $Socket = new HTTPSocket;
        $port = (isset($_SERVER['SERVER_PORT'])) ? $_SERVER['SERVER_PORT'] : 2222;
        $hostName = '127.0.0.1';

        if (SSL_MODE == 1) {
            $Socket->connect('ssl://' . $hostName,$port);
        } else {
            $Socket->connect($hostName,$port);
        }
        $Socket->set_login(RVS_USER_NAME);
        $Socket->query('/' . $api ,$aOpt);

        switch ($fetchMode) {
        	case  'fetch_parsed_body':
        		$result = $Socket->fetch_parsed_body();
        		$this->aDataList[$api][$md5] = $result;
        	break;
        	default:
        		$result = $Socket->fetch_body();
        		$this->aDataList[$api][$md5] = $result;
            break;

        }
        $resultValue = (array_values((array)$result));

        //if cannot get content goto connectAPIByHostName
        if((!isset($resultValue[0]) || count($resultValue) < 1)
        || (isset($resultValue[0]) && $resultValue[0] == "") ) {
        	$result = self::_socketAPIByHostName($api, $aOpt, $fetchMode);
        }
        return $result;
    }

	/**
	 * socket API by hostname
	 *
	 * @param unknown $api
	 * @param unknown $aOpt
	 * @param string $fetchMode
	 * @return unknown
	 */
    function _socketAPIByHostName($api, $aOpt = array(), $fetchMode  = 'fetch_parsed_body')
    {
    	$md5 = md5(serialize($aOpt) . '_' . $fetchMode);
    	if (isset($this->aDataList[$api][$md5]) && count($this->aDataList[$api][$md5]) > 0) {
    		return $this->aDataList[$api][$md5];
    	}

    	 if (class_exists('HTTPSocket') === false) {
            require_once dirname(__FILE__) . '/DaLibs/httpsocket.php';
        }

        $Socket = new HTTPSocket;
        $port = (isset($_SERVER['SERVER_PORT'])) ? $_SERVER['SERVER_PORT'] : 2222;
        $hostName = RvsLibs_Config::getHostnameAPI();

        if (SSL_MODE == 1) {
            $Socket->connect('ssl://' . $hostName,$port);
        } else {
            $Socket->connect($hostName,$port);
        }
        $Socket->set_login(RVS_USER_NAME);
        $Socket->query('/' . $api ,$aOpt);

        switch ($fetchMode) {
        	case  'fetch_parsed_body':
        		$result = $Socket->fetch_parsed_body();
        		$this->aDataList[$api][$md5] = $result;
        	break;
        	default:
        		$result = $Socket->fetch_body();
        		$this->aDataList[$api][$md5] = $result;
            break;

        }
    	return $result;
    }


    public function getDataAllUser()
    {
        SGL::logMessage(null, PEAR_LOG_DEBUG);
        $result = $this->socketAPI('CMD_API_ALL_USER_USAGE',array(),'fetch_body');
        $lines = RvsLibs_String::dbeExplode("\n", $result,-1);
        $aUser = array();
        $aData = array();
        foreach ($lines as $k => $line)
        {
            $user = strtok($line, '=');
            $data = strstr($line, '=');
            parse_str($data,$aData);
            $aData['username'] = strtok($line, '=');
            $aUser[$user] = $aData;
        }
        return $aUser;

    }

    public function getDefaultDomain()
    {
    	$aRes = $this->socketAPI('CMD_API_SHOW_USER_CONFIG');
    	$domain = isset($aRes['domain']) ? $aRes['domain'] : '';
    	SGL::logMessage('domain:' . $domain, PEAR_LOG_DEBUG);
    	return $domain;
    }

    public function getAllDomainsByUser($user)
    {
        SGL::logMessage(null, PEAR_LOG_DEBUG);
        $aRes = $this->getDataAllUser();
        $aDomain = (isset($aRes[$user]['list']) && $aRes[$user]['list']) ? RvsLibs_String::dbeExplode('<br>', $aRes[$user]['list']) : array();
        if (count($aDomain) > 0) {
        	foreach ($aDomain as $k => $v) {
        		if ($v == '') {
        			unset($aDomain[$k]);
        		}

        	}
        }
        return $aDomain;
    }

    public function createProjectLink($realProjectPath, $dirPath)
    {
    	SGL::logMessage(null, PEAR_LOG_DEBUG);
    	$aData = RvsLibs_System::ls(array('-a', '-R', $realProjectPath));
    	foreach ($aData['dirs'] as $dir) {
    		$strDir = RvsLibs_String::str_replace($realProjectPath, "", $dir);
    		if (is_dir($dirPath . $strDir) == false) {
    			RvsLibs_System::mkdir(array('-p', '-m', 0755, $dirPath . $strDir));
    		}
    	}
    	foreach ($aData['files'] as $file) {
    		$strFile = RvsLibs_String::str_replace($realProjectPath, "", $file);
    		$filePath = RvsLibs_File::buildPath(array($dirPath, $strFile));
    		if(file_exists($file) && file_exists($filePath) === false) {
    			RvsLibs_System::ln(array('-s', $file, $filePath));
    		}
    	}
    }

    public function validateDomain($defaultDomain)
    {
    	SGL::logMessage(null, PEAR_LOG_DEBUG);
    	$domainPath = RvsLibs_File::buildPath(array(RVS_USER_HOME, 'domains', $defaultDomain, 'public_html'));
    	$testFilename = RvsLibs_String::dbeSubstr(md5(time() . rand(1000, 9999)), 0, 16);
    	$testFilename = RvsLibs_String::sprintf('rvs%s.html', ($testFilename) ? $testFilename : 'rvsSADAdffbvvxbsdfgsdfg');
    	$filePath = RvsLibs_File::buildPath(array($domainPath, $testFilename));
    	if ($this->makeFileToTestUrlConnect($filePath) === false) {
    		return SGL::raiseError(
    		RvsLibs_String::translate(
                        'File Permission denied'
                        , 'vprintf'
                        , array('filename' => $filePath)
                        )
                        );
    	} else {
    		$aUrlConnect = RvsLibs_Url::urlConnect($defaultDomain, '/' . $testFilename , 80 , null , false);
    		$this->cleanFileToTestUrlConnect($filePath);
    	}

    	if (isset($aUrlConnect['CONNECT_ERROR']) && $aUrlConnect['CONNECT_ERROR'] == 1) {
    		if (isset($aUrlConnect['ERROR_CODE']) && $aUrlConnect['ERROR_CODE'] != '401') {

    			if (RvsLibs_System::function_exists("curl_init") == true) {
    				$functionConnect = 'curl_init';
    			} else {
    				$functionConnect = (RvsLibs_System::function_exists('fsockopen')) ? 'fsockopen' : 'unknown';
    			}
    			$kbCannotDomain = ($functionConnect == 'curl_init')
                                  ? 'http://support.rvsitebuilder.com/index.php?x=&mod_id=2&id=323'
                                  : 'http://support.rvsitebuilder.com/index.php?x=&mod_id=2&id=175';
    			SGL::raiseMsg( RvsLibs_String::translate(
                                'Cannot connect domain for make project link'
                                , 'vprintf'
                                , array('domainName' => $defaultDomain
                                        , 'functionConnect' => $functionConnect
                                        , 'KPCannotDomain' => $kbCannotDomain)
                                ), false);
                return false;
                //SGL::raiseMsg('string', $isTranslation = false); ไม่ต้อง translation 2 รอบ
    		}
    	}
    	return true;
    }

    /**
     * @param unknown_type $filePath
     * @return string|string|string
     */

    public function makeFileToTestUrlConnect($filePath)
    {
    	SGL::logMessage('with path ' . $filePath, PEAR_LOG_DEBUG);
    	$handle = RvsLibs_File::fopen($filePath,'w+');
    	if (SGL::isError($handle) === true) {
    		SGL::logMessage('cannot open file. ' . $handle->getMessage() , PEAR_LOG_ERR);
    		SGL_Error::pop();
    		return false;
    	}
    	if($handle === FALSE){
    		return false;
    	} else {
    		RvsLibs_File::fwrite($handle, '<!-- RVS TEST URL Connect -->');
    		RvsLibs_File::fclose($handle);
    	}
    	return true;
    }

    public function cleanFileToTestUrlConnect($filePath)
    {
    	if (is_file($filePath)) {
    		SGL::logMessage('with path ' . $filePath, PEAR_LOG_DEBUG);
    		RvsLibs_System::unlink($filePath);
    	}
    }




    ##################################
    ########## PRIVATE FUNCTION ##########
    ##################################
    private function _getCpanelTagData($module)
    {
        SGL::logMessage(null, PEAR_LOG_DEBUG);
        $timeout = 50;
        $fileOutput = $module . '.cpanelComplete';
        $aCpData = array();
        $runTime = 0;
        $fileOutputUser = RvsLibs_File::buildPath(array(RVS_USER_HOME, '.rvsitebuilder', $fileOutput));

        while ($runTime < $timeout) {
            if ( file_exists($fileOutputUser) ) {
                $aCpData = $this->_openCpData($fileOutputUser);
                if (SGL::isError($aCpData)) {
                    SGL::logMessage('Error : ' . $aCpData->getMessage(), PEAR_LOG_DEBUG);
                    SGL_Error::pop();
                    $aCpData = array();
                }
                RvsLibs_System::unlink($fileOutputUser);
                break;
            } elseif ( file_exists('/tmp/' . $fileOutput)) {
                $aCpData = $this->_openCpData('/tmp/' . $fileOutput);
                if (SGL::isError($aCpData)) {
                    SGL::logMessage('Error : ' . $aCpData->getMessage(), PEAR_LOG_DEBUG);
                    SGL_Error::pop();
                    $aCpData = array();
                }
                RvsLibs_System::unlink('/tmp/' . $fileOutput);
                break;
            }
            sleep(1);
            $runTime++;
        }

        if ($runTime >= $timeout) {
            echo $this->_buildUnloadingCode();
            die ("Cannot get cPanel data. Connection timeout. File not found {$fileOutputUser} and /tmp/{$fileOutput} in {$timeout} sec.");
        }
        //  javascript close id loading

        echo $this->_buildUnloadingCode();

        $aCpData = RvsLibs_String::dbeExplode('__RVSITEBUILDER__', $aCpData);
        if (isset($aCpData[0]) && RvsLibs_String::trim($aCpData[0]) == "") {
            unset($aCpData[0]);
        }
        return $aCpData;
    }

     private function _openCpData($file)
    {
        SGL::logMessage("=== open file::" . $file, PEAR_LOG_DEBUG);
        $aCpData = array();
        $aCpData = RvsLibs_File::file($file);
        if (SGL::isError($aCpData) === true) {
            return $aCpData;
        }

        array_walk($aCpData, array($this, '_trimValues'), '__RVSITEBUILDER__');

        foreach ($aCpData as $k => $v) {
            if ($v == "") {
                unset($aCpData[$k]);
            }
        }

        // optimize :nipaporn
        RvsLibs_System::unlink( str_replace(".cpanelComplete", ".in", $file));
        return join($aCpData);
    }

    private function _getCpIframeComplierPath()
    {
        $rvsPath = RvsLibs_File::buildPath(array(RVS_USER_HOME, '.rvsitebuilder'));

        if ( file_exists($rvsPath) && is_readable($rvsPath) ) {
            return $rvsPath;
        } elseif ( is_readable('/tmp') ) {
            return '/tmp';
        } else {
            SGL::logMessage('Cannot run cPanel tag', PEAR_LOG_ERR);
            return SGL::raiseError('The path ' . $rvsPath . ' and /tmp cannot readable.');
        }
    }

    /**
     * Build code iframe for run CP
     * @param <string> $urlSrc
     * @return <string>
     */
    private function _buildCpIframe($urlSrc)
    {
        $imageSrc =  PUBLIC_IMG_URL.'/cocock.gif';
        $frameId = rand(0, 9999);

        $frameWidth = '0%';
        $frameHeight = '0%';
        if ($this->debugMode) {
            $frameWidth = '100%';
            $frameHeight = '150';
        }

        $htmlCode = <<<EOF
<script>
/*
try {
displayloading()
} catch(e) {
function displayloading()
{
if(document.getElementById('cpLoading') == undefined){
document.write('<div id=\'cpLoading\' style=\'position:absolute;display:none;\'><img id=\'cpImg\' src="{$imageSrc}" border="0" width="163"></div>')
}
var cpLoading =  document.getElementById('cpLoading')
var cpImag = document.getElementById('cpImg')
cpLoading.style.left =(document.body.clientWidth/2)-(163/2)+'px';
cpLoading.style.top=(document.body.clientHeight/2)-(cpLoading.clientHeight/2)+'px';
cpLoading.style.display = '';
}
displayloading()
}
*/
</script>
<iframe name="cpanelcomplier{$frameId}" src="{$urlSrc}" width="{$frameWidth}" height="{$frameHeight}" scrolling="auto" frameborder="0">
[ Your user agent does not support frames or is currently configured not to display frames. ]
</iframe>
<div style="visibility: hidden; position: absolute; top: 150px;">.</div>
EOF;

        return $htmlCode;
    }

    /**
     * Javascript close id loading
     * @return <string>
     */
    private function _buildUnloadingCode()
    {
        $code = <<<EOF
<script>
if(document.getElementById('cpLoading')){
document.getElementById('cpLoading').style.display='none';
}
</script>
EOF;

        return $code;
    }

    /**
     *  Flush output buffering
     * @return <bool>
     */
    private function _flush()
    {
        // make sure output buffering is off before we start it
        // this will ensure same effect whether or not ob is enabled already
        while (ob_get_level()) {
            ob_end_flush();
        }
        // start output buffering
        if (ob_get_length() === false) {
            ob_start();
        }
        ob_flush();
        flush();
        return true;
    }

    private function _trimValues(&$value, $key, $prefix)
    {
        $value = RvsLibs_String::trim($value);
        if ($value != "") {
            $value = $prefix . $value;
        }
    }
    ####################################
    ############# END PRIVATE #############
    ####################################

    public function getCPVersion()
    {

    	$version = 'Unknown';
    	try {
    		RvsLibs_System::exec('/usr/local/directadmin/custombuild/build version', $version);
    	} catch (Exception $e) {
    		SGL::logMessage('Cannot get DirectAdmin Version: ' .  $e->getMessage(), PEAR_LOG_WARNING);
    		$version = 'Unknown';
    	}
    	return trim($version);
    }

    public function getServerSoftwareInfo()
    {
    	$info['software'] = $_SERVER['SERVER_SOFTWARE'];
    	return $info;
    }
}

Copyright 2K16 - 2K18 Indonesian Hacker Rulez