From bb95345fb24095a919c9901222e89f2dca8b8d4e Mon Sep 17 00:00:00 2001 From: ucorina Date: Thu, 18 Aug 2011 17:55:29 +0000 Subject: [PATCH] Updated DB classes to support multiple database connection strings - for when replication is used. git-svn-id: http://xe-core.googlecode.com/svn/branches/1.5.0@8808 201d5d3c-b55e-5fd7-737f-ddc643e51545 --- classes/context/Context.class.php | 23 +- classes/db/DB.class.php | 359 ++++++++++++------------- classes/db/DBCubrid.class.php | 104 +++---- classes/db/DBFirebird.class.php | 186 ++++++------- classes/db/DBMssql.class.php | 152 ++++------- classes/db/DBMysql.class.php | 93 +++---- classes/db/DBMysql_innodb.class.php | 44 ++- classes/db/DBMysqli.class.php | 58 ++-- classes/db/DBPostgresql.class.php | 96 +++---- classes/db/DBSqlite3_pdo.class.php | 14 +- classes/module/ModuleHandler.class.php | 52 ++-- modules/install/install.controller.php | 75 ++++-- 12 files changed, 576 insertions(+), 680 deletions(-) diff --git a/classes/context/Context.class.php b/classes/context/Context.class.php index 1b54dc41d..cb305009d 100644 --- a/classes/context/Context.class.php +++ b/classes/context/Context.class.php @@ -218,6 +218,27 @@ class Context { $config_file = $self->getConfigFile(); if(is_readable($config_file)) @include($config_file); + // If master_db information does not exist, the config file needs to be updated + if(!isset($db_info->master_db)) { + $db_info->master_db = array(); + $db_info->master_db["db_type"] = $db_info->db_type; unset($db_info->db_type); + $db_info->master_db["db_port"] = $db_info->db_port; unset($db_info->db_port); + $db_info->master_db["db_hostname"] = $db_info->db_hostname; unset($db_info->db_hostname); + $db_info->master_db["db_password"] = $db_info->db_password; unset($db_info->db_password); + $db_info->master_db["db_database"] = $db_info->db_database; unset($db_info->db_database); + $db_info->master_db["db_userid"] = $db_info->db_userid; unset($db_info->db_userid); + $db_info->master_db["db_table_prefix"] = $db_info->db_table_prefix; unset($db_info->db_table_prefix); + if(substr($db_info->master_db["db_table_prefix"],-1)!='_') $db_info->master_db["db_table_prefix"] .= '_'; + + $slave_db = $db_info->master_db; + $db_info->slave_db = array($slave_db); + + $self->setDBInfo($db_info); + + $oInstallController = &getController('install'); + $oInstallController->makeConfigFile(); + } + if(!$db_info->time_zone) $db_info->time_zone = date("O"); $GLOBALS['_time_zone'] = $db_info->time_zone; @@ -239,7 +260,7 @@ class Context { **/ function getDBType() { is_a($this,'Context')?$self=&$this:$self=&Context::getInstance(); - return $self->db_info->db_type; + return $self->db_info->master_db["db_type"]; } /** diff --git a/classes/db/DB.class.php b/classes/db/DB.class.php index 3717f4965..e49e200a6 100644 --- a/classes/db/DB.class.php +++ b/classes/db/DB.class.php @@ -47,7 +47,8 @@ 'null' => 'is null', ); - var $fd = NULL; ///< connector resource or file description + var $master_db = NULL; // master database connection string + var $slave_db = NULL; // array of slave databases connection strings var $result = NULL; ///< result @@ -202,8 +203,9 @@ * @brief check if is connected * @return true: connected, false: not connected **/ - function isConnected() { - return $this->is_connected ? true : false; + function isConnected($type = 'master', $indx = 0) { + if($type == 'master') return $this->master_db["is_connected"] ? true : false; + else return $this->slave_db[$indx]["is_connected"] ? true : false; } /** @@ -309,7 +311,7 @@ * @return result of query * @remarks this function finds xml file or cache file of $query_id, compiles it and then execute it **/ - function executeQuery($query_id, $args = NULL, $arg_columns = NULL) { + function executeQuery($query_id, $args = NULL, $arg_columns = NULL, $database_type = 'master') { if(!$query_id) return new Object(-1, 'msg_invalid_queryid'); $this->query_id = $query_id; @@ -333,7 +335,7 @@ $cache_file = $this->checkQueryCacheFile($query_id, $xml_file); // execute query - return $this->_executeQuery($cache_file, $args, $query_id, $arg_columns); + return $this->_executeQuery($cache_file, $args, $query_id, $arg_columns, $database_type); } @@ -369,7 +371,7 @@ * @param[in] $query_id query id * @return result of query **/ - function _executeQuery($cache_file, $source_args, $query_id, $arg_columns) { + function _executeQuery($cache_file, $source_args, $query_id, $arg_columns, $database_type) { global $lang; if(!file_exists($cache_file)) return new Object(-1, 'msg_invalid_queryid'); @@ -397,7 +399,8 @@ case 'select' : $arg_columns = is_array($arg_columns)?$arg_columns:array(); $output->setColumnList($arg_columns); - $output = $this->_executeSelectAct($output); + $connection = $this->_getConnection('slave'); + $output = $this->_executeSelectAct($output, $connection); break; } @@ -580,192 +583,170 @@ return new DBParser('"'); } - - // TO BE REMOVED - Used for query compare - /** - * @brief returns type of column - * @param[in] $column_type_list list of column type - * @param[in] $name name of column type - * @return column type of $name - * @remarks columns are usually like a.b, so it needs another function - **/ - function getColumnType($column_type_list, $name) { - if(strpos($name, '.') === false) return $column_type_list[$name]; - list($prefix, $name) = explode('.', $name); - return $column_type_list[$name]; - } - /** - * @brief returns the value of condition - * @param[in] $name name of condition - * @param[in] $value value of condition - * @param[in] $operation operation this is used in condition - * @param[in] $type type of condition - * @param[in] $column_type type of column - * @return well modified $value - * @remarks if $operation is like or like_prefix, $value itself will be modified - * @remarks if $type is not 'number', call addQuotes() and wrap with ' ' - **/ - function getConditionValue($name, $value, $operation, $type, $column_type) { - if(!in_array($operation,array('in','notin','between')) && $type == 'number') { - if(is_array($value)){ - $value = join(',',$value); - } - if(strpos($value, ',') === false && strpos($value, '(') === false) return (int)$value; - return $value; - } - - if(!is_array($value) && strpos($name, '.') !== false && strpos($value, '.') !== false) { - list($table_name, $column_name) = explode('.', $value); - if($column_type[$column_name]) return $value; - } - - switch($operation) { - case 'like_prefix' : - if(!is_array($value)) $value = preg_replace('/(^\'|\'$){1}/', '', $value); - $value = $value.'%'; - break; - case 'like_tail' : - if(!is_array($value)) $value = preg_replace('/(^\'|\'$){1}/', '', $value); - $value = '%'.$value; - break; - case 'like' : - if(!is_array($value)) $value = preg_replace('/(^\'|\'$){1}/', '', $value); - $value = '%'.$value.'%'; - break; - case 'notin' : - if(is_array($value)) - { - $value = $this->addQuotesArray($value); - if($type=='number') return join(',',$value); - else return "'". join("','",$value)."'"; - } - else - { - return $value; - } - break; - case 'in' : - if(is_array($value)) - { - $value = $this->addQuotesArray($value); - if($type=='number') return join(',',$value); - else return "'". join("','",$value)."'"; - } - else - { - return $value; - } - break; - case 'between' : - if(!is_array($value)) $value = array($value); - $value = $this->addQuotesArray($value); - if($type!='number') - { - foreach($value as $k=>$v) - { - $value[$k] = "'".$v."'"; - } - } - - return $value; - break; - default: - if(!is_array($value)) $value = preg_replace('/(^\'|\'$){1}/', '', $value); - } - - return "'".$this->addQuotes($value)."'"; - } - /** - * @brief returns part of condition - * @param[in] $name name of condition - * @param[in] $value value of condition - * @param[in] $operation operation that is used in condition - * @return detail condition - **/ - function getConditionPart($name, $value, $operation) { - switch($operation) { - case 'equal' : - case 'more' : - case 'excess' : - case 'less' : - case 'below' : - case 'like_tail' : - case 'like_prefix' : - case 'like' : - case 'in' : - case 'notin' : - case 'notequal' : - // if variable is not set or is not string or number, return - if(!isset($value)) return; - if($value === '') return; - if(!in_array(gettype($value), array('string', 'integer'))) return; - break; - case 'between' : - if(!is_array($value)) return; - if(count($value)!=2) return; - - } - - switch($operation) { - case 'equal' : - return $name.' = '.$value; - break; - case 'more' : - return $name.' >= '.$value; - break; - case 'excess' : - return $name.' > '.$value; - break; - case 'less' : - return $name.' <= '.$value; - break; - case 'below' : - return $name.' < '.$value; - break; - case 'like_tail' : - case 'like_prefix' : - case 'like' : - return $name.' like '.$value; - break; - case 'in' : - return $name.' in ('.$value.')'; - break; - case 'notin' : - return $name.' not in ('.$value.')'; - break; - case 'notequal' : - return $name.' <> '.$value; - break; - case 'notnull' : - return $name.' is not null'; - break; - case 'null' : - return $name.' is null'; - break; - case 'between' : - return $name.' between ' . $value[0] . ' and ' . $value[1]; - break; - } + function _getSlaveConnectionStringIndex() { + $max = count($this->slave_db); + $indx = rand(0, $max - 1); + return $indx; } - /** - * @brief returns condition key - * @param[in] $output result of query - * @return array of conditions of $output - **/ - function getConditionList($output) { - $conditions = array(); - if(count($output->conditions)) { - foreach($output->conditions as $key => $val) { - if($val['condition']) { - foreach($val['condition'] as $k => $v) { - $conditions[] = $v['column']; - } - } - } + function _getConnection($type = 'master', $indx = NULL){ + if($type == master){ + if(!$this->master_db['is_connected']) + $this->_connect($type); + return $this->master_db["resource"]; } - return $conditions; + if($indx === NULL) + $indx = $this->_getSlaveConnectionStringIndex($type); + + if(!$this->slave_db[$indx]['is_connected']) + $this->_connect($type, $indx); + return $this->slave_db[$indx]["resource"]; } + + function _dbInfoExists() { + if (!$this->master_db) + return false; + if (count($this->slave_db) === 0) + return false; + return true; + } + + function _close($connection){ + + } + + /** + * @brief DB disconnection + * */ + function close($type = 'master', $indx = 0) { + if (!$this->isConnected($type, $indx)) + return; + + if ($type == 'master') + $connection = &$this->master_db; + else + $connection = &$this->slave_db[$indx]; + + $this->_close($connection["resource"]); + + $connection["is_connected"] = false; + } + + function _begin(){ + return true; + } + /** + * @brief Begin transaction + * */ + function begin() { + if (!$this->isConnected() || $this->transaction_started) + return; + + if($this->_begin()) + $this->transaction_started = true; + } + + function _rollback(){ + return true; + } + + /** + * @brief Rollback + * */ + function rollback() { + if (!$this->isConnected() || !$this->transaction_started) + return; + if($this->_rollback()) + $this->transaction_started = false; + } + + function _commit(){ + return true; + } + /** + * @brief Commits + * */ + function commit($force = false) { + if (!$force && (!$this->isConnected() || !$this->transaction_started)) + return; + if($this->_commit()) + $this->transaction_started = false; + } + + function __query($query, $connection){ + + } + /** + * @brief : Run a query and fetch the result + * + * query: run a query and return the result \n + * fetch: NULL if no value is returned \n + * array object if rows are returned \n + * object if a row is returned \n + * return\n + * */ + function _query($query, $connection = null) { + if($connection == null) + $connection = $this->_getConnection('master'); + // Notify to start a query execution + $this->actStart($query); + + // Run the query statement + $result = $this->__query($query, $connection); + + // Notify to complete a query execution + $this->actFinish(); + // Return result + return $result; + } + + /** + * @brief DB settings and connect/close + * */ + function _setDBInfo(){ + $db_info = Context::getDBInfo(); + $this->master_db = $db_info->master_db; + $this->slave_db = $db_info->slave_db; + $this->prefix = $db_info->master_db["db_table_prefix"]; + } + + function __connect(){ + + } + + function _afterConnect($connection){ + + } + /** + * @brief DB Connection + * */ + function _connect($type = 'master', $indx = 0) { + if ($this->isConnected($type, $indx)) + return; + + // Ignore if no DB information exists + if (!$this->_dbInfoExists()) + return; + + if ($type == 'master') + $connection = &$this->master_db; + else + $connection = &$this->slave_db[$indx]; + + $result = $this->__connect($connection); + if($result === NULL || $result === false) { + $connection["is_connected"] = false; + return; + } + + // Check connections + $connection["resource"] = $result; + $connection["is_connected"] = true; + + $this->_afterConnect($result); + } + + } ?> diff --git a/classes/db/DBCubrid.class.php b/classes/db/DBCubrid.class.php index 948da154c..09f203caf 100644 --- a/classes/db/DBCubrid.class.php +++ b/classes/db/DBCubrid.class.php @@ -16,12 +16,7 @@ /** * @brief CUBRID DB connection information **/ - var $hostname = '127.0.0.1'; ///< hostname - var $userid = NULL; ///< user id - var $password = NULL; ///< password - var $database = NULL; ///< database - var $port = 33000; ///< db server port - var $prefix = 'xe'; // / hostname = $db_info->db_hostname; - $this->userid = $db_info->db_userid; - $this->password = $db_info->db_password; - $this->database = $db_info->db_database; - $this->port = $db_info->db_port; - $this->prefix = $db_info->db_table_prefix; - - if (!substr($this->prefix, -1) != '_') $this->prefix .= '_'; - } - /** * @brief DB Connection **/ - function _connect() + function __connect($connection) { - // ignore if db information not exists - if (!$this->hostname || !$this->userid || !$this->password || !$this->database || !$this->port) return; - - // attempts to connect - $this->fd = @cubrid_connect ($this->hostname, $this->port, $this->database, $this->userid, $this->password); + // attempts to connect + $result = @cubrid_connect($connection["db_hostname"], $connection["db_port"], $connection["db_database"], $connection["db_userid"], $connection["db_password"]); // check connections - if (!$this->fd) { + if (!$result) { $this->setError (-1, 'database connect fail'); - return $this->is_connected = false; + return; } - - $this->is_connected = true; - $this->password = md5 ($this->password); + return $result; } /** * @brief DB disconnect **/ - function close() + function _close($connection) { - if (!$this->isConnected ()) return; - - @cubrid_commit ($this->fd); - @cubrid_disconnect ($this->fd); + @cubrid_commit ($connection); + @cubrid_disconnect ($connection); $this->transaction_started = false; } @@ -123,8 +95,6 @@ **/ function addQuotes($string) { - if (!$this->fd) return $string; - if (version_compare (PHP_VERSION, "5.9.0", "<") && get_magic_quotes_gpc ()) { $string = stripslashes (str_replace ("\\","\\\\", $string)); @@ -149,32 +119,29 @@ /** * @brief Begin transaction **/ - function begin() + function _begin() { - if (!$this->isConnected () || $this->transaction_started) return; - $this->transaction_started = true; + return true; } /** * @brief Rollback **/ - function rollback() + function _rollback() { - if (!$this->isConnected () || !$this->transaction_started) return; - @cubrid_rollback ($this->fd); - $this->transaction_started = false; + $connection = $this->_getConnection('master'); + @cubrid_rollback ($connection); + return true; } /** * @brief Commit **/ - function commit() + function _commit() { - if (!$force && (!$this->isConnected () || - !$this->transaction_started)) return; - - @cubrid_commit($this->fd); - $this->transaction_started = false; + $connection = $this->_getConnection('master'); + @cubrid_commit($connection); + return true; } /** @@ -186,15 +153,10 @@ * object if a row returned \n * return\n **/ - function _query($query) + function __query($query, $connection) { - if (!$query || !$this->isConnected ()) return; - - // Notify to start a query execution - $this->actStart ($query); - // Execute the query - $result = @cubrid_execute ($this->fd, $query); + $result = @cubrid_execute ($connection, $query); // error check if (cubrid_error_code ()) { $code = cubrid_error_code (); @@ -202,10 +164,6 @@ $this->setError ($code, $msg); } - - // Notify to complete a query execution - $this->actFinish (); - // Return the result return $result; } @@ -583,7 +541,7 @@ $result = $this->_query ($query); if ($result && !$this->transaction_started) { - @cubrid_commit ($this->fd); + $this->_commit(); } return $result; @@ -599,7 +557,7 @@ $result = $this->_query($query); - if ($result && !$this->transaction_started) @cubrid_commit ($this->fd); + if ($result && !$this->transaction_started) $this->_commit(); return $result; } @@ -615,7 +573,7 @@ $result = $this->_query ($query); - if ($result && !$this->transaction_started) @cubrid_commit ($this->fd); + if ($result && !$this->transaction_started) $this->_commit(); return $result; } @@ -626,17 +584,17 @@ * to get a specific page list easily in select statement,\n * a method, navigation, is used **/ - function _executeSelectAct($queryObject){ + function _executeSelectAct($queryObject, $connection = null){ $query = $this->getSelectSql($queryObject); if(is_a($query, 'Object')) return; $query .= (__DEBUG_QUERY__&1 && $queryObject->query_id)?sprintf (' '.$this->comment_syntax, $this->query_id):''; - $result = $this->_query ($query); + $result = $this->_query ($query, $connection); if ($this->isError ()) return $this->queryError($queryObject); else - return $this->queryPageLimit($queryObject, $result); + return $this->queryPageLimit($queryObject, $result, $connection); } function queryError($queryObject){ @@ -652,7 +610,7 @@ return; } - function queryPageLimit($queryObject, $result){ + function queryPageLimit($queryObject, $result, $connection){ if ($queryObject->getLimit() && $queryObject->getLimit()->isPageHandler()) { // Total count @@ -662,7 +620,7 @@ } $count_query .= (__DEBUG_QUERY__&1 && $queryObject->query_id)?sprintf (' '.$this->comment_syntax, $this->query_id):''; - $result = $this->_query($count_query); + $result = $this->_query($count_query, $connection); $count_output = $this->_fetch($result); $total_count = (int)$count_output->count; @@ -687,7 +645,7 @@ $query = $this->getSelectPageSql($queryObject, true, $start_count, $list_count); $query .= (__DEBUG_QUERY__&1 && $queryObject->query_id)?sprintf (' '.$this->comment_syntax, $this->query_id):''; - $result = $this->_query ($query); + $result = $this->_query ($query, $connection); if ($this->isError ()) return $this->queryError($queryObject); diff --git a/classes/db/DBFirebird.class.php b/classes/db/DBFirebird.class.php index b70bcecb6..af5f2c504 100644 --- a/classes/db/DBFirebird.class.php +++ b/classes/db/DBFirebird.class.php @@ -13,13 +13,9 @@ /** * @brief connection to Firebird DB **/ - var $hostname = '127.0.0.1'; ///< hostname - var $userid = NULL; ///< user id - var $password = NULL; ///< password - var $database = NULL; ///< database - var $prefix = 'xe'; // / hostname = $db_info->db_hostname; - $this->port = $db_info->db_port; - $this->userid = $db_info->db_userid; - $this->password = $db_info->db_password; - $this->database = $db_info->db_database; - $this->prefix = $db_info->db_table_prefix; - if(!substr($this->prefix,-1)!='_') $this->prefix .= '_'; - } - /** * @brief DB Connection **/ - function _connect() { - // ignore if db information not exists - if(!$this->hostname || !$this->port || !$this->userid || !$this->password || !$this->database) return; - + function __connect($connection) { //if(strpos($this->hostname, ':')===false && $this->port) $this->hostname .= ':'.$this->port; // attempts to connect - $host = $this->hostname."/".$this->port.":".$this->database; + $host = $connection["db_hostname"]."/".$connection["db_port"].":".$connection["db_database"]; - $this->fd = ibase_connect($host, $this->userid, $this->password); + $result = ibase_connect($host, $connection["db_userid"], $connection["db_password"]); if(ibase_errmsg()) { $this->setError(ibase_errcode(), ibase_errmsg()); - return $this->is_connected = false; + return; } // Error when Firebird version is lower than 2.0 - if (($service = ibase_service_attach($this->hostname, $this->userid, $this->password)) != FALSE) { + if (($service = ibase_service_attach($connection["db_hostname"], $connection["db_userid"], $connection["db_password"])) != FALSE) { // get server version and implementation strings $server_info = ibase_server_info($service, IBASE_SVC_SERVER_VERSION); ibase_service_detach($service); } else { $this->setError(ibase_errcode(), ibase_errmsg()); - ibase_close($this->fd); - return $this->is_connected = false; + ibase_close($result); + return; } $pos = strpos($server_info, "Firebird"); @@ -112,22 +91,18 @@ if($ver < "2.0") { $this->setError(-1, "XE cannot be installed under the version of firebird 2.0. Current firebird version is ".$ver); - ibase_close($this->fd); - return $this->is_connected = false; + ibase_close($result); + return; } - // Check connections - $this->is_connected = true; - $this->password = md5($this->password); + return $result; } /** * @brief DB disconnect **/ - function close() { - if(!$this->isConnected()) return; - ibase_commit($this->fd); - ibase_close($this->fd); - $this->transaction_started = false; + function _close($connection) { + ibase_commit($connection); + ibase_close($connection); } /** @@ -252,27 +227,26 @@ /** * @brief Begin transaction **/ - function begin() { - if(!$this->isConnected() || $this->transaction_started) return; - $this->transaction_started = true; + function _begin() { + return true; } /** * @brief Rollback **/ - function rollback() { - if(!$this->isConnected() || !$this->transaction_started) return; - ibase_rollback($this->fd); - $this->transaction_started = false; + function _rollback() { + $connection = $this->_getConnection('master'); + ibase_rollback($connection); + return true; } /** * @brief Commits **/ - function commit() { - if(!$force && (!$this->isConnected() || !$this->transaction_started)) return; - ibase_commit($this->fd); - $this->transaction_started = false; + function _commit() { + $connection = $this->_getConnection('master'); + ibase_commit($connection); + return true; } /** @@ -284,41 +258,31 @@ * object if a row returned \n * return\n **/ - function _query($query, $params=null) { - if(!$this->isConnected()) return; - + function __query($query, $connection, $params = null) { if(count($params) == 0) { - // Notify to start a query execution - $this->actStart($query); // Execute the query statement - $result = ibase_query($this->fd, $query); + $result = ibase_query($connection, $query); } else { - // Notify to start a query execution - $log = $query."\n\t\t\t"; - $log .= implode(",", $params); - $this->actStart($log); // Execute the query(for blob type) - $query = ibase_prepare($this->fd, $query); + $query = ibase_prepare($connection, $query); //$fnarr = array_merge(array($query), $params); $result = ibase_execute($query); } // Error Check if(ibase_errmsg()) $this->setError(ibase_errcode(), ibase_errmsg()); - // Notify to complete a query execution - $this->actFinish(); - // Return the result + return $result; } - function _queryInsertUpdateDeleteSelect($query, $params=null) { - if(!$this->isConnected()) return; + function _queryInsertUpdateDeleteSelect($query, $params=null, $connection) { + if(!$connection) return; if(count($params) == 0) { // Notify to start a query execution $this->actStart($query); // Execute the query statement - $trans = ibase_trans(IBASE_DEFAULT,$this->fd); + $trans = ibase_trans(IBASE_DEFAULT,$connection); $result = ibase_query($trans, $query); ibase_commit($trans); unset($trans); @@ -329,7 +293,7 @@ $log .= implode(",", $params); $this->actStart($log); // Execute the query(for blob type) - $query = ibase_prepare($this->fd, $query); + $query = ibase_prepare($connection, $query); //$fnarr = array_merge(array($query), $params); $result = ibase_execute($query); } @@ -340,7 +304,7 @@ // Return the result return $result; } - + function getTableInfo($result){ $coln = ibase_num_fields($result); $column_type = array(); @@ -424,11 +388,12 @@ $query = sprintf("select rdb\$relation_name from rdb\$relations where rdb\$system_flag=0 and rdb\$relation_name = '%s%s';", $this->prefix, $target_name); $result = $this->_query($query); $tmp = $this->_fetch($result); + $connection = $this->_getConnection('master'); if(!$tmp) { - if(!$this->transaction_started) ibase_rollback($this->fd); + if(!$this->transaction_started) ibase_rollback($connection); return false; } - if(!$this->transaction_started) ibase_commit($this->fd); + if(!$this->transaction_started) ibase_commit($connection); return true; } @@ -449,7 +414,11 @@ if($notnull) $query .= " NOT NULL "; $this->_query($query); - if(!$this->transaction_started) ibase_commit($this->fd); + + if(!$this->transaction_started) { + $connection = $this->_getConnection('master'); + ibase_commit($connection); + } } /** @@ -458,7 +427,11 @@ function dropColumn($table_name, $column_name) { $query = sprintf("alter table %s%s drop %s ", $this->prefix, $table_name, $column_name); $this->_query($query); - if(!$this->transaction_started) ibase_commit($this->fd); + if(!$this->transaction_started) { + $connection = $this->_getConnection('master'); + ibase_commit($connection); + } + } @@ -468,13 +441,15 @@ function isColumnExists($table_name, $column_name) { $query = sprintf("SELECT RDB\$FIELD_NAME as \"FIELD\" FROM RDB\$RELATION_FIELDS WHERE RDB\$RELATION_NAME = '%s%s'", $this->prefix, $table_name); $result = $this->_query($query); + $connection = $this->_getConnection('master'); + if($this->isError()) { - if(!$this->transaction_started) ibase_rollback($this->fd); + if(!$this->transaction_started) ibase_rollback($connection); return false; } $output = $this->_fetch($result); - if(!$this->transaction_started) ibase_commit($this->fd); + if(!$this->transaction_started) ibase_commit($connection); if($output) { $column_name = strtolower($column_name); @@ -500,7 +475,8 @@ $query = sprintf('CREATE %s INDEX "" ON "%s%s" ("%s");', $is_unique?'UNIQUE':'', $this->prefix, $table_name, implode('", "',$target_columns)); $this->_query($query); - if(!$this->transaction_started) ibase_commit($this->fd); + $connection = $this->_getConnection('master'); + if(!$this->transaction_started) ibase_commit($connection); } /** @@ -510,7 +486,8 @@ $query = sprintf('DROP INDEX "%s" ON "%s%s"', $index_name, $this->prefix, $table_name); $this->_query($query); - if(!$this->transaction_started) ibase_commit($this->fd); + $connection = $this->_getConnection('master'); + if(!$this->transaction_started) ibase_commit($connection); } @@ -537,11 +514,15 @@ $output = $this->_fetch($result); if(!$output) { - if(!$this->transaction_started) ibase_rollback($this->fd); + $connection = $this->_getConnection('master'); + if(!$this->transaction_started) ibase_rollback($connection); return false; } - if(!$this->transaction_started) ibase_commit($this->fd); + if(!$this->transaction_started) { + $connection = $this->_getConnection('master'); + ibase_commit($connection); + } if(!is_array($output)) $output = array($output); for($i=0;$i_query($schema); - if(!$this->transaction_started) ibase_commit($this->fd); + if(!$this->transaction_started) { + $connection = $this->_getConnection('master'); + ibase_commit($connection); + } if(!$output) return false; if(count($index_list)) { @@ -641,7 +625,10 @@ $schema = sprintf("CREATE INDEX \"\" ON \"%s\" (\"%s\");", $table_name, implode($val, "\",\"")); $output = $this->_query($schema); - if(!$this->transaction_started) ibase_commit($this->fd); + if(!$this->transaction_started) { + $connection = $this->_getConnection('master'); + ibase_commit($connection); + } if(!$output) return false; } } @@ -649,7 +636,10 @@ if($_GLOBALS['XE_EXISTS_SEQUENCE']) return; $schema = 'CREATE GENERATOR GEN_XE_SEQUENCE_ID;'; $output = $this->_query($schema); - if(!$this->transaction_started) ibase_commit($this->fd); + if(!$this->transaction_started) { + $connection = $this->_getConnection('master'); + ibase_commit($connection); + } if(!$output) return false; $_GLOBALS['XE_EXISTS_SEQUENCE'] = true; /*if($auto_increment_list) @@ -711,7 +701,7 @@ * In order to get a list of pages easily when selecting \n * it supports a method as navigation **/ - function _executeSelectAct($queryObject) { + function _executeSelectAct($queryObject, $connection) { $query = $this->getSelectSql($queryObject); if(strpos($query, "substr")) { $query = str_replace ("substr", "substring", $query); @@ -719,10 +709,10 @@ } if(is_a($query, 'Object')) return; $query .= (__DEBUG_QUERY__&1 && $queryObject->query_id)?sprintf(' '.$this->comment_syntax,$this->query_id):''; - $result = $this->_queryInsertUpdateDeleteSelect ($query); + $result = $this->_queryInsertUpdateDeleteSelect ($query, null, $connection); if ($this->isError ()) return $this->queryError($queryObject); - else return $this->queryPageLimit($queryObject, $result); + else return $this->queryPageLimit($queryObject, $result, $connection); } function queryError($queryObject) { @@ -737,7 +727,7 @@ return; } - function queryPageLimit($queryObject, $result) { + function queryPageLimit($queryObject, $result, $connection) { if ($queryObject->getLimit() && $queryObject->getLimit()->isPageHandler()) { // Total count $count_query = sprintf('select count(*) as "count" %s %s', 'FROM ' . $queryObject->getFromString(), ($queryObject->getWhereString() === '' ? '' : ' WHERE ' . $queryObject->getWhereString())); @@ -746,7 +736,7 @@ } $count_query .= ( __DEBUG_QUERY__ & 1 && $output->query_id) ? sprintf(' ' . $this->comment_syntax, $this->query_id) : ''; - $result_count = $this->_query($count_query); + $result_count = $this->_query($count_query, null, $connection); $count_output = $this->_fetch($result_count); $total_count = (int) $count_output->count; @@ -762,23 +752,23 @@ if($page > $total_page) $page = $total_page; $start_count = ($page-1)*$list_count; - + $query = $this->getSelectSql($queryObject, true, $start_count); if(strpos($query, "substr")) { $query = str_replace ("substr", "substring", $query); $query = $this->replaceSubstrFormat($query); } $query .= (__DEBUG_QUERY__&1 && $queryObject->query_id)?sprintf (' '.$this->comment_syntax, $this->query_id):''; - $result = $this->_query ($query); + $result = $this->_query ($query, null, $connection); if ($this->isError ()) return $this->queryError($queryObject); - + $virtual_no = $total_count - ($page - 1) * $list_count; while ($tmp = ibase_fetch_object($result)) $data[$virtual_no--] = $tmp; if (!$this->transaction_started) - ibase_commit($this->fd); + ibase_commit($connection); $buff = new Object (); $buff->total_count = $total_count; @@ -808,9 +798,9 @@ $start_count = ($page - 1) * $list_count; $limit = sprintf('SELECT FIRST %d SKIP %d ', $list_count, $start_count); } - + $select = $query->getSelectString($with_values); - + if ($select == '') return new Object(-1, "Invalid query"); @@ -837,13 +827,13 @@ return $select . ' ' . $from . ' ' . $where . ' ' . $groupBy . ' ' . $orderBy; } - + function getDeleteSql($query, $with_values = true){ $sql = 'DELETE '; $from = $query->getFromString($with_values); if($from == '') return new Object(-1, "Invalid query"); - + $sql .= ' FROM '.$from; $where = $query->getWhereString($with_values); @@ -851,8 +841,8 @@ return $sql; } - - function replaceSubstrFormat($queryString){ + + function replaceSubstrFormat($queryString){ //replacing substr("string",number,number) with substr("string" from number for number) $pattern = '/substring\("(\w+)",(\d+),(\d+)\)/i'; $replacement = 'substring("${1}" from $2 for $3)'; diff --git a/classes/db/DBMssql.class.php b/classes/db/DBMssql.class.php index f1be1b088..643d5e72f 100644 --- a/classes/db/DBMssql.class.php +++ b/classes/db/DBMssql.class.php @@ -12,11 +12,9 @@ /** * information to connect to DB **/ - var $conn = NULL; - var $database = NULL; ///< database var $prefix = 'xe'; // / hostname = $db_info->db_hostname; - $this->port = $db_info->db_port; - $this->userid = $db_info->db_userid; - $this->password = $db_info->db_password; - $this->database = $db_info->db_database; - $this->prefix = $db_info->db_table_prefix; - - if(!substr($this->prefix,-1)!='_') $this->prefix .= '_'; - } - /** * @brief DB Connection **/ - function _connect() { - // ignore if db information not exists - if(!$this->hostname || !$this->database) return; + function __connect($connection) { + //sqlsrv_configure( 'WarningsReturnAsErrors', 0 ); + //sqlsrv_configure( 'LogSeverity', SQLSRV_LOG_SEVERITY_ALL ); + //sqlsrv_configure( 'LogSubsystems', SQLSRV_LOG_SYSTEM_ALL ); + $result = @sqlsrv_connect($connection["db_hostname"], array('Database' => $connection["db_database"], 'UID' => $connection["db_userid"], 'PWD' => $connection["db_password"])); - //sqlsrv_configure( 'WarningsReturnAsErrors', 0 ); - //sqlsrv_configure( 'LogSeverity', SQLSRV_LOG_SEVERITY_ALL ); - //sqlsrv_configure( 'LogSubsystems', SQLSRV_LOG_SYSTEM_ALL ); - - $this->conn = sqlsrv_connect( $this->hostname, - array( 'Database' => $this->database,'UID'=>$this->userid,'PWD'=>$this->password )); - - - // Check connections - if($this->conn){ - $this->is_connected = true; - $this->password = md5($this->password); - }else{ - $this->is_connected = false; - } + if(!$result) + { + $errors = print_r(sqlsrv_errors(), true); + $this->setError (-1, 'database connect fail' . PHP_EOL . $errors); + return; + } + return $result; } /** * @brief DB disconnect **/ - function close() { - if($this->is_connected == false) return; - + function _close($connection) { $this->commit(); - sqlsrv_close($this->conn); - $this->conn = null; + sqlsrv_close($connection); } /** @@ -123,31 +97,28 @@ /** * @brief Begin transaction **/ - function begin() { - if($this->is_connected == false || $this->transaction_started) return; - if(sqlsrv_begin_transaction( $this->conn ) === false) return; - - $this->transaction_started = true; + function _begin() { + $connection = $this->_getConnection('master'); + if(sqlsrv_begin_transaction($connection) === false) return; + return true; } /** * @brief Rollback **/ - function rollback() { - if($this->is_connected == false || !$this->transaction_started) return; - - $this->transaction_started = false; - sqlsrv_rollback( $this->conn ); + function _rollback() { + $connection = $this->_getConnection('master'); + sqlsrv_rollback($connection); + return true; } /** * @brief Commit **/ - function commit($force = false) { - if(!$force && ($this->is_connected == false || !$this->transaction_started)) return; - - $this->transaction_started = false; - sqlsrv_commit( $this->conn ); + function _commit() { + $connection = $this->_getConnection('master'); + sqlsrv_commit($connection); + return true; } /** @@ -159,47 +130,40 @@ * object if a row returned \n * return\n **/ - function _query($query) { - if($this->is_connected == false || !$query) return; + function __query($query, $connection) { + $_param = array(); - $_param = array(); - - if(count($this->param)){ - foreach($this->param as $k => $o){ - if($o->getType() == 'number'){ - $value = $o->getUnescapedValue(); - if(is_array($value)) $_param = array_merge($_param, $value); - else $_param[] = $o->getUnescapedValue(); - }else{ - $value = $o->getUnescapedValue(); - if(is_array($value)) { - foreach($value as $v) - $_param[] = array($v, SQLSRV_PARAM_IN, SQLSRV_PHPTYPE_STRING('utf-8')); - } - else $_param[] = array($value, SQLSRV_PARAM_IN, SQLSRV_PHPTYPE_STRING('utf-8')); - } - } - } - - // Notify to start a query execution - $this->actStart($query); + if(count($this->param)){ + foreach($this->param as $k => $o){ + if($o->getType() == 'number'){ + $value = $o->getUnescapedValue(); + if(is_array($value)) $_param = array_merge($_param, $value); + else $_param[] = $o->getUnescapedValue(); + }else{ + $value = $o->getUnescapedValue(); + if(is_array($value)) { + foreach($value as $v) + $_param[] = array($v, SQLSRV_PARAM_IN, SQLSRV_PHPTYPE_STRING('utf-8')); + } + else $_param[] = array($value, SQLSRV_PARAM_IN, SQLSRV_PHPTYPE_STRING('utf-8')); + } + } + } // Run the query statement $result = false; if(count($_param)){ - $result = @sqlsrv_query($this->conn, $query, $_param); + $result = @sqlsrv_query($connection, $query, $_param); }else{ - $result = @sqlsrv_query($this->conn, $query); + $result = @sqlsrv_query($connection, $query); } -// Error Check + // Error Check if(!$result) $this->setError(print_r(sqlsrv_errors(),true)); - // Notify to complete a query execution - $this->actFinish(); - $this->param = array(); + $this->param = array(); - return $result; + return $result; } /** @@ -490,7 +454,7 @@ * In order to get a list of pages easily when selecting \n * it supports a method as navigation **/ - function _executeSelectAct($queryObject) { + function _executeSelectAct($queryObject, $connection = null) { $query = $this->getSelectSql($queryObject); if(strpos($query, "substr")) $query = str_replace ("substr", "substring", $query); @@ -499,10 +463,10 @@ $this->param = $queryObject->getArguments(); $query .= (__DEBUG_QUERY__&1 && $output->query_id)?sprintf(' '.$this->comment_syntax,$this->query_id):''; - $result = $this->_query($query); + $result = $this->_query($query, $connection); if ($this->isError ()) return $this->queryError($queryObject); - else return $this->queryPageLimit($queryObject, $result); + else return $this->queryPageLimit($queryObject, $result, $connection); } function getParser(){ @@ -522,7 +486,7 @@ return; } - function queryPageLimit($queryObject, $result){ + function queryPageLimit($queryObject, $result, $connection){ if ($queryObject->getLimit() && $queryObject->getLimit()->isPageHandler()) { // Total count $count_query = sprintf('select count(*) as "count" %s %s', 'FROM ' . $queryObject->getFromString(), ($queryObject->getWhereString() === '' ? '' : ' WHERE '. $queryObject->getWhereString())); @@ -531,7 +495,7 @@ } $count_query .= (__DEBUG_QUERY__&1 && $output->query_id)?sprintf (' '.$this->comment_syntax, $this->query_id):''; - $result_count = $this->_query($count_query); + $result_count = $this->_query($count_query, $connection); $count_output = $this->_fetch($result_count); $total_count = (int)$count_output->count; @@ -549,9 +513,9 @@ // check the page variables if ($page > $total_page) $page = $total_page; $start_count = ($page - 1) * $list_count; - + $query .= (__DEBUG_QUERY__&1 && $queryObject->query_id)?sprintf (' '.$this->comment_syntax, $this->query_id):''; - $result = $this->_query ($query); + $result = $this->_query ($query, $connection); if ($this->isError ()) return $this->queryError($queryObject); diff --git a/classes/db/DBMysql.class.php b/classes/db/DBMysql.class.php index eaa094994..9f67e5337 100644 --- a/classes/db/DBMysql.class.php +++ b/classes/db/DBMysql.class.php @@ -13,12 +13,8 @@ /** * @brief Connection information for Mysql DB **/ - var $hostname = '127.0.0.1'; ///< hostname - var $userid = NULL; ///< user id - var $password = NULL; ///< password - var $database = NULL; ///< database - var $prefix = 'xe'; // / hostname = $db_info->db_hostname; - $this->port = $db_info->db_port; - $this->userid = $db_info->db_userid; - $this->password = $db_info->db_password; - $this->database = $db_info->db_database; - $this->prefix = $db_info->db_table_prefix; - if(!substr($this->prefix,-1)!='_') $this->prefix .= '_'; - } - /** * @brief DB Connection **/ - function _connect() { + function __connect($connection) { // Ignore if no DB information exists - if(!$this->hostname || !$this->userid || !$this->password || !$this->database) return; + if (strpos($connection["db_hostname"], ':') === false && $connection["db_port"]) + $connection["db_hostname"] .= ':' . $connection["db_port"]; - if(strpos($this->hostname, ':')===false && $this->port) $this->hostname .= ':'.$this->port; // Attempt to connect - $this->fd = @mysql_connect($this->hostname, $this->userid, $this->password); + $result = @mysql_connect($connection["db_hostname"], $connection["db_userid"], $connection["db_password"]); + if(mysql_error()) { $this->setError(mysql_errno(), mysql_error()); return; } // Error appears if the version is lower than 4.1 - if(mysql_get_server_info($this->fd)<"4.1") { + if(mysql_get_server_info($result)<"4.1") { $this->setError(-1, "XE cannot be installed under the version of mysql 4.1. Current mysql version is ".mysql_get_server_info()); return; } // select db - @mysql_select_db($this->database, $this->fd); + @mysql_select_db($connection["db_database"], $result); if(mysql_error()) { $this->setError(mysql_errno(), mysql_error()); return; } - // Check connections - $this->is_connected = true; - $this->password = md5($this->password); + return $result; + // Set utf8 if a database is MySQL $this->_query("set names 'utf8'"); } + function _afterConnect($connection){ + // Set utf8 if a database is MySQL + $this->_query("set names 'utf8'", $connection); + } + /** * @brief DB disconnection **/ - function close() { - if(!$this->isConnected()) return; - @mysql_close($this->fd); + function _close($connection) { + @mysql_close($connection); } /** @@ -123,19 +109,22 @@ /** * @brief Begin transaction **/ - function begin() { + function _begin() { + return true; } /** * @brief Rollback **/ - function rollback() { + function _rollback() { + return true; } /** * @brief Commits **/ - function commit() { + function _commit() { + return true; } /** @@ -147,16 +136,11 @@ * object if a row is returned \n * return\n **/ - function _query($query) { - if(!$this->isConnected()) return; - // Notify to start a query execution - $this->actStart($query); + function __query($query, $connection) { // Run the query statement - $result = mysql_query($query, $this->fd); + $result = mysql_query($query, $connection); // Error Check - if(mysql_error($this->fd)) $this->setError(mysql_errno($this->fd), mysql_error($this->fd)); - // Notify to complete a query execution - $this->actFinish(); + if(mysql_error($connection)) $this->setError(mysql_errno($connection), mysql_error($connection)); // Return result return $result; } @@ -427,7 +411,7 @@ * In order to get a list of pages easily when selecting \n * it supports a method as navigation **/ - function _executeSelectAct($queryObject) { + function _executeSelectAct($queryObject, $connection = null) { $query = $this->getSelectSql($queryObject); if(is_a($query, 'Object')) return; @@ -437,14 +421,15 @@ // TODO Add support for click count // TODO Add code for pagination - $result = $this->_query ($query); + $result = $this->_query ($query, $connection); if ($this->isError ()) return $this->queryError($queryObject); - else return $this->queryPageLimit($queryObject, $result); + else return $this->queryPageLimit($queryObject, $result, $connection); } function db_insert_id() { - return mysql_insert_id($this->fd); + $connection = $this->_getConnection('master'); + return mysql_insert_id($connection); } function db_fetch_object(&$result) @@ -469,7 +454,7 @@ return; } - function queryPageLimit($queryObject, $result){ + function queryPageLimit($queryObject, $result, $connection){ if ($queryObject->getLimit() && $queryObject->getLimit()->isPageHandler()) { // Total count $count_query = sprintf('select count(*) as "count" %s %s', 'FROM ' . $queryObject->getFromString(), ($queryObject->getWhereString() === '' ? '' : ' WHERE '. $queryObject->getWhereString())); @@ -477,8 +462,8 @@ $count_query = sprintf('select count(*) as "count" from (%s) xet', $count_query); } - $count_query .= (__DEBUG_QUERY__&1 && $output->query_id)?sprintf (' '.$this->comment_syntax, $this->query_id):''; - $result_count = $this->_query($count_query); + $count_query .= (__DEBUG_QUERY__&1 && $queryObject->query_id)?sprintf (' '.$this->comment_syntax, $this->query_id):''; + $result_count = $this->_query($count_query, $connection); $count_output = $this->_fetch($result_count); $total_count = (int)$count_output->count; @@ -500,12 +485,12 @@ $start_count = ($page - 1) * $list_count; $query = $this->getSelectPageSql($queryObject, true, $start_count, $list_count); - + $query .= (__DEBUG_QUERY__&1 && $queryObject->query_id)?sprintf (' '.$this->comment_syntax, $this->query_id):''; - $result = $this->_query ($query); + $result = $this->_query ($query, $connection); if ($this->isError ()) return $this->queryError($queryObject); - + $virtual_no = $total_count - ($page - 1) * $list_count; $data = $this->_fetch($result, $virtual_no); @@ -527,7 +512,7 @@ $select = $query->getSelectString($with_values); if($select == '') return new Object(-1, "Invalid query"); $select = 'SELECT ' .$select; - + $from = $query->getFromString($with_values); if($from == '') return new Object(-1, "Invalid query"); $from = ' FROM '.$from; diff --git a/classes/db/DBMysql_innodb.class.php b/classes/db/DBMysql_innodb.class.php index 0c0a6bc87..fb93ae8c2 100644 --- a/classes/db/DBMysql_innodb.class.php +++ b/classes/db/DBMysql_innodb.class.php @@ -19,7 +19,7 @@ $this->_setDBInfo(); $this->_connect(); } - + /** * @brief create an instance of this class */ @@ -31,37 +31,36 @@ /** * @brief DB disconnection **/ - function close() { - if(!$this->isConnected()) return; - $this->_query("commit"); - @mysql_close($this->fd); + function _close($connection) { + $this->_query("commit", $connection); + @mysql_close($connection); } /** * @brief Begin transaction **/ - function begin() { - if(!$this->isConnected() || $this->transaction_started) return; - $this->transaction_started = true; - $this->_query("begin"); + function _begin() { + $connection = $this->_getConnection('master'); + $this->_query("begin", $connection); + return true; } /** * @brief Rollback **/ - function rollback() { - if(!$this->isConnected() || !$this->transaction_started) return; - $this->_query("rollback"); - $this->transaction_started = false; + function _rollback() { + $connection = $this->_getConnection('master'); + $this->_query("rollback", $connection); + return true; } /** * @brief Commits **/ - function commit($force = false) { - if(!$force && (!$this->isConnected() || !$this->transaction_started)) return; - $this->_query("commit"); - $this->transaction_started = false; + function _commit() { + $connection = $this->_getConnection('master'); + $this->_query("commit", $connection); + return true; } /** @@ -73,16 +72,11 @@ * object if a row is returned \n * return\n **/ - function _query($query) { - if(!$this->isConnected()) return; - // Notify to start a query execution - $this->actStart($query); + function __query($query, $connection) { // Run the query statement - $result = @mysql_query($query, $this->fd); + $result = @mysql_query($query, $connection); // Error Check - if(mysql_error($this->fd)) $this->setError(mysql_errno($this->fd), mysql_error($this->fd)); - // Notify to complete a query execution - $this->actFinish(); + if(mysql_error($connection)) $this->setError(mysql_errno($connection), mysql_error($connection)); // Return result return $result; } diff --git a/classes/db/DBMysqli.class.php b/classes/db/DBMysqli.class.php index ff37d9871..933fd8c60 100644 --- a/classes/db/DBMysqli.class.php +++ b/classes/db/DBMysqli.class.php @@ -8,7 +8,7 @@ * * mysql handling class **/ - + class DBMysqli extends DBMysql { @@ -27,7 +27,7 @@ if(!function_exists('mysqli_connect')) return false; return true; } - + /** * @brief create an instance of this class */ @@ -39,32 +39,34 @@ /** * @brief DB Connection **/ - function _connect() { - // Ignore if no DB information exists - if(!$this->hostname || !$this->userid || !$this->password || !$this->database) return; + function __connect($connection) { // Attempt to connect - if($this->port){ - $this->fd = @mysqli_connect($this->hostname, $this->userid, $this->password, $this->database, $this->port); - }else{ - $this->fd = @mysqli_connect($this->hostname, $this->userid, $this->password, $this->database); - } + if ($connection["db_port"]) { + $result = @mysqli_connect($connection["db_hostname"] + , $connection["db_userid"] + , $connection["db_password"] + , $connection["db_database"] + , $connection["db_port"]); + } else { + $result = @mysqli_connect($connection["db_hostname"] + , $connection["db_userid"] + , $connection["db_password"] + , $connection["db_database"]); + } $error = mysqli_connect_errno(); if($error) { $this->setError($error,mysqli_connect_error()); return; } - mysqli_set_charset($this->fd,'utf8'); - // Check connections - $this->is_connected = true; - $this->password = md5($this->password); + mysqli_set_charset($result,'utf8'); + return $result; } /** * @brief DB disconnection **/ - function close() { - if(!$this->isConnected()) return; - mysqli_close($this->fd); + function _close($connection) { + mysqli_close($connection); } /** @@ -72,7 +74,10 @@ **/ function addQuotes($string) { if(version_compare(PHP_VERSION, "5.9.0", "<") && get_magic_quotes_gpc()) $string = stripslashes(str_replace("\\","\\\\",$string)); - if(!is_numeric($string)) $string = mysqli_escape_string($this->fd,$string); + if(!is_numeric($string)){ + $connection = $this->_getConnection('master'); + $string = mysqli_escape_string($connection,$string); + } return $string; } @@ -85,27 +90,22 @@ * object if a row is returned \n * return\n **/ - function _query($query) { - if(!$this->isConnected()) return; - // Notify to start a query execution - $this->actStart($query); + function __query($query, $connection) { // Run the query statement - $result = mysqli_query($this->fd,$query); + $result = mysqli_query($connection,$query); // Error Check - $error = mysqli_error($this->fd); + $error = mysqli_error($connection); if($error){ - $this->setError(mysqli_errno($this->fd), $error); + $this->setError(mysqli_errno($connection), $error); } - - // Notify to complete a query execution - $this->actFinish(); // Return result return $result; } function db_insert_id() { - return mysqli_insert_id($this->fd); + $connection = $this->_getConnection('master'); + return mysqli_insert_id($connection); } function db_fetch_object(&$result) diff --git a/classes/db/DBPostgresql.class.php b/classes/db/DBPostgresql.class.php index f2167fc13..958456c71 100644 --- a/classes/db/DBPostgresql.class.php +++ b/classes/db/DBPostgresql.class.php @@ -18,12 +18,8 @@ class DBPostgresql extends DB /** * @brief Connection information for PostgreSQL DB **/ - var $hostname = '127.0.0.1'; ///< hostname - var $userid = null; ///< user id - var $password = null; ///< password - var $database = null; ///< database var $prefix = 'xe'; // / hostname = $db_info->db_hostname; - $this->port = $db_info->db_port; - $this->userid = $db_info->db_userid; - $this->password = $db_info->db_password; - $this->database = $db_info->db_database; - $this->prefix = $db_info->db_table_prefix; - if (!substr($this->prefix, -1) != '_') - $this->prefix .= '_'; - } - /** * @brief DB Connection **/ - function _connect() + function __connect($connection) { // the connection string for PG $conn_string = ""; - // Ignore if no DB information exists - if (!$this->hostname || !$this->userid || !$this->database) - return; // Create connection string - $conn_string .= ($this->hostname) ? " host=$this->hostname" : ""; - $conn_string .= ($this->userid) ? " user=$this->userid" : ""; - $conn_string .= ($this->password) ? " password=$this->password" : ""; - $conn_string .= ($this->database) ? " dbname=$this->database" : ""; - $conn_string .= ($this->port) ? " port=$this->port" : ""; + $conn_string .= ($connection["db_hostname"]) ? ' host='.$connection["db_hostname"] : ""; + $conn_string .= ($connection["db_userid"]) ? " user=" . $connection["db_userid"] : ""; + $conn_string .= ($connection["db_password"]) ? " password=" . $connection["db_password"] : ""; + $conn_string .= ($connection["db_database"]) ? " dbname=" . $connection["db_database"] : ""; + $conn_string .= ($connection["db_port"]) ? " port=" . $connection["db_port"] : ""; + // Attempt to connect - $this->fd = @pg_connect($conn_string); - if (!$this->fd || pg_connection_status($this->fd) != PGSQL_CONNECTION_OK) { + $result = @pg_connect($conn_string); + if (!$result || pg_connection_status($result) != PGSQL_CONNECTION_OK) { $this->setError(-1, "CONNECTION FAILURE"); return; } - // Check connections - $this->is_connected = true; - $this->password = md5($this->password); - // Set utf8 - //$this ->_query('set client_encoding to uhc'); + return $result; } /** * @brief DB disconnection **/ - function close() + function _close($connection) { - if (!$this->isConnected()) - return; - @pg_close($this->fd); + @pg_close($connection); } /** @@ -139,34 +111,29 @@ class DBPostgresql extends DB /** * @brief Begin transaction **/ - function begin() + function _begin() { - if (!$this->isConnected() || $this->transaction_started == false) - return; - if ($this->_query($this->fd, 'BEGIN')) - $this->transaction_started = true; + $connection = $this->_getConnection('master'); + if (!$this->_query('BEGIN')) return false; + return true; } /** * @brief Rollback **/ - function rollback() + function _rollback() { - if (!$this->isConnected() || $this->transaction_started == false) - return; - if ($this->_query($this->fd, 'ROLLBACK')) - $this->transaction_started = false; + if (!$this->_query('ROLLBACK')) return false; + return true; } /** * @brief Commits **/ - function commit() + function _commit() { - if (!$this->isConnected() || $this->transaction_started == false) - return; - if ($this->_query($this->fd, 'COMMIT')) - $this->transaction_started = false; + if (!$this->_query('COMMIT')) return false; + return true; } /** @@ -178,7 +145,7 @@ class DBPostgresql extends DB * object if a row is returned \n * return\n **/ - function _query($query) + function __query($query, $connection) { if (!$this->isConnected()) return; @@ -205,20 +172,17 @@ class DBPostgresql extends DB } */ // Notify to start a query execution - $this->actStart($query); - $arr = array('Hello', 'World!', 'Beautiful', 'Day!'); + // $arr = array('Hello', 'World!', 'Beautiful', 'Day!'); // Run the query statement - $result = @pg_query($this->fd, $query); + $result = @pg_query($connection, $query); // Error Check if (!$result) { // var_dump($l_query_array); //var_dump($query); //die("\nin query statement\n"); //var_dump(debug_backtrace()); - $this->setError(1, pg_last_error($this->fd)); + $this->setError(1, pg_last_error($connection)); } - // Notify to complete a query execution - $this->actFinish(); // Return result return $result; } @@ -565,7 +529,7 @@ class DBPostgresql extends DB * In order to get a list of pages easily when selecting \n * it supports a method as navigation **/ - function _executeSelectAct($queryObject) + function _executeSelectAct($queryObject, $connection) { $query = $this->getSelectSql($queryObject); @@ -576,7 +540,7 @@ class DBPostgresql extends DB // TODO Add support for click count // TODO Add code for pagination - $result = $this->_query ($query); + $result = $this->_query ($query, $connection); if ($this->isError ()) { if ($limit && $output->limit->isPageHandler()){ $buff = new Object (); @@ -598,7 +562,7 @@ class DBPostgresql extends DB } $count_query .= (__DEBUG_QUERY__&1 && $output->query_id)?sprintf (' '.$this->comment_syntax, $this->query_id):''; - $result_count = $this->_query($count_query); + $result_count = $this->_query($count_query, $connection); $count_output = $this->_fetch($result_count); $total_count = (int)$count_output->count; diff --git a/classes/db/DBSqlite3_pdo.class.php b/classes/db/DBSqlite3_pdo.class.php index 19f13de7a..eff6bd2fb 100644 --- a/classes/db/DBSqlite3_pdo.class.php +++ b/classes/db/DBSqlite3_pdo.class.php @@ -16,7 +16,7 @@ var $comment_syntax = '/* %s */'; /** - * Variables for using PDO + * Variables for using PDO **/ var $handler = NULL; var $stmt = NULL; @@ -26,7 +26,7 @@ /** * @brief column type used in sqlite3 * - * column_type should be replaced for each DBMS properly + * column_type should be replaced for each DBMS properly * because column_type uses a commonly defined type in schema/query xml files **/ var $column_type = array( @@ -47,7 +47,7 @@ $this->_setDBInfo(); $this->_connect(); } - + /** * @brief create an instance of this class */ @@ -131,7 +131,7 @@ } /** - * @brief Add or change quotes to the query string variables + * @brief Add or change quotes to the query string variables **/ function addQuotes($string) { if(version_compare(PHP_VERSION, "5.9.0", "<") && get_magic_quotes_gpc()) $string = stripslashes(str_replace("\\","\\\\",$string)); @@ -334,7 +334,7 @@ // xml parsing $oXml = new XmlParser(); $xml_obj = $oXml->parse($xml_doc); - // Create a table schema + // Create a table schema $table_name = $xml_obj->table->attrs->name; if($this->isTableExists($table_name)) return; $table_name = $this->prefix.$table_name; @@ -503,7 +503,7 @@ // check the page variables if ($page > $total_page) $page = $total_page; $start_count = ($page - 1) * $list_count; - + $this->_prepare($this->getSelectPageSql($queryObject, true, $start_count, $list_count)); $this->stmt->execute(); if ($this->stmt->errorCode() != '00000') { @@ -542,7 +542,7 @@ } return $buff; } - + function getSelectPageSql($query, $with_values = true, $start_count = 0, $list_count = 0) { $select = $query->getSelectString($with_values); diff --git a/classes/module/ModuleHandler.class.php b/classes/module/ModuleHandler.class.php index ebbc699a3..8a0b6bdb6 100644 --- a/classes/module/ModuleHandler.class.php +++ b/classes/module/ModuleHandler.class.php @@ -55,7 +55,7 @@ /** * @brief Initialization. It finds the target module based on module, mid, document_srl, and prepares to execute an action - * @return true: OK, false: redirected + * @return true: OK, false: redirected **/ function init() { $oModuleModel = &getModel('module'); @@ -133,7 +133,7 @@ // Set module and mid into module_info $this->module_info->module = $this->module; $this->module_info->mid = $this->mid; - + // Set site_srl add 2011 08 09 $this->module_info->site_srl = $site_module_info->site_srl; @@ -142,7 +142,7 @@ // If mid exists, set mid into context if($this->mid) Context::set('mid', $this->mid, true); - + // Call a trigger after moduleHandler init $output = ModuleHandler::triggerCall('moduleHandler.init', 'after', $this->module_info); if(!$output->toBool()) { @@ -150,7 +150,7 @@ return false; } - // Set current module info into context + // Set current module info into context Context::set('current_module_info', $this->module_info); return true; @@ -176,7 +176,7 @@ // Get action information with conf/module.xml $xml_info = $oModuleModel->getModuleActionXml($this->module); - // If not installed yet, modify act + // If not installed yet, modify act if($this->module=="install") { if(!$this->act || !$xml_info->action->{$this->act}) $this->act = $xml_info->default_index_act; } @@ -222,9 +222,9 @@ } // If there is no such action in the module object - if(!isset($xml_info->action->{$this->act}) || !method_exists($oModule, $this->act)) + if(!isset($xml_info->action->{$this->act}) || !method_exists($oModule, $this->act)) { - if(!Context::isInstalled()) + if(!Context::isInstalled()) { $this->error = 'msg_invalid_request'; return; @@ -243,7 +243,7 @@ } } - if(!$forward) + if(!$forward) { $forward = $oModuleModel->getActionForward($this->act); } @@ -277,7 +277,7 @@ $oMemberModel = &getModel('member'); $logged_info = $oMemberModel->getLoggedInfo(); - $grant = $oModuleModel->getGrant($forward, $logged_info, $xml_info); + $grant = $oModuleModel->getGrant($forward, $logged_info, $xml_info); if($logged_info->is_admin=='Y') { $orig_module->makeGnbUrl($forward->module); $oModule->setLayoutPath("./modules/admin/tpl"); @@ -362,7 +362,7 @@ { $oMemberModel = &getModel('member'); $logged_info = $oMemberModel->getLoggedInfo(); - $grant = $oModuleModel->getGrant($oModule, $logged_info, $xml_info); + $grant = $oModuleModel->getGrant($oModule, $logged_info, $xml_info); if ($logged_info->is_admin == 'Y'){ $oModule->setLayoutPath("./modules/admin/tpl"); @@ -385,7 +385,7 @@ $message = $oModule->getMessage(); $messageType = $oModule->getMessageType(); $redirectUrl = $oModule->getRedirectUrl(); - + if (!$procResult) { $this->error = $message; @@ -400,7 +400,7 @@ $_SESSION['INPUT_ERROR'] = ''; } } - + $_SESSION['XE_VALIDATOR_ERROR'] = $error; if ($message != 'success') $_SESSION['XE_VALIDATOR_MESSAGE'] = $message; $_SESSION['XE_VALIDATOR_MESSAGE_TYPE'] = $messageType; @@ -418,7 +418,7 @@ $this->_clearErrorSession(); } - + function _clearErrorSession() { $_SESSION['XE_VALIDATOR_ERROR'] = ''; @@ -445,7 +445,7 @@ } // If connection to DB has a problem even though it's not install module, set error - if($this->module != 'install' && $GLOBALS['__DB__'][Context::getDBType()]->is_connected == false) { + if($this->module != 'install' && $GLOBALS['__DB__'][Context::getDBType()]->isConnected() == false) { $this->error = 'msg_dbconnect_failed'; } @@ -455,16 +455,16 @@ // Use message view object, if HTML call if(!in_array(Context::getRequestMethod(),array('XMLRPC','JSON'))) { - + if($_SESSION['XE_VALIDATOR_RETURN_URL']) { header('location:'.$_SESSION['XE_VALIDATOR_RETURN_URL']); return; } - + // If error occurred, handle it if($this->error) { - // display content with message module instance + // display content with message module instance $type = Mobile::isFromMobilePhone() ? 'mobile' : 'view'; $oMessageObject = &ModuleHandler::getModuleInstance('message',$type); $oMessageObject->setError(-1); @@ -479,7 +479,7 @@ } else { $oModule = $oMessageObject; } - + $this->_clearErrorSession(); } @@ -495,7 +495,7 @@ if($layout_srl && !$oModule->getLayoutFile()) { - // If layout_srl exists, get information of the layout, and set the location of layout_path/ layout_file + // If layout_srl exists, get information of the layout, and set the location of layout_path/ layout_file $oLayoutModel = &getModel('layout'); $layout_info = $oLayoutModel->getLayout($layout_srl); if($layout_info) { @@ -518,7 +518,7 @@ } } - // Set layout information into context + // Set layout information into context Context::set('layout_info', $layout_info); $oModule->setLayoutPath($layout_info->path); @@ -531,7 +531,7 @@ } } - // Display contents + // Display contents $oDisplayHandler = new DisplayHandler(); $oDisplayHandler->printContent($oModule); } @@ -571,14 +571,14 @@ unset($parent_module); } - // if there is no instance of the module in global variable, create a new one + // if there is no instance of the module in global variable, create a new one if(!$GLOBALS['_loaded_module'][$module][$type][$kind]) { $parent_module = $module; $class_path = ModuleHandler::getModulePath($module); if(!is_dir(FileHandler::getRealPath($class_path))) return NULL; - // Get base class name and load the file contains it + // Get base class name and load the file contains it if(!class_exists($module)) { $high_class_file = sprintf('%s%s%s.class.php', _XE_PATH_,$class_path, $module); if(!file_exists($high_class_file)) return NULL; @@ -628,13 +628,13 @@ if(@method_exists($oModule, $instance_name)) $oModule->{$instance_name}(); } - // Store the created instance into GLOBALS variable + // Store the created instance into GLOBALS variable $GLOBALS['_loaded_module'][$module][$type][$kind] = $oModule; } if(__DEBUG__==3) $GLOBALS['__elapsed_class_load__'] += getMicroTime() - $start_time; - // return the instance + // return the instance return $GLOBALS['_loaded_module'][$module][$type][$kind]; } @@ -646,7 +646,7 @@ * @return Object **/ function triggerCall($trigger_name, $called_position, &$obj) { - // skip if not installed + // skip if not installed if(!Context::isInstalled()) return new Object(); $oModuleModel = &getModel('module'); diff --git a/modules/install/install.controller.php b/modules/install/install.controller.php index 65eff439e..267a84d10 100644 --- a/modules/install/install.controller.php +++ b/modules/install/install.controller.php @@ -35,7 +35,7 @@ $_SESSION['lgpl_agree'] = $requestVars->lgpl_agree; if($requestVars->enviroment_gather=='Y') { - FileHandler::writeFile('./files/env/install','1'); + FileHandler::writeFile('./files/env/install','1'); } $url = getNotEncodedUrl('', 'act', 'dispInstallCheckEnv'); @@ -101,7 +101,11 @@ **/ function _procDBSetting() { // Get DB-related variables - $db_info = Context::gets('db_type','db_port','db_hostname','db_userid','db_password','db_database','db_table_prefix'); + $con_string = Context::gets('db_type','db_port','db_hostname','db_userid','db_password','db_database','db_table_prefix'); + + $db_info->master_db = get_object_vars($con_string); + $db_info->slave_db[] = get_object_vars($con_string); + if(!$db_info->default_url) $db_info->default_url = Context::getRequestUri(); $db_info->lang_type = Context::getLangType(); @@ -243,7 +247,7 @@ } $oFtp->ftp_quit(); - } + } $config_file = Context::getFTPConfigFile(); FileHandler::WriteFile($config_file, $buff); @@ -297,7 +301,7 @@ // 2. Check if xml_parser_create exists if(function_exists('xml_parser_create')) $checklist['xml'] = true; else $checklist['xml'] = false; - // 3. Check if ini_get (session.auto_start) == 1 + // 3. Check if ini_get (session.auto_start) == 1 if(ini_get(session.auto_start)!=1) $checklist['session'] = true; else $checklist['session'] = false; // 4. Check if iconv exists @@ -343,7 +347,7 @@ * * Create a table by using schema xml file in the shcema directory of each module **/ - function installDownloadedModule() { + function installDownloadedModule() { $oModuleModel = &getModel('module'); // Create a table ny finding schemas/*.xml file in each module $module_list = FileHandler::readDir('./modules/', NULL, false, true); @@ -360,7 +364,7 @@ $this->installModule('module','./modules/module'); $oModule = &getClass('module'); if($oModule->checkUpdate()) $oModule->moduleUpdate(); - // Determine the order of module installation depending on category + // Determine the order of module installation depending on category $install_step = array('system','content','member'); // Install all the remaining modules foreach($install_step as $category) { @@ -423,6 +427,49 @@ return new Object(); } + function _getDbConnText($key, $val, $with_array = false){ + $buff = ''; + if($with_array) + $buff .= "\$db_info->$key = array("; + else + $buff .= "\$db_info->$key = "; + if(!$with_array) $val = array($val); + foreach($val as $con_string){ + $buff .= 'array('; + foreach($con_string as $k => $v){ + if(in_array($k, array('resource', 'is_connected'))) continue; + if($k == 'db_table_prefix'){ + if(substr($v,-1)!='_') $v .= '_'; + } + $buff .= "'$k' => '$v',"; + } + $buff = substr($buff, 0, -1); + $buff .= '),'; + } + $buff = substr($buff, 0, -1); + if($with_array) + $buff .= ');' . PHP_EOL; + else + $buff .= ';' . PHP_EOL; + return $buff; + } + + function _getDBConfigFileContents($db_info){ + $buff = ' $val) { + if($key == 'master_db'){ + $buff .= $this->_getDbConnText($key, $val); + } + else if($key == 'slave_db'){ + $buff .= $this->_getDbConnText($key, $val, true); + } + else + $buff .= sprintf("\$db_info->%s = '%s';" . PHP_EOL, $key, str_replace("'","\\'",$val)); + } + $buff .= "?>"; + return $buff; + } + /** * @brief Create DB temp config file * Create the config file when all settings are completed @@ -433,11 +480,7 @@ $db_info = Context::getDbInfo(); if(!$db_info) return; - $buff = ' $val) { - $buff .= sprintf("\$db_info->%s = '%s';\n", $key, str_replace("'","\\'",$val)); - } - $buff .= "?>"; + $buff = $this->_getDBConfigFileContents($db_info); FileHandler::writeFile($db_tmp_config_file, $buff); @@ -475,11 +518,7 @@ $db_info = Context::getDbInfo(); if(!$db_info) return; - $buff = ' $val) { - $buff .= sprintf("\$db_info->%s = '%s';\n", $key, str_replace("'","\\'",$val)); - } - $buff .= "?>"; + $buff = $this->_getDBConfigFileContents($db_info); FileHandler::writeFile($config_file, $buff); @@ -507,7 +546,7 @@ $body .= "\r\n"; $header = sprintf($fheader,$auto_config['path'],$auto_config['host'],strlen($body),$body); - $fp = @fsockopen($auto_config['host'], $auto_config['port'], $errno, $errstr, 5); + $fp = @fsockopen($auto_config['host'], $auto_config['port'], $errno, $errstr, 5); if($fp){ fputs($fp, $header); while(!feof($fp)) { @@ -516,7 +555,7 @@ fclose($fp); return false; } - } + } fclose($fp); } return true;