CHips L MINI SHELL

CHips L pro

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

<?php
if (class_exists('RvsLibs_DB') === false) {
	class RvsLibs_DB
	{
		/**
		 * Enter description here...
		 *
		 * @return unknown
		 */
		public static function isDatabaseUtf8()
		{
			$dbh = SGL_DB::singleton();
			$resultDBCharset = mysql_result(mysql_query("SELECT @@character_set_results"),0,0);
			return (RvsLibs_String::strtolower($resultDBCharset) == 'utf8') ? true : false;
		}

		/**
		 * return db potocal 'unix' or 'tcp' for case remote database
		 *
		 * @param String $hostName
		 * @return String
		 */
		public static function getDBProtocol($hostName)
		{
			return (RvsLibs_String::strtolower(RvsLibs_String::trim($hostName)) == 'localhost')
			        ? 'unix'
			        : 'tcp';
		}

		/**
		 * Detect
		 * explode user and database name _ and cut 8 character
		 * ex abcdefghijklmnop_abcd14
		 * output: abcdefgh_abcd14
		 *
		 * @param unknown $name
		 */
		public static function getMinCharacterName($name)
		{
			SGL::logMessage("debug before: " . $name, PEAR_LOG_DEBUG);
		    $oCp = CpHandle::factory();
		    if(SGL::isError($oCp) == true) {
		    	return $oCp;
		    }
		    $nameNew2 = $oCp->getDBMinChaName($name);
		    SGL::logMessage("debug return: " . $nameNew2, PEAR_LOG_DEBUG);
		    return $nameNew2;
		}

		/**
		 * Test Connect Databases form user compo
		 *
		 * @param <string> $dbuser
		 * @param <string> $dbpass
		 * @param <string> $dbname
		 * @param <string> $dbtype
		 * @param <string> $hostnstname
		 * @return obj
		 */
		public static function multiDBConnection($dbport,$dbuser, $dbpass, $dbname, $dbtype = 'mysql', $hostname = 'localhost', $showRaiseError = true, $prefix = '', $protocol = 'unix', $errorIfTableExists = false, $errorIfTableNotExists = false)
		{
			//require_once 'lib/pearDB.php';
			//fixed PHPMD scan 30/06/2544
            /*$options = array(
            'debug'       => 0,
            //'portability' => DB_PORTABILITY_ALL,
            'portability' => $portability,
            );
            */
			$dbuser = RvsLibs_DB::getMinCharacterName($dbuser);
			$dbname = RvsLibs_DB::getMinCharacterName($dbname);

			$protocol = RvsLibs_DB::getDBProtocol($hostname);
			$conf['db']['type'] = $dbtype;
			$conf['db']['user'] = $dbuser;
			$conf['db']['pass'] = $dbpass;
			$conf['db']['protocol'] = $protocol;
			$conf['db']['socket'] = '';
			$conf['db']['host'] = $hostname;
			$conf['db']['port'] = $dbport;//3306;
			$conf['db']['name'] = $dbname;
			$excludeDbName = (isset($excludeDbName)) ? $excludeDbName : false;

			$dsn = SGL_DB::_getDsnAsArray($conf, $excludeDbName);
			if (SGL_DB_DRIVER === 'DB') {
				$db =  DB::connect($dsn);
			} else {
				$db = SGL_MDB2::singleton($dsn, true);
			}

			/// Start :: Check database used  :: witoon
			if ($errorIfTableExists && !SGL::isError($db)) {
				$table = $prefix . 'module';
				$query = "SHOW TABLES LIKE " . RvsLibs_String::quoteSmart($table);
				$tableUse = $db->getRow($query);
				if ($tableUse) {
					$db = $db->raiseError(-5, null, null, null, 'Table already exists');
				}
			} elseif ($errorIfTableNotExists && !SGL::isError($db)) {
				$table = $prefix . 'module';
				$query = "SHOW TABLES LIKE " . RvsLibs_String::quoteSmart($table);
				$tableUse = $db->getOne($query);
				if (!$tableUse) {
					$db = $db->raiseError(-18, null, null, null, 'Table already NOT exists');
				}
			}
			/// End :: Check database used :: witoon
			$conn = '';
			if ($showRaiseError && SGL::isError($db)) {
				$req = SGL_Request::singleton();
				$managerName = $req->get('managerName');
				$conn = $db->getMessage();
				$conn .= "<br>" . $db->getUserinfo();
				//fixed msg go to STEP4
				$conn .= RvsLibs_DB::getDatabaseEditURL();

				$errorMsg .= "<br>" . RvsLibs_String::translate('Cannot connect to your component database.');
				$errorMsg .= " " . RvsLibs_String::translate('Click here to open your configuration.','vprintf' , array('UrlSystemDB' => SGL_Output::makeUrl(null, 'CreateDBforComponent', 'sitebuilder')));

				/*
				$conn .= "<br>" . RvsLibs_String::translate('After finished above,') . "<a href=\"" . SGL_Output::makeUrl(null, 'CreateDBforComponent', 'sitebuilder') . "\">"
				. RvsLibs_String::translate('please edit database based component settings here.') . "</a>";
				*/

				SGL::raiseMsg( RvsLibs_String::translate('Test Component Database Error','vprintf' , array('errormsg' => $conn)), false);
				SGL_Error::pop();
			}
			return $db;
		}

		/**
		 * get pagestructure in database
		 * 1 rerurn mainpage
		 * 0 return subpage
		 *
		 * @param string $projectId
		 * @param string $rvsUsrId
		 * @param int
		 * $mainPage = 1 (mainpagestructure)
		 * $mainPage = 0 (subpagestructure)
		 * @return array $aPageStructure
		 */
		public static function getPageStructureDB($projectId, $rvsUsrId, $mainPage = 1)
		{
			if ($mainPage == 1) {
				$aPageStructure = DaoFactory::Project()->findPageStructureDataByProjectIdAndUsrId($projectId, $rvsUsrId, 1,  'getassoc');
			} else {
				$aPageStructure = DaoFactory::Project()->findPageStructureDataByProjectIdAndUsrId($projectId, $rvsUsrId, 0,  'getassoc');
			}
			return $aPageStructure;
		}

		/**
		 * validate database connect all Step
		 * @param unknown_type $projectId
		 * @param unknown_type $userId
		 * @param unknown_type $ownerUserId
		 *
		 */
		//fixed PHPMD scan 30/06/2544
		public static function validateDatabaseConnect($projectId)
		{
			SGL::logMessage(null, PEAR_LOG_DEBUG);
			$isCompoDB = RvsLibs_Project::isPublishCompoDB($projectId);
			if ($isCompoDB === true) {
				RvsLibs_DB::validateDatabaseConnectUser($projectId);
			}
		}

		public static function validateDatabaseConnectUser($projectId, $returnType='RAISE_MSG')
		{
			$aConnectData = RvsLibs_Component::getDBInfoOfCompoDB($projectId);

			if(SGL::isError($aConnectData) == true) {
				$errorMsg = $aConnectData->getMessage();
				SGL_Error::pop();
				//$errorMsg message นี้ translate มาแล้ว
				SGL::raiseMsg($errorMsg, false);
				return false;
			}
			$cpUser = (isset($aConnectData['RvsUserName']))
                        ? $aConnectData['RvsUserName']
                        : '';
			$rvsUser = RvsLibs_User::getUsername(true);
			$conn = RvsLibs_DB::multiDBConnection(
                $aConnectData['Port']
                , $aConnectData['UserName']
                , $aConnectData['Password']
                , $aConnectData['DatabaseName']
                , 'mysql'
                , $aConnectData['HostName']
                , false
			);
			if (SGL::isError($conn) === true) {
				SGL_Error::pop();
				if ($cpUser != $rvsUser) {
					$databaseUsername = $aConnectData['UserName'];
					$databaseName = $aConnectData['DatabaseName'];
					$aDatabaseUsrName = RvsLibs_String::dbeExplode('_', $databaseUsername);
					$databaseUsername = preg_replace('/' . $aDatabaseUsrName[0] .'+_/', $rvsUser.'_', $databaseUsername);
					$databaseName = preg_replace('/' . $aDatabaseUsrName[0] .'+_/', $rvsUser.'_', $databaseName);
					$conn = RvsLibs_DB::multiDBConnection($aConnectData['Port'], $databaseUsername , $aConnectData['Password'] , $databaseName , 'mysql' ,$aConnectData['HostName'],false);
					if (SGL::isError($conn) === false) {
						//edit file
						$aData['DatabaseName'] = $databaseName;
						$aData['UserName'] = $databaseUsername;
						$aData['Password'] = $aConnectData['Password'];
						$aData['Port'] = $aConnectData['Port'];
						$aData['HostName'] = $aConnectData['HostName'];
						$aData['protocol'] = $aConnectData['protocol'];
						RvsLibs_Component::writeDBConfig($aData, $projectId);
						return true;
					} else {
						//case component database remote
						SGL_Error::pop();
						$conn = RvsLibs_DB::testConnectRemote($aConnectData, $databaseUsername, $databaseName);
						if (SGL::isError($conn)) {
							$res = RvsLibs_DB::_showDBComponentWarning($conn, $returnType);
							return $res;
						}
					}
				} else {
					$conn = RvsLibs_DB::testConnectRemote($aConnectData, null, null, $conn);
					if (SGL::isError($conn) === true) {
						$res = RvsLibs_DB::_showDBComponentWarning($conn, $returnType);
						return $res;
					} else {
						$host = SGL_Config::get('componentdbremote.host');
						if ($host != '' && $host != 'localhost') {
							$aConnectData['HostName'] = $host;
							$aConnectData['protocol'] = 'tcp';
							RvsLibs_Component::writeDBConfig($aConnectData, $projectId);
							SGL_Error::pop();
						}
					}
				}
			}
		}

		public static function testConnectRemote($aConnectData, $databaseUsername = null, $databaseName = null, $conn = null)
		{
			$host = SGL_Config::get('componentdbremote.host');
			SGL::logMessage("Remote host : " . $host, PEAR_LOG_DEBUG);
			if ($host != '' && $host != 'localhost') {
				$databaseUsername = (is_null($databaseUsername) === false) ? $databaseUsername : $aConnectData['UserName'];
				$databaseName = (is_null($databaseName) === false) ? $databaseName :  $aConnectData['DatabaseName'];
				$conn = RvsLibs_DB::multiDBConnection($aConnectData['Port'], $databaseUsername , $aConnectData['Password'] , $databaseName , 'mysql' , $host, false);
				return $conn;
			}
			return (is_null($conn)) ? true : $conn;
		}

		public static function _showDBComponentWarning($db, $returnType='RAISE_MSG')
		{
			$req = SGL_Request::singleton();
			$managerName = $req->get('managerName');
			$errorMsg = $db->getMessage();
			$errorMsg .= "<br>" . $db->getUserinfo();
			// sitebuilder 5 fix redirect to  CreateDBforComponent by duangdao.k
			$errorMsg .= RvsLibs_DB::getDatabaseEditURL();

			$errorMsg .= "<br>" . RvsLibs_String::translate('Cannot connect to your component database.');
			$errorMsg .= " " . RvsLibs_String::translate('Click here to open your configuration.','vprintf' , array('UrlSystemDB' => SGL_Output::makeUrl(null, 'CreateDBforComponent', 'sitebuilder')));

			/*$errorMsg .= "<br>" . RvsLibs_String::translate('After finished above,') . "<a href=\"" . SGL_Output::makeUrl(null, 'CreateDBforComponent', 'sitebuilder') . "\">"
				. RvsLibs_String::translate('please edit database based component settings here.') . "</a>";
			*/

			SGL_Error::pop();
			switch ($returnType) {
				case 'RAISE_MSG':
					SGL::raiseMsg( RvsLibs_String::translate('Test Component Database Error','vprintf' , array('errormsg' => $errorMsg)), false);;
					break;
				case 'TEXT':
					return $errorMsg;
					break;
				default:
					SGL::raiseMsg( RvsLibs_String::translate('Test Component Database Error','vprintf' , array('errormsg' => $errorMsg)), false);;
					break;
			}
		}

		/**
		 * return URL to edit database
		 *
		 * @return unknown
		 */
		public static function getDatabaseEditURL()
		{
		    ///Debug SGL::logMessage(null, PEAR_LOG_DEBUG);
		    /* modify CpHendle by nipaporn*/
		    $oCp = CpHandle::factory();
		    if(SGL::isError($oCp) === true) {
		    	return $oCp;
		    }
		    return $oCp->getDatabaseEditURL();
		}

		/**
		 * check mysql support charset
		 *
		 * @param string $projectId
		 * @return return true - supportCharset
		 *                false - not support Charset
		 */
		public static function verifyMySqlSupportCharset($projectId)
		{
			SGL::logMessage(null, PEAR_LOG_DEBUG);
			$aOutput = array();
			$aOutput['status'] = 'false';
			$aOutput['boolStatus'] = false;
			//charset before set name
			$oldDBCharset = mysql_result(mysql_query("SELECT @@character_set_results"),0,0);
			//charset  table
			$projectDbCharset = RvsLibs_Project::getProjectDBCharset($projectId);
			SGL::logMessage('projectDbCharset:' . $projectDbCharset, PEAR_LOG_DEBUG);
			$aOutput['lang'] = $projectDbCharset;
			$res = mysql_query("SET NAMES {$projectDbCharset}");
			SGL::logMessage("SET NAMES {$projectDbCharset}", PEAR_LOG_DEBUG);
			SGL::logMessage("SET NAMES res:" . $res, PEAR_LOG_DEBUG);
			// charset after set name
			$newDBProjectCharset = mysql_result(mysql_query("SELECT @@character_set_results"),0,0);
			SGL::logMessage("newDBProjectCharset:" . $newDBProjectCharset, PEAR_LOG_DEBUG);
			if ($newDBProjectCharset == $projectDbCharset) {
				$aOutput['status'] = 'true';
				$aOutput['boolStatus'] = true;
			}
			SGL::logMessage("verifyCharset:" . $aOutput['status'], PEAR_LOG_DEBUG);
			// set name default
			mysql_query("SET NAMES {$oldDBCharset}");
			return $aOutput;
		}

	 public static function getMsgDbError($projectId, $rvsUsrId, $ownerId, $showRaiseError = null)
	 {
	 	SGL::logMessage(null, PEAR_LOG_DEBUG);
	 	$aCompoDB = RvsLibs_Component::getComponentUserDB($projectId, $rvsUsrId, $ownerId);
	 	$isCombo = (count($aCompoDB))? true : false;
	 	$showMsgErr = (is_null($showRaiseError))? $isCombo : $showRaiseError;
        // check is compodb get db
	 	if ($isCombo === true) {
	 		$aData = RvsLibs_Component::getDBInfoOfCompoDB($projectId);
	 	 if (SGL::isError($aData) === false && isset($aData['DatabaseName']) && $aData['DatabaseName'] != "" ) {
	 	 	return RvsLibs_DB::multiDBConnection($aData['Port'], $aData['UserName'], $aData['Password'], $aData['DatabaseName'], 'mysql', $aData['HostName'], $showMsgErr);
	 	 }
	 	}
	 }

	 /**
	  *
	  * @param String $tableName
	  * @param Array $aValues
	  * @param Array $aField fielde ที่ต้องการ INSERT ถ้าเป็น array ว่าง INSERT ทุก field ใน ตาราง
	  * @param String $commandType default is INSERT INTO
	  * @return String SQL command
	  */
	 public static function genInsertSqlCommand($tableName, $aValues , $aField = array(), $commandType='INSERT INTO')
	 {
	     if (is_array($aValues) === false && count($aValues) <= 0) return '';
	     if (is_array($aField) && count($aField) > 0) {
	         $tableName = $tableName . ' (' . implode(',', $aField) . ')';
	     }
	     return $commandType . ' ' . $tableName . " VALUES ('" . implode("','", $aValues) . "');";
	 }

	 public static function changeKeyTableInfo($obj, $dbType, $field=null) {
	 	$dbType = is_null($dbType) || ($dbType == '') ? 'db' : $dbType;
	 	switch (RvsLibs_String::strtolower($dbType)) {
	 		case 'db':
	 			$data = (object)array_change_key_case((array)$obj);
	 			break;
	 		case 'mdb2':
	 			$data = $obj;
	 			break;
	 	}
	 	if (is_null($field) === false && ($field != '')) {
	 		$field = RvsLibs_String::strtolower($field);
	 		return $data->$field;
	 	}
	 	unset($obj, $dbType, $field);
	 	return $data;
	 }

	 /**
	  * get from
	  /etc/my.cnf
	  /root/.my.cnf

	  wait_timeout = 200
	  connect_timeout = 200

	  * @return number
	  */
	 public static function getSqlWaitTimeout()
	 {
	 	$locator = SGL_ServiceLocator::singleton();
	 	$dbh = $locator->get('DB');
	 	$waitTimeout = 10;
	 	$sessionWaitTime = $dbh->getRow('SHOW SESSION VARIABLES LIKE \'wait_timeout\'');
	 	if (SGL::isError($sessionWaitTime)) {
	 		SGL_Error::pop();
	 	}
	 	if (isset($sessionWaitTime->value)) {
	 		$waitTimeout = $sessionWaitTime->value;
	 	} else {
	 		$globalWaitTime = $dbh->getRow('SHOW GLOBAL VARIABLES LIKE \'wait_timeout\'');
	 		if (SGL::isError($globalWaitTime)) {
	 			SGL_Error::pop();
	 		}
	 		if (isset($globalWaitTime->value)) {
	 			$waitTimeout = $globalWaitTime->value;
	 		}
	 	}
	 	return $waitTimeout;
	 }

	 /**
	  * connect_timeout = 200
	  * @return number
	  */
	 public static function getSqlConnectTimeout()
	 {
	 	$locator = SGL_ServiceLocator::singleton();
	 	$dbh = $locator->get('DB');
	 	$connectTimeout = 10;
	 	$sessionConnectTime = $dbh->getRow('SHOW SESSION VARIABLES LIKE \'connect_timeout\'');
	 	if (SGL::isError($sessionConnectTime)) {
	 		SGL_Error::pop();
	 	}
	 	if (isset($sessionConnectTime->value)) {
	 		$connectTimeout = $sessionConnectTime->value;
	 	} else {
	 		$globalConnectTime = $dbh->getRow('SHOW GLOBAL VARIABLES LIKE \'connect_timeout\'');
	 		if (SGL::isError($globalConnectTime)) {
	 			SGL_Error::pop();
	 		}
	 		if (isset($globalConnectTime->value)) {
	 			$connectTimeout = $globalConnectTime->value;
	 		}
	 	}
	 	return $connectTimeout;
	 }

	}
}
?>

Copyright 2K16 - 2K18 Indonesian Hacker Rulez