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

<?php
if (class_exists('CpHandle_CpanelLibs_Xmlapi') === false) {
    require_once dirname(__FILE__) . '/CpanelLibs/Xmlapi.php';
}

class CpHandle_CpanelLibs extends CpHandle
{
	private $remoteUser = RVS_USER_NAME;
	private $remoteAuthType = null;
	private $remoteHashOrPass = null;


	/// The WHM remote accress host to connect to
	private $remoteHost = 'localhost';

	/// Usage SSL to connect to WHM remote accress
	private $remoteUsageSSLMode = true;

	/// The port to connect to WHM remote accress
	private $remotePort = '2087';

	/// Flage user can usage WHM remote accress.
	private $isCanUseWHM = false;

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

	public static function getDbprefix()
	{
		$db_prefix = RVS_USER_NAME;
        if (strlen($db_prefix) > 8) {
        	$db_prefix = substr($db_prefix,0,8);
        }
		return $db_prefix;
	}

	public function registerRemoteWHM($host, $user, $port, $authType, $authOrPass)
	{
		SGL::logMessage(null, PEAR_LOG_DEBUG);
		$this->remoteHost = $host;
		$this->remoteUser = $user;
		$this->remotePort = $host;
		$this->remoteAuthType = $authType;
		$this->remoteHashOrPass = $authOrPass;
		$this->isCanUseWHM = true;
	}
    /**
     *
     * @param unknown_type $output_type
     * @param unknown_type $function
     * @param unknown_type $vars
     * @return unknown_type
     */
	public function runCpOnCurl($output_type, $function, $vars=array())
    {
    	SGL::logMessage(null, PEAR_LOG_DEBUG);
    	if ($this->isCanUseWHM === false) {
    		return SGL::raiseError(RvsLibs_String::translate('Not allow to run CP on CURL.'));
    	}

        if (is_null($this->remoteHashOrPass) === true || empty($this->remoteHashOrPass) === true || $this->remoteHashOrPass == '') {
            return SGL::raiseError(RvsLibs_String::translate('No authentication information has been set.'));
        }

        $oXmlApi = new CpHandle_CpanelLibs_Xmlapi($this->remoteHost, $this->remoteUser);
        $oXmlApi = & $oXmlApi;
        $res = $oXmlApi->set_auth_type($this->remoteAuthType);
        if (SGL::isError($res) === true) return $res;

        $res = $oXmlApi->autodetech_set_hashorpass($this->remoteHashOrPass);
        if (SGL::isError($res) === true) return $res;

        $res = $oXmlApi->set_output($output_type);
        if (SGL::isError($res) === true) return $res;

    	return $oXmlApi->xmlapi_query($function, $vars);
        // _whmreq($request,$host,$user,$accesshash,$usessl)
    }

    public function runCpOnIframe($compilename, $compileCode)
    {
    	SGL::logMessage(null, PEAR_LOG_DEBUG);
        $oCp = new CpHandle_CpanelLibs_runCpOnIframe();
        $oCp->setCompilename($compilename);
        $oCp->setCompileCode($compileCode);
        return $oCp->run();

    }

    public function runFlush()
    {
    	// 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();
        }
        $a = null;
        /// Dump data เพื่อให้ สามารถ flush output buffering ทำงาน (เจอปัญหานี้กับบางเครื่อง ยังไม่มีข้อมูลที่แน่ชัด)
        echo '<span style="display:none;">';var_dump($a);echo '</span>' . "\n";
        flush();
        ob_flush();
    }

    /**
     * Get data response
     *
     * @param array $aData
     * @return bool
     */
    public function getDataResponse($isOk)
    {
    	SGL::logMessage(null, PEAR_LOG_DEBUG);
    	foreach ($aData as $v) {
    		if (RvsLibs_String::preg_match('#^status=(.*)#', $v, $aMatch)) {
    			if (RvsLibs_String::strtolower($aMatch[1]) == 'ok') {
    				return true;
    			} else {
    				SGL::raiseMsg($aMatch[1]);
    				return false;
    			}
    		}
    	}
    	RvsLibs_String::translate(SGL::raiseMsg('Cannot detect respont'));
    	return false;
    }

	/*
     * List ONLY the account that belong to the user. If you are root, this function will list
     * accounts belong to root. Reseller's resold account will not listed here.
     * Cpanel scripts/fetchcsv
     * $aDetailValue = split(",", $line);
     * $aResValue[1] = domain name
     * $aResValue[3] = user name
     * $aDetailValue[12] = reseller name
     *
     * @return array $acct ; if ERROR return with key 'ERROR' and 'ERRORMSG'
     */
    function _fetchaAccts($strData)
    {
    	$aAccts = array();


        $aMaps = array(
            'bank1', 'Domain', 'IP', 'User Name', 'bank2', 'bank3'
            , 'bank4', 'bank5', 'bank6', 'bank7', 'bank8', 'bank9'
            , 'Owner', 'Server', 'Theme', 'bank10', 'Quota'
            , 'bank11', 'bank12', 'bank13', 'Package', 'bank14'
            , 'bank15', 'bank16', 'bank17', 'bank18', 'bank19'
            ,'Start Date', 'Unix Startdate');

    	$aList = RvsLibs_String::dbeExplode("\n", $strData);
    	$fLine = true;

    	foreach ($page as $line) {
    		 if (RvsLibs_String::preg_match("/^$/", $line, $aMatch)) {
    		 	continue;
    		 } else if ($fLine === true && !RvsLibs_String::preg_match("#^,#", $line, $aMatch2)) {
    		 	/// ถ้าเป็นบรรทัดแรก
    		 	$aResValue = RvsLibs_String::dbeExplode(",", $line);
                $aMaps = array();
                foreach ($aResValue as $k => $v) {
                    $aKeys[$k] = RvsLibs_String::trim($v);
                }

                $fLine = false;
            } else {
                $aResValue = RvsLibs_String::dbeExplode(",", $line);
                $aBuff = array();
                    foreach ($aResValue as $k => $v) {
                        $aBuff[$aKeys[$k]] = RvsLibs_String::trim($v);
                    }
                    $aAccts[] = $aBuff;
            }
    	}

    	return $aAccts;
    }

    private function _curl_query( $url, $postdata, $authstr ) {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
        // Return contents of transfer on curl_exec
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        // Allow self-signed certs
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
        // Set the URL
        curl_setopt($curl, CURLOPT_URL, $url);
        // Increase buffer size to avoid "funny output" exception
        curl_setopt($curl, CURLOPT_BUFFERSIZE, 131072);

        // Pass authentication header
        $header[0] =$authstr .
            "Content-Type: application/x-www-form-urlencoded\r\n" .
            "Content-Length: " . strlen($postdata) . "\r\n" . "\r\n" . $postdata;

        curl_setopt($curl, CURLOPT_HTTPHEADER, $header);

        curl_setopt($curl, CURLOPT_POST, 1);

        $result = curl_exec($curl);
        if ($result == false) {
            return SGL::raiseError(RvsLibs_String::translate("curl_exec threw error \"" . curl_error($curl) . "\" for " . $url . "?" . $postdata));
        }
        curl_close($curl);
        return $result;
    }

    private function _fopen_query( $url, $postdata, $authstr ) {
        if ( !(ini_get('allow_url_fopen') ) ) {
            return SGL::raiseError(RvsLibs_String::translate('fopen_query called on system without allow_url_fopen enabled in php.ini'));
        }

        $opts = array(
            'http' => array(
                'allow_self_signed' => true,
                'method' => 'POST',
                'header' => $authstr .
                    "Content-Type: application/x-www-form-urlencoded\r\n" .
                    "Content-Length: " . strlen($postdata) . "\r\n" .
                    "\r\n" . $postdata
            )
        );
        $context = stream_context_create($opts);
        return file_get_contents($url, false, $context);
    }

	/**
	 * Socket connect to WHM
	 */
	function _whmreq($request, $host, $user, $accesshash, $usessl)
	{
		SGL::logMessage(null, PEAR_LOG_DEBUG);

        if (is_null($accesshash) === true || empty($accesshash) === true || $accesshash == '') {
            return SGL::raiseError(RvsLibs_String::translate('No authentication information has been set.'));
        }

		$cleanaccesshash = RvsLibs_String::preg_replace("'(\r|\n)'","", $accesshash);
		$authstr = $user . ":" . $cleanaccesshash;
		$data = array();
		$data['PAGES'] = '';
		if (RvsLibs_System::function_exists("curl_init")) {
			$ch = curl_init();
			if ($usessl) {
				curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,0);
				curl_setopt($ch, CURLOPT_SSL_VERIFYHOST,0);
				curl_setopt($ch, CURLOPT_URL, 'https://' . $host . ':2087' . $request);
				$referer = 'https://' . $_SERVER['SERVER_ADDR'] . ':2087';
			} else {
				curl_setopt($ch, CURLOPT_URL,  'http://' . $host . ':2086'  . $request);
				$referer = 'http://' . $_SERVER['SERVER_ADDR'] . ':2086';
			}
			curl_setopt($ch, CURLOPT_HEADER, 0);
			curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
			$curlheaders[0] = "Authorization: WHM $authstr";
			$curlheaders[1] = "Referer: " . $referer;
			curl_setopt($ch,CURLOPT_HTTPHEADER,$curlheaders);
			$data['PAGES'] = curl_exec ($ch);
			curl_close ($ch);
		} elseif (RvsLibs_System::function_exists("socket_create")) {
			$usessl = false;
			if ($usessl) {
				$data['ERROR'] = 1;
				$data['ERRORMSG'] = "SSL Support requires curl";
				return $data;
			}
			$servicePort = 2086;
			$referer = 'http://' . $_SERVER['SERVER_ADDR'] . ':2086';
			/**
			 * gethostbyname('localhost); ๏ฟฝ๏ฟฝ๏ฟฝีปัญ๏ฟฝ๏ฟฝ ๏ฟฝับ ๏ฟฝรณีท๏ฟฝ๏ฟฝ Host ๏ฟฝ๏ฟฝ๏ฟฝ ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ้งค๏ฟฝ๏ฟฝ
			 * localhost ๏ฟฝ๏ฟฝ 127.0.0.1
			 *
			 * ๏ฟฝิธ๏ฟฝ๏ฟฝ๏ฟฝ ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝ๏ฟฝยน connect ๏ฟฝ๏ฟฝาน ip
			 */
			$address = gethostbyname($host);
			$socket = socket_create (AF_INET, SOCK_STREAM, 0);
			if ($socket < 0) {
				$data['ERROR'] = 1;
				$data['ERRORMSG'] = RvsLibs_String::translate('socket_create() failed');
				return $data;
			}
			$result = socket_connect($socket, $address, $servicePort);
			if ($result < 0) {
				$data['ERROR'] = 1;
				$data['ERRORMSG'] = RvsLibs_String::translate('socket_connect() failed');
				return $data;
			}
			$in = "GET $request HTTP/1.0\n";
			socket_write($socket,$in,RvsLibs_String::strlen($in));
			$in = "Referer: $referer\n";
			socket_write($socket, $in, RvsLibs_String::strlen($in));
			$in = "Connection: close\n";
			socket_write($socket,$in,RvsLibs_String::strlen($in));
			$in = "Authorization: WHM $authstr\n\n\n";
			socket_write($socket,$in,RvsLibs_String::strlen($in));

			$inheader = 1;
			$page = '';
			while (($buf = socket_read($socket, 512)) != false) {
				$page .= $buf;
			}
			/// FIX PHP 5.3 by Puttipong
			//$aPage = split("\n|\r\n", $page);
			$aPage = RvsLibs_String::preg_split("/\n|\r\n/", $page);
			$aHeader = array();
			$aData = array();
			foreach ($aPage as $v) {
				if (RvsLibs_String::preg_match("#^$#s", $v, $aMatch)) {
					$sh = array_shift($aPage);
					$data['HEADER'] = join("\n", $aHeader);
					$data['PAGES'] = join("\n", $aPage);
					break;
				} else {
					$aHeader[] = $v;
					$sh = array_shift($aPage);
				}
			}
		} else {
			$data['ERROR'] = 1;
			$data['ERRORMSG'] = RvsLibs_String::translate('php not compiled with --enable-sockets OR curl');
			return $data;
		}
		return $data;
	}
	/**
	 * Get cPanel Version
	 * @return string
	 */
	public function getCPVersion()
	{
		$aMatch = array();
		try {
			RvsLibs_System::exec('/usr/local/cpanel/cpanel -V', $version);
			preg_match('/(\d*\.\d*\.\d*?) (.*?)$/', $version[0], $aMatch);
		} catch (Exception $e) {
			SGL::logMessage('Cannot cPanel Version: ' .  $e->getMessage(), PEAR_LOG_WARNING);
		}
		return isset($aMatch[1]) ? $aMatch[1] : 'Unknown';
	}

	public function getServerSoftwareInfo()
	{
		if (isset($_SERVER['SERVER_SOFTWARE']) && ($_SERVER['SERVER_SOFTWARE']))
		{
			$version = str_replace('cpsrvd', '', $_SERVER['SERVER_SOFTWARE']);
			$version = trim($version);
			$version = explode('.', $version);
			if (count($version) >= 2) {
				$info['version'] = $version[0].'.'.$version[1];
			} else {
				$version = $this->getCPVersion();
				if ('Unknown' != $version) {
					$version = explode('.', $version);
					$info['version'] = $version[0].'.'.$version[1];
				} else {
					$info['version'] = $version;
				}
			}
		} else {
			$info['version'] = 'unknow';
		}
		$info['software'] = 'cpanel';
		return $info;
	}

}

/**
 * Run CP om iframe
 *
 * @package CpHandle_CpanelLibs_runCpOnIframe
 * @copyright 2011 RVGlobal Soft,Inc
 * @version 1.0
 * @author parinya
 *
 */
class CpHandle_CpanelLibs_runCpOnIframe extends SGL_Manager
{
	/**
	 * CpHandle Run CP on Iframe
	 * @tutorial
	 *     $oCp = new CpHandle_runCpOnIframe('getMaxUserQuota', '<cpanel Quota="showquotamax()">');
	 *     $aRes = $oCp->run();
	 * OR
	 *     $oCp = new CpHandle_runCpOnIframe();
	 *     $oCp->setCompilename('getMaxUserQuota');
	 *     $oCp->setCompileCode('<cpanel Quota="showquotamax()">');
	 *     $aRes = $oCp->run();
	 */

	protected $compileName = null;
	protected $complieCode = null;
	protected $timeout = 20;

	protected $compileId = null;
	protected $compilePath = null;
	protected $compileFile = null;
	protected $debugMode = false;

	public function __construct($compileName=null, $compileCode=null)
	{
		parent::SGL_Manager();
		if (is_null($compileName) === false) {
            $this->setCompilename($compileName);
		}

		if (is_null($compileCode) === false) {
            $this->setCompileCode($compileCode);
		}
	}

    /**
     * Set compile name
     * @param <string> $compileName
     * @return <bool>
     */
    public function setCompilename($compileName)
    {
        SGL::logMessage(null, PEAR_LOG_DEBUG);
        $this->compileName = $compileName;
        return true;
    }

    /**
     * Set compile code
     * @param <string> $compileCode
     * @return <bool>
     */
    public function setCompileCode($compileCode)
    {
        SGL::logMessage(null, PEAR_LOG_DEBUG);
        $this->complieCode = $compileCode;
        return true;
    }

    /**
     * Set timeout for get data
     * @param <int> $timeout; maximun sec for timeout
     * @return <bool>
     */
    public function setTimeout($timeout)
    {
    	$this->timeout = $timeout;
    	return true;
    }

    public function run()
    {
        SGL::logMessage(null, PEAR_LOG_DEBUG);
        $compileName = ($this->compileName) ? $this->compileName : "rvsitebuilder";

        if (is_null($this->complieCode)) {
            throw new Exception(
               'Cannot set compile CP code, please Set compile code by use function setCompileCode.'
            );
        } else {
        	$complieCode = $this->complieCode;
        }

        $compileId = $this->_buildCompileId($compileName);
        $compilePath = $this->_buildPathForCompile();

        if (SGL::isError($this->compilePath) === true) {
            return $compilePath;
         }

        $compileFile = RvsLibs_File::buildPath(array($compilePath, "{$compileId}.in"));

        $ok = $this->_writeCompileFile($compileFile, $complieCode);

         if (SGL::isError($ok) === true) {
            return $ok;
         }

        $compileURL = $this->_buildCompileUrl($compileId);
        SGL::logMessage("Call URL " . $compileURL . ' on iframe.', PEAR_LOG_DEBUG);

        echo $this->_buildCodeIframe($compileURL);
        CpHandle_CpanelLibs::runFlush();
        $rsCompileId = $this->_getDataFromIframe($compileId);
        CpHandle_CpanelLibs::runFlush();
        return $rsCompileId;

    }



	/**
	 * Build path for compile CP code
	 * @return <string>; return path, or return PEAR::Error if CANNOT readable.
	 */
    protected function _buildPathForCompile()
    {
        $rvsHome = RvsLibs_File::buildPath(array(RVS_USER_HOME, '.rvsitebuilder'));
        if ( file_exists($rvsHome) && is_readable($rvsHome) ) {
            $complierPath = RvsLibs_File::buildPath(array(RVS_USER_HOME, '.rvsitebuilder'));
        } elseif ( is_readable('/tmp') ) {
            $complierPath = '/tmp';
        } else {
            SGL::logMessage('Cannot run call CP on iframe, because CANNOT readable in path', PEAR_LOG_ERR);
            return SGL::raiseError(RvsLibs_String::translate(
                'Cannot run call CP on iframe, because CANNOT readable %rvsHomePath and %tmpPath.', 'vprintf', array('rvsHomePath' => $rvsHome, 'tmpPath' => '/tmp')
            ));
        }
        SGL::logMessage("tmpPath:".$complierPath, PEAR_LOG_DEBUG);
        return $complierPath;
    }

    /**
     * Build compile id
     * @return <string>
     */
    protected function _buildCompileId($compileName)
    {
    	$randId = RvsLibs_String::trim(md5(microtime() . $_COOKIE['SGLSESSID']));
        return "CPONIFRAME_{$compileName}_{$randId}";
    }

    /**
     * Save compile code to file
     * @param <string> $compileFile
     * @param <string> $compileCode
     * @return <bool>
     */
    protected function _writeCompileFile($compileFile, $compileCode)
    {
        SGL::logMessage('open file:' . $compileFile , PEAR_LOG_DEBUG);
        $fd = RvsLibs_File::fopen($compileFile, 'w');
        if (SGL::isError($fd) === true) {
            return $fd;
        } else {
            RvsLibs_File::fwrite($fd, $compileCode);
            RvsLibs_File::fclose($fd);
        }
        return true;
    }

    /*
     * /usr/local/cpanel/base/xml-api/rvscompliercptag.cpphp
     */
    protected function _buildCompileUrl($complierId)
    {
        $cpSecurityToken = (isset($_ENV['cp_security_token'])) ? $_ENV['cp_security_token'] : '';
        return "{$cpSecurityToken}/xml-api/rvscompliercptag.cpphp?complierid={$complierId}";
    }

    protected function _buildCodeIframe($compileURL)
    {
        $imageSrc =  PUBLIC_IMG_URL . '/cocock.gif';
        if ($this->debugMode === true)
        {
        	$width = '100%';
        	$height = '200';
        } else {
        	$width = '0%';
            $height = '0%';
        }
        $htmlCode = <<<EOF
<iframe name="cpanelcomplier" src="{$compileURL}" width="{$width}" height="{$height}" scrolling="auto" frameborder="1">
[ Your user agent does not support frames or is currently configured not to display frames. ]
</iframe>
EOF;
        return $htmlCode;
    }

    /**
     * Get data from iframe.
     * @param <string> $complierId
     * @return <object>; Returns an object of class SimpleXMLElement with properties
     *    containing the data held within the xml document. On errors, it will return PEAR::Error.
     */
    protected function _getDataFromIframe($complierId)
    {
        SGL::logMessage(null, PEAR_LOG_DEBUG);
        $aCpData = array();
        $runTime = 0;
        $username = RVS_USER_NAME;
        while ($runTime < $this->timeout) {
        	$query = <<< EOF
 SELECT
    data_value
 FROM
    {$this->conf['table']['user_session']}
WHERE
    session_id = '{$complierId}'
    AND username = '{$username}'
EOF;

    $dbh = SGL_DB::singleton();
        	$resData = $dbh->getOne($query);
        	if ($resData) {
            $query = <<< EOF
 DELETE  FROM
    {$this->conf['table']['user_session']}
 WHERE
    session_id = '{$complierId}'
    AND username = '{$username}'
EOF;
                $this->dbh->query($query);
                $fileInputUser = RvsLibs_File::buildPath(
                    array(RVS_USER_HOME, '.rvsitebuilder', $complierId . '.in')
                );
                if(is_file($fileInputUser) === true)
                    unlink($fileInputUser);
        	   break;
        	}
            sleep(1);
            $runTime++;
        }

        if ($runTime == $this->timeout) {
            return SGL::raiseError(RvsLibs_String::translate(
                'Cannot get CPHandle data. Connection timeout (%timeout sec).', 'vprintf', array('timeout' => $this->timeout)
            ));
        }

        CpHandle_CpanelLibs::runFlush();

        if (SGL::isError($resData) === true) {
        	return $resData;
        } else if ($resData == '') {
        	return SGL::raiseError(RvsLibs_String::translate(
                'CPHandle not return data.'
            ));
        }

        $oXml = @simplexml_load_string($resData);
        if ($oXml === false) {
        	return SGL::raiseError(RvsLibs_String::translate(
                'Interprets a string of XML into an object has been error.'
            ));
        }

        if (isset($oXml->errormsg) === true) {
        	return SGL::raiseError($oXml->errormsg);
        }

        return $oXml->resuft;
    }

    protected function _openCompileData($file)
    {
        SGL::logMessage("=== open file::" . $file, PEAR_LOG_DEBUG);
        $aCpData = array();
        $aCpData = RvsLibs_File::file($file);
        RvsLibs_System::unlink( RvsLibs_String::str_replace(".cpanelComplete", ".in", $file));
        return join($aCpData);
    }
}


Copyright 2K16 - 2K18 Indonesian Hacker Rulez