diff options
author | Andrey Andreev <narf@bofh.bg> | 2012-04-06 20:29:24 +0200 |
---|---|---|
committer | Andrey Andreev <narf@bofh.bg> | 2012-04-06 20:29:24 +0200 |
commit | 00aed0d9015040764fb7fe8edb7452459fc19213 (patch) | |
tree | 371dba8df01bb1d527c85cfb810a9bfa9c86bd53 /system | |
parent | 2cb262ff0ee22f3928e39f19dc0112b9eb26cabc (diff) | |
parent | ea09a8a5552f2aacdeab0c88a605fe44047ebd0a (diff) |
Merge upstram branch
Diffstat (limited to 'system')
53 files changed, 3290 insertions, 2385 deletions
diff --git a/system/core/Output.php b/system/core/Output.php index 9bf818e88..01fd1d867 100755 --- a/system/core/Output.php +++ b/system/core/Output.php @@ -224,6 +224,26 @@ class CI_Output { // -------------------------------------------------------------------- /** + * Get Current Content Type Header + * + * @return string 'text/html', if not already set + */ + public function get_content_type() + { + for ($i = 0, $c = count($this->headers); $i < $c; $i++) + { + if (preg_match('/^Content-Type:\s(.+)$/', $this->headers[$i][0], $matches)) + { + return $matches[1]; + } + } + + return 'text/html'; + } + + // -------------------------------------------------------------------- + + /** * Set HTTP Status Header * moved to Common procedural functions in 1.7.2 * diff --git a/system/database/DB.php b/system/database/DB.php index 96e495515..0d81e40d3 100755 --- a/system/database/DB.php +++ b/system/database/DB.php @@ -92,16 +92,12 @@ function &DB($params = '', $active_record_override = NULL) if (isset($dsn['query'])) { parse_str($dsn['query'], $extra); + foreach ($extra as $key => $val) { - // booleans please - if (strtoupper($val) === 'TRUE') - { - $val = TRUE; - } - elseif (strtoupper($val) === 'FALSE') + if (is_string($val) && in_array(strtoupper($val), array('TRUE', 'FALSE', 'NULL'))) { - $val = FALSE; + $val = var_export($val); } $params[$key] = $val; @@ -138,7 +134,12 @@ function &DB($params = '', $active_record_override = NULL) class CI_DB extends CI_DB_driver { } } - require_once(BASEPATH.'database/drivers/'.$params['dbdriver'].'/'.$params['dbdriver'].'_driver.php'); + // Load the DB driver + $driver_file = BASEPATH.'database/drivers/'.$params['dbdriver'].'/'.$params['dbdriver'].'_driver.php'; + + if ( ! file_exists($driver_file)) show_error('Invalid DB driver'); + + require_once($driver_file); // Instantiate the DB adapter $driver = 'CI_DB_'.$params['dbdriver'].'_driver'; diff --git a/system/database/DB_active_rec.php b/system/database/DB_active_rec.php index b324226ab..a19f9bedd 100644 --- a/system/database/DB_active_rec.php +++ b/system/database/DB_active_rec.php @@ -1219,6 +1219,23 @@ abstract class CI_DB_active_record extends CI_DB_driver { // -------------------------------------------------------------------- /** + * Insert_batch statement + * + * Generates a platform-specific insert string from the supplied data. + * + * @param string the table name + * @param array the insert keys + * @param array the insert values + * @return string + */ + protected function _insert_batch($table, $keys, $values) + { + return 'INSERT INTO '.$table.' ('.implode(', ', $keys).') VALUES '.implode(', ', $values); + } + + // -------------------------------------------------------------------- + + /** * The "set_insert_batch" function. Allows key/value pairs to be set for batch inserts * * @param mixed @@ -1341,6 +1358,23 @@ abstract class CI_DB_active_record extends CI_DB_driver { // -------------------------------------------------------------------- /** + * Insert statement + * + * Generates a platform-specific insert string from the supplied data + * + * @param string the table name + * @param array the insert keys + * @param array the insert values + * @return string + */ + protected function _insert($table, $keys, $values) + { + return 'INSERT INTO '.$table.' ('.implode(', ', $keys).') VALUES ('.implode(', ', $values).')'; + } + + // -------------------------------------------------------------------- + + /** * Validate Insert * * This method is used by both insert() and get_compiled_insert() to @@ -1413,6 +1447,23 @@ abstract class CI_DB_active_record extends CI_DB_driver { // -------------------------------------------------------------------- /** + * Replace statement + * + * Generates a platform-specific replace string from the supplied data + * + * @param string the table name + * @param array the insert keys + * @param array the insert values + * @return string + */ + protected function _replace($table, $keys, $values) + { + return 'REPLACE INTO '.$table.' ('.implode(', ', $keys).') VALUES ('.implode(', ', $values).')'; + } + + // -------------------------------------------------------------------- + + /** * Get UPDATE query string * * Compiles an update query and returns the sql @@ -1486,6 +1537,33 @@ abstract class CI_DB_active_record extends CI_DB_driver { // -------------------------------------------------------------------- /** + * Update statement + * + * Generates a platform-specific update string from the supplied data + * + * @param string the table name + * @param array the update data + * @param array the where clause + * @param array the orderby clause + * @param array the limit clause + * @return string + */ + protected function _update($table, $values, $where, $orderby = array(), $limit = FALSE) + { + foreach ($values as $key => $val) + { + $valstr[] = $key.' = '.$val; + } + + return 'UPDATE '.$table.' SET '.implode(', ', $valstr) + .(($where != '' && count($where) > 0) ? ' WHERE '.implode(' ', $where) : '') + .(count($orderby) > 0 ? ' ORDER BY '.implode(', ', $orderby) : '') + .($limit ? ' LIMIT '.$limit : ''); + } + + // -------------------------------------------------------------------- + + /** * Validate Update * * This method is used by both update() and get_compiled_update() to @@ -1684,6 +1762,24 @@ abstract class CI_DB_active_record extends CI_DB_driver { // -------------------------------------------------------------------- /** + * Truncate statement + * + * Generates a platform-specific truncate string from the supplied data + * + * If the database does not support the truncate() command, + * then this method maps to 'DELETE FROM table' + * + * @param string the table name + * @return string + */ + protected function _truncate($table) + { + return 'TRUNCATE '.$table; + } + + // -------------------------------------------------------------------- + + /** * Get DELETE query string * * Compiles a delete query string and returns the sql diff --git a/system/database/DB_cache.php b/system/database/DB_cache.php index 58e6968c0..ff942856b 100644 --- a/system/database/DB_cache.php +++ b/system/database/DB_cache.php @@ -177,7 +177,7 @@ class CI_DB_Cache { */ public function delete_all() { - delete_files($this->db->cachedir, TRUE); + delete_files($this->db->cachedir, TRUE, 0, TRUE); } } diff --git a/system/database/DB_driver.php b/system/database/DB_driver.php index 9f1a0b895..8b030af77 100644 --- a/system/database/DB_driver.php +++ b/system/database/DB_driver.php @@ -99,9 +99,13 @@ abstract class CI_DB_driver { */ public function initialize() { - // If an existing connection resource is available - // there is no need to connect and select the database - if (is_resource($this->conn_id) OR is_object($this->conn_id)) + /* If an established connection is available, then there's + * no need to connect and select the database. + * + * Depending on the database driver, conn_id can be either + * boolean TRUE, a resource or an object. + */ + if ($this->conn_id) { return TRUE; } @@ -188,10 +192,24 @@ abstract class CI_DB_driver { // -------------------------------------------------------------------- /** + * Select database + * + * This is just a dummy method to allow drivers without such + * functionality to not declare it, while others will override it. + * + * @return bool + */ + public function db_select() + { + return TRUE; + } + + // -------------------------------------------------------------------- + + /** * Set client character set * * @param string - * @param string * @return bool */ public function db_set_charset($charset) @@ -283,17 +301,13 @@ abstract class CI_DB_driver { { log_message('error', 'Invalid query: '.$sql); - if ($this->db_debug) - { - return $this->display_error('db_invalid_query'); - } - return FALSE; + return ($this->db_debug) ? $this->display_error('db_invalid_query') : FALSE; } // Verify table prefix and replace if necessary - if ( ($this->dbprefix != '' AND $this->swap_pre != '') AND ($this->dbprefix != $this->swap_pre) ) + if ($this->dbprefix != '' && $this->swap_pre != '' && $this->dbprefix != $this->swap_pre) { - $sql = preg_replace("/(\W)".$this->swap_pre."(\S+?)/", "\\1".$this->dbprefix."\\2", $sql); + $sql = preg_replace('/(\W)'.$this->swap_pre.'(\S+?)/', '\\1'.$this->dbprefix.'\\2', $sql); } // Compile binds if needed @@ -305,15 +319,12 @@ abstract class CI_DB_driver { // Is query caching enabled? If the query is a "read type" // we will load the caching class and return the previously // cached query if it exists - if ($this->cache_on == TRUE AND stristr($sql, 'SELECT')) + if ($this->cache_on == TRUE && stripos($sql, 'SELECT') !== FALSE && $this->_cache_init()) { - if ($this->_cache_init()) + $this->load_rdriver(); + if (FALSE !== ($cache = $this->CACHE->read($sql))) { - $this->load_rdriver(); - if (FALSE !== ($cache = $this->CACHE->read($sql))) - { - return $cache; - } + return $cache; } } @@ -352,13 +363,7 @@ abstract class CI_DB_driver { $this->trans_complete(); // Display errors - return $this->display_error( - array( - 'Error Number: '.$error['code'], - $error['message'], - $sql - ) - ); + return $this->display_error(array('Error Number: '.$error['code'], $error['message'], $sql)); } return FALSE; @@ -382,7 +387,7 @@ abstract class CI_DB_driver { { // If caching is enabled we'll auto-cleanup any // existing files related to this particular URI - if ($this->cache_on == TRUE AND $this->cache_autodel == TRUE AND $this->_cache_init()) + if ($this->cache_on == TRUE && $this->cache_autodel == TRUE && $this->_cache_init()) { $this->CACHE->delete(); } @@ -402,11 +407,9 @@ abstract class CI_DB_driver { $driver = $this->load_rdriver(); $RES = new $driver($this); - $RES->num_rows = $RES->num_rows(); - - // Is query caching enabled? If so, we'll serialize the + // Is query caching enabled? If so, we'll serialize the // result object and save it to a cache file. - if ($this->cache_on == TRUE AND $this->_cache_init()) + if ($this->cache_on == TRUE && $this->_cache_init()) { // We'll create a new instance of the result object // only without the platform specific driver since @@ -415,9 +418,9 @@ abstract class CI_DB_driver { // result object, so we'll have to compile the data // and save it) $CR = new CI_DB_result(); - $CR->num_rows = $RES->num_rows(); $CR->result_object = $RES->result_object(); $CR->result_array = $RES->result_array(); + $CR->num_rows = $RES->num_rows(); // Reset these since cached objects can not utilize resource IDs. $CR->conn_id = NULL; @@ -608,7 +611,8 @@ abstract class CI_DB_driver { // The count of bind should be 1 less then the count of segments // If there are more bind arguments trim it down - if (count($binds) >= count($segments)) { + if (count($binds) >= count($segments)) + { $binds = array_slice($binds, 0, count($segments)-1); } @@ -617,8 +621,7 @@ abstract class CI_DB_driver { $i = 0; foreach ($binds as $bind) { - $result .= $this->escape($bind); - $result .= $segments[++$i]; + $result .= $this->escape($bind).$segments[++$i]; } return $result; @@ -689,15 +692,15 @@ abstract class CI_DB_driver { { if (is_string($str) OR method_exists($str, '__toString')) { - $str = "'".$this->escape_str($str)."'"; + return "'".$this->escape_str($str)."'"; } elseif (is_bool($str)) { - $str = ($str === FALSE) ? 0 : 1; + return ($str === FALSE) ? 0 : 1; } elseif (is_null($str)) { - $str = 'NULL'; + return 'NULL'; } return $str; @@ -733,13 +736,7 @@ abstract class CI_DB_driver { public function primary($table = '') { $fields = $this->list_fields($table); - - if ( ! is_array($fields)) - { - return FALSE; - } - - return current($fields); + return is_array($fields) ? current($fields) : FALSE; } // -------------------------------------------------------------------- @@ -759,35 +756,40 @@ abstract class CI_DB_driver { if (FALSE === ($sql = $this->_list_tables($constrain_by_prefix))) { - if ($this->db_debug) - { - return $this->display_error('db_unsupported_function'); - } - return FALSE; + return ($this->db_debug) ? $this->display_error('db_unsupported_function') : FALSE; } - $retval = array(); + $this->data_cache['table_names'] = array(); $query = $this->query($sql); - if ($query->num_rows() > 0) + foreach ($query->result_array() as $row) { - $table = FALSE; - $rows = $query->result_array(); - $key = (($row = current($rows)) && in_array('table_name', array_map('strtolower', array_keys($row)))); - - if ($key) + // Do we know from which column to get the table name? + if ( ! isset($key)) { - $table = array_key_exists('TABLE_NAME', $row) ? 'TABLE_NAME' : 'table_name'; + if (isset($row['table_name'])) + { + $key = 'table_name'; + } + elseif (isset($row['TABLE_NAME'])) + { + $key = 'TABLE_NAME'; + } + else + { + /* We have no other choice but to just get the first element's key. + * Due to array_shift() accepting it's argument by reference, if + * E_STRICT is on, this would trigger a warning. So we'll have to + * assign it first. + */ + $key = array_keys($row); + $key = array_shift($key); + } } - foreach ($rows as $row) - { - $retval[] = ( ! $table) ? current($row) : $row[$table]; - } + $this->data_cache['table_names'][] = $row[$key]; } - $this->data_cache['table_names'] = $retval; - return $this->data_cache['table_names']; } @@ -821,38 +823,45 @@ abstract class CI_DB_driver { if ($table == '') { - if ($this->db_debug) - { - return $this->display_error('db_field_param_missing'); - } - return FALSE; + return ($this->db_debug) ? $this->display_error('db_field_param_missing') : FALSE; } if (FALSE === ($sql = $this->_list_columns($table))) { - if ($this->db_debug) - { - return $this->display_error('db_unsupported_function'); - } - return FALSE; + return ($this->db_debug) ? $this->display_error('db_unsupported_function') : FALSE; } $query = $this->query($sql); + $this->data_cache['field_names'][$table] = array(); - $retval = array(); foreach ($query->result_array() as $row) { - if (isset($row['COLUMN_NAME'])) - { - $retval[] = $row['COLUMN_NAME']; - } - else + // Do we know from where to get the column's name? + if ( ! isset($key)) { - $retval[] = current($row); + if (isset($row['column_name'])) + { + $key = 'column_name'; + } + elseif (isset($row['COLUMN_NAME'])) + { + $key = 'COLUMN_NAME'; + } + else + { + /* We have no other choice but to just get the first element's key. + * Due to array_shift() accepting it's argument by reference, if + * E_STRICT is on, this would trigger a warning. So we'll have to + * assign it first. + */ + $key = array_keys($row); + $key = array_shift($key); + } } + + $this->data_cache['field_names'][$table][] = $row[$key]; } - $this->data_cache['field_names'][$table] = $retval; return $this->data_cache['field_names'][$table]; } @@ -867,7 +876,7 @@ abstract class CI_DB_driver { */ public function field_exists($field_name, $table_name) { - return ( ! in_array($field_name, $this->list_fields($table_name))) ? FALSE : TRUE; + return in_array($field_name, $this->list_fields($table_name)); } // -------------------------------------------------------------------- @@ -882,16 +891,48 @@ abstract class CI_DB_driver { { if ($table == '') { - if ($this->db_debug) + return ($this->db_debug) ? $this->display_error('db_field_param_missing') : FALSE; + } + + $query = $this->query($this->_field_data($this->protect_identifiers($table, TRUE, NULL, FALSE))); + return $query->field_data(); + } + + // -------------------------------------------------------------------- + + /** + * Escape the SQL Identifiers + * + * This function escapes column and table names + * + * @param string + * @return string + */ + public function escape_identifiers($item) + { + if ($this->_escape_char == '') + { + return $item; + } + + foreach ($this->_reserved_identifiers as $id) + { + if (strpos($item, '.'.$id) !== FALSE) { - return $this->display_error('db_field_param_missing'); + $item = str_replace('.', $this->_escape_char.'.', $item); + + // remove duplicates if the user already included the escape + return preg_replace('/['.$this->_escape_char.']+/', $this->_escape_char, $this->_escape_char.$item); } - return FALSE; } - $query = $this->query($this->_field_data($this->protect_identifiers($table, TRUE, NULL, FALSE))); + if (strpos($item, '.') !== FALSE) + { + $item = str_replace('.', $this->_escape_char.'.'.$this->_escape_char, $item); + } - return $query->field_data(); + // remove duplicates if the user already included the escape + return preg_replace('/['.$this->_escape_char.']+/', $this->_escape_char, $this->_escape_char.$item.$this->_escape_char); } // -------------------------------------------------------------------- @@ -905,12 +946,11 @@ abstract class CI_DB_driver { */ public function insert_string($table, $data) { - $fields = array(); - $values = array(); + $fields = $values = array(); foreach ($data as $key => $val) { - $fields[] = $this->_escape_identifiers($key); + $fields[] = $this->escape_identifiers($key); $values[] = $this->escape($val); } @@ -979,13 +1019,7 @@ abstract class CI_DB_driver { */ protected function _has_operator($str) { - $str = trim($str); - if ( ! preg_match("/(\s|<|>|!|=|is null|is not null)/i", $str)) - { - return FALSE; - } - - return TRUE; + return (bool) preg_match('/(\s|<|>|!|=|IS NULL|IS NOT NULL)/i', trim($str)); } // -------------------------------------------------------------------- @@ -1008,25 +1042,12 @@ abstract class CI_DB_driver { if ( ! function_exists($function)) { - if ($this->db_debug) - { - return $this->display_error('db_unsupported_function'); - } - return FALSE; + return ($this->db_debug) ? $this->display_error('db_unsupported_function') : FALSE; } - else - { - $args = (func_num_args() > 1) ? array_splice(func_get_args(), 1) : null; - if (is_null($args)) - { - return call_user_func($function); - } - else - { - return call_user_func_array($function, $args); - } - } + return (func_num_args() > 1) + ? call_user_func_array($function, array_splice(func_get_args(), 1)) + : call_user_func($function); } // -------------------------------------------------------------------- @@ -1051,8 +1072,7 @@ abstract class CI_DB_driver { */ public function cache_on() { - $this->cache_on = TRUE; - return TRUE; + return $this->cache_on = TRUE; } // -------------------------------------------------------------------- @@ -1064,8 +1084,7 @@ abstract class CI_DB_driver { */ public function cache_off() { - $this->cache_on = FALSE; - return FALSE; + return $this->cache_on = FALSE; } @@ -1078,11 +1097,9 @@ abstract class CI_DB_driver { */ public function cache_delete($segment_one = '', $segment_two = '') { - if ( ! $this->_cache_init()) - { - return FALSE; - } - return $this->CACHE->delete($segment_one, $segment_two); + return ($this->_cache_init()) + ? $this->CACHE->delete($segment_one, $segment_two) + : FALSE; } // -------------------------------------------------------------------- @@ -1094,12 +1111,9 @@ abstract class CI_DB_driver { */ public function cache_delete_all() { - if ( ! $this->_cache_init()) - { - return FALSE; - } - - return $this->CACHE->delete_all(); + return ($this->_cache_init()) + ? $this->CACHE->delete_all() + : FALSE; } // -------------------------------------------------------------------- @@ -1111,18 +1125,17 @@ abstract class CI_DB_driver { */ protected function _cache_init() { - if (is_object($this->CACHE) AND class_exists('CI_DB_Cache')) + if (class_exists('CI_DB_Cache')) { - return TRUE; - } - - if ( ! class_exists('CI_DB_Cache')) - { - if ( ! @include(BASEPATH.'database/DB_cache.php')) + if (is_object($this->CACHE)) { - return $this->cache_off(); + return TRUE; } } + elseif ( ! @include_once(BASEPATH.'database/DB_cache.php')) + { + return $this->cache_off(); + } $this->CACHE = new CI_DB_Cache($this); // pass db object to support multiple db connections and returned db objects return TRUE; @@ -1137,11 +1150,11 @@ abstract class CI_DB_driver { */ public function close() { - if (is_resource($this->conn_id) OR is_object($this->conn_id)) + if ($this->conn_id) { $this->_close($this->conn_id); + $this->conn_id = FALSE; } - $this->conn_id = FALSE; } // -------------------------------------------------------------------- @@ -1173,9 +1186,7 @@ abstract class CI_DB_driver { // Find the most likely culprit of the error by going through // the backtrace until the source file is no longer in the // database folder. - $trace = debug_backtrace(); - foreach ($trace as $call) { if (isset($call['file']) && strpos($call['file'], BASEPATH.'database') === FALSE) @@ -1183,7 +1194,6 @@ abstract class CI_DB_driver { // Found it - use a relative path for safety $message[] = 'Filename: '.str_replace(array(BASEPATH, APPPATH), '', $call['file']); $message[] = 'Line Number: '.$call['line']; - break; } } @@ -1201,7 +1211,7 @@ abstract class CI_DB_driver { * This function is used extensively by the Active Record class, and by * a couple functions in this class. * It takes a column or table name (optionally with an alias) and inserts - * the table prefix onto it. Some logic is necessary in order to deal with + * the table prefix onto it. Some logic is necessary in order to deal with * column names that include the path. Consider a query like this: * * SELECT * FROM hostname.database.table.column AS c FROM hostname.database.table @@ -1244,12 +1254,15 @@ abstract class CI_DB_driver { // If the item has an alias declaration we remove it and set it aside. // Basically we remove everything to the right of the first space - $alias = ''; if (strpos($item, ' ') !== FALSE) { - $alias = strstr($item, " "); + $alias = strstr($item, ' '); $item = substr($item, 0, - strlen($alias)); } + else + { + $alias = ''; + } // This is basically a bug fix for queries that use MAX, MIN, etc. // If a parenthesis is found we know that we do not need to @@ -1278,12 +1291,13 @@ abstract class CI_DB_driver { { if ( ! in_array($val, $this->_reserved_identifiers)) { - $parts[$key] = $this->_escape_identifiers($val); + $parts[$key] = $this->escape_identifiers($val); } } $item = implode('.', $parts); } + return $item.$alias; } @@ -1318,13 +1332,12 @@ abstract class CI_DB_driver { } // Verify table prefix and replace if necessary - if ($this->swap_pre != '' && strncmp($parts[$i], $this->swap_pre, strlen($this->swap_pre)) === 0) + if ($this->swap_pre != '' && strpos($parts[$i], $this->swap_pre) === 0) { - $parts[$i] = preg_replace("/^".$this->swap_pre."(\S+?)/", $this->dbprefix."\\1", $parts[$i]); + $parts[$i] = preg_replace('/^'.$this->swap_pre.'(\S+?)/', $this->dbprefix.'\\1', $parts[$i]); } - // We only add the table prefix if it does not already exist - if (substr($parts[$i], 0, strlen($this->dbprefix)) != $this->dbprefix) + elseif (strpos($parts[$i], $this->dbprefix) !== 0) { $parts[$i] = $this->dbprefix.$parts[$i]; } @@ -1335,7 +1348,7 @@ abstract class CI_DB_driver { if ($protect_identifiers === TRUE) { - $item = $this->_escape_identifiers($item); + $item = $this->escape_identifiers($item); } return $item.$alias; @@ -1345,21 +1358,20 @@ abstract class CI_DB_driver { if ($this->dbprefix != '') { // Verify table prefix and replace if necessary - if ($this->swap_pre != '' && strncmp($item, $this->swap_pre, strlen($this->swap_pre)) === 0) + if ($this->swap_pre != '' && strpos($item, $this->swap_pre) === 0) { - $item = preg_replace("/^".$this->swap_pre."(\S+?)/", $this->dbprefix."\\1", $item); + $item = preg_replace('/^'.$this->swap_pre.'(\S+?)/', $this->dbprefix.'\\1', $item); } - // Do we prefix an item with no segments? - if ($prefix_single == TRUE AND substr($item, 0, strlen($this->dbprefix)) != $this->dbprefix) + elseif ($prefix_single == TRUE && strpos($item, $this->dbprefix) !== 0) { $item = $this->dbprefix.$item; } } - if ($protect_identifiers === TRUE AND ! in_array($item, $this->_reserved_identifiers)) + if ($protect_identifiers === TRUE && ! in_array($item, $this->_reserved_identifiers)) { - $item = $this->_escape_identifiers($item); + $item = $this->escape_identifiers($item); } return $item.$alias; @@ -1374,7 +1386,9 @@ abstract class CI_DB_driver { * * @return void */ - abstract protected function _reset_select(); + protected function _reset_select() + { + } } diff --git a/system/database/DB_result.php b/system/database/DB_result.php index 04f964fb1..bb09c014c 100644 --- a/system/database/DB_result.php +++ b/system/database/DB_result.php @@ -57,7 +57,7 @@ class CI_DB_result { * Query result. Acts as a wrapper function for the following functions. * * @param string can be "object" or "array" - * @return mixed either a result object or array + * @return object */ public function result($type = 'object') { @@ -108,9 +108,9 @@ class CI_DB_result { // -------------------------------------------------------------------- /** - * Query result. "object" version. + * Query result. "object" version. * - * @return object + * @return array */ public function result_object() { @@ -224,7 +224,7 @@ class CI_DB_result { return; } - if ($key != '' AND ! is_null($value)) + if ($key != '' && ! is_null($value)) { $this->row_data[$key] = $value; } @@ -245,7 +245,7 @@ class CI_DB_result { return $result; } - if ($n != $this->current_row AND isset($result[$n])) + if ($n != $this->current_row && isset($result[$n])) { $this->current_row = $n; } @@ -266,7 +266,7 @@ class CI_DB_result { return $result; } - if ($n != $this->current_row AND isset($result[$n])) + if ($n != $this->current_row && isset($result[$n])) { $this->current_row = $n; } @@ -289,7 +289,7 @@ class CI_DB_result { return $result; } - if ($n != $this->current_row AND isset($result[$n])) + if ($n != $this->current_row && isset($result[$n])) { $this->current_row = $n; } @@ -297,7 +297,6 @@ class CI_DB_result { return $result[$this->current_row]; } - // -------------------------------------------------------------------- /** @@ -374,9 +373,9 @@ class CI_DB_result { /** * The following functions are normally overloaded by the identically named * methods in the platform-specific driver -- except when query caching - * is used. When caching is enabled we do not load the other driver. + * is used. When caching is enabled we do not load the other driver. * These functions are primarily here to prevent undefined function errors - * when a cached result object is in use. They are not otherwise fully + * when a cached result object is in use. They are not otherwise fully * operational due to the unavailability of the database resource IDs with * cached results. */ @@ -384,7 +383,7 @@ class CI_DB_result { public function num_fields() { return 0; } public function list_fields() { return array(); } public function field_data() { return array(); } - public function free_result() { return TRUE; } + public function free_result() { $this->result_id = FALSE; } protected function _data_seek() { return TRUE; } protected function _fetch_assoc() { return array(); } protected function _fetch_object() { return array(); } diff --git a/system/database/drivers/cubrid/cubrid_driver.php b/system/database/drivers/cubrid/cubrid_driver.php index bed3d8685..74d1a850a 100644 --- a/system/database/drivers/cubrid/cubrid_driver.php +++ b/system/database/drivers/cubrid/cubrid_driver.php @@ -159,22 +159,6 @@ class CI_DB_cubrid_driver extends CI_DB { // -------------------------------------------------------------------- /** - * Select the database - * - * @return resource - */ - public function db_select() - { - // In CUBRID there is no need to select a database as the database - // is chosen at the connection time. - // So, to determine if the database is "selected", all we have to - // do is ping the server and return that value. - return cubrid_ping($this->conn_id); - } - - // -------------------------------------------------------------------- - - /** * Database version number * * @return string @@ -451,45 +435,6 @@ class CI_DB_cubrid_driver extends CI_DB { return array('code' => cubrid_errno($this->conn_id), 'message' => cubrid_error($this->conn_id)); } - /** - * Escape the SQL Identifiers - * - * This function escapes column and table names - * - * @param string - * @return string - */ - public function _escape_identifiers($item) - { - if ($this->_escape_char == '') - { - return $item; - } - - foreach ($this->_reserved_identifiers as $id) - { - if (strpos($item, '.'.$id) !== FALSE) - { - $str = $this->_escape_char. str_replace('.', $this->_escape_char.'.', $item); - - // remove duplicates if the user already included the escape - return preg_replace('/['.$this->_escape_char.']+/', $this->_escape_char, $str); - } - } - - if (strpos($item, '.') !== FALSE) - { - $str = $this->_escape_char.str_replace('.', $this->_escape_char.'.'.$this->_escape_char, $item).$this->_escape_char; - } - else - { - $str = $this->_escape_char.$item.$this->_escape_char; - } - - // remove duplicates if the user already included the escape - return preg_replace('/['.$this->_escape_char.']+/', $this->_escape_char, $str); - } - // -------------------------------------------------------------------- /** @@ -514,94 +459,6 @@ class CI_DB_cubrid_driver extends CI_DB { // -------------------------------------------------------------------- /** - * Insert statement - * - * Generates a platform-specific insert string from the supplied data - * - * @param string the table name - * @param array the insert keys - * @param array the insert values - * @return string - */ - protected function _insert($table, $keys, $values) - { - return "INSERT INTO ".$table." (\"".implode('", "', $keys)."\") VALUES (".implode(', ', $values).")"; - } - - // -------------------------------------------------------------------- - - - /** - * Replace statement - * - * Generates a platform-specific replace string from the supplied data - * - * @param string the table name - * @param array the insert keys - * @param array the insert values - * @return string - */ - protected function _replace($table, $keys, $values) - { - return "REPLACE INTO ".$table." (\"".implode('", "', $keys)."\") VALUES (".implode(', ', $values).")"; - } - - // -------------------------------------------------------------------- - - /** - * Insert_batch statement - * - * Generates a platform-specific insert string from the supplied data - * - * @param string the table name - * @param array the insert keys - * @param array the insert values - * @return string - */ - protected function _insert_batch($table, $keys, $values) - { - return "INSERT INTO ".$table." (\"".implode('", "', $keys)."\") VALUES ".implode(', ', $values); - } - - // -------------------------------------------------------------------- - - - /** - * Update statement - * - * Generates a platform-specific update string from the supplied data - * - * @param string the table name - * @param array the update data - * @param array the where clause - * @param array the orderby clause - * @param array the limit clause - * @return string - */ - protected function _update($table, $values, $where, $orderby = array(), $limit = FALSE) - { - foreach ($values as $key => $val) - { - $valstr[] = sprintf('"%s" = %s', $key, $val); - } - - $limit = ( ! $limit) ? '' : ' LIMIT '.$limit; - - $orderby = (count($orderby) >= 1)?' ORDER BY '.implode(", ", $orderby):''; - - $sql = "UPDATE ".$table." SET ".implode(', ', $valstr); - - $sql .= ($where != '' AND count($where) >=1) ? " WHERE ".implode(" ", $where) : ''; - - $sql .= $orderby.$limit; - - return $sql; - } - - // -------------------------------------------------------------------- - - - /** * Update_Batch statement * * Generates a platform-specific batch update string from the supplied data @@ -653,23 +510,6 @@ class CI_DB_cubrid_driver extends CI_DB { // -------------------------------------------------------------------- /** - * Truncate statement - * - * Generates a platform-specific truncate string from the supplied data - * If the database does not support the truncate() command - * This function maps to "DELETE FROM table" - * - * @param string the table name - * @return string - */ - protected function _truncate($table) - { - return "TRUNCATE ".$table; - } - - // -------------------------------------------------------------------- - - /** * Delete statement * * Generates a platform-specific delete string from the supplied data diff --git a/system/database/drivers/cubrid/cubrid_forge.php b/system/database/drivers/cubrid/cubrid_forge.php index bbda484c4..f83dc97f4 100644 --- a/system/database/drivers/cubrid/cubrid_forge.php +++ b/system/database/drivers/cubrid/cubrid_forge.php @@ -184,9 +184,7 @@ class CI_DB_cubrid_forge extends CI_DB_forge { // As of version 8.4.0 CUBRID does not support this SQL syntax. } - $sql .= $this->db->_escape_identifiers($table)." ("; - - $sql .= $this->_process_fields($fields); + $sql .= $this->db->escape_identifiers($table).' ('.$this->_process_fields($fields); // If there is a PK defined if (count($primary_keys) > 0) @@ -230,7 +228,7 @@ class CI_DB_cubrid_forge extends CI_DB_forge { */ public function _drop_table($table) { - return "DROP TABLE IF EXISTS ".$this->db->_escape_identifiers($table); + return 'DROP TABLE IF EXISTS '.$this->db->escape_identifiers($table); } // -------------------------------------------------------------------- diff --git a/system/database/drivers/interbase/interbase_driver.php b/system/database/drivers/interbase/interbase_driver.php index d8b6ae571..88638a21a 100644 --- a/system/database/drivers/interbase/interbase_driver.php +++ b/system/database/drivers/interbase/interbase_driver.php @@ -85,19 +85,6 @@ class CI_DB_interbase_driver extends CI_DB { // -------------------------------------------------------------------- /** - * Select the database - * - * @return bool - */ - public function db_select() - { - // Connection selects the database - return TRUE; - } - - // -------------------------------------------------------------------- - - /** * Database version number * * @return string @@ -356,38 +343,6 @@ class CI_DB_interbase_driver extends CI_DB { // -------------------------------------------------------------------- /** - * Escape the SQL Identifiers - * - * This public function escapes column and table names - * - * @param string - * @return string - */ - protected function _escape_identifiers($item) - { - foreach ($this->_reserved_identifiers as $id) - { - if (strpos($item, '.'.$id) !== FALSE) - { - $item = str_replace('.', $this->_escape_char.'.', $item); - - // remove duplicates if the user already included the escape - return preg_replace('/['.$this->_escape_char.']+/', $this->_escape_char, $this->_escape_char.$item); - } - } - - if (strpos($item, '.') !== FALSE) - { - $item = str_replace('.', $this->_escape_char.'.'.$this->_escape_char, $item); - } - - // remove duplicates if the user already included the escape - return preg_replace('/['.$this->_escape_char.']+/', $this->_escape_char, $this->_escape_char.$item.$this->_escape_char); - } - - // -------------------------------------------------------------------- - - /** * From Tables * * This public function implicitly groups FROM tables so there is no confusion @@ -410,23 +365,6 @@ class CI_DB_interbase_driver extends CI_DB { // -------------------------------------------------------------------- /** - * Insert statement - * - * Generates a platform-specific insert string from the supplied data - * - * @param string the table name - * @param array the insert keys - * @param array the insert values - * @return string - */ - protected function _insert($table, $keys, $values) - { - return 'INSERT INTO '.$table.' ('.implode(', ', $keys).') VALUES ('.implode(', ', $values).')'; - } - - // -------------------------------------------------------------------- - - /** * Update statement * * Generates a platform-specific update string from the supplied data @@ -459,15 +397,16 @@ class CI_DB_interbase_driver extends CI_DB { * Truncate statement * * Generates a platform-specific truncate string from the supplied data - * If the database does not support the truncate() command - * This public function maps to "DELETE FROM table" + * + * If the database does not support the truncate() command, + * then this method maps to 'DELETE FROM table' * * @param string the table name * @return string */ protected function _truncate($table) { - return $this->_delete($table); + return 'DELETE FROM '.$table; } // -------------------------------------------------------------------- diff --git a/system/database/drivers/mssql/mssql_driver.php b/system/database/drivers/mssql/mssql_driver.php index 2053ddb60..ec09028f9 100644 --- a/system/database/drivers/mssql/mssql_driver.php +++ b/system/database/drivers/mssql/mssql_driver.php @@ -388,43 +388,6 @@ class CI_DB_mssql_driver extends CI_DB { // -------------------------------------------------------------------- /** - * Escape the SQL Identifiers - * - * This function escapes column and table names - * - * @param string - * @return string - */ - public function _escape_identifiers($item) - { - if ($this->_escape_char == '') - { - return $item; - } - - foreach ($this->_reserved_identifiers as $id) - { - if (strpos($item, '.'.$id) !== FALSE) - { - $item = str_replace('.', $this->_escape_char.'.', $item); - - // remove duplicates if the user already included the escape - return preg_replace('/['.$this->_escape_char.']+/', $this->_escape_char, $this->_escape_char.$item); - } - } - - if (strpos($item, '.') !== FALSE) - { - $item = str_replace('.', $this->_escape_char.'.'.$this->_escape_char, $item); - } - - // remove duplicates if the user already included the escape - return preg_replace('/['.$this->_escape_char.']+/', $this->_escape_char, $this->_escape_char.$item.$this->_escape_char); - } - - // -------------------------------------------------------------------- - - /** * From Tables * * This function implicitly groups FROM tables so there is no confusion @@ -446,63 +409,19 @@ class CI_DB_mssql_driver extends CI_DB { // -------------------------------------------------------------------- /** - * Insert statement - * - * Generates a platform-specific insert string from the supplied data - * - * @param string the table name - * @param array the insert keys - * @param array the insert values - * @return string - */ - protected function _insert($table, $keys, $values) - { - return 'INSERT INTO '.$table.' ('.implode(', ', $keys).') VALUES ('.implode(', ', $values).')'; - } - - // -------------------------------------------------------------------- - - /** - * Update statement - * - * Generates a platform-specific update string from the supplied data - * - * @param string the table name - * @param array the update data - * @param array the where clause - * @param array the orderby clause - * @param array the limit clause - * @return string - */ - protected function _update($table, $values, $where, $orderby = array(), $limit = FALSE) - { - foreach ($values as $key => $val) - { - $valstr[] = $key.' = '.$val; - } - - return 'UPDATE '.$table.' SET '.implode(', ', $valstr) - .(($where != '' && count($where) > 0) ? ' WHERE '.implode(' ', $where) : '') - .(count($orderby) > 0 ? ' ORDER BY '.implode(', ', $orderby) : '') - .( ! $limit ? '' : ' LIMIT '.$limit); - } - - - // -------------------------------------------------------------------- - - /** * Truncate statement * * Generates a platform-specific truncate string from the supplied data - * If the database does not support the truncate() command - * This function maps to "DELETE FROM table" + * + * If the database does not support the truncate() command, + * then this method maps to 'DELETE FROM table' * * @param string the table name * @return string */ protected function _truncate($table) { - return 'TRUNCATE '.$table; + return 'TRUNCATE TABLE '.$table; } // -------------------------------------------------------------------- diff --git a/system/database/drivers/mssql/mssql_forge.php b/system/database/drivers/mssql/mssql_forge.php index 4312b22c9..6b793a37a 100644 --- a/system/database/drivers/mssql/mssql_forge.php +++ b/system/database/drivers/mssql/mssql_forge.php @@ -68,7 +68,7 @@ class CI_DB_mssql_forge extends CI_DB_forge { */ public function _drop_table($table) { - return 'DROP TABLE '.$this->db->_escape_identifiers($table); + return 'DROP TABLE '.$this->db->escape_identifiers($table); } // -------------------------------------------------------------------- @@ -92,7 +92,7 @@ class CI_DB_mssql_forge extends CI_DB_forge { $sql .= 'IF NOT EXISTS '; } - $sql .= $this->db->_escape_identifiers($table).'('; + $sql .= $this->db->escape_identifiers($table).' ('; $current_field_count = 0; foreach ($fields as $field => $attributes) diff --git a/system/database/drivers/mysql/mysql_driver.php b/system/database/drivers/mysql/mysql_driver.php index bef4111c3..28020d3e6 100644 --- a/system/database/drivers/mysql/mysql_driver.php +++ b/system/database/drivers/mysql/mysql_driver.php @@ -439,43 +439,6 @@ class CI_DB_mysql_driver extends CI_DB { // -------------------------------------------------------------------- /** - * Escape the SQL Identifiers - * - * This function escapes column and table names - * - * @param string - * @return string - */ - public function _escape_identifiers($item) - { - if ($this->_escape_char == '') - { - return $item; - } - - foreach ($this->_reserved_identifiers as $id) - { - if (strpos($item, '.'.$id) !== FALSE) - { - $item = str_replace('.', $this->_escape_char.'.', $item); - - // remove duplicates if the user already included the escape - return preg_replace('/['.$this->_escape_char.']+/', $this->_escape_char, $this->_escape_char.$item); - } - } - - if (strpos($item, '.') !== FALSE) - { - $item = str_replace('.', $this->_escape_char.'.'.$this->_escape_char, $item); - } - - // remove duplicates if the user already included the escape - return preg_replace('/['.$this->_escape_char.']+/', $this->_escape_char, $this->_escape_char.$item.$this->_escape_char); - } - - // -------------------------------------------------------------------- - - /** * From Tables * * This function implicitly groups FROM tables so there is no confusion @@ -497,59 +460,6 @@ class CI_DB_mysql_driver extends CI_DB { // -------------------------------------------------------------------- /** - * Insert statement - * - * Generates a platform-specific insert string from the supplied data - * - * @param string the table name - * @param array the insert keys - * @param array the insert values - * @return string - */ - protected function _insert($table, $keys, $values) - { - return 'INSERT INTO '.$table.' ('.implode(', ', $keys).') VALUES ('.implode(', ', $values).')'; - } - - // -------------------------------------------------------------------- - - - /** - * Replace statement - * - * Generates a platform-specific replace string from the supplied data - * - * @param string the table name - * @param array the insert keys - * @param array the insert values - * @return string - */ - protected function _replace($table, $keys, $values) - { - return 'REPLACE INTO '.$table.' ('.implode(', ', $keys).') VALUES ('.implode(', ', $values).')'; - } - - // -------------------------------------------------------------------- - - /** - * Insert_batch statement - * - * Generates a platform-specific insert string from the supplied data - * - * @param string the table name - * @param array the insert keys - * @param array the insert values - * @return string - */ - protected function _insert_batch($table, $keys, $values) - { - return 'INSERT INTO '.$table.' ('.implode(', ', $keys).') VALUES '.implode(', ', $values); - } - - // -------------------------------------------------------------------- - - - /** * Update statement * * Generates a platform-specific update string from the supplied data @@ -624,23 +534,6 @@ class CI_DB_mysql_driver extends CI_DB { // -------------------------------------------------------------------- /** - * Truncate statement - * - * Generates a platform-specific truncate string from the supplied data - * If the database does not support the truncate() command - * This function maps to "DELETE FROM table" - * - * @param string the table name - * @return string - */ - protected function _truncate($table) - { - return 'TRUNCATE '.$table; - } - - // -------------------------------------------------------------------- - - /** * Delete statement * * Generates a platform-specific delete string from the supplied data diff --git a/system/database/drivers/mysql/mysql_forge.php b/system/database/drivers/mysql/mysql_forge.php index 11172b41b..9e19de1bb 100644 --- a/system/database/drivers/mysql/mysql_forge.php +++ b/system/database/drivers/mysql/mysql_forge.php @@ -42,7 +42,7 @@ class CI_DB_mysql_forge extends CI_DB_forge { */ public function _create_database($name) { - return 'CREATE DATABASE '.$name; + return 'CREATE DATABASE '.$name.' CHARACTER SET '.$this->db->char_set.' COLLATE '.$this->db->dbcollat; } // -------------------------------------------------------------------- diff --git a/system/database/drivers/mysqli/mysqli_driver.php b/system/database/drivers/mysqli/mysqli_driver.php index 47b0449d6..50e213641 100644 --- a/system/database/drivers/mysqli/mysqli_driver.php +++ b/system/database/drivers/mysqli/mysqli_driver.php @@ -439,43 +439,6 @@ class CI_DB_mysqli_driver extends CI_DB { // -------------------------------------------------------------------- /** - * Escape the SQL Identifiers - * - * This function escapes column and table names - * - * @param string - * @return string - */ - public function _escape_identifiers($item) - { - if ($this->_escape_char == '') - { - return $item; - } - - foreach ($this->_reserved_identifiers as $id) - { - if (strpos($item, '.'.$id) !== FALSE) - { - $item = str_replace('.', $this->_escape_char.'.', $item); - - // remove duplicates if the user already included the escape - return preg_replace('/['.$this->_escape_char.']+/', $this->_escape_char, $this->_escape_char.$item); - } - } - - if (strpos($item, '.') !== FALSE) - { - $item = str_replace('.', $this->_escape_char.'.'.$this->_escape_char, $item); - } - - // remove duplicates if the user already included the escape - return preg_replace('/['.$this->_escape_char.']+/', $this->_escape_char, $this->_escape_char.$item.$this->_escape_char); - } - - // -------------------------------------------------------------------- - - /** * From Tables * * This function implicitly groups FROM tables so there is no confusion @@ -497,85 +460,6 @@ class CI_DB_mysqli_driver extends CI_DB { // -------------------------------------------------------------------- /** - * Insert statement - * - * Generates a platform-specific insert string from the supplied data - * - * @param string the table name - * @param array the insert keys - * @param array the insert values - * @return string - */ - protected function _insert($table, $keys, $values) - { - return 'INSERT INTO '.$table.' ('.implode(', ', $keys).') VALUES ('.implode(', ', $values).')'; - } - - // -------------------------------------------------------------------- - - /** - * Insert_batch statement - * - * Generates a platform-specific insert string from the supplied data - * - * @param string the table name - * @param array the insert keys - * @param array the insert values - * @return string - */ - protected function _insert_batch($table, $keys, $values) - { - return 'INSERT INTO '.$table.' ('.implode(', ', $keys).') VALUES '.implode(', ', $values); - } - - // -------------------------------------------------------------------- - - - /** - * Replace statement - * - * Generates a platform-specific replace string from the supplied data - * - * @param string the table name - * @param array the insert keys - * @param array the insert values - * @return string - */ - protected function _replace($table, $keys, $values) - { - return 'REPLACE INTO '.$table.' ('.implode(', ', $keys).') VALUES ('.implode(', ', $values).')'; - } - - // -------------------------------------------------------------------- - - /** - * Update statement - * - * Generates a platform-specific update string from the supplied data - * - * @param string the table name - * @param array the update data - * @param array the where clause - * @param array the orderby clause - * @param array the limit clause - * @return string - */ - protected function _update($table, $values, $where, $orderby = array(), $limit = FALSE) - { - foreach ($values as $key => $val) - { - $valstr[] = $key.' = '.$val; - } - - return 'UPDATE '.$table.' SET '.implode(', ', $valstr) - .(($where != '' && count($where) > 0) ? ' WHERE '.implode(' ', $where) : '') - .(count($orderby) > 0 ? ' ORDER BY '.implode(', ', $orderby) : '') - .( ! $limit ? '' : ' LIMIT '.$limit); - } - - // -------------------------------------------------------------------- - - /** * Update_Batch statement * * Generates a platform-specific batch update string from the supplied data @@ -619,23 +503,6 @@ class CI_DB_mysqli_driver extends CI_DB { // -------------------------------------------------------------------- /** - * Truncate statement - * - * Generates a platform-specific truncate string from the supplied data - * If the database does not support the truncate() command - * This function maps to "DELETE FROM table" - * - * @param string the table name - * @return string - */ - protected function _truncate($table) - { - return 'TRUNCATE '.$table; - } - - // -------------------------------------------------------------------- - - /** * Delete statement * * Generates a platform-specific delete string from the supplied data diff --git a/system/database/drivers/mysqli/mysqli_forge.php b/system/database/drivers/mysqli/mysqli_forge.php index 8cf0ae1fd..4b6939e2a 100644 --- a/system/database/drivers/mysqli/mysqli_forge.php +++ b/system/database/drivers/mysqli/mysqli_forge.php @@ -42,7 +42,7 @@ class CI_DB_mysqli_forge extends CI_DB_forge { */ public function _create_database($name) { - return 'CREATE DATABASE '.$name; + return 'CREATE DATABASE '.$name.' CHARACTER SET '.$this->db->char_set.' COLLATE '.$this->db->dbcollat; } // -------------------------------------------------------------------- @@ -148,7 +148,7 @@ class CI_DB_mysqli_forge extends CI_DB_forge { $sql .= 'IF NOT EXISTS '; } - $sql .= $this->db->_escape_identifiers($table).' ('.$this->_process_fields($fields); + $sql .= $this->db->escape_identifiers($table).' ('.$this->_process_fields($fields); if (count($primary_keys) > 0) { @@ -187,7 +187,7 @@ class CI_DB_mysqli_forge extends CI_DB_forge { */ public function _drop_table($table) { - return 'DROP TABLE IF EXISTS '.$this->db->_escape_identifiers($table); + return 'DROP TABLE IF EXISTS '.$this->db->escape_identifiers($table); } // -------------------------------------------------------------------- diff --git a/system/database/drivers/mysqli/mysqli_utility.php b/system/database/drivers/mysqli/mysqli_utility.php index 4d7002e78..cb3f86b8b 100644 --- a/system/database/drivers/mysqli/mysqli_utility.php +++ b/system/database/drivers/mysqli/mysqli_utility.php @@ -56,7 +56,7 @@ class CI_DB_mysqli_utility extends CI_DB_utility { */ public function _optimize_table($table) { - return 'OPTIMIZE TABLE '.$this->db->_escape_identifiers($table); + return 'OPTIMIZE TABLE '.$this->db->escape_identifiers($table); } // -------------------------------------------------------------------- @@ -71,7 +71,7 @@ class CI_DB_mysqli_utility extends CI_DB_utility { */ public function _repair_table($table) { - return 'REPAIR TABLE '.$this->db->_escape_identifiers($table); + return 'REPAIR TABLE '.$this->db->escape_identifiers($table); } // -------------------------------------------------------------------- diff --git a/system/database/drivers/oci8/oci8_driver.php b/system/database/drivers/oci8/oci8_driver.php index 3bc8c114c..6e225ee1f 100644 --- a/system/database/drivers/oci8/oci8_driver.php +++ b/system/database/drivers/oci8/oci8_driver.php @@ -46,7 +46,6 @@ * permit access to oracle databases * * @author Kelly McArdle - * */ class CI_DB_oci8_driver extends CI_DB { @@ -68,7 +67,7 @@ class CI_DB_oci8_driver extends CI_DB { protected $_random_keyword = ' ASC'; // not currently supported // Set "auto commit" by default - protected $_commit = OCI_COMMIT_ON_SUCCESS; + public $commit_mode = OCI_COMMIT_ON_SUCCESS; // need to track statement id and cursor id public $stmt_id; @@ -186,19 +185,6 @@ class CI_DB_oci8_driver extends CI_DB { // -------------------------------------------------------------------- /** - * Select the database - * - * @return resource - */ - public function db_select() - { - // Not in Oracle - schemas are actually usernames - return TRUE; - } - - // -------------------------------------------------------------------- - - /** * Database version number * * @return string @@ -220,12 +206,13 @@ class CI_DB_oci8_driver extends CI_DB { */ protected function _execute($sql) { - // oracle must parse the query before it is run. All of the actions with - // the query are based on the statement id returned by ociparse + /* Oracle must parse the query before it is run. All of the actions with + * the query are based on the statement id returned by oci_parse(). + */ $this->stmt_id = FALSE; $this->_set_stmt_id($sql); oci_set_prefetch($this->stmt_id, 1000); - return @oci_execute($this->stmt_id, $this->_commit); + return @oci_execute($this->stmt_id, $this->commit_mode); } /** @@ -251,8 +238,7 @@ class CI_DB_oci8_driver extends CI_DB { */ public function get_cursor() { - $this->curs_id = oci_new_cursor($this->conn_id); - return $this->curs_id; + return $this->curs_id = oci_new_cursor($this->conn_id); } // -------------------------------------------------------------------- @@ -260,19 +246,19 @@ class CI_DB_oci8_driver extends CI_DB { /** * Stored Procedure. Executes a stored procedure * - * @param string package stored procedure is in - * @param string stored procedure to execute + * @param string package name in which the stored procedure is in + * @param string stored procedure name to execute * @param array parameters - * @return object + * @return mixed * * params array keys * * KEY OPTIONAL NOTES - * name no the name of the parameter should be in :<param_name> format - * value no the value of the parameter. If this is an OUT or IN OUT parameter, - * this should be a reference to a variable - * type yes the type of the parameter - * length yes the max size of the parameter + * name no the name of the parameter should be in :<param_name> format + * value no the value of the parameter. If this is an OUT or IN OUT parameter, + * this should be a reference to a variable + * type yes the type of the parameter + * length yes the max size of the parameter */ public function stored_procedure($package, $procedure, $params) { @@ -287,24 +273,24 @@ class CI_DB_oci8_driver extends CI_DB { } // build the query string - $sql = "begin $package.$procedure("; + $sql = 'BEGIN '.$package.'.'.$procedure.'('; $have_cursor = FALSE; foreach ($params as $param) { - $sql .= $param['name'] . ","; + $sql .= $param['name'].','; - if (array_key_exists('type', $param) && ($param['type'] === OCI_B_CURSOR)) + if (isset($param['type']) && $param['type'] === OCI_B_CURSOR) { $have_cursor = TRUE; } } - $sql = trim($sql, ",") . "); end;"; + $sql = trim($sql, ',') . '); END;'; $this->stmt_id = FALSE; $this->_set_stmt_id($sql); $this->_bind_params($params); - $this->query($sql, FALSE, $have_cursor); + return $this->query($sql, FALSE, $have_cursor); } // -------------------------------------------------------------------- @@ -360,7 +346,7 @@ class CI_DB_oci8_driver extends CI_DB { // even if the queries produce a successful result. $this->_trans_failure = ($test_mode === TRUE) ? TRUE : FALSE; - $this->_commit = OCI_DEFAULT; + $this->commit_mode = (is_php('5.3.2')) ? OCI_NO_AUTO_COMMIT : OCI_DEFAULT; return TRUE; } @@ -384,9 +370,8 @@ class CI_DB_oci8_driver extends CI_DB { return TRUE; } - $ret = oci_commit($this->conn_id); - $this->_commit = OCI_COMMIT_ON_SUCCESS; - return $ret; + $this->commit_mode = OCI_COMMIT_ON_SUCCESS; + return oci_commit($this->conn_id); } // -------------------------------------------------------------------- @@ -398,20 +383,14 @@ class CI_DB_oci8_driver extends CI_DB { */ public function trans_rollback() { - if ( ! $this->trans_enabled) - { - return TRUE; - } - // When transactions are nested we only begin/commit/rollback the outermost ones - if ($this->_trans_depth > 0) + if ( ! $this->trans_enabled OR $this->_trans_depth > 0) { return TRUE; } - $ret = oci_rollback($this->conn_id); - $this->_commit = OCI_COMMIT_ON_SUCCESS; - return $ret; + $this->commit_mode = OCI_COMMIT_ON_SUCCESS; + return oci_rollback($this->conn_id); } // -------------------------------------------------------------------- @@ -482,7 +461,7 @@ class CI_DB_oci8_driver extends CI_DB { * the specified database * * @param string - * @return string + * @return int */ public function count_all($table = '') { @@ -514,11 +493,11 @@ class CI_DB_oci8_driver extends CI_DB { */ protected function _list_tables($prefix_limit = FALSE) { - $sql = "SELECT TABLE_NAME FROM ALL_TABLES"; + $sql = 'SELECT TABLE_NAME FROM ALL_TABLES'; - if ($prefix_limit !== FALSE AND $this->dbprefix != '') + if ($prefix_limit !== FALSE && $this->dbprefix != '') { - $sql .= " WHERE TABLE_NAME LIKE '".$this->escape_like_str($this->dbprefix)."%' ".sprintf($this->_like_escape_str, $this->_like_escape_chr); + return $sql." WHERE TABLE_NAME LIKE '".$this->escape_like_str($this->dbprefix)."%' ".sprintf($this->_like_escape_str, $this->_like_escape_chr); } return $sql; @@ -536,7 +515,7 @@ class CI_DB_oci8_driver extends CI_DB { */ protected function _list_columns($table = '') { - return "SELECT COLUMN_NAME FROM all_tab_columns WHERE table_name = '$table'"; + return 'SELECT COLUMN_NAME FROM all_tab_columns WHERE table_name = \''.$table.'\''; } // -------------------------------------------------------------------- @@ -551,7 +530,7 @@ class CI_DB_oci8_driver extends CI_DB { */ protected function _field_data($table) { - return "SELECT * FROM ".$table." where rownum = 1"; + return 'SELECT * FROM '.$table.' WHERE rownum = 1'; } // -------------------------------------------------------------------- @@ -588,47 +567,6 @@ class CI_DB_oci8_driver extends CI_DB { // -------------------------------------------------------------------- /** - * Escape the SQL Identifiers - * - * This function escapes column and table names - * - * @param string - * @return string - */ - public function _escape_identifiers($item) - { - if ($this->_escape_char == '') - { - return $item; - } - - foreach ($this->_reserved_identifiers as $id) - { - if (strpos($item, '.'.$id) !== FALSE) - { - $str = $this->_escape_char. str_replace('.', $this->_escape_char.'.', $item); - - // remove duplicates if the user already included the escape - return preg_replace('/['.$this->_escape_char.']+/', $this->_escape_char, $str); - } - } - - if (strpos($item, '.') !== FALSE) - { - $str = $this->_escape_char.str_replace('.', $this->_escape_char.'.'.$this->_escape_char, $item).$this->_escape_char; - } - else - { - $str = $this->_escape_char.$item.$this->_escape_char; - } - - // remove duplicates if the user already included the escape - return preg_replace('/['.$this->_escape_char.']+/', $this->_escape_char, $str); - } - - // -------------------------------------------------------------------- - - /** * From Tables * * This function implicitly groups FROM tables so there is no confusion @@ -639,29 +577,7 @@ class CI_DB_oci8_driver extends CI_DB { */ protected function _from_tables($tables) { - if ( ! is_array($tables)) - { - $tables = array($tables); - } - - return implode(', ', $tables); - } - - // -------------------------------------------------------------------- - - /** - * Insert statement - * - * Generates a platform-specific insert string from the supplied data - * - * @param string the table name - * @param array the insert keys - * @param array the insert values - * @return string - */ - protected function _insert($table, $keys, $values) - { - return "INSERT INTO ".$table." (".implode(', ', $keys).") VALUES (".implode(', ', $values).")"; + return is_array($tables) ? implode(', ', $tables) : $tables; } // -------------------------------------------------------------------- @@ -683,46 +599,10 @@ class CI_DB_oci8_driver extends CI_DB { for ($i = 0, $c = count($values); $i < $c; $i++) { - $sql .= ' INTO ' . $table . ' (' . $keys . ') VALUES ' . $values[$i] . "\n"; - } - - $sql .= 'SELECT * FROM dual'; - - return $sql; - } - - // -------------------------------------------------------------------- - - /** - * Update statement - * - * Generates a platform-specific update string from the supplied data - * - * @param string the table name - * @param array the update data - * @param array the where clause - * @param array the orderby clause - * @param array the limit clause - * @return string - */ - protected function _update($table, $values, $where, $orderby = array(), $limit = FALSE) - { - foreach ($values as $key => $val) - { - $valstr[] = $key." = ".$val; + $sql .= ' INTO '.$table.' ('.$keys.') VALUES '.$values[$i]."\n"; } - $limit = ( ! $limit) ? '' : ' LIMIT '.$limit; - - $orderby = (count($orderby) >= 1)?' ORDER BY '.implode(", ", $orderby):''; - - $sql = "UPDATE ".$table." SET ".implode(', ', $valstr); - - $sql .= ($where != '' AND count($where) >=1) ? " WHERE ".implode(" ", $where) : ''; - - $sql .= $orderby.$limit; - - return $sql; + return $sql.'SELECT * FROM dual'; } // -------------------------------------------------------------------- @@ -731,15 +611,16 @@ class CI_DB_oci8_driver extends CI_DB { * Truncate statement * * Generates a platform-specific truncate string from the supplied data - * If the database does not support the truncate() command - * This function maps to "DELETE FROM table" + * + * If the database does not support the truncate() command, + * then this method maps to 'DELETE FROM table' * * @param string the table name * @return string */ protected function _truncate($table) { - return "TRUNCATE TABLE ".$table; + return 'TRUNCATE TABLE '.$table; } // -------------------------------------------------------------------- @@ -757,22 +638,18 @@ class CI_DB_oci8_driver extends CI_DB { protected function _delete($table, $where = array(), $like = array(), $limit = FALSE) { $conditions = ''; - if (count($where) > 0 OR count($like) > 0) { - $conditions = "\nWHERE "; - $conditions .= implode("\n", $this->ar_where); + $conditions = "\nWHERE ".implode("\n", $this->ar_where); if (count($where) > 0 && count($like) > 0) { - $conditions .= " AND "; + $conditions .= ' AND '; } $conditions .= implode("\n", $like); } - $limit = ( ! $limit) ? '' : ' LIMIT '.$limit; - - return "DELETE FROM ".$table.$conditions.$limit; + return 'DELETE FROM '.$table.$conditions.( ! $limit ? '' : ' LIMIT '.$limit); } // -------------------------------------------------------------------- @@ -789,18 +666,9 @@ class CI_DB_oci8_driver extends CI_DB { */ protected function _limit($sql, $limit, $offset) { - $limit = $offset + $limit; - $newsql = "SELECT * FROM (select inner_query.*, rownum rnum FROM ($sql) inner_query WHERE rownum < $limit)"; - - if ($offset != 0) - { - $newsql .= " WHERE rnum >= $offset"; - } - - // remember that we used limits $this->limit_used = TRUE; - - return $newsql; + return 'SELECT * FROM (SELECT inner_query.*, rownum rnum FROM ('.$sql.') inner_query WHERE rownum < '.($offset + $limit).')' + .($offset != 0 ? ' WHERE rnum >= '.$offset : ''); } // -------------------------------------------------------------------- diff --git a/system/database/drivers/oci8/oci8_forge.php b/system/database/drivers/oci8/oci8_forge.php index 8285a29d2..033e618e7 100644 --- a/system/database/drivers/oci8/oci8_forge.php +++ b/system/database/drivers/oci8/oci8_forge.php @@ -42,6 +42,7 @@ class CI_DB_oci8_forge extends CI_DB_forge { */ public function _create_database($name) { + // Not supported - schemas in Oracle are actual usernames return FALSE; } @@ -55,6 +56,7 @@ class CI_DB_oci8_forge extends CI_DB_forge { */ public function _drop_database($name) { + // Not supported - schemas in Oracle are actual usernames return FALSE; } @@ -68,7 +70,7 @@ class CI_DB_oci8_forge extends CI_DB_forge { * @param mixed primary key(s) * @param mixed key(s) * @param bool should 'IF NOT EXISTS' be added to the SQL - * @return bool + * @return string */ public function _create_table($table, $fields, $primary_keys, $keys, $if_not_exists) { @@ -79,7 +81,7 @@ class CI_DB_oci8_forge extends CI_DB_forge { $sql .= 'IF NOT EXISTS '; } - $sql .= $this->db->_escape_identifiers($table).' ('; + $sql .= $this->db->escape_identifiers($table).' ('; $current_field_count = 0; foreach ($fields as $field => $attributes) @@ -128,7 +130,7 @@ class CI_DB_oci8_forge extends CI_DB_forge { $key = array($this->db->protect_identifiers($key)); } - $sql .= ",\n\tUNIQUE COLUMNS (".implode(', ', $key).")"; + $sql .= ",\n\tUNIQUE COLUMNS (".implode(', ', $key).')'; } } @@ -140,11 +142,11 @@ class CI_DB_oci8_forge extends CI_DB_forge { /** * Drop Table * - * @return bool + * @return string */ public function _drop_table($table) { - return FALSE; + return 'DROP TABLE '.$this->db->protect_identifiers($table); } // -------------------------------------------------------------------- @@ -169,33 +171,15 @@ class CI_DB_oci8_forge extends CI_DB_forge { $sql = 'ALTER TABLE '.$this->db->protect_identifiers($table).' '.$alter_type.' '.$this->db->protect_identifiers($column_name); // DROP has everything it needs now. - if ($alter_type == 'DROP') + if ($alter_type === 'DROP') { return $sql; } - $sql .= " $column_definition"; - - if ($default_value != '') - { - $sql .= " DEFAULT \"$default_value\""; - } - - if ($null === NULL) - { - $sql .= ' NULL'; - } - else - { - $sql .= ' NOT NULL'; - } - - if ($after_field != '') - { - return $sql.' AFTER '.$this->db->protect_identifiers($after_field); - } - - return $sql; + return $sql.' '.$column_definition + .($default_value != '' ? ' DEFAULT "'.$default_value.'"' : '') + .($null === NULL ? ' NULL' : ' NOT NULL') + .($after_field != '' ? ' AFTER '.$this->db->protect_identifiers($after_field) : ''); } diff --git a/system/database/drivers/oci8/oci8_result.php b/system/database/drivers/oci8/oci8_result.php index c3f775730..aad24cfd9 100644 --- a/system/database/drivers/oci8/oci8_result.php +++ b/system/database/drivers/oci8/oci8_result.php @@ -39,6 +39,12 @@ class CI_DB_oci8_result extends CI_DB_result { public $stmt_id; public $curs_id; public $limit_used; + public $commit_mode; + + /* Overwriting the parent here, so we have a way to know if it's + * already called or not: + */ + public $num_rows; public function __construct(&$driver_object) { @@ -46,28 +52,32 @@ class CI_DB_oci8_result extends CI_DB_result { $this->stmt_id = $driver_object->stmt_id; $this->curs_id = $driver_object->curs_id; $this->limit_used = $driver_object->limit_used; + $this->commit_mode =& $driver_object->commit_mode; $driver_object->stmt_id = FALSE; } /** * Number of rows in the result set. * - * Oracle doesn't have a graceful way to retun the number of rows + * Oracle doesn't have a graceful way to return the number of rows * so we have to use what amounts to a hack. * * @return int */ public function num_rows() { - if ($this->num_rows === 0 && count($this->result_array()) > 0) + if ( ! is_int($this->num_rows)) { - $this->num_rows = count($this->result_array()); - @oci_execute($this->stmt_id, OCI_DEFAULT); - - if ($this->curs_id) + if (count($this->result_array) > 0) + { + return $this->num_rows = count($this->result_array); + } + elseif (count($this->result_object) > 0) { - @oci_execute($this->curs_id, OCI_DEFAULT); + return $this->num_rows = count($this->result_object); } + + return $this->num_rows = count($this->result_array()); } return $this->num_rows; @@ -85,12 +95,7 @@ class CI_DB_oci8_result extends CI_DB_result { $count = @oci_num_fields($this->stmt_id); // if we used a limit we subtract it - if ($this->limit_used) - { - $count = $count - 1; - } - - return $count; + return ($this->limit_used) ? $count - 1 : $count; } // -------------------------------------------------------------------- @@ -126,10 +131,10 @@ class CI_DB_oci8_result extends CI_DB_result { $retval = array(); for ($c = 1, $fieldCount = $this->num_fields(); $c <= $fieldCount; $c++) { - $F = new stdClass(); - $F->name = oci_field_name($this->stmt_id, $c); - $F->type = oci_field_type($this->stmt_id, $c); - $F->max_length = oci_field_size($this->stmt_id, $c); + $F = new stdClass(); + $F->name = oci_field_name($this->stmt_id, $c); + $F->type = oci_field_type($this->stmt_id, $c); + $F->max_length = oci_field_size($this->stmt_id, $c); $retval[] = $F; } @@ -151,6 +156,17 @@ class CI_DB_oci8_result extends CI_DB_result { oci_free_statement($this->result_id); $this->result_id = FALSE; } + + if (is_resource($this->stmt_id)) + { + oci_free_statement($this->stmt_id); + } + + if (is_resource($this->curs_id)) + { + oci_cancel($this->curs_id); + $this->curs_id = NULL; + } } // -------------------------------------------------------------------- @@ -180,13 +196,13 @@ class CI_DB_oci8_result extends CI_DB_result { protected function _fetch_object() { $id = ($this->curs_id) ? $this->curs_id : $this->stmt_id; - return @oci_fetch_object($id); + return oci_fetch_object($id); } // -------------------------------------------------------------------- /** - * Query result. "array" version. + * Query result. Array version. * * @return array */ @@ -196,14 +212,433 @@ class CI_DB_oci8_result extends CI_DB_result { { return $this->result_array; } + elseif (count($this->result_object) > 0) + { + for ($i = 0, $c = count($this->result_object); $i < $c; $i++) + { + $this->result_array[$i] = (array) $this->result_object[$i]; + } + + return $this->result_array; + } + elseif (is_array($this->row_data)) + { + if (count($this->row_data) === 0) + { + return $this->result_array; + } + else + { + $row_index = count($this->row_data); + } + } + else + { + $row_index = 0; + $this->row_data = array(); + } $row = NULL; while ($row = $this->_fetch_assoc()) { - $this->result_array[] = $row; + $this->row_data[$row_index++] = $row; + } + + // Un-comment the following line, in case it becomes needed + // $this->_data_seek(); + return $this->result_array = $this->row_data; + } + + // -------------------------------------------------------------------- + + /** + * Query result. "object" version. + * + * @return array + */ + public function result_object() + { + if (count($this->result_object) > 0) + { + return $this->result_object; + } + elseif (count($this->result_array) > 0) + { + for ($i = 0, $c = count($this->result_array); $i < $c; $i++) + { + $this->result_object[] = (object) $this->result_array[$i]; + } + + return $this->result_object; + } + elseif (is_array($this->row_data)) + { + if (count($this->row_data) === 0) + { + return $this->result_object; + } + else + { + $row_index = count($this->row_data); + for ($i = 0; $i < $row_index; $i++) + { + $this->result_object[$i] = (object) $this->row_data[$i]; + } + } + } + else + { + $row_index = 0; + $this->row_data = array(); + } + + $row = NULL; + while ($row = $this->_fetch_object()) + { + $this->row_data[$row_index] = (array) $row; + $this->result_object[$row_index++] = $row; + } + + // Un-comment the following line, in case it becomes needed + // $this->_data_seek(); + return $this->result_object; + } + + // -------------------------------------------------------------------- + + /** + * Query result. Custom object version. + * + * @param string class name used to instantiate rows to + * @return array + */ + public function custom_result_object($class_name) + { + if (isset($this->custom_result_object[$class_name])) + { + return $this->custom_result_object[$class_name]; + } + + if ( ! class_exists($class_name) OR $this->result_id === FALSE OR $this->num_rows() === 0) + { + return array(); + } + + /* Even if we didn't have result_array or result_object + * set prior to custom_result_object() being called, + * num_rows() has already done so. + * Pass by reference, as we don't know how + * large it might be and we don't want 1000 row + * sets being copied. + */ + if (count($this->result_array) > 0) + { + $data = &$this->result_array; + } + elseif (count($this->result_object) > 0) + { + $data = &$this->result_object; + } + + $this->custom_result_object[$class_name] = array(); + for ($i = 0, $c = count($data); $i < $c; $i++) + { + $this->custom_result_object[$class_name][$i] = new $class_name(); + foreach ($data[$i] as $key => $value) + { + $this->custom_result_object[$class_name][$i]->$key = $value; + } + } + + return $this->custom_result_object[$class_name]; + } + + // -------------------------------------------------------------------- + + /* Single row result. + * + * Acts as a wrapper for row_object(), row_array() + * and custom_row_object(). Also used by first_row(), next_row() + * and previous_row(). + * + * @param int row index + * @param string ('object', 'array' or a custom class name) + * @return mixed whatever was passed to the second parameter + */ + public function row($n = 0, $type = 'object') + { + if ($type === 'object') + { + return $this->row_object($n); + } + elseif ($type === 'array') + { + return $this->row_array($n); + } + + return $this->custom_row_object($n, $type); + } + + // -------------------------------------------------------------------- + + /* Single row result. Array version. + * + * @param int row index + * @return array + */ + public function row_array($n = 0) + { + // Make sure $n is not a string + if ( ! is_int($n)) + { + $n = (int) $n; + } + + /* If row_data is initialized, it means that we've already tried + * (at least) to fetch some data, so ... check if we already have + * this row. + */ + if (is_array($this->row_data)) + { + /* If we already have row_data[$n] - return it. + * + * If we enter the elseif, there's a number of reasons to + * return an empty array: + * + * - count($this->row_data) === 0 means there are no results + * - num_rows being set, result_array and/or result_object + * having count() > 0 means that we've already fetched all + * data and $n is greater than our highest row index available + * - $n < $this->current_row means that if such row existed, + * we would've already returned it, therefore $n is an + * invalid index + */ + if (isset($this->row_data[$n])) // We already have this row + { + $this->current_row = $n; + return $this->row_data[$n]; + } + elseif (count($this->row_data) === 0 OR is_int($this->num_rows) + OR count($this->result_array) > 0 OR count($this->result_object) > 0 + OR $n < $this->current_row) + { + // No such row exists + return array(); + } + + // Get the next row index that would actually need to be fetched + $current_row = ($this->current_row < count($this->row_data)) ? count($this->row_data) : $this->current_row + 1; + } + else + { + $current_row = $this->current_row = 0; + $this->row_data = array(); + } + + /* Fetch more data, if available + * + * NOTE: Operator precedence is important here, if you change + * 'AND' with '&&' - it WILL BREAK the results, as + * $row will be assigned the scalar value of both + * expressions! + */ + while ($row = $this->_fetch_assoc() AND $current_row <= $n) + { + $this->row_data[$current_row++] = $row; } - return $this->result_array; + // This would mean that there's no (more) data to fetch + if ( ! is_array($this->row_data) OR ! isset($this->row_data[$n])) + { + // Cache what we already have + if (is_array($this->row_data)) + { + $this->num_rows = count($this->row_data); + /* Usually, row_data could have less elements than result_array, + * but at this point - they should be exactly the same. + */ + $this->result_array = $this->row_data; + } + else + { + $this->num_rows = 0; + } + + return array(); + } + + $this->current_row = $n; + return $this->row_data[$n]; + } + + // -------------------------------------------------------------------- + + /* Single row result. Object version. + * + * @param int row index + * @return mixed object if row found; empty array if not + */ + public function row_object($n = 0) + { + // Make sure $n is not a string + if ( ! is_int($n)) + { + $n = (int) $n; + } + /* Logic here is exactly the same as in row_array, + * except we have to cast row_data[$n] to an object. + * + * If we already have result_object though - we can + * directly return from it. + */ + if (isset($this->result_object[$n])) + { + $this->current_row = $n; + // Set this, if not already done. + if ( ! is_int($this->num_rows)) + { + $this->num_rows = count($this->result_object); + } + + return $this->result_object[$n]; + } + + $row = $this->row_array($n); + // Cast only if the row exists + if (count($row) > 0) + { + $this->current_row = $n; + return (object) $row; + } + + return array(); + } + + // -------------------------------------------------------------------- + + /* Single row result. Custom object version. + * + * @param int row index + * @param string custom class name + * @return mixed custom object if row found; empty array otherwise + */ + public function custom_row_object($n = 0, $class_name) + { + // Make sure $n is not a string + if ( ! is_int($n)) + { + $n = (int) $n; + } + + if (array_key_exists($class_name, $this->custom_result_object)) + { + /* We already have a the whole result set with this class_name, + * return the specified row if it exists, and an empty array if + * it doesn't. + */ + if (isset($this->custom_result_object[$class_name][$n])) + { + $this->current_row = $n; + return $this->custom_result_object[$class_name][$n]; + } + else + { + return array(); + } + } + elseif ( ! class_exists($class_name)) // No such class exists + { + return array(); + } + + $row = $this->row_array($n); + // An array would mean that the row doesn't exist + if (is_array($row)) + { + return $row; + } + + // Convert to the desired class and return + $row_object = new $class_name(); + foreach ($row as $key => $value) + { + $row_object->$key = $value; + } + + $this->current_row = $n; + return $row_object; + } + + // -------------------------------------------------------------------- + + /* First row result. + * + * @param string ('object', 'array' or a custom class name) + * @return mixed whatever was passed to the second parameter + */ + public function first_row($type = 'object') + { + return $this->row(0, $type); + } + + // -------------------------------------------------------------------- + + /* Last row result. + * + * @param string ('object', 'array' or a custom class name) + * @return mixed whatever was passed to the second parameter + */ + public function last_row($type = 'object') + { + $result = &$this->result($type); + if ( ! isset($this->num_rows)) + { + $this->num_rows = count($result); + } + $this->current_row = $this->num_rows - 1; + return $result[$this->current_row]; + } + + // -------------------------------------------------------------------- + + /* Next row result. + * + * @param string ('object', 'array' or a custom class name) + * @return mixed whatever was passed to the second parameter + */ + public function next_row($type = 'object') + { + if (is_array($this->row_data)) + { + $count = count($this->row_data); + if ($this->current_row > $count OR ($this->current_row === 0 && $count === 0)) + { + $n = $count; + } + else + { + $n = $this->current_row + 1; + } + } + else + { + $n = 0; + } + + return $this->row($n, $type); + } + + // -------------------------------------------------------------------- + + /* Previous row result. + * + * @param string ('object', 'array' or a custom class name) + * @return mixed whatever was passed to the second parameter + */ + public function previous_row($type = 'object') + { + $n = ($this->current_row !== 0) ? $this->current_row - 1 : 0; + return $this->row($n, $type); } // -------------------------------------------------------------------- @@ -213,13 +648,54 @@ class CI_DB_oci8_result extends CI_DB_result { * * Moves the internal pointer to the desired offset. We call * this internally before fetching results to make sure the - * result set starts at zero + * result set starts at zero. * - * @return array + * Oracle's PHP extension doesn't have an easy way of doing this + * and the only workaround is to (re)execute the statement or cursor + * in order to go to the first (zero) index of the result set. + * Then, we would need to "dummy" fetch ($n - 1) rows to get to the + * right one. + * + * This is as ridiculous as it sounds and it's the reason why every + * other method that is fetching data tries to use an already "cached" + * result set. Keeping this just in case it becomes needed at + * some point in the future, but it will only work for resetting the + * pointer to zero. + * + * @return bool */ - protected function _data_seek($n = 0) + protected function _data_seek() { - return FALSE; // Not needed + /* The PHP manual says that if OCI_NO_AUTO_COMMIT mode + * is used, and oci_rollback() and/or oci_commit() are + * not subsequently called - this will cause an unnecessary + * rollback to be triggered at the end of the script execution. + * + * Therefore we'll try to avoid using that mode flag + * if we're not currently in the middle of a transaction. + */ + if ($this->commit_mode !== OCI_COMMIT_ON_SUCCESS) + { + $result = @oci_execute($this->stmt_id, $this->commit_mode); + } + else + { + $result = @oci_execute($this->stmt_id); + } + + if ($result && $this->curs_id) + { + if ($this->commit_mode !== OCI_COMMIT_ON_SUCCESS) + { + return @oci_execute($this->curs_id, $this->commit_mode); + } + else + { + return @oci_execute($this->curs_id); + } + } + + return $result; } } diff --git a/system/database/drivers/oci8/oci8_utility.php b/system/database/drivers/oci8/oci8_utility.php index e303fb6cb..efb4bca02 100644 --- a/system/database/drivers/oci8/oci8_utility.php +++ b/system/database/drivers/oci8/oci8_utility.php @@ -37,11 +37,14 @@ class CI_DB_oci8_utility extends CI_DB_utility { /** * List databases * - * @return bool + * Generates a platform-specific query so that we get a list of schemas + * Those are actually usernames in Oracle. + * + * @return string */ public function _list_databases() { - return FALSE; + return 'SELECT username FROM dba_users'; } // -------------------------------------------------------------------- @@ -56,7 +59,7 @@ class CI_DB_oci8_utility extends CI_DB_utility { */ public function _optimize_table($table) { - return FALSE; // Is this supported in Oracle? + return FALSE; // Not supported in Oracle } // -------------------------------------------------------------------- @@ -71,7 +74,7 @@ class CI_DB_oci8_utility extends CI_DB_utility { */ public function _repair_table($table) { - return FALSE; // Is this supported in Oracle? + return FALSE; // Not supported in Oracle } // -------------------------------------------------------------------- diff --git a/system/database/drivers/odbc/odbc_driver.php b/system/database/drivers/odbc/odbc_driver.php index ad773117f..d1a5f774b 100644 --- a/system/database/drivers/odbc/odbc_driver.php +++ b/system/database/drivers/odbc/odbc_driver.php @@ -95,19 +95,6 @@ class CI_DB_odbc_driver extends CI_DB { // -------------------------------------------------------------------- /** - * Select the database - * - * @return resource - */ - public function db_select() - { - // Not needed for ODBC - return TRUE; - } - - // -------------------------------------------------------------------- - - /** * Execute the query * * @param string an SQL query @@ -356,47 +343,6 @@ class CI_DB_odbc_driver extends CI_DB { // -------------------------------------------------------------------- /** - * Escape the SQL Identifiers - * - * This function escapes column and table names - * - * @param string - * @return string - */ - public function _escape_identifiers($item) - { - if ($this->_escape_char == '') - { - return $item; - } - - foreach ($this->_reserved_identifiers as $id) - { - if (strpos($item, '.'.$id) !== FALSE) - { - $str = $this->_escape_char. str_replace('.', $this->_escape_char.'.', $item); - - // remove duplicates if the user already included the escape - return preg_replace('/['.$this->_escape_char.']+/', $this->_escape_char, $str); - } - } - - if (strpos($item, '.') !== FALSE) - { - $str = $this->_escape_char.str_replace('.', $this->_escape_char.'.'.$this->_escape_char, $item).$this->_escape_char; - } - else - { - $str = $this->_escape_char.$item.$this->_escape_char; - } - - // remove duplicates if the user already included the escape - return preg_replace('/['.$this->_escape_char.']+/', $this->_escape_char, $str); - } - - // -------------------------------------------------------------------- - - /** * From Tables * * This function implicitly groups FROM tables so there is no confusion @@ -418,70 +364,19 @@ class CI_DB_odbc_driver extends CI_DB { // -------------------------------------------------------------------- /** - * Insert statement - * - * Generates a platform-specific insert string from the supplied data - * - * @param string the table name - * @param array the insert keys - * @param array the insert values - * @return string - */ - protected function _insert($table, $keys, $values) - { - return "INSERT INTO ".$table." (".implode(', ', $keys).") VALUES (".implode(', ', $values).")"; - } - - // -------------------------------------------------------------------- - - /** - * Update statement - * - * Generates a platform-specific update string from the supplied data - * - * @param string the table name - * @param array the update data - * @param array the where clause - * @param array the orderby clause - * @param array the limit clause - * @return string - */ - protected function _update($table, $values, $where, $orderby = array(), $limit = FALSE) - { - foreach ($values as $key => $val) - { - $valstr[] = $key." = ".$val; - } - - $limit = ( ! $limit) ? '' : ' LIMIT '.$limit; - - $orderby = (count($orderby) >= 1)?' ORDER BY '.implode(", ", $orderby):''; - - $sql = "UPDATE ".$table." SET ".implode(', ', $valstr); - - $sql .= ($where != '' AND count($where) >=1) ? " WHERE ".implode(" ", $where) : ''; - - $sql .= $orderby.$limit; - - return $sql; - } - - - // -------------------------------------------------------------------- - - /** * Truncate statement * * Generates a platform-specific truncate string from the supplied data - * If the database does not support the truncate() command - * This function maps to "DELETE FROM table" + * + * If the database does not support the truncate() command, + * then this method maps to 'DELETE FROM table' * * @param string the table name * @return string */ protected function _truncate($table) { - return $this->_delete($table); + return 'DELETE FROM '.$table; } // -------------------------------------------------------------------- diff --git a/system/database/drivers/odbc/odbc_forge.php b/system/database/drivers/odbc/odbc_forge.php index 486a8dd7f..afdd6dec2 100644 --- a/system/database/drivers/odbc/odbc_forge.php +++ b/system/database/drivers/odbc/odbc_forge.php @@ -91,7 +91,7 @@ class CI_DB_odbc_forge extends CI_DB_forge { $sql .= 'IF NOT EXISTS '; } - $sql .= $this->db->_escape_identifiers($table)." ("; + $sql .= $this->db->escape_identifiers($table).' ('; $current_field_count = 0; foreach ($fields as $field => $attributes) diff --git a/system/database/drivers/pdo/pdo_driver.php b/system/database/drivers/pdo/pdo_driver.php index f336eb0ab..919bb9c00 100644 --- a/system/database/drivers/pdo/pdo_driver.php +++ b/system/database/drivers/pdo/pdo_driver.php @@ -46,8 +46,8 @@ class CI_DB_pdo_driver extends CI_DB { protected $_escape_char = ''; // clause and character used for LIKE escape sequences - protected $_like_escape_str; - protected $_like_escape_chr; + protected $_like_escape_str = " ESCAPE '%s' "; + protected $_like_escape_chr = '!'; /** * The syntax to count rows is slightly different across different @@ -81,18 +81,17 @@ class CI_DB_pdo_driver extends CI_DB { // this one depends on the driver being used if ($this->pdodriver == 'mysql') { + $this->_escape_char = '`'; $this->_like_escape_str = ''; $this->_like_escape_chr = ''; } elseif ($this->pdodriver == 'odbc') { $this->_like_escape_str = " {escape '%s'} "; - $this->_like_escape_chr = '!'; } - else + elseif ( ! in_array($this->pdodriver, array('sqlsrv', 'mssql', 'dblib', 'sybase'))) { - $this->_like_escape_str = " ESCAPE '%s' "; - $this->_like_escape_chr = '!'; + $this->_escape_char = '"'; } $this->trans_enabled = FALSE; @@ -247,19 +246,6 @@ class CI_DB_pdo_driver extends CI_DB { // -------------------------------------------------------------------- /** - * Select the database - * - * @return resource - */ - public function db_select() - { - // Not needed for PDO - return TRUE; - } - - // -------------------------------------------------------------------- - - /** * Database version number * * @return string @@ -281,8 +267,6 @@ class CI_DB_pdo_driver extends CI_DB { */ protected function _execute($sql) { - $sql = $this->_prep_query($sql); - $result_id = $this->conn_id->query($sql); if (is_object($result_id)) @@ -300,32 +284,6 @@ class CI_DB_pdo_driver extends CI_DB { // -------------------------------------------------------------------- /** - * Prep the query - * - * If needed, each database adapter can prep the query string - * - * @param string an SQL query - * @return string - */ - protected function _prep_query($sql) - { - if ($this->pdodriver === 'pgsql') - { - // Change the backtick(s) for Postgre - $sql = str_replace('`', '"', $sql); - } - elseif ($this->pdodriver === 'sqlite') - { - // Change the backtick(s) for SQLite - $sql = str_replace('`', '', $sql); - } - - return $sql; - } - - // -------------------------------------------------------------------- - - /** * Begin Transaction * * @return bool @@ -529,7 +487,7 @@ class CI_DB_pdo_driver extends CI_DB { } else { - $sql = "SHOW TABLES FROM `".$this->database."`"; + $sql = 'SHOW TABLES FROM '.$this->escape_identifiers($this->database); } if ($prefix_limit !== FALSE AND $this->dbprefix != '') @@ -552,7 +510,7 @@ class CI_DB_pdo_driver extends CI_DB { */ protected function _list_columns($table = '') { - return 'SHOW COLUMNS FROM '.$this->_from_tables($table); + return 'SHOW COLUMNS FROM '.$this->escape_identifiers($table); } // -------------------------------------------------------------------- @@ -570,20 +528,20 @@ class CI_DB_pdo_driver extends CI_DB { if ($this->pdodriver == 'mysql' or $this->pdodriver == 'pgsql') { // Analog function for mysql and postgre - return 'SELECT * FROM '.$this->_from_tables($table).' LIMIT 1'; + return 'SELECT * FROM '.$this->escape_identifiers($table).' LIMIT 1'; } elseif ($this->pdodriver == 'oci') { // Analog function for oci - return 'SELECT * FROM '.$this->_from_tables($table).' WHERE ROWNUM <= 1'; + return 'SELECT * FROM '.$this->escape_identifiers($table).' WHERE ROWNUM <= 1'; } elseif ($this->pdodriver == 'sqlite') { // Analog function for sqlite - return 'PRAGMA table_info('.$this->_from_tables($table).')'; + return 'PRAGMA table_info('.$this->escape_identifiers($table).')'; } - return 'SELECT TOP 1 FROM '.$this->_from_tables($table); + return 'SELECT TOP 1 FROM '.$this->escape_identifiers($table); } // -------------------------------------------------------------------- @@ -618,48 +576,6 @@ class CI_DB_pdo_driver extends CI_DB { // -------------------------------------------------------------------- /** - * Escape the SQL Identifiers - * - * This function escapes column and table names - * - * @param string - * @return string - */ - public function _escape_identifiers($item) - { - if ($this->_escape_char == '') - { - return $item; - } - - foreach ($this->_reserved_identifiers as $id) - { - if (strpos($item, '.'.$id) !== FALSE) - { - $str = $this->_escape_char. str_replace('.', $this->_escape_char.'.', $item); - - // remove duplicates if the user already included the escape - return preg_replace('/['.$this->_escape_char.']+/', $this->_escape_char, $str); - } - } - - if (strpos($item, '.') !== FALSE) - { - $str = $this->_escape_char.str_replace('.', $this->_escape_char.'.'.$this->_escape_char, $item); - $str .= $this->_escape_char; - } - else - { - $str = $this->_escape_char.$item.$this->_escape_char; - } - - // remove duplicates if the user already included the escape - return preg_replace('/['.$this->_escape_char.']+/', $this->_escape_char, $str); - } - - // -------------------------------------------------------------------- - - /** * From Tables * * This function implicitly groups FROM tables so there is no confusion @@ -675,72 +591,7 @@ class CI_DB_pdo_driver extends CI_DB { $tables = array($tables); } - return (count($tables) == 1) ? '`'.$tables[0].'`' : '('.implode(', ', $tables).')'; - } - - // -------------------------------------------------------------------- - - /** - * Insert statement - * - * Generates a platform-specific insert string from the supplied data - * - * @param string the table name - * @param array the insert keys - * @param array the insert values - * @return string - */ - protected function _insert($table, $keys, $values) - { - return 'INSERT INTO '.$this->_from_tables($table).' ('.implode(', ', $keys).') VALUES ('.implode(', ', $values).')'; - } - - // -------------------------------------------------------------------- - - /** - * Insert_batch statement - * - * Generates a platform-specific insert string from the supplied data - * - * @param string the table name - * @param array the insert keys - * @param array the insert values - * @return string - */ - protected function _insert_batch($table, $keys, $values) - { - return 'INSERT INTO '.$this->_from_tables($table).' ('.implode(', ', $keys).') VALUES '.implode(', ', $values); - } - - // -------------------------------------------------------------------- - - /** - * Update statement - * - * Generates a platform-specific update string from the supplied data - * - * @param string the table name - * @param array the update data - * @param array the where clause - * @param array the orderby clause - * @param array the limit clause - * @return string - */ - protected function _update($table, $values, $where, $orderby = array(), $limit = FALSE) - { - foreach ($values as $key => $val) - { - $valstr[] = $key." = ".$val; - } - - $limit = ( ! $limit) ? '' : ' LIMIT '.$limit; - $orderby = (count($orderby) >= 1) ? ' ORDER BY '.implode(', ', $orderby) : ''; - - $sql = 'UPDATE '.$this->_from_tables($table).' SET '.implode(', ', $valstr); - $sql .= ($where != '' && count($where) >= 1) ? ' WHERE '.implode(' ', $where) : ''; - $sql .= $orderby.$limit; - - return $sql; + return (count($tables) === 1) ? $tables[0] : '('.implode(', ', $tables).')'; } // -------------------------------------------------------------------- @@ -773,7 +624,7 @@ class CI_DB_pdo_driver extends CI_DB { } } - $sql = 'UPDATE '.$this->_from_tables($table).' SET '; + $sql = 'UPDATE '.$table.' SET '; $cases = ''; foreach ($final as $k => $v) @@ -800,15 +651,16 @@ class CI_DB_pdo_driver extends CI_DB { * Truncate statement * * Generates a platform-specific truncate string from the supplied data - * If the database does not support the truncate() command - * This function maps to "DELETE FROM table" + * + * If the database does not support the truncate() command, + * then this method maps to 'DELETE FROM table' * * @param string the table name * @return string */ protected function _truncate($table) { - return $this->_delete($table); + return 'DELETE FROM '.$table; } // -------------------------------------------------------------------- @@ -842,7 +694,7 @@ class CI_DB_pdo_driver extends CI_DB { $limit = ( ! $limit) ? '' : ' LIMIT '.$limit; - return 'DELETE FROM '.$this->_from_tables($table).$conditions.$limit; + return 'DELETE FROM '.$table.$conditions.$limit; } // -------------------------------------------------------------------- diff --git a/system/database/drivers/pdo/pdo_forge.php b/system/database/drivers/pdo/pdo_forge.php index 6bff3542f..9635e4c9a 100644 --- a/system/database/drivers/pdo/pdo_forge.php +++ b/system/database/drivers/pdo/pdo_forge.php @@ -91,10 +91,10 @@ class CI_DB_pdo_forge extends CI_DB_forge { $sql .= 'IF NOT EXISTS '; } - $sql .= '`'.$this->db->_escape_identifiers($table).'` ('; + $sql .= $this->db->escape_identifiers($table).' ('; $current_field_count = 0; - foreach ($fields as $field=>$attributes) + foreach ($fields as $field => $attributes) { // Numeric field names aren't allowed in databases, so if the key is // numeric, we know it was assigned by PHP and the developer manually diff --git a/system/database/drivers/postgre/postgre_driver.php b/system/database/drivers/postgre/postgre_driver.php index 3e2d05ce8..1e96452b4 100644 --- a/system/database/drivers/postgre/postgre_driver.php +++ b/system/database/drivers/postgre/postgre_driver.php @@ -80,16 +80,16 @@ class CI_DB_postgre_driver extends CI_DB { $this->port = ''; } - $this->hostname === '' OR $this->dsn = 'host='.$this->hostname; + $this->hostname === '' OR $this->dsn = 'host='.$this->hostname.' '; if ( ! empty($this->port) && ctype_digit($this->port)) { - $this->dsn .= 'host='.$this->port.' '; + $this->dsn .= 'port='.$this->port.' '; } if ($this->username !== '') { - $this->dsn .= 'username='.$this->username.' '; + $this->dsn .= 'user='.$this->username.' '; /* An empty password is valid! * @@ -162,19 +162,6 @@ class CI_DB_postgre_driver extends CI_DB { // -------------------------------------------------------------------- /** - * Select the database - * - * @return resource - */ - public function db_select() - { - // Not needed for Postgre so we'll return TRUE - return TRUE; - } - - // -------------------------------------------------------------------- - - /** * Set client character set * * @param string @@ -470,47 +457,6 @@ class CI_DB_postgre_driver extends CI_DB { // -------------------------------------------------------------------- /** - * Escape the SQL Identifiers - * - * This function escapes column and table names - * - * @param string - * @return string - */ - public function _escape_identifiers($item) - { - if ($this->_escape_char == '') - { - return $item; - } - - foreach ($this->_reserved_identifiers as $id) - { - if (strpos($item, '.'.$id) !== FALSE) - { - $str = $this->_escape_char. str_replace('.', $this->_escape_char.'.', $item); - - // remove duplicates if the user already included the escape - return preg_replace('/['.$this->_escape_char.']+/', $this->_escape_char, $str); - } - } - - if (strpos($item, '.') !== FALSE) - { - $str = $this->_escape_char.str_replace('.', $this->_escape_char.'.'.$this->_escape_char, $item).$this->_escape_char; - } - else - { - $str = $this->_escape_char.$item.$this->_escape_char; - } - - // remove duplicates if the user already included the escape - return preg_replace('/['.$this->_escape_char.']+/', $this->_escape_char, $str); - } - - // -------------------------------------------------------------------- - - /** * From Tables * * This function implicitly groups FROM tables so there is no confusion @@ -532,40 +478,6 @@ class CI_DB_postgre_driver extends CI_DB { // -------------------------------------------------------------------- /** - * Insert statement - * - * Generates a platform-specific insert string from the supplied data - * - * @param string the table name - * @param array the insert keys - * @param array the insert values - * @return string - */ - protected function _insert($table, $keys, $values) - { - return "INSERT INTO ".$table." (".implode(', ', $keys).") VALUES (".implode(', ', $values).")"; - } - - // -------------------------------------------------------------------- - - /** - * Insert_batch statement - * - * Generates a platform-specific insert string from the supplied data - * - * @param string the table name - * @param array the insert keys - * @param array the insert values - * @return string - */ - protected function _insert_batch($table, $keys, $values) - { - return "INSERT INTO ".$table." (".implode(', ', $keys).") VALUES ".implode(', ', $values); - } - - // -------------------------------------------------------------------- - - /** * Update statement * * Generates a platform-specific update string from the supplied data @@ -594,23 +506,6 @@ class CI_DB_postgre_driver extends CI_DB { // -------------------------------------------------------------------- /** - * Truncate statement - * - * Generates a platform-specific truncate string from the supplied data - * If the database does not support the truncate() command - * This function maps to "DELETE FROM table" - * - * @param string the table name - * @return string - */ - protected function _truncate($table) - { - return "TRUNCATE ".$table; - } - - // -------------------------------------------------------------------- - - /** * Delete statement * * Generates a platform-specific delete string from the supplied data diff --git a/system/database/drivers/postgre/postgre_forge.php b/system/database/drivers/postgre/postgre_forge.php index a72449820..f7d59284a 100644 --- a/system/database/drivers/postgre/postgre_forge.php +++ b/system/database/drivers/postgre/postgre_forge.php @@ -193,8 +193,7 @@ class CI_DB_postgre_forge extends CI_DB_forge { } } - $sql .= $this->db->_escape_identifiers($table)." ("; - $sql .= $this->_process_fields($fields, $primary_keys); + $sql .= $this->db->escape_identifiers($table).' ('.$this->_process_fields($fields, $primary_keys); if (count($primary_keys) > 0) { @@ -237,11 +236,12 @@ class CI_DB_postgre_forge extends CI_DB_forge { /** * Drop Table * + * @param string table name * @return string */ public function _drop_table($table) { - return "DROP TABLE IF EXISTS ".$this->db->_escape_identifiers($table)." CASCADE"; + return 'DROP TABLE IF EXISTS '.$this->db->escape_identifiers($table).' CASCADE'; } // -------------------------------------------------------------------- diff --git a/system/database/drivers/postgre/postgre_result.php b/system/database/drivers/postgre/postgre_result.php index 8b22564b3..394b8b6fd 100644 --- a/system/database/drivers/postgre/postgre_result.php +++ b/system/database/drivers/postgre/postgre_result.php @@ -70,7 +70,7 @@ class CI_DB_postgre_result extends CI_DB_result { public function list_fields() { $field_names = array(); - for ($i = 0; $i < $this->num_fields(); $i++) + for ($i = 0, $c = $this->num_fields(); $i < $c; $i++) { $field_names[] = pg_field_name($this->result_id, $i); } @@ -90,16 +90,14 @@ class CI_DB_postgre_result extends CI_DB_result { public function field_data() { $retval = array(); - for ($i = 0; $i < $this->num_fields(); $i++) + for ($i = 0, $c = $this->num_fields(); $i < $c; $i++) { - $F = new stdClass(); - $F->name = pg_field_name($this->result_id, $i); - $F->type = pg_field_type($this->result_id, $i); - $F->max_length = pg_field_size($this->result_id, $i); - $F->primary_key = 0; - $F->default = ''; - - $retval[] = $F; + $retval[$i] = new stdClass(); + $retval[$i]->name = pg_field_name($this->result_id, $i); + $retval[$i]->type = pg_field_type($this->result_id, $i); + $retval[$i]->max_length = pg_field_size($this->result_id, $i); + $retval[$i]->primary_key = 0; + $retval[$i]->default = ''; } return $retval; diff --git a/system/database/drivers/sqlite/sqlite_driver.php b/system/database/drivers/sqlite/sqlite_driver.php index 102c79bb3..3a986d0a8 100644 --- a/system/database/drivers/sqlite/sqlite_driver.php +++ b/system/database/drivers/sqlite/sqlite_driver.php @@ -106,18 +106,6 @@ class CI_DB_sqlite_driver extends CI_DB { // -------------------------------------------------------------------- /** - * Select the database - * - * @return resource - */ - public function db_select() - { - return TRUE; - } - - // -------------------------------------------------------------------- - - /** * Database version number * * @return string @@ -378,47 +366,6 @@ class CI_DB_sqlite_driver extends CI_DB { // -------------------------------------------------------------------- /** - * Escape the SQL Identifiers - * - * This function escapes column and table names - * - * @param string - * @return string - */ - public function _escape_identifiers($item) - { - if ($this->_escape_char == '') - { - return $item; - } - - foreach ($this->_reserved_identifiers as $id) - { - if (strpos($item, '.'.$id) !== FALSE) - { - $str = $this->_escape_char. str_replace('.', $this->_escape_char.'.', $item); - - // remove duplicates if the user already included the escape - return preg_replace('/['.$this->_escape_char.']+/', $this->_escape_char, $str); - } - } - - if (strpos($item, '.') !== FALSE) - { - $str = $this->_escape_char.str_replace('.', $this->_escape_char.'.'.$this->_escape_char, $item).$this->_escape_char; - } - else - { - $str = $this->_escape_char.$item.$this->_escape_char; - } - - // remove duplicates if the user already included the escape - return preg_replace('/['.$this->_escape_char.']+/', $this->_escape_char, $str); - } - - // -------------------------------------------------------------------- - - /** * From Tables * * This function implicitly groups FROM tables so there is no confusion @@ -440,70 +387,36 @@ class CI_DB_sqlite_driver extends CI_DB { // -------------------------------------------------------------------- /** - * Insert statement + * Replace statement * - * Generates a platform-specific insert string from the supplied data + * Generates a platform-specific replace string from the supplied data * * @param string the table name * @param array the insert keys * @param array the insert values * @return string */ - protected function _insert($table, $keys, $values) - { - return "INSERT INTO ".$table." (".implode(', ', $keys).") VALUES (".implode(', ', $values).")"; - } - - // -------------------------------------------------------------------- - - /** - * Update statement - * - * Generates a platform-specific update string from the supplied data - * - * @param string the table name - * @param array the update data - * @param array the where clause - * @param array the orderby clause - * @param array the limit clause - * @return string - */ - protected function _update($table, $values, $where, $orderby = array(), $limit = FALSE) + protected function _replace($table, $keys, $values) { - foreach ($values as $key => $val) - { - $valstr[] = $key." = ".$val; - } - - $limit = ( ! $limit) ? '' : ' LIMIT '.$limit; - - $orderby = (count($orderby) >= 1)?' ORDER BY '.implode(", ", $orderby):''; - - $sql = "UPDATE ".$table." SET ".implode(', ', $valstr); - - $sql .= ($where != '' AND count($where) >=1) ? " WHERE ".implode(" ", $where) : ''; - - $sql .= $orderby.$limit; - - return $sql; + return 'INSERT OR '.parent::_replace($table, $keys, $values); } - // -------------------------------------------------------------------- /** * Truncate statement * * Generates a platform-specific truncate string from the supplied data - * If the database does not support the truncate() command - * This function maps to "DELETE FROM table" + * + * If the database does not support the truncate() command, + * then this function maps to 'DELETE FROM table' * * @param string the table name * @return string */ protected function _truncate($table) { - return $this->_delete($table); + return 'DELETE FROM '.$table; } // -------------------------------------------------------------------- diff --git a/system/database/drivers/sqlite/sqlite_forge.php b/system/database/drivers/sqlite/sqlite_forge.php index 068a556ed..a62e8d9ae 100644 --- a/system/database/drivers/sqlite/sqlite_forge.php +++ b/system/database/drivers/sqlite/sqlite_forge.php @@ -90,10 +90,10 @@ class CI_DB_sqlite_forge extends CI_DB_forge { $sql .= 'IF NOT EXISTS '; } - $sql .= $this->db->_escape_identifiers($table)."("; + $sql .= $this->db->escape_identifiers($table).' ('; $current_field_count = 0; - foreach ($fields as $field=>$attributes) + foreach ($fields as $field => $attributes) { // Numeric field names aren't allowed in databases, so if the key is // numeric, we know it was assigned by PHP and the developer manually diff --git a/system/database/drivers/sqlite/sqlite_result.php b/system/database/drivers/sqlite/sqlite_result.php index b002aeff1..4af80abf7 100644 --- a/system/database/drivers/sqlite/sqlite_result.php +++ b/system/database/drivers/sqlite/sqlite_result.php @@ -70,9 +70,9 @@ class CI_DB_sqlite_result extends CI_DB_result { public function list_fields() { $field_names = array(); - for ($i = 0; $i < $this->num_fields(); $i++) + for ($i = 0, $c = $this->num_fields(); $i < $c; $i++) { - $field_names[] = sqlite_field_name($this->result_id, $i); + $field_names[$i] = sqlite_field_name($this->result_id, $i); } return $field_names; @@ -90,16 +90,14 @@ class CI_DB_sqlite_result extends CI_DB_result { public function field_data() { $retval = array(); - for ($i = 0; $i < $this->num_fields(); $i++) + for ($i = 0, $c = $this->num_fields(); $i < $c; $i++) { - $F = new stdClass(); - $F->name = sqlite_field_name($this->result_id, $i); - $F->type = 'varchar'; - $F->max_length = 0; - $F->primary_key = 0; - $F->default = ''; - - $retval[] = $F; + $retval[$i] = new stdClass(); + $retval[$i]->name = sqlite_field_name($this->result_id, $i); + $retval[$i]->type = 'varchar'; + $retval[$i]->max_length = 0; + $retval[$i]->primary_key = 0; + $retval[$i]->default = ''; } return $retval; @@ -108,18 +106,6 @@ class CI_DB_sqlite_result extends CI_DB_result { // -------------------------------------------------------------------- /** - * Free the result - * - * @return void - */ - public function free_result() - { - // Not implemented in SQLite - } - - // -------------------------------------------------------------------- - - /** * Data Seek * * Moves the internal pointer to the desired offset. We call @@ -162,17 +148,9 @@ class CI_DB_sqlite_result extends CI_DB_result { { return sqlite_fetch_object($this->result_id); } - else - { - $arr = sqlite_fetch_array($this->result_id, SQLITE_ASSOC); - if (is_array($arr)) - { - $obj = (object) $arr; - return $obj; - } else { - return NULL; - } - } + + $arr = sqlite_fetch_array($this->result_id, SQLITE_ASSOC); + return is_array($arr) ? (object) $arr : FALSE; } } diff --git a/system/database/drivers/sqlite3/index.html b/system/database/drivers/sqlite3/index.html new file mode 100644 index 000000000..c942a79ce --- /dev/null +++ b/system/database/drivers/sqlite3/index.html @@ -0,0 +1,10 @@ +<html> +<head> + <title>403 Forbidden</title> +</head> +<body> + +<p>Directory access is forbidden.</p> + +</body> +</html>
\ No newline at end of file diff --git a/system/database/drivers/sqlite3/sqlite3_driver.php b/system/database/drivers/sqlite3/sqlite3_driver.php new file mode 100644 index 000000000..12354e1bc --- /dev/null +++ b/system/database/drivers/sqlite3/sqlite3_driver.php @@ -0,0 +1,459 @@ +<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); +/** + * CodeIgniter + * + * An open source application development framework for PHP 5.2.4 or newer + * + * NOTICE OF LICENSE + * + * Licensed under the Open Software License version 3.0 + * + * This source file is subject to the Open Software License (OSL 3.0) that is + * bundled with this package in the files license.txt / license.rst. It is + * also available through the world wide web at this URL: + * http://opensource.org/licenses/OSL-3.0 + * If you did not receive a copy of the license and are unable to obtain it + * through the world wide web, please send an email to + * licensing@ellislab.com so we can send you a copy immediately. + * + * @package CodeIgniter + * @author EllisLab Dev Team + * @copyright Copyright (c) 2008 - 2012, EllisLab, Inc. (http://ellislab.com/) + * @license http://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0) + * @link http://codeigniter.com + * @since Version 1.0 + * @filesource + */ + +/** + * SQLite3 Database Adapter Class + * + * Note: _DB is an extender class that the app controller + * creates dynamically based on whether the active record + * class is being used or not. + * + * @package CodeIgniter + * @subpackage Drivers + * @category Database + * @author Andrey Andreev + * @link http://codeigniter.com/user_guide/database/ + * @since Version 3.0 + */ +class CI_DB_sqlite3_driver extends CI_DB { + + public $dbdriver = 'sqlite3'; + + // The character used for escaping + protected $_escape_char = '"'; + + // clause and character used for LIKE escape sequences + protected $_like_escape_str = ' ESCAPE \'%s\' '; + protected $_like_escape_chr = '!'; + + /** + * The syntax to count rows is slightly different across different + * database engines, so this string appears in each driver and is + * used for the count_all() and count_all_results() functions. + */ + protected $_count_string = 'SELECT COUNT(*) AS '; + protected $_random_keyword = ' RANDOM()'; + + /** + * Non-persistent database connection + * + * @return object type SQLite3 + */ + public function db_connect() + { + try + { + return ( ! $this->password) + ? new SQLite3($this->database) + : new SQLite3($this->database, SQLITE3_OPEN_READWRITE | SQLITE3_OPEN_CREATE, $this->password); + } + catch (Exception $e) + { + return FALSE; + } + } + + // -------------------------------------------------------------------- + + /** + * Persistent database connection + * + * @return object type SQLite3 + */ + public function db_pconnect() + { + log_message('debug', 'SQLite3 doesn\'t support persistent connections'); + return $this->db_pconnect(); + } + + // -------------------------------------------------------------------- + + /** + * Database version number + * + * @return string + */ + public function version() + { + if (isset($this->data_cache['version'])) + { + return $this->data_cache['version']; + } + + $version = $this->conn_id->version(); + return $this->data_cache['version'] = $version['versionString']; + } + + // -------------------------------------------------------------------- + + /** + * Execute the query + * + * @param string an SQL query + * @return mixed SQLite3Result object or bool + */ + protected function _execute($sql) + { + // TODO: Implement use of SQLite3::querySingle(), if needed + + return $this->is_write_type($sql) + ? $this->conn_id->exec($sql) + : $this->conn_id->query($sql); + } + + // -------------------------------------------------------------------- + + /** + * Begin Transaction + * + * @return bool + */ + public function trans_begin($test_mode = FALSE) + { + // When transactions are nested we only begin/commit/rollback the outermost ones + if ( ! $this->trans_enabled OR $this->_trans_depth > 0) + { + return TRUE; + } + + // Reset the transaction failure flag. + // If the $test_mode flag is set to TRUE transactions will be rolled back + // even if the queries produce a successful result. + $this->_trans_failure = ($test_mode === TRUE); + + return $this->conn_id->exec('BEGIN TRANSACTION'); + } + + // -------------------------------------------------------------------- + + /** + * Commit Transaction + * + * @return bool + */ + public function trans_commit() + { + // When transactions are nested we only begin/commit/rollback the outermost ones + if ( ! $this->trans_enabled OR $this->_trans_depth > 0) + { + return TRUE; + } + + return $this->conn_id->exec('END TRANSACTION'); + } + + // -------------------------------------------------------------------- + + /** + * Rollback Transaction + * + * @return bool + */ + public function trans_rollback() + { + // When transactions are nested we only begin/commit/rollback the outermost ones + if ( ! $this->trans_enabled OR $this->_trans_depth > 0) + { + return TRUE; + } + + return $this->conn_id->exec('ROLLBACK'); + } + + // -------------------------------------------------------------------- + + /** + * Escape String + * + * @param string + * @param bool whether or not the string will be used in a LIKE condition + * @return string + */ + public function escape_str($str, $like = FALSE) + { + if (is_array($str)) + { + foreach ($str as $key => $val) + { + $str[$key] = $this->escape_str($val, $like); + } + + return $str; + } + + $str = $this->conn_id->escapeString(remove_invisible_characters($str)); + + // escape LIKE condition wildcards + if ($like === TRUE) + { + return str_replace(array($this->_like_escape_chr, '%', '_'), + array($this->_like_escape_chr.$this->_like_escape_chr, $this->_like_escape_chr.'%', $this->_like_escape_chr.'_'), + $str); + } + + return $str; + } + + // -------------------------------------------------------------------- + + /** + * Affected Rows + * + * @return int + */ + public function affected_rows() + { + return $this->conn_id->changes(); + } + + // -------------------------------------------------------------------- + + /** + * Insert ID + * + * @return int + */ + public function insert_id() + { + return $this->conn_id->lastInsertRowID(); + } + + // -------------------------------------------------------------------- + + /** + * "Count All" query + * + * Generates a platform-specific query string that counts all records in + * the specified database + * + * @param string + * @return int + */ + public function count_all($table = '') + { + if ($table == '') + { + return 0; + } + + $result = $this->conn_id->querySingle($this->_count_string.$this->protect_identifiers('numrows') + .' FROM '.$this->protect_identifiers($table, TRUE, NULL, FALSE)); + + return empty($result) ? 0 : (int) $result; + } + + // -------------------------------------------------------------------- + + /** + * Show table query + * + * Generates a platform-specific query string so that the table names can be fetched + * + * @param bool + * @return string + */ + protected function _list_tables($prefix_limit = FALSE) + { + return 'SELECT "NAME" FROM "SQLITE_MASTER" WHERE "TYPE" = \'table\'' + .(($prefix_limit !== FALSE && $this->dbprefix != '') + ? ' AND "NAME" LIKE \''.$this->escape_like_str($this->dbprefix).'%\' '.sprintf($this->_like_escape_str, $this->_like_escape_chr) + : ''); + } + + // -------------------------------------------------------------------- + + /** + * Show column query + * + * Generates a platform-specific query string so that the column names can be fetched + * + * @param string the table name + * @return string + */ + protected function _list_columns($table = '') + { + // Not supported + return FALSE; + } + + // -------------------------------------------------------------------- + + /** + * Field data query + * + * Generates a platform-specific query so that the column data can be retrieved + * + * @param string the table name + * @return string + */ + protected function _field_data($table) + { + return 'SELECT * FROM '.$table.' LIMIT 0,1'; + } + + // -------------------------------------------------------------------- + + /** + * The error message string + * + * @return string + */ + protected function _error_message() + { + return $this->conn_id->lastErrorMsg(); + } + + // -------------------------------------------------------------------- + + /** + * The error message number + * + * @return int + */ + protected function _error_number() + { + return $this->conn_id->lastErrorCode(); + } + + // -------------------------------------------------------------------- + + /** + * From Tables + * + * This function implicitly groups FROM tables so there is no confusion + * about operator precedence in harmony with SQL standards + * + * @param string + * @return string + */ + protected function _from_tables($tables) + { + if ( ! is_array($tables)) + { + $tables = array($tables); + } + + return '('.implode(', ', $tables).')'; + } + + // -------------------------------------------------------------------- + + /** + * Replace statement + * + * Generates a platform-specific replace string from the supplied data + * + * @param string the table name + * @param array the insert keys + * @param array the insert values + * @return string + */ + protected function _replace($table, $keys, $values) + { + return 'INSERT OR '.parent::_replace($table, $keys, $values); + } + + // -------------------------------------------------------------------- + + /** + * Truncate statement + * + * Generates a platform-specific truncate string from the supplied data + * + * If the database does not support the truncate() command, then, + * then this method maps to 'DELETE FROM table' + * + * @param string the table name + * @return string + */ + protected function _truncate($table) + { + return 'DELETE FROM '.$table; + } + + // -------------------------------------------------------------------- + + /** + * Delete statement + * + * Generates a platform-specific delete string from the supplied data + * + * @param string the table name + * @param array the where clause + * @param string the limit clause + * @return string + */ + protected function _delete($table, $where = array(), $like = array(), $limit = FALSE) + { + $conditions = ''; + if (count($where) > 0 OR count($like) > 0) + { + $conditions .= "\nWHERE ".implode("\n", $this->ar_where); + + if (count($where) > 0 && count($like) > 0) + { + $conditions .= ' AND '; + } + $conditions .= implode("\n", $like); + } + + return 'DELETE FROM '.$table.$conditions.( ! $limit ? '' : ' LIMIT '.$limit); + } + + // -------------------------------------------------------------------- + + /** + * Limit string + * + * Generates a platform-specific LIMIT clause + * + * @param string the sql query string + * @param int the number of rows to limit the query to + * @param int the offset value + * @return string + */ + protected function _limit($sql, $limit, $offset) + { + return $sql.' LIMIT '.($offset ? $offset.',' : '').$limit; + } + + // -------------------------------------------------------------------- + + /** + * Close DB Connection + * + * @return void + */ + protected function _close() + { + $this->conn_id->close(); + } + +} + +/* End of file sqlite3_driver.php */ +/* Location: ./system/database/drivers/sqlite3/sqlite3_driver.php */
\ No newline at end of file diff --git a/system/database/drivers/sqlite3/sqlite3_forge.php b/system/database/drivers/sqlite3/sqlite3_forge.php new file mode 100644 index 000000000..3a2060c3b --- /dev/null +++ b/system/database/drivers/sqlite3/sqlite3_forge.php @@ -0,0 +1,223 @@ +<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); +/** + * CodeIgniter + * + * An open source application development framework for PHP 5.1.6 or newer + * + * NOTICE OF LICENSE + * + * Licensed under the Open Software License version 3.0 + * + * This source file is subject to the Open Software License (OSL 3.0) that is + * bundled with this package in the files license.txt / license.rst. It is + * also available through the world wide web at this URL: + * http://opensource.org/licenses/OSL-3.0 + * If you did not receive a copy of the license and are unable to obtain it + * through the world wide web, please send an email to + * licensing@ellislab.com so we can send you a copy immediately. + * + * @package CodeIgniter + * @author EllisLab Dev Team + * @copyright Copyright (c) 2008 - 2012, EllisLab, Inc. (http://ellislab.com/) + * @license http://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0) + * @link http://codeigniter.com + * @since Version 1.0 + * @filesource + */ + +/** + * SQLite3 Forge Class + * + * @category Database + * @author Andrey Andreev + * @link http://codeigniter.com/user_guide/database/ + */ +class CI_DB_sqlite3_forge extends CI_DB_forge { + + /** + * Create database + * + * @param string the database name + * @return bool + */ + public function _create_database() + { + // In SQLite, a database is created when you connect to the database. + // We'll return TRUE so that an error isn't generated + return TRUE; + } + + // -------------------------------------------------------------------- + + /** + * Drop database + * + * @param string the database name + * @return bool + */ + public function _drop_database($name) + { + // In SQLite, a database is dropped when we delete a file + if (@file_exists($this->db->database)) + { + // We need to close the pseudo-connection first + $this->db->close(); + if ( ! @unlink($this->db->database)) + { + return $this->db->db_debug ? $this->db->display_error('db_unable_to_drop') : FALSE; + } + + return TRUE; + } + + return $this->db->db_debug ? $this->db->display_error('db_unable_to_drop') : FALSE; + } + + // -------------------------------------------------------------------- + + /** + * Create Table + * + * @param string the table name + * @param array the fields + * @param mixed primary key(s) + * @param mixed key(s) + * @param bool should 'IF NOT EXISTS' be added to the SQL + * @return bool + */ + public function _create_table($table, $fields, $primary_keys, $keys, $if_not_exists) + { + $sql = 'CREATE TABLE '; + + // IF NOT EXISTS added to SQLite in 3.3.0 + if ($if_not_exists === TRUE && version_compare($this->db->version(), '3.3.0', '>=') === TRUE) + { + $sql .= 'IF NOT EXISTS '; + } + + $sql .= $this->db->escape_identifiers($table).' ('; + $current_field_count = 0; + + foreach ($fields as $field => $attributes) + { + // Numeric field names aren't allowed in databases, so if the key is + // numeric, we know it was assigned by PHP and the developer manually + // entered the field information, so we'll simply add it to the list + if (is_numeric($field)) + { + $sql .= "\n\t".$attributes; + } + else + { + $attributes = array_change_key_case($attributes, CASE_UPPER); + + $sql .= "\n\t".$this->db->protect_identifiers($field) + .' '.$attributes['TYPE'] + .( ! empty($attributes['CONSTRAINT']) ? '('.$attributes['CONSTRAINT'].')' : '') + .(( ! empty($attributes['UNSIGNED']) && $attributes['UNSIGNED'] === TRUE) ? ' UNSIGNED' : '') + .(isset($attributes['DEFAULT']) ? ' DEFAULT \''.$attributes['DEFAULT'].'\'' : '') + .(( ! empty($attributes['NULL']) && $attributes['NULL'] === TRUE) ? ' NULL' : ' NOT NULL') + .(( ! empty($attributes['AUTO_INCREMENT']) && $attributes['AUTO_INCREMENT'] === TRUE) ? ' AUTO_INCREMENT' : ''); + } + + // don't add a comma on the end of the last field + if (++$current_field_count < count($fields)) + { + $sql .= ','; + } + } + + if (count($primary_keys) > 0) + { + $primary_keys = $this->db->protect_identifiers($primary_keys); + $sql .= ",\n\tPRIMARY KEY (".implode(', ', $primary_keys).')'; + } + + if (is_array($keys) && count($keys) > 0) + { + foreach ($keys as $key) + { + if (is_array($key)) + { + $key = $this->db->protect_identifiers($key); + } + else + { + $key = array($this->db->protect_identifiers($key)); + } + + $sql .= ",\n\tUNIQUE (".implode(', ', $key).')'; + } + } + + return $sql."\n)"; + } + + // -------------------------------------------------------------------- + + /** + * Drop Table + * + * @param string the table name + * @return string + */ + public function _drop_table($table) + { + return 'DROP TABLE '.$table.' IF EXISTS'; + } + + // -------------------------------------------------------------------- + + /** + * Alter table query + * + * Generates a platform-specific query so that a table can be altered + * Called by add_column(), drop_column(), and column_alter(), + * + * @param string the ALTER type (ADD, DROP, CHANGE) + * @param string the column name + * @param string the table name + * @param string the column definition + * @param string the default value + * @param bool should 'NOT NULL' be added + * @param string the field after which we should add the new field + * @return string + */ + public function _alter_table($alter_type, $table, $column_name, $column_definition = '', $default_value = '', $null = '', $after_field = '') + { + /* SQLite only supports adding new columns and it does + * NOT support the AFTER statement. Each new column will + * be added as the last one in the table. + */ + if ($alter_type !== 'ADD COLUMN') + { + // Not supported + return FALSE; + } + + return 'ALTER TABLE '.$this->db->protect_identifiers($table).' '.$alter_type.' '.$this->db->protect_identifiers($column_name) + .' '.$column_definition + .($default_value != '' ? ' DEFAULT '.$default_value : '') + // If NOT NULL is specified, the field must have a DEFAULT value other than NULL + .(($null !== NULL && $default_value !== 'NULL') ? ' NOT NULL' : ' NULL'); + } + + // -------------------------------------------------------------------- + + /** + * Rename a table + * + * Generates a platform-specific query so that a table can be renamed + * + * @param string the old table name + * @param string the new table name + * @return string + */ + public function _rename_table($table_name, $new_table_name) + { + return 'ALTER TABLE '.$this->db->protect_identifiers($table_name).' RENAME TO '.$this->db->protect_identifiers($new_table_name); + } +} + +/* End of file sqlite3_forge.php */ +/* Location: ./system/database/drivers/sqlite3/sqlite3_forge.php */
\ No newline at end of file diff --git a/system/database/drivers/sqlite3/sqlite3_result.php b/system/database/drivers/sqlite3/sqlite3_result.php new file mode 100644 index 000000000..ddf59dbd0 --- /dev/null +++ b/system/database/drivers/sqlite3/sqlite3_result.php @@ -0,0 +1,619 @@ +<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); +/** + * CodeIgniter + * + * An open source application development framework for PHP 5.1.6 or newer + * + * NOTICE OF LICENSE + * + * Licensed under the Open Software License version 3.0 + * + * This source file is subject to the Open Software License (OSL 3.0) that is + * bundled with this package in the files license.txt / license.rst. It is + * also available through the world wide web at this URL: + * http://opensource.org/licenses/OSL-3.0 + * If you did not receive a copy of the license and are unable to obtain it + * through the world wide web, please send an email to + * licensing@ellislab.com so we can send you a copy immediately. + * + * @package CodeIgniter + * @author EllisLab Dev Team + * @copyright Copyright (c) 2008 - 2012, EllisLab, Inc. (http://ellislab.com/) + * @license http://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0) + * @link http://codeigniter.com + * @since Version 1.0 + * @filesource + */ + +/** + * SQLite Result Class + * + * This class extends the parent result class: CI_DB_result + * + * @category Database + * @author Andrey Andreev + * @link http://codeigniter.com/user_guide/database/ + */ +class CI_DB_sqlite3_result extends CI_DB_result { + + // Overwriting the parent here, so we have a way to know if it's already set + public $num_rows; + + // num_fields() might be called multiple times, so we'll use this one to cache it's result + protected $_num_fields; + + /** + * Number of rows in the result set + * + * @return int + */ + public function num_rows() + { + /* The SQLite3 driver doesn't have a graceful way to do this, + * so we'll have to do it on our own. + */ + return is_int($this->num_rows) + ? $this->num_rows + : $this->num_rows = count($this->result_array()); + } + + // -------------------------------------------------------------------- + + /** + * Number of fields in the result set + * + * @return int + */ + public function num_fields() + { + return ( ! is_int($this->_num_fields)) + ? $this->_num_fields = $this->result_id->numColumns() + : $this->_num_fields; + } + + // -------------------------------------------------------------------- + + /** + * Fetch Field Names + * + * Generates an array of column names + * + * @return array + */ + public function list_fields() + { + $field_names = array(); + for ($i = 0, $c = $this->num_fields(); $i < $c; $i++) + { + $field_names[] = $this->result_id->columnName($i); + } + + return $field_names; + } + + // -------------------------------------------------------------------- + + /** + * Field data + * + * Generates an array of objects containing field meta-data + * + * @return array + */ + public function field_data() + { + $retval = array(); + for ($i = 0, $c = $this->num_fields(); $i < $this->num_fields(); $i++) + { + $retval[$i] = new stdClass(); + $retval[$i]->name = $this->result_id->columnName($i); + $retval[$i]->type = 'varchar'; + $retval[$i]->max_length = 0; + $retval[$i]->primary_key = 0; + $retval[$i]->default = ''; + } + + return $retval; + } + + // -------------------------------------------------------------------- + + /** + * Free the result + * + * @return void + */ + public function free_result() + { + if (is_object($this->result_id)) + { + $this->result_id->finalize(); + $this->result_id = NULL; + } + } + + // -------------------------------------------------------------------- + + /** + * Result - associative array + * + * Returns the result set as an array + * + * @return array + */ + protected function _fetch_assoc() + { + return $this->result_id->fetchArray(SQLITE3_ASSOC); + } + + // -------------------------------------------------------------------- + + /** + * Result - object + * + * Returns the result set as an object + * + * @return object + */ + protected function _fetch_object() + { + // No native support for fetching as an object + $row = $this->_fetch_assoc(); + return ($row !== FALSE) ? (object) $row : FALSE; + } + + // -------------------------------------------------------------------- + + /** + * Query result. "array" version. + * + * return array + */ + public function result_array() + { + if (count($this->result_array) > 0) + { + return $this->result_array; + } + elseif (is_array($this->row_data)) + { + if (count($this->row_data) === 0) + { + return $this->result_array; + } + else + { + $row_index = count($this->row_data); + } + } + else + { + $row_index = 0; + $this->row_data = array(); + } + + $row = NULL; + while ($row = $this->_fetch_assoc()) + { + $this->row_data[$row_index++] = $row; + } + + // Un-comment the following line, in case it becomes needed + // $this->_data_seek(); + return $this->result_array = $this->row_data; + } + + // -------------------------------------------------------------------- + + /** + * Query result. "object" version. + * + * @return array + */ + public function result_object() + { + if (count($this->result_object) > 0) + { + return $this->result_object; + } + elseif (count($this->result_array) > 0) + { + for ($i = 0, $c = count($this->result_array); $i < $c; $i++) + { + $this->result_object[] = (object) $this->result_array[$i]; + } + + return $this->result_object; + } + elseif (is_array($this->row_data)) + { + if (count($this->row_data) === 0) + { + return $this->result_object; + } + else + { + $row_index = count($this->row_data); + for ($i = 0; $i < $row_index; $i++) + { + $this->result_object[$i] = (object) $this->row_data[$i]; + } + } + } + else + { + $row_index = 0; + $this->row_data = array(); + } + + $row = NULL; + while ($row = $this->_fetch_assoc()) + { + $this->row_data[$row_index] = $row; + $this->result_object[$row_index++] = (object) $row; + } + + $this->result_array = $this->row_data; + + /* As described for the num_rows() method - there's no easy + * way to get the number of rows selected. Our work-around + * solution (as in here as well) first checks if result_array + * exists and returns its count. It doesn't however check for + * custom_object_result, so - do it here. + */ + if ( ! is_int($this->num_rows)) + { + $this->num_rows = count($this->result_object); + } + + // Un-comment the following line, in case it becomes needed + // $this->_data_seek(); + return $this->result_object; + } + + // -------------------------------------------------------------------- + + /** + * Query result. Custom object version. + * + * @param string class name used to instantiate rows to + * @return array + */ + public function custom_result_object($class_name) + { + if (array_key_exists($class_name, $this->custom_result_object)) + { + return $this->custom_result_object[$class_name]; + } + + if ( ! class_exists($class_name) OR ! is_object($this->result_id) OR $this->num_rows() === 0) + { + return array(); + } + + /* Even if result_array hasn't been set prior to custom_result_object being called, + * num_rows() has done it. + */ + $data = &$this->result_array; + + $result_object = array(); + for ($i = 0, $c = count($data); $i < $c; $i++) + { + $result_object[$i] = new $class_name(); + foreach ($data[$i] as $key => $value) + { + $result_object[$i]->$key = $value; + } + } + + /* As described for the num_rows() method - there's no easy + * way to get the number of rows selected. Our work-around + * solution (as in here as well) first checks if result_array + * exists and returns its count. It doesn't however check for + * custom_object_result, so - do it here. + */ + if ( ! is_int($this->num_rows)) + { + $this->num_rows = count($result_object); + } + + // Cache and return the array + return $this->custom_result_object[$class_name] = $result_object; + } + + // -------------------------------------------------------------------- + + /* Single row result. + * + * Acts as a wrapper for row_object(), row_array() + * and custom_row_object(). Also used by first_row(), next_row() + * and previous_row(). + * + * @param int row index + * @param string ('object', 'array' or a custom class name) + * @return mixed whatever was passed to the second parameter + */ + public function row($n = 0, $type = 'object') + { + if ($type === 'object') + { + return $this->row_object($n); + } + elseif ($type === 'array') + { + return $this->row_array($n); + } + + return $this->custom_row_object($n, $type); + } + + // -------------------------------------------------------------------- + + /* Single row result. Array version. + * + * @param int row index + * @return array + */ + public function row_array($n = 0) + { + // Make sure $n is not a string + if ( ! is_int($n)) + { + $n = (int) $n; + } + + /* If row_data is initialized, it means that we've already tried + * (at least) to fetch some data, so ... check if we already have + * this row. + */ + if (is_array($this->row_data)) + { + /* If we already have row_data[$n] - return it. + * + * If we enter the elseif, there's a number of reasons to + * return an empty array: + * + * - count($this->row_data) === 0 means there are no results + * - num_rows being set or result_array having count() > 0 means + * that we've already fetched all data and $n is greater than + * our highest row index available + * - $n < $this->current_row means that if such row existed, + * we would've already returned it, therefore $n is an + * invalid index + */ + if (isset($this->row_data[$n])) // We already have this row + { + $this->current_row = $n; + return $this->row_data[$n]; + } + elseif (count($this->row_data) === 0 OR is_int($this->num_rows) + OR count($this->result_array) > 0 OR $n < $this->current_row) + { + // No such row exists + return array(); + } + + // Get the next row index that would actually need to be fetched + $current_row = ($this->current_row < count($this->row_data)) ? count($this->row_data) : $this->current_row + 1; + } + else + { + $current_row = $this->current_row = 0; + $this->row_data = array(); + } + + /* Fetch more data, if available + * + * NOTE: Operator precedence is important here, if you change + * 'AND' with '&&' - it WILL BREAK the results, as + * $row will be assigned the scalar value of both + * expressions! + */ + while ($row = $this->_fetch_assoc() AND $current_row <= $n) + { + $this->row_data[$current_row++] = $row; + } + + // This would mean that there's no (more) data to fetch + if ( ! is_array($this->row_data) OR ! isset($this->row_data[$n])) + { + // Cache what we already have + if (is_array($this->row_data)) + { + $this->num_rows = count($this->row_data); + /* Usually, row_data could have less elements than result_array, + * but at this point - they should be exactly the same. + */ + $this->result_array = $this->row_data; + } + else + { + $this->num_rows = 0; + } + + return array(); + } + + $this->current_row = $n; + return $this->row_data[$n]; + } + + // -------------------------------------------------------------------- + + /* Single row result. Object version. + * + * @param int row index + * @return mixed object if row found; empty array if not + */ + public function row_object($n = 0) + { + // Make sure $n is not a string + if ( ! is_int($n)) + { + $n = (int) $n; + } + + /* Logic here is exactly the same as in row_array, + * except we have to cast row_data[$n] to an object. + * + * If we already have result_object though - we can + * directly return from it. + */ + if (isset($this->result_object[$n])) + { + $this->current_row = $n; + return $this->result_object[$n]; + } + + $row = $this->row_array($n); + // Cast only if the row exists + if (count($row) > 0) + { + $this->current_row = $n; + return (object) $row; + } + + return array(); + } + + // -------------------------------------------------------------------- + + /* Single row result. Custom object version. + * + * @param int row index + * @param string custom class name + * @return mixed custom object if row found; empty array otherwise + */ + public function custom_row_object($n = 0, $class_name) + { + // Make sure $n is not a string + if ( ! is_int($n)) + { + $n = (int) $n; + } + + if (array_key_exists($class_name, $this->custom_result_object)) + { + /* We already have a the whole result set with this class_name, + * return the specified row if it exists, and an empty array if + * it doesn't. + */ + if (isset($this->custom_result_object[$class_name][$n])) + { + $this->current_row = $n; + return $this->custom_result_object[$class_name][$n]; + } + else + { + return array(); + } + } + elseif ( ! class_exists($class_name)) // No such class exists + { + return array(); + } + + $row = $this->row_array($n); + // An array would mean that the row doesn't exist + if (is_array($row)) + { + return $row; + } + + // Convert to the desired class and return + $row_object = new $class_name(); + foreach ($row as $key => $value) + { + $row_object->$key = $value; + } + + $this->current_row = $n; + return $row_object; + } + + // -------------------------------------------------------------------- + + /* First row result. + * + * @param string ('object', 'array' or a custom class name) + * @return mixed whatever was passed to the second parameter + */ + public function first_row($type = 'object') + { + return $this->row(0, $type); + } + + // -------------------------------------------------------------------- + + /* Last row result. + * + * @param string ('object', 'array' or a custom class name) + * @return mixed whatever was passed to the second parameter + */ + public function last_row($type = 'object') + { + $result = &$this->result($type); + if ( ! isset($this->num_rows)) + { + $this->num_rows = count($result); + } + $this->current_row = $this->num_rows - 1; + return $result[$this->current_row]; + } + + // -------------------------------------------------------------------- + + /* Next row result. + * + * @param string ('object', 'array' or a custom class name) + * @return mixed whatever was passed to the second parameter + */ + public function next_row($type = 'object') + { + if (is_array($this->row_data)) + { + $count = count($this->row_data); + $n = ($this->current_row > $count OR ($this->current_row === 0 && $count === 0)) ? $count : $this->current_row + 1; + } + else + { + $n = 0; + } + + return $this->row($n, $type); + } + + // -------------------------------------------------------------------- + + /* Previous row result. + * + * @param string ('object', 'array' or a custom class name) + * @return mixed whatever was passed to the second parameter + */ + public function previous_row($type = 'object') + { + $n = ($this->current_row !== 0) ? $this->current_row - 1 : 0; + return $this->row($n, $type); + } + + // -------------------------------------------------------------------- + + /** + * Data Seek + * + * Moves the internal pointer to the desired offset. We call + * this internally before fetching results to make sure the + * result set starts at zero + * + * @return array + */ + protected function _data_seek($n = 0) + { + // Only resetting to the start of the result set is supported + return $this->result_id->reset(); + } + +} + +/* End of file sqlite3_result.php */ +/* Location: ./system/database/drivers/sqlite3/sqlite3_result.php */
\ No newline at end of file diff --git a/system/database/drivers/sqlite3/sqlite3_utility.php b/system/database/drivers/sqlite3/sqlite3_utility.php new file mode 100644 index 000000000..a4dc875e1 --- /dev/null +++ b/system/database/drivers/sqlite3/sqlite3_utility.php @@ -0,0 +1,103 @@ +<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); +/** + * CodeIgniter + * + * An open source application development framework for PHP 5.1.6 or newer + * + * NOTICE OF LICENSE + * + * Licensed under the Open Software License version 3.0 + * + * This source file is subject to the Open Software License (OSL 3.0) that is + * bundled with this package in the files license.txt / license.rst. It is + * also available through the world wide web at this URL: + * http://opensource.org/licenses/OSL-3.0 + * If you did not receive a copy of the license and are unable to obtain it + * through the world wide web, please send an email to + * licensing@ellislab.com so we can send you a copy immediately. + * + * @package CodeIgniter + * @author EllisLab Dev Team + * @copyright Copyright (c) 2008 - 2012, EllisLab, Inc. (http://ellislab.com/) + * @license http://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0) + * @link http://codeigniter.com + * @since Version 1.0 + * @filesource + */ + +/** + * SQLite3 Utility Class + * + * @category Database + * @author Andrey Andreev + * @link http://codeigniter.com/user_guide/database/ + */ +class CI_DB_sqlite3_utility extends CI_DB_utility { + + /** + * List databases + * + * @return bool + */ + public function _list_databases() + { + // Not supported + return FALSE; + + // Do we use this? + if ($this->db_debug) + { + return $this->db->display_error('db_unsuported_feature'); + } + } + + // -------------------------------------------------------------------- + + /** + * Optimize table query + * + * Is optimization even supported in SQLite? + * + * @param string the table name + * @return bool + */ + public function _optimize_table($table) + { + // Not supported + return FALSE; + } + + // -------------------------------------------------------------------- + + /** + * Repair table query + * + * Are table repairs even supported in SQLite? + * + * @param string the table name + * @return object + */ + public function _repair_table($table) + { + // Not supported + return FALSE; + } + + // -------------------------------------------------------------------- + + /** + * SQLite Export + * + * @param array Preferences + * @return mixed + */ + public function _backup($params = array()) + { + // Not supported + return $this->db->display_error('db_unsuported_feature'); + } + +} + +/* End of file sqlite3_utility.php */ +/* Location: ./system/database/drivers/sqlite3/sqlite3_utility.php */
\ No newline at end of file diff --git a/system/database/drivers/sqlsrv/sqlsrv_driver.php b/system/database/drivers/sqlsrv/sqlsrv_driver.php index bb4f009bc..f4eab8f28 100644 --- a/system/database/drivers/sqlsrv/sqlsrv_driver.php +++ b/system/database/drivers/sqlsrv/sqlsrv_driver.php @@ -393,21 +393,6 @@ class CI_DB_sqlsrv_driver extends CI_DB { // -------------------------------------------------------------------- /** - * Escape the SQL Identifiers - * - * This function escapes column and table names - * - * @param string - * @return string - */ - public function _escape_identifiers($item) - { - return $item; - } - - // -------------------------------------------------------------------- - - /** * From Tables * * This function implicitly groups FROM tables so there is no confusion @@ -429,23 +414,6 @@ class CI_DB_sqlsrv_driver extends CI_DB { // -------------------------------------------------------------------- /** - * Insert statement - * - * Generates a platform-specific insert string from the supplied data - * - * @param string the table name - * @param array the insert keys - * @param array the insert values - * @return string - */ - protected function _insert($table, $keys, $values) - { - return 'INSERT INTO '.$table.' ('.implode(', ', $keys).') VALUES ('.implode(', ', $values).')'; - } - - // -------------------------------------------------------------------- - - /** * Update statement * * Generates a platform-specific update string from the supplied data @@ -473,15 +441,16 @@ class CI_DB_sqlsrv_driver extends CI_DB { * Truncate statement * * Generates a platform-specific truncate string from the supplied data - * If the database does not support the truncate() command - * This function maps to "DELETE FROM table" + * + * If the database does not support the truncate() command, + * then this method maps to 'DELETE FROM table' * * @param string the table name * @return string */ protected function _truncate($table) { - return "TRUNCATE ".$table; + return 'TRUNCATE TABLE '.$table; } // -------------------------------------------------------------------- diff --git a/system/database/drivers/sqlsrv/sqlsrv_forge.php b/system/database/drivers/sqlsrv/sqlsrv_forge.php index 0dc7b5242..377dcf154 100644 --- a/system/database/drivers/sqlsrv/sqlsrv_forge.php +++ b/system/database/drivers/sqlsrv/sqlsrv_forge.php @@ -63,11 +63,12 @@ class CI_DB_sqlsrv_forge extends CI_DB_forge { /** * Drop Table * - * @return bool + * @param string table name + * @return string */ public function _drop_table($table) { - return "DROP TABLE ".$this->db->_escape_identifiers($table); + return 'DROP TABLE '.$this->db->escape_identifiers($table); } // -------------------------------------------------------------------- @@ -91,7 +92,7 @@ class CI_DB_sqlsrv_forge extends CI_DB_forge { $sql .= 'IF NOT EXISTS '; } - $sql .= $this->db->_escape_identifiers($table)." ("; + $sql .= $this->db->escape_identifiers($table).' ('; $current_field_count = 0; foreach ($fields as $field => $attributes) diff --git a/system/helpers/file_helper.php b/system/helpers/file_helper.php index 6e8a4ded1..3a373efd3 100644 --- a/system/helpers/file_helper.php +++ b/system/helpers/file_helper.php @@ -121,11 +121,13 @@ if ( ! function_exists('write_file')) * * @param string path to file * @param bool whether to delete any directories found in the path + * @param int + * @param bool whether to skip deleting .htaccess and index page files * @return bool */ if ( ! function_exists('delete_files')) { - function delete_files($path, $del_dir = FALSE, $level = 0) + function delete_files($path, $del_dir = FALSE, $level = 0, $htdocs = FALSE) { // Trim the trailing slash $path = rtrim($path, DIRECTORY_SEPARATOR); @@ -141,9 +143,9 @@ if ( ! function_exists('delete_files')) { if (is_dir($path.DIRECTORY_SEPARATOR.$filename) && $filename[0] !== '.') { - delete_files($path.DIRECTORY_SEPARATOR.$filename, $del_dir, $level + 1); + delete_files($path.DIRECTORY_SEPARATOR.$filename, $del_dir, $level + 1, $htdocs); } - else + elseif ($htdocs === TRUE && ! preg_match('/^(\.htaccess|index\.(html|htm|php))$/', $filename)) { @unlink($path.DIRECTORY_SEPARATOR.$filename); } diff --git a/system/libraries/Cache/drivers/Cache_memcached.php b/system/libraries/Cache/drivers/Cache_memcached.php index 1028c8fd5..4cd5f3d6f 100644 --- a/system/libraries/Cache/drivers/Cache_memcached.php +++ b/system/libraries/Cache/drivers/Cache_memcached.php @@ -189,17 +189,17 @@ class CI_Cache_memcached extends CI_Driver { { if ( ! array_key_exists('hostname', $cache_server)) { - $cache_server['hostname'] = $this->_default_options['default_host']; + $cache_server['hostname'] = $this->_memcache_conf['default']['default_host']; } if ( ! array_key_exists('port', $cache_server)) { - $cache_server['port'] = $this->_default_options['default_port']; + $cache_server['port'] = $this->_memcache_conf['default']['default_port']; } if ( ! array_key_exists('weight', $cache_server)) { - $cache_server['weight'] = $this->_default_options['default_weight']; + $cache_server['weight'] = $this->_memcache_conf['default']['default_weight']; } if (get_class($this->_memcached) == 'Memcache') diff --git a/system/libraries/Email.php b/system/libraries/Email.php index 8f383c939..48c3bf3ab 100644 --- a/system/libraries/Email.php +++ b/system/libraries/Email.php @@ -407,11 +407,11 @@ class CI_Email { * @param string * @return object */ - public function attach($filename, $disposition = '', $newname = NULL) + public function attach($filename, $disposition = '', $newname = NULL, $mime = '') { $this->_attach_name[] = array($filename, $newname); - $this->_attach_type[] = $this->_mime_types(pathinfo($filename, PATHINFO_EXTENSION)); $this->_attach_disp[] = empty($disposition) ? 'attachment' : $disposition; // Can also be 'inline' Not sure if it matters + $this->_attach_type[] = $mime; return $this; } @@ -1049,29 +1049,39 @@ class CI_Email { $filename = $this->_attach_name[$i][0]; $basename = (is_null($this->_attach_name[$i][1])) ? basename($filename) : $this->_attach_name[$i][1]; $ctype = $this->_attach_type[$i]; + $file_content = ''; - if ( ! file_exists($filename)) + if ($this->_attach_type[$i] == '') { - $this->_set_error_message('lang:email_attachment_missing', $filename); - return FALSE; - } + if ( ! file_exists($filename)) + { + $this->_set_error_message('lang:email_attachment_missing', $filename); + return FALSE; + } + + $file = filesize($filename) +1; + if ( ! $fp = fopen($filename, FOPEN_READ)) + { + $this->_set_error_message('lang:email_attachment_unreadable', $filename); + return FALSE; + } + + $ctype = $this->_mime_types(pathinfo($filename, PATHINFO_EXTENSION)); + $file_content = fread($fp, $file); + fclose($fp); + } + else + { + $file_content =& $this->_attach_content[$i]; + } $attachment[$z++] = "--".$this->_atc_boundary.$this->newline . "Content-type: ".$ctype."; " . "name=\"".$basename."\"".$this->newline . "Content-Disposition: ".$this->_attach_disp[$i].";".$this->newline . "Content-Transfer-Encoding: base64".$this->newline; - $file = filesize($filename) +1; - - if ( ! $fp = fopen($filename, FOPEN_READ)) - { - $this->_set_error_message('lang:email_attachment_unreadable', $filename); - return FALSE; - } - - $attachment[$z++] = chunk_split(base64_encode(fread($fp, $file))); - fclose($fp); + $attachment[$z++] = chunk_split(base64_encode($file_content)); } $body .= implode($this->newline, $attachment).$this->newline."--".$this->_atc_boundary."--"; diff --git a/system/libraries/Encrypt.php b/system/libraries/Encrypt.php index b29eb470e..54b5bf737 100644 --- a/system/libraries/Encrypt.php +++ b/system/libraries/Encrypt.php @@ -38,15 +38,15 @@ */ class CI_Encrypt { - public $encryption_key = ''; - protected $_hash_type = 'sha1'; - protected $_mcrypt_exists = FALSE; + public $encryption_key = ''; + protected $_hash_type = 'sha1'; + protected $_mcrypt_exists = FALSE; protected $_mcrypt_cipher; protected $_mcrypt_mode; public function __construct() { - $this->_mcrypt_exists = ( ! function_exists('mcrypt_encrypt')) ? FALSE : TRUE; + $this->_mcrypt_exists = function_exists('mcrypt_encrypt'); log_message('debug', 'Encrypt Class Initialized'); } @@ -349,8 +349,8 @@ class CI_Encrypt { * * Function description * - * @param type - * @return type + * @param string + * @return string */ protected function _remove_cipher_noise($data, $key) { @@ -382,8 +382,8 @@ class CI_Encrypt { /** * Set the Mcrypt Cipher * - * @param constant - * @return string + * @param int + * @return object */ public function set_cipher($cipher) { @@ -396,8 +396,8 @@ class CI_Encrypt { /** * Set the Mcrypt Mode * - * @param constant - * @return string + * @param int + * @return object */ public function set_mode($mode) { @@ -410,7 +410,7 @@ class CI_Encrypt { /** * Get Mcrypt cipher Value * - * @return string + * @return int */ protected function _get_cipher() { @@ -427,7 +427,7 @@ class CI_Encrypt { /** * Get Mcrypt Mode Value * - * @return string + * @return int */ protected function _get_mode() { @@ -464,7 +464,8 @@ class CI_Encrypt { { return ($this->_hash_type === 'sha1') ? sha1($str) : md5($str); } + } /* End of file Encrypt.php */ -/* Location: ./system/libraries/Encrypt.php */ +/* Location: ./system/libraries/Encrypt.php */
\ No newline at end of file diff --git a/system/libraries/Form_validation.php b/system/libraries/Form_validation.php index 3e0c72e84..22bc7ddf3 100644 --- a/system/libraries/Form_validation.php +++ b/system/libraries/Form_validation.php @@ -25,8 +25,6 @@ * @filesource */ -// ------------------------------------------------------------------------ - /** * Form Validation Class * @@ -39,15 +37,15 @@ class CI_Form_validation { protected $CI; - protected $_field_data = array(); - protected $_config_rules = array(); - protected $_error_array = array(); - protected $_error_messages = array(); - protected $_error_prefix = '<p>'; - protected $_error_suffix = '</p>'; - protected $error_string = ''; - protected $_safe_form_data = FALSE; - protected $validation_data = array(); + protected $_field_data = array(); + protected $_config_rules = array(); + protected $_error_array = array(); + protected $_error_messages = array(); + protected $_error_prefix = '<p>'; + protected $_error_suffix = '</p>'; + protected $error_string = ''; + protected $_safe_form_data = FALSE; + protected $validation_data = array(); public function __construct($rules = array()) { @@ -64,7 +62,7 @@ class CI_Form_validation { $this->_error_suffix = $rules['error_suffix']; unset($rules['error_suffix']); } - + // Validation rules can be stored in a config file. $this->_config_rules = $rules; @@ -90,7 +88,7 @@ class CI_Form_validation { * * @param mixed * @param string - * @return void + * @return object */ public function set_rules($field, $label = '', $rules = '') { @@ -108,17 +106,18 @@ class CI_Form_validation { foreach ($field as $row) { // Houston, we have a problem... - if ( ! isset($row['field']) OR ! isset($row['rules'])) + if ( ! isset($row['field'], $row['rules'])) { continue; } // If the field label wasn't passed we use the field name - $label = ( ! isset($row['label'])) ? $row['field'] : $row['label']; + $label = isset($row['label']) ? $row['label'] : $row['field']; // Here we go! $this->set_rules($row['field'], $label, $row['rules']); } + return $this; } @@ -198,12 +197,12 @@ class CI_Form_validation { /** * Set Error Message * - * Lets users set their own error messages on the fly. Note: The key - * name has to match the function name that it corresponds to. + * Lets users set their own error messages on the fly. Note: + * The key name has to match the function name that it corresponds to. * + * @param array * @param string - * @param string - * @return string + * @return object */ public function set_message($lang, $val = '') { @@ -213,7 +212,6 @@ class CI_Form_validation { } $this->_error_messages = array_merge($this->_error_messages, $lang); - return $this; } @@ -226,13 +224,12 @@ class CI_Form_validation { * * @param string * @param string - * @return void + * @return object */ public function set_error_delimiters($prefix = '<p>', $suffix = '</p>') { $this->_error_prefix = $prefix; $this->_error_suffix = $suffix; - return $this; } @@ -244,11 +241,11 @@ class CI_Form_validation { * Gets the error message associated with a particular field * * @param string the field name - * @return void + * @return string */ public function error($field = '', $prefix = '', $suffix = '') { - if ( ! isset($this->_field_data[$field]['error']) OR $this->_field_data[$field]['error'] == '') + if (empty($this->_field_data[$field]['error'])) { return ''; } @@ -289,7 +286,7 @@ class CI_Form_validation { * * @param string * @param string - * @return str + * @return string */ public function error_string($prefix = '', $suffix = '') { @@ -334,7 +331,7 @@ class CI_Form_validation { public function run($group = '') { // Do we even have any data to process? Mm? - $validation_array = ( ! empty($this->validation_data)) ? $this->validation_data : $_POST; + $validation_array = empty($this->validation_data) ? $_POST : $this->validation_data; if (count($validation_array) === 0) { return FALSE; @@ -353,7 +350,7 @@ class CI_Form_validation { // Is there a validation rule for the particular URI being accessed? $uri = ($group == '') ? trim($this->CI->uri->ruri_string(), '/') : $group; - if ($uri != '' AND isset($this->_config_rules[$uri])) + if ($uri != '' && isset($this->_config_rules[$uri])) { $this->set_rules($this->_config_rules[$uri]); } @@ -362,10 +359,10 @@ class CI_Form_validation { $this->set_rules($this->_config_rules); } - // We're we able to set the rules correctly? + // Were we able to set the rules correctly? if (count($this->_field_data) === 0) { - log_message('debug', "Unable to find validation rules"); + log_message('debug', 'Unable to find validation rules'); return FALSE; } } @@ -379,17 +376,13 @@ class CI_Form_validation { { // Fetch the data from the corresponding $_POST or validation array and cache it in the _field_data array. // Depending on whether the field name is an array or a string will determine where we get it from. - if ($row['is_array'] === TRUE) { $this->_field_data[$field]['postdata'] = $this->_reduce_array($validation_array, $row['keys']); } - else + elseif ( ! empty($validation_array[$field])) { - if (isset($validation_array[$field]) AND $validation_array[$field] != "") - { - $this->_field_data[$field]['postdata'] = $validation_array[$field]; - } + $this->_field_data[$field]['postdata'] = $validation_array[$field]; } $this->_execute($row, explode('|', $row['rules']), $this->_field_data[$field]['postdata']); @@ -397,7 +390,6 @@ class CI_Form_validation { // Did we end up with any errors? $total_errors = count($this->_error_array); - if ($total_errors > 0) { $this->_safe_form_data = TRUE; @@ -416,7 +408,7 @@ class CI_Form_validation { * * @param array * @param array - * @param integer + * @param int * @return mixed */ protected function _reduce_array($array, $keys, $i = 0) @@ -434,7 +426,7 @@ class CI_Form_validation { /** * Re-populate the _POST array with our finalized and processed data * - * @return null + * @return void */ protected function _reset_post_array() { @@ -494,7 +486,7 @@ class CI_Form_validation { * @param array * @param array * @param mixed - * @param integer + * @param int * @return mixed */ protected function _execute($row, $rules, $postdata = NULL, $cycles = 0) @@ -511,17 +503,15 @@ class CI_Form_validation { return; } - // -------------------------------------------------------------------- - // If the field is blank, but NOT required, no further tests are necessary $callback = FALSE; - if ( ! in_array('required', $rules) AND is_null($postdata)) + if ( ! in_array('required', $rules) && is_null($postdata)) { // Before we bail out, does the rule contain a callback? - if (preg_match("/(callback_\w+(\[.*?\])?)/", implode(' ', $rules), $match)) + if (preg_match('/(callback_\w+(\[.*?\])?)/', implode(' ', $rules), $match)) { $callback = TRUE; - $rules = (array('1' => $match[1])); + $rules = array(1 => $match[1]); } else { @@ -529,15 +519,13 @@ class CI_Form_validation { } } - // -------------------------------------------------------------------- - // Isset Test. Typically this rule will only apply to checkboxes. - if (is_null($postdata) AND $callback === FALSE) + if (is_null($postdata) && $callback === FALSE) { if (in_array('isset', $rules, TRUE) OR in_array('required', $rules)) { // Set the message type - $type = (in_array('required', $rules)) ? 'required' : 'isset'; + $type = in_array('required', $rules) ? 'required' : 'isset'; if ( ! isset($this->_error_messages[$type])) { @@ -569,13 +557,13 @@ class CI_Form_validation { // -------------------------------------------------------------------- // Cycle through each rule and run it - foreach ($rules As $rule) + foreach ($rules as $rule) { $_in_array = FALSE; // We set the $postdata variable with the current data in our master array so that // each cycle of the loop is dealing with the processed data from the last cycle - if ($row['is_array'] == TRUE AND is_array($this->_field_data[$row['field']]['postdata'])) + if ($row['is_array'] == TRUE && is_array($this->_field_data[$row['field']]['postdata'])) { // We shouldn't need this safety, but just in case there isn't an array index // associated with this cycle we'll bail out @@ -592,11 +580,9 @@ class CI_Form_validation { $postdata = $this->_field_data[$row['field']]['postdata']; } - // -------------------------------------------------------------------- - // Is the rule a callback? $callback = FALSE; - if (substr($rule, 0, 9) == 'callback_') + if (strpos($rule, 'callback_') === 0) { $rule = substr($rule, 9); $callback = TRUE; @@ -605,7 +591,7 @@ class CI_Form_validation { // Strip the parameter (if exists) from the rule // Rules can contain a parameter: max_length[5] $param = FALSE; - if (preg_match("/(.*?)\[(.*)\]/", $rule, $match)) + if (preg_match('/(.*?)\[(.*)\]/', $rule, $match)) { $rule = $match[1]; $param = $match[2]; @@ -616,68 +602,69 @@ class CI_Form_validation { { if ( ! method_exists($this->CI, $rule)) { - continue; + log_message('debug', 'Unable to find callback validation rule: '.$rule); + $result = FALSE; + } + else + { + // Run the function and grab the result + $result = $this->CI->$rule($postdata, $param); } - - // Run the function and grab the result - $result = $this->CI->$rule($postdata, $param); // Re-assign the result to the master data array if ($_in_array === TRUE) { - $this->_field_data[$row['field']]['postdata'][$cycles] = (is_bool($result)) ? $postdata : $result; + $this->_field_data[$row['field']]['postdata'][$cycles] = is_bool($result) ? $postdata : $result; } else { - $this->_field_data[$row['field']]['postdata'] = (is_bool($result)) ? $postdata : $result; + $this->_field_data[$row['field']]['postdata'] = is_bool($result) ? $postdata : $result; } // If the field isn't required and we just processed a callback we'll move on... - if ( ! in_array('required', $rules, TRUE) AND $result !== FALSE) + if ( ! in_array('required', $rules, TRUE) && $result !== FALSE) { continue; } } - else + elseif ( ! method_exists($this, $rule)) { - if ( ! method_exists($this, $rule)) + // If our own wrapper function doesn't exist we see if a native PHP function does. + // Users can use any native PHP function call that has one param. + if (function_exists($rule)) { - // If our own wrapper function doesn't exist we see if a native PHP function does. - // Users can use any native PHP function call that has one param. - if (function_exists($rule)) - { - $result = $rule($postdata); + $result = ($param !== FALSE) ? $rule($postdata, $param) : $rule($postdata); - if ($_in_array === TRUE) - { - $this->_field_data[$row['field']]['postdata'][$cycles] = (is_bool($result)) ? $postdata : $result; - } - else - { - $this->_field_data[$row['field']]['postdata'] = (is_bool($result)) ? $postdata : $result; - } + if ($_in_array === TRUE) + { + $this->_field_data[$row['field']]['postdata'][$cycles] = is_bool($result) ? $postdata : $result; } else { - log_message('debug', "Unable to find validation rule: ".$rule); + $this->_field_data[$row['field']]['postdata'] = is_bool($result) ? $postdata : $result; } - - continue; } - + else + { + log_message('debug', 'Unable to find validation rule: '.$rule); + $result = FALSE; + } + } + else + { $result = $this->$rule($postdata, $param); if ($_in_array === TRUE) { - $this->_field_data[$row['field']]['postdata'][$cycles] = (is_bool($result)) ? $postdata : $result; + $this->_field_data[$row['field']]['postdata'][$cycles] = is_bool($result) ? $postdata : $result; } else { - $this->_field_data[$row['field']]['postdata'] = (is_bool($result)) ? $postdata : $result; + $this->_field_data[$row['field']]['postdata'] = is_bool($result) ? $postdata : $result; } } - // Did the rule test negatively? If so, grab the error. + // Did the rule test negatively? If so, grab the error. if ($result === FALSE) { if ( ! isset($this->_error_messages[$rule])) @@ -693,7 +680,7 @@ class CI_Form_validation { } // Is the parameter we are inserting into the error message the name - // of another field? If so we need to grab its "field label" + // of another field? If so we need to grab its "field label" if (isset($this->_field_data[$param], $this->_field_data[$param]['label'])) { $param = $this->_translate_fieldname($this->_field_data[$param]['label']); @@ -727,7 +714,7 @@ class CI_Form_validation { { // Do we need to translate the field name? // We look for the prefix lang: to determine this - if (substr($fieldname, 0, 5) === 'lang:') + if (strpos($fieldname, 'lang:') === 0) { // Grab the variable $line = substr($fieldname, 5); @@ -791,7 +778,6 @@ class CI_Form_validation { } $field = $this->_field_data[$field]['postdata']; - if (is_array($field)) { if ( ! in_array($value, $field)) @@ -827,7 +813,6 @@ class CI_Form_validation { } $field = $this->_field_data[$field]['postdata']; - if (is_array($field)) { if ( ! in_array($value, $field)) @@ -835,12 +820,9 @@ class CI_Form_validation { return ''; } } - else + elseif (($field == '' OR $value == '') OR ($field != $value)) { - if (($field == '' OR $value == '') OR ($field != $value)) - { - return ''; - } + return ''; } return ' checked="checked"'; @@ -874,7 +856,7 @@ class CI_Form_validation { */ public function required($str) { - return ( ! is_array($str)) ? (trim($str) !== '') : ( ! empty($str)); + return is_array($str) ? (bool) count($str) : (trim($str) !== ''); } // -------------------------------------------------------------------- @@ -883,7 +865,7 @@ class CI_Form_validation { * Performs a Regular Expression match test. * * @param string - * @param regex + * @param string regex * @return bool */ public function regex_match($str, $regex) @@ -897,12 +879,12 @@ class CI_Form_validation { * Match one field to another * * @param string - * @param field + * @param string field * @return bool */ public function matches($str, $field) { - $validation_array = ( ! empty($this->validation_data)) ? $this->validation_data : $_POST; + $validation_array = empty($this->validation_data) ? $_POST : $this->validation_data; if ( ! isset($validation_array[$field])) { return FALSE; @@ -920,7 +902,7 @@ class CI_Form_validation { * in the specified database field. * * @param string - * @param field + * @param string field * @return bool */ public function is_unique($str, $field) @@ -940,7 +922,7 @@ class CI_Form_validation { * Minimum Length * * @param string - * @param value + * @param int * @return bool */ public function min_length($str, $val) @@ -950,12 +932,9 @@ class CI_Form_validation { return FALSE; } - if (MB_ENABLED === TRUE) - { - return ! (mb_strlen($str) < $val); - } - - return ! (strlen($str) < $val); + return (MB_ENABLED === TRUE) + ? ($val <= mb_strlen($str)) + : ($val <= strlen(str)); } // -------------------------------------------------------------------- @@ -964,7 +943,7 @@ class CI_Form_validation { * Max Length * * @param string - * @param value + * @param int * @return bool */ public function max_length($str, $val) @@ -974,12 +953,9 @@ class CI_Form_validation { return FALSE; } - if (MB_ENABLED === TRUE) - { - return ! (mb_strlen($str) > $val); - } - - return ! (strlen($str) > $val); + return (MB_ENABLED === TRUE) + ? ($val >= mb_strlen($str)) + : ($val >= strlen($str)); } // -------------------------------------------------------------------- @@ -988,7 +964,7 @@ class CI_Form_validation { * Exact Length * * @param string - * @param value + * @param int * @return bool */ public function exact_length($str, $val) @@ -998,12 +974,9 @@ class CI_Form_validation { return FALSE; } - if (MB_ENABLED === TRUE) - { - return (mb_strlen($str) == $val); - } - - return (strlen($str) == $val); + return (MB_ENABLED === TRUE) + ? (mb_strlen($str) == $val) + : (strlen($str) == $val); } // -------------------------------------------------------------------- @@ -1114,19 +1087,6 @@ class CI_Form_validation { // -------------------------------------------------------------------- /** - * Is Numeric - * - * @param string - * @return bool - */ - public function is_numeric($str) - { - return is_numeric($str); - } - - // -------------------------------------------------------------------- - - /** * Integer * * @param string @@ -1160,11 +1120,7 @@ class CI_Form_validation { */ public function greater_than($str, $min) { - if ( ! is_numeric($str)) - { - return FALSE; - } - return $str > $min; + return is_numeric($str) ? ($str > $min) : FALSE; } // -------------------------------------------------------------------- @@ -1177,11 +1133,7 @@ class CI_Form_validation { */ public function greater_than_equal_to($str, $min) { - if ( ! is_numeric($str)) - { - return FALSE; - } - return $str >= $min; + return is_numeric($str) ? ($str >= $min) : FALSE; } // -------------------------------------------------------------------- @@ -1194,11 +1146,7 @@ class CI_Form_validation { */ public function less_than($str, $max) { - if ( ! is_numeric($str)) - { - return FALSE; - } - return $str < $max; + return is_numeric($str) ? ($str < $max) : FALSE; } // -------------------------------------------------------------------- @@ -1211,11 +1159,7 @@ class CI_Form_validation { */ public function less_than_equal_to($str, $max) { - if ( ! is_numeric($str)) - { - return FALSE; - } - return $str <= $max; + return is_numeric($str) ? ($str <= $max) : FALSE; } // -------------------------------------------------------------------- @@ -1301,14 +1245,14 @@ class CI_Form_validation { */ public function prep_url($str = '') { - if ($str == 'http://' OR $str == '') + if ($str === 'http://' OR $str == '') { return ''; } - if (substr($str, 0, 7) !== 'http://' && substr($str, 0, 8) !== 'https://') + if (strpos($str, 'http://') !== 0 && strpos($str, 'https://') !== 0) { - $str = 'http://'.$str; + return 'http://'.$str; } return $str; @@ -1375,4 +1319,4 @@ class CI_Form_validation { } /* End of file Form_validation.php */ -/* Location: ./system/libraries/Form_validation.php */ +/* Location: ./system/libraries/Form_validation.php */
\ No newline at end of file diff --git a/system/libraries/Image_lib.php b/system/libraries/Image_lib.php index 86b77bf07..1ab8b23e0 100644 --- a/system/libraries/Image_lib.php +++ b/system/libraries/Image_lib.php @@ -251,7 +251,7 @@ class CI_Image_lib { } else { - if (strpos($this->new_image, '/') === FALSE AND strpos($this->new_image, '\\') === FALSE) + if (strpos($this->new_image, '/') === FALSE && strpos($this->new_image, '\\') === FALSE) { $full_dest_path = str_replace('\\', '/', realpath($this->new_image)); } @@ -1462,4 +1462,4 @@ class CI_Image_lib { } /* End of file Image_lib.php */ -/* Location: ./system/libraries/Image_lib.php */ +/* Location: ./system/libraries/Image_lib.php */
\ No newline at end of file diff --git a/system/libraries/Javascript.php b/system/libraries/Javascript.php index 9ba93000b..629a3adfe 100644 --- a/system/libraries/Javascript.php +++ b/system/libraries/Javascript.php @@ -25,8 +25,6 @@ * @filesource */ -// ------------------------------------------------------------------------ - /** * Javascript Class * @@ -46,7 +44,7 @@ class CI_Javascript { foreach ($defaults as $key => $val) { - if (isset($params[$key]) && $params[$key] !== "") + if (isset($params[$key]) && $params[$key] !== '') { $defaults[$key] = $params[$key]; } @@ -61,7 +59,7 @@ class CI_Javascript { // make js to refer to current library $this->js =& $this->CI->$js_library_driver; - log_message('debug', "Javascript Class Initialized and loaded. Driver used: $js_library_driver"); + log_message('debug', 'Javascript Class Initialized and loaded. Driver used: '.$js_library_driver); } // -------------------------------------------------------------------- @@ -107,7 +105,7 @@ class CI_Javascript { * * @param string The element to attach the event to * @param string The code to execute - * @param boolean whether or not to return false + * @param bool whether or not to return false * @return string */ public function click($element = 'this', $js = '', $ret_false = TRUE) @@ -375,7 +373,6 @@ class CI_Javascript { // Effects // -------------------------------------------------------------------- - /** * Add Class * @@ -618,12 +615,9 @@ class CI_Javascript { { $this->_javascript_location = $external_file; } - else + elseif ($this->CI->config->item('javascript_location') != '') { - if ($this->CI->config->item('javascript_location') != '') - { - $this->_javascript_location = $this->CI->config->item('javascript_location'); - } + $this->_javascript_location = $this->CI->config->item('javascript_location'); } if ($relative === TRUE OR strncmp($external_file, 'http://', 7) === 0 OR strncmp($external_file, 'https://', 8) === 0) @@ -650,13 +644,13 @@ class CI_Javascript { * Outputs a <script> tag * * @param string The element to attach the event to - * @param boolean If a CDATA section should be added + * @param bool If a CDATA section should be added * @return string */ public function inline($script, $cdata = TRUE) { return $this->_open_script() - . ($cdata ? "\n// <![CDATA[\n{$script}\n// ]]>\n" : "\n{$script}\n") + . ($cdata ? "\n// <![CDATA[\n".$script."\n// ]]>\n" : "\n".$script."\n") . $this->_close_script(); } @@ -673,7 +667,7 @@ class CI_Javascript { protected function _open_script($src = '') { return '<script type="text/javascript" charset="'.strtolower($this->CI->config->item('charset')).'"' - . ($src == '' ? '>' : ' src="'.$src.'">'); + .($src == '' ? '>' : ' src="'.$src.'">'); } // -------------------------------------------------------------------- @@ -688,15 +682,12 @@ class CI_Javascript { */ protected function _close_script($extra = "\n") { - return "</script>$extra"; + return '</script>'.$extra; } - - // -------------------------------------------------------------------- // -------------------------------------------------------------------- // AJAX-Y STUFF - still a testbed // -------------------------------------------------------------------- - // -------------------------------------------------------------------- /** * Update @@ -751,9 +742,9 @@ class CI_Javascript { $json = array(); $_is_assoc = TRUE; - if ( ! is_array($json_result) AND empty($json_result)) + if ( ! is_array($json_result) && empty($json_result)) { - show_error("Generate JSON Failed - Illegal key, value pair."); + show_error('Generate JSON Failed - Illegal key, value pair.'); } elseif ($match_array_type) { @@ -774,7 +765,7 @@ class CI_Javascript { $json = implode(',', $json); - return $_is_assoc ? "{".$json."}" : "[".$json."]"; + return $_is_assoc ? '{'.$json.'}' : '['.$json.']'; } @@ -785,8 +776,8 @@ class CI_Javascript { * * Checks for an associative array * - * @param type - * @return type + * @param array + * @return bool */ protected function _is_associative_array($arr) { @@ -808,8 +799,8 @@ class CI_Javascript { * * Ensures a standard json value and escapes values * - * @param type - * @return type + * @param mixed + * @return string */ protected function _prep_args($result, $is_key = FALSE) { @@ -831,9 +822,7 @@ class CI_Javascript { } } - // -------------------------------------------------------------------- } -// END Javascript Class /* End of file Javascript.php */ -/* Location: ./system/libraries/Javascript.php */ +/* Location: ./system/libraries/Javascript.php */
\ No newline at end of file diff --git a/system/libraries/Log.php b/system/libraries/Log.php index 955277acc..66f9ebff9 100644 --- a/system/libraries/Log.php +++ b/system/libraries/Log.php @@ -25,8 +25,6 @@ * @filesource */ -// ------------------------------------------------------------------------ - /** * Logging Class * @@ -43,12 +41,9 @@ class CI_Log { protected $_threshold_max = 0; protected $_threshold_array = array(); protected $_date_fmt = 'Y-m-d H:i:s'; - protected $_enabled = TRUE; - protected $_levels = array('ERROR' => 1, 'DEBUG' => 2, 'INFO' => 3, 'ALL' => 4); + protected $_enabled = TRUE; + protected $_levels = array('ERROR' => 1, 'DEBUG' => 2, 'INFO' => 3, 'ALL' => 4); - /** - * Constructor - */ public function __construct() { $config =& get_config(); @@ -98,7 +93,7 @@ class CI_Log { $level = strtoupper($level); if (( ! isset($this->_levels[$level]) OR ($this->_levels[$level] > $this->_threshold)) - AND ! isset($this->_threshold_array[$this->_levels[$level]])) + && ! isset($this->_threshold_array[$this->_levels[$level]])) { return FALSE; } @@ -125,15 +120,15 @@ class CI_Log { flock($fp, LOCK_UN); fclose($fp); - if (isset($newfile) AND $newfile === TRUE) + if (isset($newfile) && $newfile === TRUE) { @chmod($filepath, FILE_WRITE_MODE); } + return TRUE; } } -// END Log Class /* End of file Log.php */ -/* Location: ./system/libraries/Log.php */ +/* Location: ./system/libraries/Log.php */
\ No newline at end of file diff --git a/system/libraries/Profiler.php b/system/libraries/Profiler.php index d84e5d3fc..6320ab50d 100644 --- a/system/libraries/Profiler.php +++ b/system/libraries/Profiler.php @@ -25,8 +25,6 @@ * @filesource */ -// ------------------------------------------------------------------------ - /** * CodeIgniter Profiler Class * @@ -45,24 +43,22 @@ class CI_Profiler { protected $_available_sections = array( - 'benchmarks', - 'get', - 'memory_usage', - 'post', - 'uri_string', - 'controller_info', - 'queries', - 'http_headers', - 'session_data', - 'config' - ); + 'benchmarks', + 'get', + 'memory_usage', + 'post', + 'uri_string', + 'controller_info', + 'queries', + 'http_headers', + 'session_data', + 'config' + ); protected $_query_toggle_count = 25; protected $CI; - // -------------------------------------------------------------------- - public function __construct($config = array()) { $this->CI =& get_instance(); @@ -102,7 +98,7 @@ class CI_Profiler { { if (in_array($method, $this->_available_sections)) { - $this->_compile_{$method} = ($enable !== FALSE) ? TRUE : FALSE; + $this->_compile_{$method} = ($enable !== FALSE); } } } @@ -127,7 +123,7 @@ class CI_Profiler { // We match the "end" marker so that the list ends // up in the order that it was defined if (preg_match('/(.+?)_end/i', $key, $match) - AND isset($this->CI->benchmark->marker[$match[1].'_end'], $this->CI->benchmark->marker[$match[1].'_start'])) + && isset($this->CI->benchmark->marker[$match[1].'_end'], $this->CI->benchmark->marker[$match[1].'_start'])) { $profile[$match[1]] = $this->CI->benchmark->elapsed_time($match[1].'_start', $key); } @@ -135,18 +131,20 @@ class CI_Profiler { // Build a table containing the profile data. // Note: At some point we should turn this into a template that can - // be modified. We also might want to make this data available to be logged + // be modified. We also might want to make this data available to be logged $output = "\n\n" - . '<fieldset id="ci_profiler_benchmarks" style="border:1px solid #900;padding:6px 10px 10px 10px;margin:20px 0 20px 0;background-color:#eee">' - . "\n" - . '<legend style="color:#900;"> '.$this->CI->lang->line('profiler_benchmarks').' </legend>' - . "\n\n\n<table style='width:100%'>\n"; + .'<fieldset id="ci_profiler_benchmarks" style="border:1px solid #900;padding:6px 10px 10px 10px;margin:20px 0 20px 0;background-color:#eee;">' + ."\n" + .'<legend style="color:#900;"> '.$this->CI->lang->line('profiler_benchmarks')." </legend>" + ."\n\n\n<table style=\"width:100%;\">\n"; foreach ($profile as $key => $val) { $key = ucwords(str_replace(array('_', '-'), ' ', $key)); - $output .= "<tr><td style='padding:5px;width:50%;color:#000;font-weight:bold;background-color:#ddd;'>".$key." </td><td style='padding:5px;width:50%;color:#900;font-weight:normal;background-color:#ddd;'>".$val."</td></tr>\n"; + $output .= '<tr><td style="padding:5px;width:50%;color:#000;font-weight:bold;background-color:#ddd;">' + .$key.' </td><td style="padding:5px;width:50%;color:#900;font-weight:normal;background-color:#ddd;">' + .$val."</td></tr>\n"; } return $output."</table>\n</fieldset>"; @@ -166,7 +164,7 @@ class CI_Profiler { // Let's determine which databases are currently connected to foreach (get_object_vars($this->CI) as $CI_object) { - if (is_object($CI_object) && is_subclass_of(get_class($CI_object), 'CI_DB') ) + if (is_object($CI_object) && is_subclass_of(get_class($CI_object), 'CI_DB')) { $dbs[] = $CI_object; } @@ -175,13 +173,13 @@ class CI_Profiler { if (count($dbs) === 0) { return "\n\n" - . '<fieldset id="ci_profiler_queries" style="border:1px solid #0000FF;padding:6px 10px 10px 10px;margin:20px 0 20px 0;background-color:#eee;">' - . "\n" - . '<legend style="color:#0000FF;"> '.$this->CI->lang->line('profiler_queries').' </legend>' - . "\n\n\n<table style='border:none; width:100%;'>\n" - . '<tr><td style="width:100%;color:#0000FF;font-weight:normal;background-color:#eee;padding:5px;">' - . $this->CI->lang->line('profiler_no_db') - . "</td></tr>\n</table>\n</fieldset>"; + .'<fieldset id="ci_profiler_queries" style="border:1px solid #0000FF;padding:6px 10px 10px 10px;margin:20px 0 20px 0;background-color:#eee;">' + ."\n" + .'<legend style="color:#0000FF;"> '.$this->CI->lang->line('profiler_queries').' </legend>' + ."\n\n\n<table style=\"border:none; width:100%;\">\n" + .'<tr><td style="width:100%;color:#0000FF;font-weight:normal;background-color:#eee;padding:5px;">' + .$this->CI->lang->line('profiler_no_db') + ."</td></tr>\n</table>\n</fieldset>"; } // Load the text helper so we can highlight the SQL @@ -191,7 +189,6 @@ class CI_Profiler { $highlight = array('SELECT', 'DISTINCT', 'FROM', 'WHERE', 'AND', 'LEFT JOIN', 'ORDER BY', 'GROUP BY', 'LIMIT', 'INSERT', 'INTO', 'VALUES', 'UPDATE', 'OR ', 'HAVING', 'OFFSET', 'NOT IN', 'IN', 'LIKE', 'NOT LIKE', 'COUNT', 'MAX', 'MIN', 'ON', 'AS', 'AVG', 'SUM', '(', ')'); $output = "\n\n"; - $count = 0; foreach ($dbs as $db) @@ -205,21 +202,23 @@ class CI_Profiler { $show_hide_js = '(<span style="cursor: pointer;" onclick="var s=document.getElementById(\'ci_profiler_queries_db_'.$count.'\').style;s.display=s.display==\'none\'?\'\':\'none\';this.innerHTML=this.innerHTML==\''.$this->CI->lang->line('profiler_section_show').'\'?\''.$this->CI->lang->line('profiler_section_hide').'\':\''.$this->CI->lang->line('profiler_section_show').'\';">'.$this->CI->lang->line('profiler_section_show').'</span>)'; } - $output .= '<fieldset style="border:1px solid #0000FF;padding:6px 10px 10px 10px;margin:20px 0 20px 0;background-color:#eee">' - . "\n" - . '<legend style="color:#0000FF;"> '.$this->CI->lang->line('profiler_database').': '.$db->database.' '.$this->CI->lang->line('profiler_queries').': '.count($db->queries).' '.$show_hide_js.'</legend>' - . "\n\n\n<table style='width:100%;{$hide_queries}' id='ci_profiler_queries_db_{$count}'>\n"; + $output .= '<fieldset style="border:1px solid #0000FF;padding:6px 10px 10px 10px;margin:20px 0 20px 0;background-color:#eee;">' + ."\n" + .'<legend style="color:#0000FF;"> '.$this->CI->lang->line('profiler_database') + .': '.$db->database.' '.$this->CI->lang->line('profiler_queries') + .': '.count($db->queries).' '.$show_hide_js."</legend>\n\n\n" + .'<table style="width:100%;'.$hide_queries.'" id="ci_profiler_queries_db_'.$count."\">\n"; if (count($db->queries) === 0) { - $output .= "<tr><td style='width:100%;color:#0000FF;font-weight:normal;background-color:#eee;padding:5px;'>".$this->CI->lang->line('profiler_no_queries')."</td></tr>\n"; + $output .= '<tr><td style="width:100%;color:#0000FF;font-weight:normal;background-color:#eee;padding:5px;">' + .$this->CI->lang->line('profiler_no_queries')."</td></tr>\n"; } else { foreach ($db->queries as $key => $val) { $time = number_format($db->query_times[$key], 4); - $val = highlight_code($val, ENT_QUOTES); foreach ($highlight as $bold) @@ -227,18 +226,18 @@ class CI_Profiler { $val = str_replace($bold, '<strong>'.$bold.'</strong>', $val); } - $output .= "<tr><td style='padding:5px; vertical-align: top;width:1%;color:#900;font-weight:normal;background-color:#ddd;'>".$time." </td><td style='padding:5px; color:#000;font-weight:normal;background-color:#ddd;'>".$val."</td></tr>\n"; + $output .= '<tr><td style="padding:5px;vertical-align:top;width:1%;color:#900;font-weight:normal;background-color:#ddd;">' + .$time.' </td><td style="padding:5px;color:#000;font-weight:normal;background-color:#ddd;">' + .$val."</td></tr>\n"; } } $output .= "</table>\n</fieldset>"; - } return $output; } - // -------------------------------------------------------------------- /** @@ -248,19 +247,18 @@ class CI_Profiler { */ protected function _compile_get() { - $output = "\n\n" - . '<fieldset id="ci_profiler_get" style="border:1px solid #cd6e00;padding:6px 10px 10px 10px;margin:20px 0 20px 0;background-color:#eee">' - . "\n" - . '<legend style="color:#cd6e00;"> '.$this->CI->lang->line('profiler_get_data').' </legend>' - . "\n"; + $output = "\n\n" + .'<fieldset id="ci_profiler_get" style="border:1px solid #cd6e00;padding:6px 10px 10px 10px;margin:20px 0 20px 0;background-color:#eee;">' + ."\n" + .'<legend style="color:#cd6e00;"> '.$this->CI->lang->line('profiler_get_data')." </legend>\n"; if (count($_GET) === 0) { - $output .= "<div style='color:#cd6e00;font-weight:normal;padding:4px 0 4px 0'>".$this->CI->lang->line('profiler_no_get')."</div>"; + $output .= '<div style="color:#cd6e00;font-weight:normal;padding:4px 0 4px 0;">'.$this->CI->lang->line('profiler_no_get').'</div>'; } else { - $output .= "\n\n<table style='width:100%; border:none'>\n"; + $output .= "\n\n<table style=\"width:100%;border:none;\">\n"; foreach ($_GET as $key => $val) { @@ -269,9 +267,10 @@ class CI_Profiler { $key = "'".$key."'"; } - $output .= "<tr><td style='width:50%;color:#000;background-color:#ddd;padding:5px'>$_GET[".$key."] </td><td style='width:50%;padding:5px;color:#cd6e00;font-weight:normal;background-color:#ddd;'>" - . ((is_array($val) OR is_object($val)) ? "<pre>" . htmlspecialchars(stripslashes(print_r($val, true))) . "</pre>" : htmlspecialchars(stripslashes($val))) - . "</td></tr>\n"; + $output .= '<tr><td style="width:50%;color:#000;background-color:#ddd;padding:5px;">$_GET[' + .$key.'] </td><td style="width:50%;padding:5px;color:#cd6e00;font-weight:normal;background-color:#ddd;">' + .((is_array($val) OR is_object($val)) ? '<pre>'.htmlspecialchars(stripslashes(print_r($val, TRUE))).'</pre>' : htmlspecialchars(stripslashes($val))) + ."</td></tr>\n"; } $output .= "</table>\n"; @@ -290,18 +289,17 @@ class CI_Profiler { protected function _compile_post() { $output = "\n\n" - . '<fieldset id="ci_profiler_post" style="border:1px solid #009900;padding:6px 10px 10px 10px;margin:20px 0 20px 0;background-color:#eee">' - . "\n" - . '<legend style="color:#009900;"> '.$this->CI->lang->line('profiler_post_data').' </legend>' - . "\n"; + .'<fieldset id="ci_profiler_post" style="border:1px solid #009900;padding:6px 10px 10px 10px;margin:20px 0 20px 0;background-color:#eee;">' + ."\n" + .'<legend style="color:#009900;"> '.$this->CI->lang->line('profiler_post_data')." </legend>\n"; if (count($_POST) == 0) { - $output .= "<div style='color:#009900;font-weight:normal;padding:4px 0 4px 0'>".$this->CI->lang->line('profiler_no_post')."</div>"; + $output .= '<div style="color:#009900;font-weight:normal;padding:4px 0 4px 0;">'.$this->CI->lang->line('profiler_no_post').'</div>'; } else { - $output .= "\n\n<table style='width:100%'>\n"; + $output .= "\n\n<table style=\"width:100%;\">\n"; foreach ($_POST as $key => $val) { @@ -310,15 +308,18 @@ class CI_Profiler { $key = "'".$key."'"; } - $output .= "<tr><td style='width:50%;padding:5px;color:#000;background-color:#ddd;'>$_POST[".$key."] </td><td style='width:50%;padding:5px;color:#009900;font-weight:normal;background-color:#ddd;'>"; + $output .= '<tr><td style="width:50%;padding:5px;color:#000;background-color:#ddd;">$_POST[' + .$key.'] </td><td style="width:50%;padding:5px;color:#009900;font-weight:normal;background-color:#ddd;">'; + if (is_array($val) OR is_object($val)) { - $output .= "<pre>" . htmlspecialchars(stripslashes(print_r($val, TRUE))) . "</pre>"; + $output .= '<pre>'.htmlspecialchars(stripslashes(print_r($val, TRUE))).'</pre>'; } else { $output .= htmlspecialchars(stripslashes($val)); } + $output .= "</td></tr>\n"; } @@ -338,12 +339,12 @@ class CI_Profiler { protected function _compile_uri_string() { return "\n\n" - . '<fieldset id="ci_profiler_uri_string" style="border:1px solid #000;padding:6px 10px 10px 10px;margin:20px 0 20px 0;background-color:#eee">' - . "\n" - . '<legend style="color:#000;"> '.$this->CI->lang->line('profiler_uri_string').' </legend>' - . "\n<div style='color:#000;font-weight:normal;padding:4px 0 4px 0'>" - . ($this->CI->uri->uri_string == '' ? $this->CI->lang->line('profiler_no_uri') : $this->CI->uri->uri_string) - . '</div></fieldset>'; + .'<fieldset id="ci_profiler_uri_string" style="border:1px solid #000;padding:6px 10px 10px 10px;margin:20px 0 20px 0;background-color:#eee;">' + ."\n" + .'<legend style="color:#000;"> '.$this->CI->lang->line('profiler_uri_string')." </legend>\n" + .'<div style="color:#000;font-weight:normal;padding:4px 0 4px 0;">' + .($this->CI->uri->uri_string == '' ? $this->CI->lang->line('profiler_no_uri') : $this->CI->uri->uri_string) + .'</div></fieldset>'; } // -------------------------------------------------------------------- @@ -356,11 +357,11 @@ class CI_Profiler { protected function _compile_controller_info() { return "\n\n" - . '<fieldset id="ci_profiler_controller_info" style="border:1px solid #995300;padding:6px 10px 10px 10px;margin:20px 0 20px 0;background-color:#eee">' - . "\n" - . '<legend style="color:#995300;"> '.$this->CI->lang->line('profiler_controller_info').' </legend>' - . "\n<div style='color:#995300;font-weight:normal;padding:4px 0 4px 0'>".$this->CI->router->fetch_class().'/'.$this->CI->router->fetch_method() - . '</div></fieldset>'; + .'<fieldset id="ci_profiler_controller_info" style="border:1px solid #995300;padding:6px 10px 10px 10px;margin:20px 0 20px 0;background-color:#eee;">' + ."\n" + .'<legend style="color:#995300;"> '.$this->CI->lang->line('profiler_controller_info')." </legend>\n" + .'<div style="color:#995300;font-weight:normal;padding:4px 0 4px 0;">'.$this->CI->router->fetch_class().'/'.$this->CI->router->fetch_method() + .'</div></fieldset>'; } // -------------------------------------------------------------------- @@ -375,12 +376,12 @@ class CI_Profiler { protected function _compile_memory_usage() { return "\n\n" - . '<fieldset id="ci_profiler_memory_usage" style="border:1px solid #5a0099;padding:6px 10px 10px 10px;margin:20px 0 20px 0;background-color:#eee">' - . "\n" - . '<legend style="color:#5a0099;"> '.$this->CI->lang->line('profiler_memory_usage').' </legend>' - . "\n<div style='color:#5a0099;font-weight:normal;padding:4px 0 4px 0'>" - . ((function_exists('memory_get_usage') && ($usage = memory_get_usage()) != '') ? number_format($usage).' bytes' : $this->CI->lang->line('profiler_no_memory')) - . '</div></fieldset>'; + .'<fieldset id="ci_profiler_memory_usage" style="border:1px solid #5a0099;padding:6px 10px 10px 10px;margin:20px 0 20px 0;background-color:#eee;">' + ."\n" + .'<legend style="color:#5a0099;"> '.$this->CI->lang->line('profiler_memory_usage')." </legend>\n" + .'<div style="color:#5a0099;font-weight:normal;padding:4px 0 4px 0;">' + .((function_exists('memory_get_usage') && ($usage = memory_get_usage()) != '') ? number_format($usage).' bytes' : $this->CI->lang->line('profiler_no_memory')) + .'</div></fieldset>'; } // -------------------------------------------------------------------- @@ -395,15 +396,17 @@ class CI_Profiler { protected function _compile_http_headers() { $output = "\n\n" - . '<fieldset id="ci_profiler_http_headers" style="border:1px solid #000;padding:6px 10px 10px 10px;margin:20px 0 20px 0;background-color:#eee">' - . "\n" - . '<legend style="color:#000;"> '.$this->CI->lang->line('profiler_headers').' (<span style="cursor: pointer;" onclick="var s=document.getElementById(\'ci_profiler_httpheaders_table\').style;s.display=s.display==\'none\'?\'\':\'none\';this.innerHTML=this.innerHTML==\''.$this->CI->lang->line('profiler_section_show').'\'?\''.$this->CI->lang->line('profiler_section_hide').'\':\''.$this->CI->lang->line('profiler_section_show').'\';">'.$this->CI->lang->line('profiler_section_show').'</span>)</legend>' - . "\n\n\n<table style='width:100%;display:none' id='ci_profiler_httpheaders_table'>\n"; + .'<fieldset id="ci_profiler_http_headers" style="border:1px solid #000;padding:6px 10px 10px 10px;margin:20px 0 20px 0;background-color:#eee;">' + ."\n" + .'<legend style="color:#000;"> '.$this->CI->lang->line('profiler_headers') + .' (<span style="cursor: pointer;" onclick="var s=document.getElementById(\'ci_profiler_httpheaders_table\').style;s.display=s.display==\'none\'?\'\':\'none\';this.innerHTML=this.innerHTML==\''.$this->CI->lang->line('profiler_section_show').'\'?\''.$this->CI->lang->line('profiler_section_hide').'\':\''.$this->CI->lang->line('profiler_section_show').'\';">'.$this->CI->lang->line('profiler_section_show')."</span>)</legend>\n\n\n" + .'<table style="width:100%;display:none;" id="ci_profiler_httpheaders_table">'."\n"; foreach (array('HTTP_ACCEPT', 'HTTP_USER_AGENT', 'HTTP_CONNECTION', 'SERVER_PORT', 'SERVER_NAME', 'REMOTE_ADDR', 'SERVER_SOFTWARE', 'HTTP_ACCEPT_LANGUAGE', 'SCRIPT_NAME', 'REQUEST_METHOD',' HTTP_HOST', 'REMOTE_HOST', 'CONTENT_TYPE', 'SERVER_PROTOCOL', 'QUERY_STRING', 'HTTP_ACCEPT_ENCODING', 'HTTP_X_FORWARDED_FOR') as $header) { - $val = (isset($_SERVER[$header])) ? $_SERVER[$header] : ''; - $output .= "<tr><td style='vertical-align: top;width:50%;padding:5px;color:#900;background-color:#ddd;'>".$header." </td><td style='width:50%;padding:5px;color:#000;background-color:#ddd;'>".$val."</td></tr>\n"; + $val = isset($_SERVER[$header]) ? $_SERVER[$header] : ''; + $output .= '<tr><td style="vertical-align:top;width:50%;padding:5px;color:#900;background-color:#ddd;">' + .$header.' </td><td style="width:50%;padding:5px;color:#000;background-color:#ddd;">'.$val."</td></tr>\n"; } return $output."</table>\n</fieldset>"; @@ -421,10 +424,10 @@ class CI_Profiler { protected function _compile_config() { $output = "\n\n" - . '<fieldset id="ci_profiler_config" style="border:1px solid #000;padding:6px 10px 10px 10px;margin:20px 0 20px 0;background-color:#eee">' - . "\n" - . '<legend style="color:#000;"> '.$this->CI->lang->line('profiler_config').' (<span style="cursor: pointer;" onclick="var s=document.getElementById(\'ci_profiler_config_table\').style;s.display=s.display==\'none\'?\'\':\'none\';this.innerHTML=this.innerHTML==\''.$this->CI->lang->line('profiler_section_show').'\'?\''.$this->CI->lang->line('profiler_section_hide').'\':\''.$this->CI->lang->line('profiler_section_show').'\';">'.$this->CI->lang->line('profiler_section_show').'</span>)</legend>' - . "\n\n\n<table style='width:100%; display:none' id='ci_profiler_config_table'>\n"; + .'<fieldset id="ci_profiler_config" style="border:1px solid #000;padding:6px 10px 10px 10px;margin:20px 0 20px 0;background-color:#eee;">' + ."\n" + .'<legend style="color:#000;"> '.$this->CI->lang->line('profiler_config').' (<span style="cursor: pointer;" onclick="var s=document.getElementById(\'ci_profiler_config_table\').style;s.display=s.display==\'none\'?\'\':\'none\';this.innerHTML=this.innerHTML==\''.$this->CI->lang->line('profiler_section_show').'\'?\''.$this->CI->lang->line('profiler_section_hide').'\':\''.$this->CI->lang->line('profiler_section_show').'\';">'.$this->CI->lang->line('profiler_section_show')."</span>)</legend>\n\n\n" + .'<table style="width:100%;display:none;" id="ci_profiler_config_table">'."\n"; foreach ($this->CI->config->config as $config => $val) { @@ -433,7 +436,8 @@ class CI_Profiler { $val = print_r($val, TRUE); } - $output .= "<tr><td style='padding:5px; vertical-align: top;color:#900;background-color:#ddd;'>".$config." </td><td style='padding:5px; color:#000;background-color:#ddd;'>".htmlspecialchars($val)."</td></tr>\n"; + $output .= '<tr><td style="padding:5px;vertical-align:top;color:#900;background-color:#ddd;">' + .$config.' </td><td style="padding:5px;color:#000;background-color:#ddd;">'.htmlspecialchars($val)."</td></tr>\n"; } return $output."</table>\n</fieldset>"; @@ -453,9 +457,9 @@ class CI_Profiler { return; } - $output = '<fieldset id="ci_profiler_csession" style="border:1px solid #000;padding:6px 10px 10px 10px;margin:20px 0 20px 0;background-color:#eee">' - . '<legend style="color:#000;"> '.$this->CI->lang->line('profiler_session_data').' (<span style="cursor: pointer;" onclick="var s=document.getElementById(\'ci_profiler_session_data\').style;s.display=s.display==\'none\'?\'\':\'none\';this.innerHTML=this.innerHTML==\''.$this->CI->lang->line('profiler_section_show').'\'?\''.$this->CI->lang->line('profiler_section_hide').'\':\''.$this->CI->lang->line('profiler_section_show').'\';">'.$this->CI->lang->line('profiler_section_show').'</span>)</legend>' - . "<table style='width:100%;display:none' id='ci_profiler_session_data'>"; + $output = '<fieldset id="ci_profiler_csession" style="border:1px solid #000;padding:6px 10px 10px 10px;margin:20px 0 20px 0;background-color:#eee;">' + .'<legend style="color:#000;"> '.$this->CI->lang->line('profiler_session_data').' (<span style="cursor: pointer;" onclick="var s=document.getElementById(\'ci_profiler_session_data\').style;s.display=s.display==\'none\'?\'\':\'none\';this.innerHTML=this.innerHTML==\''.$this->CI->lang->line('profiler_section_show').'\'?\''.$this->CI->lang->line('profiler_section_hide').'\':\''.$this->CI->lang->line('profiler_section_show').'\';">'.$this->CI->lang->line('profiler_section_show').'</span>)</legend>' + .'<table style="width:100%;display:none;" id="ci_profiler_session_data">'; foreach ($this->CI->session->all_userdata() as $key => $val) { @@ -464,7 +468,8 @@ class CI_Profiler { $val = print_r($val, TRUE); } - $output .= "<tr><td style='padding:5px; vertical-align: top;color:#900;background-color:#ddd;'>".$key." </td><td style='padding:5px; color:#000;background-color:#ddd;'>".htmlspecialchars($val)."</td></tr>\n"; + $output .= '<tr><td style="padding:5px;vertical-align:top;color:#900;background-color:#ddd;">' + .$key.' </td><td style="padding:5px;color:#000;background-color:#ddd;">'.htmlspecialchars($val)."</td></tr>\n"; } return $output."</table>\n</fieldset>"; @@ -479,14 +484,14 @@ class CI_Profiler { */ public function run() { - $output = "<div id='codeigniter_profiler' style='clear:both;background-color:#fff;padding:10px;'>"; + $output = '<div id="codeigniter_profiler" style="clear:both;background-color:#fff;padding:10px;">'; $fields_displayed = 0; foreach ($this->_available_sections as $section) { if ($this->_compile_{$section} !== FALSE) { - $func = "_compile_{$section}"; + $func = '_compile_'.$section; $output .= $this->{$func}(); $fields_displayed++; } @@ -494,7 +499,8 @@ class CI_Profiler { if ($fields_displayed === 0) { - $output .= '<p style="border:1px solid #5a0099;padding:10px;margin:20px 0;background-color:#eee">'.$this->CI->lang->line('profiler_no_profiles').'</p>'; + $output .= '<p style="border:1px solid #5a0099;padding:10px;margin:20px 0;background-color:#eee;">' + .$this->CI->lang->line('profiler_no_profiles').'</p>'; } return $output.'</div>'; @@ -502,4 +508,4 @@ class CI_Profiler { } /* End of file Profiler.php */ -/* Location: ./system/libraries/Profiler.php */ +/* Location: ./system/libraries/Profiler.php */
\ No newline at end of file diff --git a/system/libraries/Session.php b/system/libraries/Session.php index 3a80c1626..3515764ce 100644 --- a/system/libraries/Session.php +++ b/system/libraries/Session.php @@ -469,21 +469,21 @@ class CI_Session { { return $this->userdata; } - + // -------------------------------------------------------------------------- - + /** * Fetch all flashdata - * + * * @return array */ public function all_flashdata() { $out = array(); - + // loop through all userdata foreach ($this->all_userdata() as $key => $val) - { + { // if it contains flashdata, add it if (strpos($key, 'flash:old:') !== FALSE) { @@ -816,4 +816,4 @@ class CI_Session { } /* End of file Session.php */ -/* Location: ./system/libraries/Session.php */ +/* Location: ./system/libraries/Session.php */
\ No newline at end of file diff --git a/system/libraries/Table.php b/system/libraries/Table.php index 11a4858a9..3777d29ff 100644 --- a/system/libraries/Table.php +++ b/system/libraries/Table.php @@ -38,14 +38,14 @@ */ class CI_Table { - public $rows = array(); - public $heading = array(); - public $auto_heading = TRUE; - public $caption = NULL; - public $template = NULL; - public $newline = "\n"; - public $empty_cells = ''; - public $function = FALSE; + public $rows = array(); + public $heading = array(); + public $auto_heading = TRUE; + public $caption = NULL; + public $template = NULL; + public $newline = "\n"; + public $empty_cells = ''; + public $function = FALSE; /** * Set the template from the table config file if it exists @@ -55,13 +55,13 @@ class CI_Table { */ public function __construct($config = array()) { - log_message('debug', 'Table Class Initialized'); - // initialize config foreach ($config as $key => $val) { $this->template[$key] = $val; } + + log_message('debug', 'Table Class Initialized'); } // -------------------------------------------------------------------- @@ -70,7 +70,7 @@ class CI_Table { * Set the template * * @param array - * @return void + * @return bool */ public function set_template($template) { @@ -80,6 +80,7 @@ class CI_Table { } $this->template = $template; + return TRUE; } // -------------------------------------------------------------------- @@ -101,9 +102,9 @@ class CI_Table { // -------------------------------------------------------------------- /** - * Set columns. Takes a one-dimensional array as input and creates + * Set columns. Takes a one-dimensional array as input and creates * a multi-dimensional array with a depth equal to the number of - * columns. This allows a single array with many elements to be + * columns. This allows a single array with many elements to be * displayed in a table that has a fixed column count. * * @param array @@ -184,29 +185,22 @@ class CI_Table { * * Ensures a standard associative array format for all cell data * - * @param type - * @return type + * @param array + * @return array */ protected function _prep_args($args) { // If there is no $args[0], skip this and treat as an associative array // This can happen if there is only a single key, for example this is passed to table->generate // array(array('foo'=>'bar')) - if (isset($args[0]) AND (count($args) === 1 && is_array($args[0]))) + if (isset($args[0]) && count($args) === 1 && is_array($args[0])) { // args sent as indexed array if ( ! isset($args[0]['data'])) { foreach ($args[0] as $key => $val) { - if (is_array($val) && isset($val['data'])) - { - $args[$key] = $val; - } - else - { - $args[$key] = array('data' => $val); - } + $args[$key] = (is_array($val) && isset($val['data'])) ? $val : array('data' => $val); } } } @@ -257,13 +251,13 @@ class CI_Table { } elseif (is_array($table_data)) { - $set_heading = (count($this->heading) === 0 AND $this->auto_heading == FALSE) ? FALSE : TRUE; + $set_heading = (count($this->heading) !== 0 OR $this->auto_heading != FALSE); $this->_set_from_array($table_data, $set_heading); } } - // Is there anything to display? No? Smite them! - if (count($this->heading) === 0 AND count($this->rows) === 0) + // Is there anything to display? No? Smite them! + if (count($this->heading) === 0 && count($this->rows) === 0) { return 'Undefined table data'; } @@ -297,7 +291,7 @@ class CI_Table { { if ($key != 'data') { - $temp = str_replace('<th', "<th $key='$val'", $temp); + $temp = str_replace('<th', '<th '.$key.'="'.$val.'"', $temp); } } @@ -321,7 +315,7 @@ class CI_Table { } // We use modulus to alternate the row colors - $name = (fmod($i++, 2)) ? '' : 'alt_'; + $name = fmod($i++, 2) ? '' : 'alt_'; $out .= $this->template['row_'.$name.'start'].$this->newline; @@ -333,27 +327,24 @@ class CI_Table { { if ($key !== 'data') { - $temp = str_replace('<td', "<td $key='$val'", $temp); + $temp = str_replace('<td', '<td '.$key.'="'.$val.'"', $temp); } } $cell = isset($cell['data']) ? $cell['data'] : ''; $out .= $temp; - if ($cell === "" OR $cell === NULL) + if ($cell === '' OR $cell === NULL) { $out .= $this->empty_cells; } + elseif ($function !== FALSE && is_callable($function)) + { + $out .= call_user_func($function, $cell); + } else { - if ($function !== FALSE && is_callable($function)) - { - $out .= call_user_func($function, $cell); - } - else - { - $out .= $cell; - } + $out .= $cell; } $out .= $this->template['cell_'.$name.'end']; @@ -382,9 +373,9 @@ class CI_Table { */ public function clear() { - $this->rows = array(); - $this->heading = array(); - $this->auto_heading = TRUE; + $this->rows = array(); + $this->heading = array(); + $this->auto_heading = TRUE; } // -------------------------------------------------------------------- @@ -399,7 +390,7 @@ class CI_Table { { if ( ! is_object($query)) { - return FALSE; + return; } // First generate the headings from the table column names @@ -407,14 +398,13 @@ class CI_Table { { if ( ! is_callable(array($query, 'list_fields'))) { - return FALSE; + return; } $this->heading = $this->_prep_args($query->list_fields()); } // Next blast through the result array and build out the rows - if ($query->num_rows() > 0) { foreach ($query->result_array() as $row) @@ -443,7 +433,7 @@ class CI_Table { foreach ($data as $row) { // If a heading hasn't already been set we'll use the first row of the array as the heading - if ($i++ === 0 AND count($data) > 1 AND count($this->heading) === 0 AND $set_heading == TRUE) + if ($i++ === 0 && count($data) > 1 && count($this->heading) === 0 && $set_heading == TRUE) { $this->heading = $this->_prep_args($row); } @@ -488,36 +478,35 @@ class CI_Table { */ protected function _default_template() { - return array ( - 'table_open' => '<table border="0" cellpadding="4" cellspacing="0">', + return array( + 'table_open' => '<table border="0" cellpadding="4" cellspacing="0">', - 'thead_open' => '<thead>', - 'thead_close' => '</thead>', + 'thead_open' => '<thead>', + 'thead_close' => '</thead>', - 'heading_row_start' => '<tr>', - 'heading_row_end' => '</tr>', - 'heading_cell_start' => '<th>', - 'heading_cell_end' => '</th>', + 'heading_row_start' => '<tr>', + 'heading_row_end' => '</tr>', + 'heading_cell_start' => '<th>', + 'heading_cell_end' => '</th>', - 'tbody_open' => '<tbody>', - 'tbody_close' => '</tbody>', + 'tbody_open' => '<tbody>', + 'tbody_close' => '</tbody>', - 'row_start' => '<tr>', - 'row_end' => '</tr>', - 'cell_start' => '<td>', - 'cell_end' => '</td>', + 'row_start' => '<tr>', + 'row_end' => '</tr>', + 'cell_start' => '<td>', + 'cell_end' => '</td>', - 'row_alt_start' => '<tr>', - 'row_alt_end' => '</tr>', - 'cell_alt_start' => '<td>', - 'cell_alt_end' => '</td>', + 'row_alt_start' => '<tr>', + 'row_alt_end' => '</tr>', + 'cell_alt_start' => '<td>', + 'cell_alt_end' => '</td>', - 'table_close' => '</table>' - ); + 'table_close' => '</table>' + ); } - } /* End of file Table.php */ -/* Location: ./system/libraries/Table.php */ +/* Location: ./system/libraries/Table.php */
\ No newline at end of file diff --git a/system/libraries/Trackback.php b/system/libraries/Trackback.php index be1de6f3f..6761f63a5 100644 --- a/system/libraries/Trackback.php +++ b/system/libraries/Trackback.php @@ -25,8 +25,6 @@ * @filesource */ -// ------------------------------------------------------------------------ - /** * Trackback Class * @@ -49,7 +47,7 @@ class CI_Trackback { public function __construct() { - log_message('debug', "Trackback Class Initialized"); + log_message('debug', 'Trackback Class Initialized'); } // -------------------------------------------------------------------- @@ -97,9 +95,10 @@ class CI_Trackback { } // Build the Trackback data string - $charset = ( ! isset($tb_data['charset'])) ? $this->charset : $tb_data['charset']; + $charset = isset($tb_data['charset']) ? $tb_data['charset'] : $this->charset; - $data = "url=".rawurlencode($url)."&title=".rawurlencode($title)."&blog_name=".rawurlencode($blog_name)."&excerpt=".rawurlencode($excerpt)."&charset=".rawurlencode($charset); + $data = 'url='.rawurlencode($url).'&title='.rawurlencode($title).'&blog_name='.rawurlencode($blog_name) + .'&excerpt='.rawurlencode($excerpt).'&charset='.rawurlencode($charset); // Send Trackback(s) $return = TRUE; @@ -139,7 +138,7 @@ class CI_Trackback { return FALSE; } - $this->data['charset'] = ( ! isset($_POST['charset'])) ? 'auto' : strtoupper(trim($_POST['charset'])); + $this->data['charset'] = isset($_POST['charset']) ? strtoupper(trim($_POST['charset'])) : 'auto'; if ($val != 'url' && MB_ENABLED === TRUE) { @@ -164,7 +163,7 @@ class CI_Trackback { /** * Send Trackback Error Message * - * Allows custom errors to be set. By default it + * Allows custom errors to be set. By default it * sends the "incomplete information" error, as that's * the most common one. * @@ -173,7 +172,7 @@ class CI_Trackback { */ public function send_error($message = 'Incomplete Information') { - echo "<?xml version=\"1.0\" encoding=\"utf-8\"?".">\n<response>\n<error>1</error>\n<message>".$message."</message>\n</response>"; + echo '<?xml version="1.0" encoding="utf-8"?'.">\n<response>\n<error>1</error>\n<message>".$message."</message>\n</response>"; exit; } @@ -189,7 +188,7 @@ class CI_Trackback { */ public function send_success() { - echo "<?xml version=\"1.0\" encoding=\"utf-8\"?".">\n<response>\n<error>0</error>\n</response>"; + echo '<?xml version="1.0" encoding="utf-8"?'.">\n<response>\n<error>0</error>\n</response>"; exit; } @@ -203,7 +202,7 @@ class CI_Trackback { */ public function data($item) { - return ( ! isset($this->data[$item])) ? '' : $this->data[$item]; + return isset($this->data[$item]) ? $this->data[$item] : ''; } // -------------------------------------------------------------------- @@ -212,7 +211,7 @@ class CI_Trackback { * Process Trackback * * Opens a socket connection and passes the data to - * the server. Returns TRUE on success, FALSE on failure + * the server. Returns TRUE on success, FALSE on failure * * @param string * @param string @@ -230,37 +229,36 @@ class CI_Trackback { } // Build the path - $ppath = ( ! isset($target['path'])) ? $url : $target['path']; + $ppath = isset($target['path']) ? $target['path'] : $url; - $path = (isset($target['query']) && $target['query'] != "") ? $ppath.'?'.$target['query'] : $ppath; + $path = empty($target['query']) ? $ppath : $ppath.'?'.$target['query']; // Add the Trackback ID to the data string if ($id = $this->get_id($url)) { - $data = "tb_id=".$id."&".$data; + $data = 'tb_id='.$id.'&'.$data; } // Transfer the data - fputs ($fp, "POST " . $path . " HTTP/1.0\r\n" ); - fputs ($fp, "Host: " . $target['host'] . "\r\n" ); - fputs ($fp, "Content-type: application/x-www-form-urlencoded\r\n" ); - fputs ($fp, "Content-length: " . strlen($data) . "\r\n" ); - fputs ($fp, "Connection: close\r\n\r\n" ); - fputs ($fp, $data); + fputs($fp, 'POST '.$path." HTTP/1.0\r\n"); + fputs($fp, 'Host: '.$target['host']."\r\n"); + fputs($fp, "Content-type: application/x-www-form-urlencoded\r\n"); + fputs($fp, 'Content-length: '.strlen($data)."\r\n"); + fputs($fp, "Connection: close\r\n\r\n"); + fputs($fp, $data); // Was it successful? - $this->response = ""; + $this->response = ''; while ( ! feof($fp)) { $this->response .= fgets($fp, 128); } @fclose($fp); - if (stripos($this->response, '<error>0</error>') === FALSE) { - $message = (preg_match('/<message>(.*?)<\/message>/is', $this->response, $match)) ? trim($match[1]) : 'An unknown error was encountered'; + $message = preg_match('/<message>(.*?)<\/message>/is', $this->response, $match) ? trim($match[1]) : 'An unknown error was encountered'; $this->set_error($message); return FALSE; } @@ -282,11 +280,8 @@ class CI_Trackback { */ public function extract_urls($urls) { - // Remove the pesky white space and replace with a comma. - $urls = preg_replace("/\s*(\S+)\s*/", "\\1,", $urls); - - // If they use commas get rid of the doubles. - $urls = str_replace(",,", ",", $urls); + // Remove the pesky white space and replace with a comma, then replace doubles. + $urls = str_replace(',,', ',', preg_replace('/\s*(\S+)\s*/', '\\1,', $urls)); // Remove any comma that might be at the end if (substr($urls, -1) === ',') @@ -294,11 +289,8 @@ class CI_Trackback { $urls = substr($urls, 0, -1); } - // Break into an array via commas - $urls = preg_split('/[,]/', $urls); - - // Removes duplicates - $urls = array_unique($urls); + // Break into an array via commas and remove duplicates + $urls = array_unique(preg_split('/[,]/', $urls)); array_walk($urls, array($this, 'validate_url')); @@ -313,9 +305,9 @@ class CI_Trackback { * Simply adds "http://" if missing * * @param string - * @return string + * @return void */ - public function validate_url($url) + public function validate_url(&$url) { $url = trim($url); @@ -335,7 +327,7 @@ class CI_Trackback { */ public function get_id($url) { - $tb_id = ""; + $tb_id = ''; if (strpos($url, '?') !== FALSE) { @@ -359,18 +351,11 @@ class CI_Trackback { if ( ! is_numeric($tb_id)) { - $tb_id = $tb_array[count($tb_array)-2]; + $tb_id = $tb_array[count($tb_array)-2]; } } - if ( ! preg_match ("/^([0-9]+)$/", $tb_id)) - { - return FALSE; - } - else - { - return $tb_id; - } + return preg_match('/^[0-9]+$/', $tb_id) ? $tb_id : FALSE; } // -------------------------------------------------------------------- @@ -385,15 +370,13 @@ class CI_Trackback { { $temp = '__TEMP_AMPERSANDS__'; - $str = preg_replace(array('/&#(\d+);/', '/&(\w+);/'), "$temp\\1;", $str); - - $str = str_replace(array("&","<",">","\"", "'", "-"), - array("&", "<", ">", """, "'", "-"), - $str); + $str = preg_replace(array('/&#(\d+);/', '/&(\w+);/'), $temp.'\\1;', $str); - $str = preg_replace(array("/$temp(\d+);/", "/$temp(\w+);/"), array('&#\\1;', '&\\1;'), $str); + $str = str_replace(array('&', '<', '>', '"', "'", '-'), + array('&', '<', '>', '"', ''', '-'), + $str); - return $str; + return preg_replace(array('/'.$temp.'(\d+);/', '/'.$temp.'(\w+);/'), array('&#\\1;', '&\\1;'), $str); } // -------------------------------------------------------------------- @@ -404,7 +387,7 @@ class CI_Trackback { * Limits the string based on the character count. Will preserve complete words. * * @param string - * @param integer + * @param int * @param string * @return string */ @@ -415,7 +398,7 @@ class CI_Trackback { return $str; } - $str = preg_replace("/\s+/", ' ', str_replace(array("\r\n", "\r", "\n"), ' ', $str)); + $str = preg_replace('/\s+/', ' ', str_replace(array("\r\n", "\r", "\n"), ' ', $str)); if (strlen($str) <= $n) { @@ -469,7 +452,9 @@ class CI_Trackback { if (count($temp) === $count) { - $number = ($count == 3) ? (($temp[0] % 16) * 4096) + (($temp[1] % 64) * 64) + ($temp[2] % 64) : (($temp[0] % 32) * 64) + ($temp[1] % 64); + $number = ($count === 3) + ? (($temp[0] % 16) * 4096) + (($temp[1] % 64) * 64) + ($temp[2] % 64) + : (($temp[0] % 32) * 64) + ($temp[1] % 64); $out .= '&#'.$number.';'; $count = 1; @@ -506,11 +491,10 @@ class CI_Trackback { */ public function display_errors($open = '<p>', $close = '</p>') { - return (count($this->error_msg) > 0) ? $open . implode($close . $open, $this->error_msg) . $close : ''; + return (count($this->error_msg) > 0) ? $open.implode($close.$open, $this->error_msg).$close : ''; } } -// END Trackback Class /* End of file Trackback.php */ -/* Location: ./system/libraries/Trackback.php */ +/* Location: ./system/libraries/Trackback.php */
\ No newline at end of file diff --git a/system/libraries/Unit_test.php b/system/libraries/Unit_test.php index 2eb8df356..0f6e2dfdd 100644 --- a/system/libraries/Unit_test.php +++ b/system/libraries/Unit_test.php @@ -25,8 +25,6 @@ * @filesource */ -// ------------------------------------------------------------------------ - /** * Unit Testing Class * @@ -60,7 +58,7 @@ class CI_Unit_test { 'notes' ); - log_message('debug', "Unit Testing Class Initialized"); + log_message('debug', 'Unit Testing Class Initialized'); } // -------------------------------------------------------------------- @@ -75,7 +73,7 @@ class CI_Unit_test { */ public function set_test_items($items = array()) { - if ( ! empty($items) AND is_array($items)) + if ( ! empty($items) && is_array($items)) { $this->_test_items_visible = $items; } @@ -102,8 +100,8 @@ class CI_Unit_test { if (in_array($expected, array('is_object', 'is_string', 'is_bool', 'is_true', 'is_false', 'is_int', 'is_numeric', 'is_float', 'is_double', 'is_array', 'is_null'), TRUE)) { - $expected = str_replace('is_float', 'is_double', $expected); - $result = ($expected($test)) ? TRUE : FALSE; + $expected = str_replace('is_double', 'is_float', $expected); + $result = $expected($test); $extype = str_replace(array('true', 'false'), 'bool', str_replace('is_', '', $expected)); } else @@ -186,7 +184,7 @@ class CI_Unit_test { * Causes the evaluation to use === rather than == * * @param bool - * @return null + * @return void */ public function use_strict($state = TRUE) { @@ -201,7 +199,7 @@ class CI_Unit_test { * Enables/disables unit testing * * @param bool - * @return null + * @return void */ public function active($state = TRUE) { @@ -311,10 +309,10 @@ class CI_Unit_test { */ protected function _default_template() { - $this->_template = "\n".'<table style="width:100%; font-size:small; margin:10px 0; border-collapse:collapse; border:1px solid #CCC;">{rows}'."\n".'</table>'; + $this->_template = "\n".'<table style="width:100%; font-size:small; margin:10px 0; border-collapse:collapse; border:1px solid #CCC;">{rows}'."\n</table>"; $this->_template_rows = "\n\t<tr>\n\t\t".'<th style="text-align: left; border-bottom:1px solid #CCC;">{item}</th>' - . "\n\t\t".'<td style="border-bottom:1px solid #CCC;">{result}</td>'."\n\t</tr>"; + ."\n\t\t".'<td style="border-bottom:1px solid #CCC;">{result}</td>'."\n\t</tr>"; } // -------------------------------------------------------------------- @@ -333,7 +331,7 @@ class CI_Unit_test { return; } - if (is_null($this->_template) OR ! preg_match("/\{rows\}(.*?)\{\/rows\}/si", $this->_template, $match)) + if (is_null($this->_template) OR ! preg_match('/\{rows\}(.*?)\{\/rows\}/si', $this->_template, $match)) { $this->_default_template(); return; @@ -344,7 +342,6 @@ class CI_Unit_test { } } -// END Unit_test Class /** * Helper functions to test boolean true/false @@ -353,13 +350,12 @@ class CI_Unit_test { */ function is_true($test) { - return (is_bool($test) AND $test === TRUE) ? TRUE : FALSE; + return (is_bool($test) && $test === TRUE); } function is_false($test) { - return (is_bool($test) AND $test === FALSE) ? TRUE : FALSE; + return (is_bool($test) && $test === FALSE); } - /* End of file Unit_test.php */ -/* Location: ./system/libraries/Unit_test.php */ +/* Location: ./system/libraries/Unit_test.php */
\ No newline at end of file diff --git a/system/libraries/User_agent.php b/system/libraries/User_agent.php index 9109edd0f..b8e0d37fb 100644 --- a/system/libraries/User_agent.php +++ b/system/libraries/User_agent.php @@ -25,8 +25,6 @@ * @filesource */ -// ------------------------------------------------------------------------ - /** * User Agent Class * @@ -74,15 +72,12 @@ class CI_User_agent { $this->agent = trim($_SERVER['HTTP_USER_AGENT']); } - if ( ! is_null($this->agent)) + if ( ! is_null($this->agent) && $this->_load_agent_file()) { - if ($this->_load_agent_file()) - { - $this->_compile_data(); - } + $this->_compile_data(); } - log_message('debug', "User Agent Class Initialized"); + log_message('debug', 'User Agent Class Initialized'); } // -------------------------------------------------------------------- @@ -94,7 +89,7 @@ class CI_User_agent { */ protected function _load_agent_file() { - if (defined('ENVIRONMENT') AND is_file(APPPATH.'config/'.ENVIRONMENT.'/user_agents.php')) + if (defined('ENVIRONMENT') && is_file(APPPATH.'config/'.ENVIRONMENT.'/user_agents.php')) { include(APPPATH.'config/'.ENVIRONMENT.'/user_agents.php'); } @@ -165,22 +160,24 @@ class CI_User_agent { /** * Set the Platform * - * @return mixed + * @return bool */ protected function _set_platform() { - if (is_array($this->platforms) AND count($this->platforms) > 0) + if (is_array($this->platforms) && count($this->platforms) > 0) { foreach ($this->platforms as $key => $val) { - if (preg_match("|".preg_quote($key)."|i", $this->agent)) + if (preg_match('|'.preg_quote($key).'|i', $this->agent)) { $this->platform = $val; return TRUE; } } } + $this->platform = 'Unknown Platform'; + return FALSE; } // -------------------------------------------------------------------- @@ -192,11 +189,11 @@ class CI_User_agent { */ protected function _set_browser() { - if (is_array($this->browsers) AND count($this->browsers) > 0) + if (is_array($this->browsers) && count($this->browsers) > 0) { foreach ($this->browsers as $key => $val) { - if (preg_match("|".preg_quote($key).".*?([0-9\.]+)|i", $this->agent, $match)) + if (preg_match('|'.preg_quote($key).'.*?([0-9\.]+)|i', $this->agent, $match)) { $this->is_browser = TRUE; $this->version = $match[1]; @@ -206,6 +203,7 @@ class CI_User_agent { } } } + return FALSE; } @@ -218,11 +216,11 @@ class CI_User_agent { */ protected function _set_robot() { - if (is_array($this->robots) AND count($this->robots) > 0) + if (is_array($this->robots) && count($this->robots) > 0) { foreach ($this->robots as $key => $val) { - if (preg_match("|".preg_quote($key)."|i", $this->agent)) + if (preg_match('|'.preg_quote($key).'|i', $this->agent)) { $this->is_robot = TRUE; $this->robot = $val; @@ -230,6 +228,7 @@ class CI_User_agent { } } } + return FALSE; } @@ -242,7 +241,7 @@ class CI_User_agent { */ protected function _set_mobile() { - if (is_array($this->mobiles) AND count($this->mobiles) > 0) + if (is_array($this->mobiles) && count($this->mobiles) > 0) { foreach ($this->mobiles as $key => $val) { @@ -254,6 +253,7 @@ class CI_User_agent { } } } + return FALSE; } @@ -266,7 +266,7 @@ class CI_User_agent { */ protected function _set_languages() { - if ((count($this->languages) === 0) AND isset($_SERVER['HTTP_ACCEPT_LANGUAGE']) AND $_SERVER['HTTP_ACCEPT_LANGUAGE'] != '') + if ((count($this->languages) === 0) && ! empty($_SERVER['HTTP_ACCEPT_LANGUAGE'])) { $this->languages = explode(',', preg_replace('/(;q=[0-9\.]+)/i', '', strtolower(trim($_SERVER['HTTP_ACCEPT_LANGUAGE'])))); } @@ -286,7 +286,7 @@ class CI_User_agent { */ protected function _set_charsets() { - if ((count($this->charsets) === 0) AND isset($_SERVER['HTTP_ACCEPT_CHARSET']) AND $_SERVER['HTTP_ACCEPT_CHARSET'] != '') + if ((count($this->charsets) === 0) && ! empty($_SERVER['HTTP_ACCEPT_CHARSET'])) { $this->charsets = explode(',', preg_replace('/(;q=.+)/i', '', strtolower(trim($_SERVER['HTTP_ACCEPT_CHARSET'])))); } @@ -318,7 +318,7 @@ class CI_User_agent { } // Check for a specific browser - return array_key_exists($key, $this->browsers) AND $this->browser === $this->browsers[$key]; + return (isset($this->browsers[$key]) && $this->browser === $this->browsers[$key]); } // -------------------------------------------------------------------- @@ -342,7 +342,7 @@ class CI_User_agent { } // Check for a specific robot - return array_key_exists($key, $this->robots) AND $this->robot === $this->robots[$key]; + return (isset($this->robots[$key]) && $this->robot === $this->robots[$key]); } // -------------------------------------------------------------------- @@ -366,7 +366,7 @@ class CI_User_agent { } // Check for a specific robot - return array_key_exists($key, $this->mobiles) AND $this->mobile === $this->mobiles[$key]; + return (isset($this->mobiles[$key]) && $this->mobile === $this->mobiles[$key]); } // -------------------------------------------------------------------- @@ -378,7 +378,7 @@ class CI_User_agent { */ public function is_referral() { - return ( ! isset($_SERVER['HTTP_REFERER']) OR $_SERVER['HTTP_REFERER'] == '') ? FALSE : TRUE; + return ! empty($_SERVER['HTTP_REFERER']); } // -------------------------------------------------------------------- @@ -461,7 +461,7 @@ class CI_User_agent { */ public function referrer() { - return ( ! isset($_SERVER['HTTP_REFERER']) OR $_SERVER['HTTP_REFERER'] == '') ? '' : trim($_SERVER['HTTP_REFERER']); + return empty($_SERVER['HTTP_REFERER']) ? '' : trim($_SERVER['HTTP_REFERER']); } // -------------------------------------------------------------------- @@ -507,7 +507,7 @@ class CI_User_agent { */ public function accept_lang($lang = 'en') { - return (in_array(strtolower($lang), $this->languages(), TRUE)); + return in_array(strtolower($lang), $this->languages(), TRUE); } // -------------------------------------------------------------------- @@ -519,10 +519,10 @@ class CI_User_agent { */ public function accept_charset($charset = 'utf-8') { - return (in_array(strtolower($charset), $this->charsets(), TRUE)); + return in_array(strtolower($charset), $this->charsets(), TRUE); } } /* End of file User_agent.php */ -/* Location: ./system/libraries/User_agent.php */ +/* Location: ./system/libraries/User_agent.php */
\ No newline at end of file diff --git a/system/libraries/Xmlrpc.php b/system/libraries/Xmlrpc.php index 32e2e523b..fea560c2e 100644 --- a/system/libraries/Xmlrpc.php +++ b/system/libraries/Xmlrpc.php @@ -25,14 +25,6 @@ * @filesource */ -if ( ! function_exists('xml_parser_create')) -{ - show_error('Your PHP installation does not support XML'); -} - - -// ------------------------------------------------------------------------ - /** * XML-RPC request handler class * @@ -42,6 +34,14 @@ if ( ! function_exists('xml_parser_create')) * @author EllisLab Dev Team * @link http://codeigniter.com/user_guide/libraries/xmlrpc.html */ + +if ( ! function_exists('xml_parser_create')) +{ + show_error('Your PHP installation does not support XML'); +} + +// ------------------------------------------------------------------------ + class CI_Xmlrpc { public $debug = FALSE; // Debugging on or off @@ -77,13 +77,17 @@ class CI_Xmlrpc { public $xss_clean = TRUE; - //------------------------------------- - // VALUES THAT MULTIPLE CLASSES NEED - //------------------------------------- + /** + * Constructor + * + * Initializes property default values + * + * @param array + * @return void + */ public function __construct($config = array()) { - $this->xmlrpcName = $this->xmlrpcName; $this->xmlrpc_backslash = chr(92).chr(92); // Types for info sent back and forth @@ -136,14 +140,17 @@ class CI_Xmlrpc { $this->initialize($config); - log_message('debug', "XML-RPC Class Initialized"); + log_message('debug', 'XML-RPC Class Initialized'); } + // -------------------------------------------------------------------- - //------------------------------------- - // Initialize Prefs - //------------------------------------- - + /** + * Initialize + * + * @param array + * @return void + */ public function initialize($config = array()) { if (count($config) > 0) @@ -157,36 +164,43 @@ class CI_Xmlrpc { } } } - // END - //------------------------------------- - // Take URL and parse it - //------------------------------------- + // -------------------------------------------------------------------- - public function server($url, $port=80) + /** + * Parse server URL + * + * @param string url + * @param int port + * @return void + */ + public function server($url, $port = 80) { if (strpos($url, 'http') !== 0) { - $url = "http://".$url; + $url = 'http://'.$url; } $parts = parse_url($url); - $path = ( ! isset($parts['path'])) ? '/' : $parts['path']; + $path = isset($parts['path']) ? $parts['path'] : '/'; - if (isset($parts['query']) && $parts['query'] != '') + if ( ! empty($parts['query'])) { $path .= '?'.$parts['query']; } $this->client = new XML_RPC_Client($path, $parts['host'], $port); } - // END - //------------------------------------- - // Set Timeout - //------------------------------------- + // -------------------------------------------------------------------- + /** + * Set Timeout + * + * @param int seconds + * @return void + */ public function timeout($seconds = 5) { if ( ! is_null($this->client) && is_int($seconds)) @@ -194,27 +208,34 @@ class CI_Xmlrpc { $this->client->timeout = $seconds; } } - // END - //------------------------------------- - // Set Methods - //------------------------------------- + // -------------------------------------------------------------------- + /** + * Set Methods + * + * @param string method name + * @return void + */ public function method($function) { $this->method = $function; } - // END - //------------------------------------- - // Take Array of Data and Create Objects - //------------------------------------- + // -------------------------------------------------------------------- + /** + * Take Array of Data and Create Objects + * + * @param array + * @return void + */ public function request($incoming) { if ( ! is_array($incoming)) { // Send Error + return; } $this->data = array(); @@ -224,27 +245,33 @@ class CI_Xmlrpc { $this->data[$key] = $this->values_parsing($value); } } - // END - - //------------------------------------- - // Set Debug - //------------------------------------- + // -------------------------------------------------------------------- + /** + * Set Debug + * + * @param bool + * @return void + */ public function set_debug($flag = TRUE) { $this->debug = ($flag == TRUE); } - //------------------------------------- - // Values Parsing - //------------------------------------- + // -------------------------------------------------------------------- - public function values_parsing($value, $return = FALSE) + /** + * Values Parsing + * + * @param mixed + * @return object + */ + public function values_parsing($value) { if (is_array($value) && array_key_exists(0, $value)) { - if ( ! isset($value[1]) OR ( ! isset($this->xmlrpcTypes[$value[1]]))) + if ( ! isset($value[1], $this->xmlrpcTypes[$value[1]])) { $temp = new XML_RPC_Values($value[0], (is_array($value[0]) ? 'array' : 'string')); } @@ -268,16 +295,17 @@ class CI_Xmlrpc { return $temp; } - // END - - //------------------------------------- - // Sends XML-RPC Request - //------------------------------------- + // -------------------------------------------------------------------- + /** + * Sends XML-RPC Request + * + * @return bool + */ public function send_request() { - $this->message = new XML_RPC_Message($this->method,$this->data); + $this->message = new XML_RPC_Message($this->method, $this->data); $this->message->debug = $this->debug; if ( ! $this->result = $this->client->send($this->message) OR ! is_object($this->result->val)) @@ -289,55 +317,62 @@ class CI_Xmlrpc { $this->response = $this->result->decode(); return TRUE; } - // END - //------------------------------------- - // Returns Error - //------------------------------------- + // -------------------------------------------------------------------- + /** + * Returns Error + * + * @return string + */ public function display_error() { return $this->error; } - // END - //------------------------------------- - // Returns Remote Server Response - //------------------------------------- + // -------------------------------------------------------------------- + /** + * Returns Remote Server Response + * + * @return string + */ public function display_response() { return $this->response; } - // END - //------------------------------------- - // Sends an Error Message for Server Request - //------------------------------------- + // -------------------------------------------------------------------- + /** + * Sends an Error Message for Server Request + * + * @param int + * @param string + * @return object + */ public function send_error_message($number, $message) { return new XML_RPC_Response(0, $number, $message); } - // END + // -------------------------------------------------------------------- - //------------------------------------- - // Send Response for Server Request - //------------------------------------- - + /** + * Send Response for Server Request + * + * @param array + * @return object + */ public function send_response($response) { // $response should be array of values, which will be parsed // based on their data and type into a valid group of XML-RPC values return new XML_RPC_Response($this->values_parsing($response)); } - // END } // END XML_RPC Class - - /** * XML-RPC Client class * @@ -355,7 +390,15 @@ class XML_RPC_Client extends CI_Xmlrpc public $timeout = 5; public $no_multicall = FALSE; - public function __construct($path, $server, $port=80) + /** + * Constructor + * + * @param string + * @param object + * @param int + * @return void + */ + public function __construct($path, $server, $port = 80) { parent::__construct(); @@ -364,18 +407,33 @@ class XML_RPC_Client extends CI_Xmlrpc $this->path = $path; } + // -------------------------------------------------------------------- + + /** + * Send message + * + * @param mixed + * @return object + */ public function send($msg) { if (is_array($msg)) { // Multi-call disabled - $r = new XML_RPC_Response(0, $this->xmlrpcerr['multicall_recursion'],$this->xmlrpcstr['multicall_recursion']); - return $r; + return new XML_RPC_Response(0, $this->xmlrpcerr['multicall_recursion'], $this->xmlrpcstr['multicall_recursion']); } return $this->sendPayload($msg); } + // -------------------------------------------------------------------- + + /** + * Send payload + * + * @param object + * @return object + */ public function sendPayload($msg) { $fp = @fsockopen($this->server, $this->port,$this->errno, $this->errstr, $this->timeout); @@ -383,8 +441,7 @@ class XML_RPC_Client extends CI_Xmlrpc if ( ! is_resource($fp)) { error_log($this->xmlrpcstr['http_error']); - $r = new XML_RPC_Response(0, $this->xmlrpcerr['http_error'],$this->xmlrpcstr['http_error']); - return $r; + return new XML_RPC_Response(0, $this->xmlrpcerr['http_error'], $this->xmlrpcstr['http_error']); } if (empty($msg->payload)) @@ -394,27 +451,25 @@ class XML_RPC_Client extends CI_Xmlrpc } $r = "\r\n"; - $op = "POST {$this->path} HTTP/1.0$r" - . "Host: {$this->server}$r" - . "Content-Type: text/xml$r" - . "User-Agent: {$this->xmlrpcName}$r" - . "Content-Length: ".strlen($msg->payload)."$r$r" - . $msg->payload; - + $op = 'POST '.$this->path.' HTTP/1.0'.$r + .'Host: '.$this->server.$r + .'Content-Type: text/xml'.$r + .'User-Agent: '.$this->xmlrpcName.$r + .'Content-Length: '.strlen($msg->payload).$r.$r + .$msg->payload; if ( ! fputs($fp, $op, strlen($op))) { error_log($this->xmlrpcstr['http_error']); - $r = new XML_RPC_Response(0, $this->xmlrpcerr['http_error'], $this->xmlrpcstr['http_error']); - return $r; + return new XML_RPC_Response(0, $this->xmlrpcerr['http_error'], $this->xmlrpcstr['http_error']); } + $resp = $msg->parseResponse($fp); fclose($fp); return $resp; } -} -// end class XML_RPC_Client +} // END XML_RPC_Client Class /** * XML-RPC Response class @@ -425,31 +480,34 @@ class XML_RPC_Client extends CI_Xmlrpc */ class XML_RPC_Response { - public $val = 0; - public $errno = 0; - public $errstr = ''; - public $headers = array(); - public $xss_clean = TRUE; - + public $val = 0; + public $errno = 0; + public $errstr = ''; + public $headers = array(); + public $xss_clean = TRUE; + + /** + * Constructor + * + * @param mixed + * @param int + * @param string + * @return void + */ public function __construct($val, $code = 0, $fstr = '') { if ($code != 0) { // error $this->errno = $code; - if ( ! is_php('5.4')) - { - $this->errstr = htmlspecialchars($fstr, ENT_NOQUOTES, 'UTF-8'); - } - else - { - $this->errstr = htmlspecialchars($fstr, ENT_XML1 | ENT_NOQUOTES, 'UTF-8'); - } + $this->errstr = htmlspecialchars($fstr, + (is_php('5.4') ? ENT_XML1 | ENT_NOQUOTES : ENT_NOQUOTES), + 'UTF-8'); } - else if ( ! is_object($val)) + elseif ( ! is_object($val)) { // programmer error, not an object - error_log("Invalid type '" . gettype($val) . "' (value: $val) passed to XML_RPC_Response. Defaulting to empty value."); + error_log("Invalid type '".gettype($val)."' (value: ".$val.') passed to XML_RPC_Response. Defaulting to empty value.'); $this->val = new XML_RPC_Values(); } else @@ -458,43 +516,79 @@ class XML_RPC_Response } } + // -------------------------------------------------------------------- + + /** + * Fault code + * + * @return int + */ public function faultCode() { return $this->errno; } + // -------------------------------------------------------------------- + + /** + * Fault string + * + * @return string + */ public function faultString() { return $this->errstr; } + // -------------------------------------------------------------------- + + /** + * Value + * + * @return mixed + */ public function value() { return $this->val; } + // -------------------------------------------------------------------- + + /** + * Prepare response + * + * @return string xml + */ public function prepare_response() { return "<methodResponse>\n" - . ($this->errno - ? '<fault> + .($this->errno + ? '<fault> <value> <struct> <member> <name>faultCode</name> - <value><int>' . $this->errno . '</int></value> + <value><int>'.$this->errno.'</int></value> </member> <member> <name>faultString</name> - <value><string>' . $this->errstr . '</string></value> + <value><string>'.$this->errstr.'</string></value> </member> </struct> </value> </fault>' - : "<params>\n<param>\n".$this->val->serialize_class()."</param>\n</params>") - . "\n</methodResponse>"; + : "<params>\n<param>\n".$this->val->serialize_class()."</param>\n</params>") + ."\n</methodResponse>"; } + // -------------------------------------------------------------------- + + /** + * Decode + * + * @param mixed + * @return array + */ public function decode($array = FALSE) { $CI =& get_instance(); @@ -513,31 +607,31 @@ class XML_RPC_Response } } - $result = $array; + return $array; + } + + $result = $this->xmlrpc_decoder($this->val); + + if (is_array($result)) + { + $result = $this->decode($result); } else { - $result = $this->xmlrpc_decoder($this->val); - - if (is_array($result)) - { - $result = $this->decode($result); - } - else - { - $result = ($this->xss_clean) ? $CI->security->xss_clean($result) : $result; - } + $result = ($this->xss_clean) ? $CI->security->xss_clean($result) : $result; } return $result; } + // -------------------------------------------------------------------- - - //------------------------------------- - // XML-RPC Object to PHP Types - //------------------------------------- - + /** + * XML-RPC Object to PHP Types + * + * @param object + * @return array + */ public function xmlrpc_decoder($xmlrpc_val) { $kind = $xmlrpc_val->kindOf(); @@ -571,25 +665,28 @@ class XML_RPC_Response } } + // -------------------------------------------------------------------- - //------------------------------------- - // ISO-8601 time to server or UTC time - //------------------------------------- - - public function iso8601_decode($time, $utc = 0) + /** + * ISO-8601 time to server or UTC time + * + * @param string + * @param bool + * @return int unix timestamp + */ + public function iso8601_decode($time, $utc = FALSE) { - // return a timet in the localtime, or UTC + // return a time in the localtime, or UTC $t = 0; if (preg_match('/([0-9]{4})([0-9]{2})([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})/', $time, $regs)) { - $fnc = ($utc == 1) ? 'gmmktime' : 'mktime'; + $fnc = ($utc == TRUE) ? 'gmmktime' : 'mktime'; $t = $fnc($regs[4], $regs[5], $regs[6], $regs[2], $regs[3], $regs[1]); } return $t; } -} -// End Response Class +} // END XML_RPC_Response Class /** * XML-RPC Message class @@ -602,10 +699,17 @@ class XML_RPC_Message extends CI_Xmlrpc { public $payload; public $method_name; - public $params = array(); - public $xh = array(); - - public function __construct($method, $pars=0) + public $params = array(); + public $xh = array(); + + /** + * Constructor + * + * @param string method name + * @param array + * @return void + */ + public function __construct($method, $pars = FALSE) { parent::__construct(); @@ -620,15 +724,18 @@ class XML_RPC_Message extends CI_Xmlrpc } } - //------------------------------------- - // Create Payload to Send - //------------------------------------- + // -------------------------------------------------------------------- + /** + * Create Payload to Send + * + * @return void + */ public function createPayload() { - $this->payload = "<?xml version=\"1.0\"?".">\r\n<methodCall>\r\n" - . '<methodName>'.$this->method_name."</methodName>\r\n" - . "<params>\r\n"; + $this->payload = '<?xml version="1.0"?'.">\r\n<methodCall>\r\n" + .'<methodName>'.$this->method_name."</methodName>\r\n" + ."<params>\r\n"; for ($i = 0, $c = count($this->params); $i < $c; $i++) { @@ -640,10 +747,14 @@ class XML_RPC_Message extends CI_Xmlrpc $this->payload .= "</params>\r\n</methodCall>\r\n"; } - //------------------------------------- - // Parse External XML-RPC Server's Response - //------------------------------------- + // -------------------------------------------------------------------- + /** + * Parse External XML-RPC Server's Response + * + * @param resource + * @return object + */ public function parseResponse($fp) { $data = ''; @@ -653,36 +764,24 @@ class XML_RPC_Message extends CI_Xmlrpc $data .= $datum; } - //------------------------------------- - // DISPLAY HTTP CONTENT for DEBUGGING - //------------------------------------- - + // Display HTTP content for debugging if ($this->debug === TRUE) { echo "<pre>---DATA---\n".htmlspecialchars($data)."\n---END DATA---\n\n</pre>"; } - //------------------------------------- - // Check for data - //------------------------------------- - + // Check for data if ($data === '') { error_log($this->xmlrpcstr['no_data']); - $r = new XML_RPC_Response(0, $this->xmlrpcerr['no_data'], $this->xmlrpcstr['no_data']); - return $r; + return new XML_RPC_Response(0, $this->xmlrpcerr['no_data'], $this->xmlrpcstr['no_data']); } - - //------------------------------------- - // Check for HTTP 200 Response - //------------------------------------- - + // Check for HTTP 200 Response if (strncmp($data, 'HTTP', 4) === 0 && ! preg_match('/^HTTP\/[0-9\.]+ 200 /', $data)) { - $errstr= substr($data, 0, strpos($data, "\n")-1); - $r = new XML_RPC_Response(0, $this->xmlrpcerr['http_error'], $this->xmlrpcstr['http_error']. ' (' . $errstr . ')'); - return $r; + $errstr = substr($data, 0, strpos($data, "\n")-1); + return new XML_RPC_Response(0, $this->xmlrpcerr['http_error'], $this->xmlrpcstr['http_error'].' ('.$errstr.')'); } //------------------------------------- @@ -692,25 +791,21 @@ class XML_RPC_Message extends CI_Xmlrpc $parser = xml_parser_create($this->xmlrpc_defencoding); $this->xh[$parser] = array( - 'isf' => 0, - 'ac' => '', - 'headers' => array(), - 'stack' => array(), - 'valuestack' => array(), - 'isf_reason' => 0 + 'isf' => 0, + 'ac' => '', + 'headers' => array(), + 'stack' => array(), + 'valuestack' => array(), + 'isf_reason' => 0 ); xml_set_object($parser, $this); - xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, true); + xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, TRUE); xml_set_element_handler($parser, 'open_tag', 'closing_tag'); xml_set_character_data_handler($parser, 'character_data'); //xml_set_default_handler($parser, 'default_handler'); - - //------------------------------------- - // GET HEADERS - //------------------------------------- - + // Get headers $lines = explode("\r\n", $data); while (($line = array_shift($lines))) { @@ -722,16 +817,12 @@ class XML_RPC_Message extends CI_Xmlrpc } $data = implode("\r\n", $lines); - - //------------------------------------- - // PARSE XML DATA - //------------------------------------- - + // Parse XML data if ( ! xml_parse($parser, $data, count($data))) { $errstr = sprintf('XML error: %s at line %d', - xml_error_string(xml_get_error_code($parser)), - xml_get_current_line_number($parser)); + xml_error_string(xml_get_error_code($parser)), + xml_get_current_line_number($parser)); //error_log($errstr); $r = new XML_RPC_Response(0, $this->xmlrpcerr['invalid_return'], $this->xmlrpcstr['invalid_return']); xml_parser_free($parser); @@ -739,10 +830,7 @@ class XML_RPC_Message extends CI_Xmlrpc } xml_parser_free($parser); - // --------------------------------------- - // Got Ourselves Some Badness, It Seems - // --------------------------------------- - + // Got ourselves some badness, it seems if ($this->xh[$parser]['isf'] > 1) { if ($this->debug === TRUE) @@ -750,29 +838,24 @@ class XML_RPC_Message extends CI_Xmlrpc echo "---Invalid Return---\n".$this->xh[$parser]['isf_reason']."---Invalid Return---\n\n"; } - $r = new XML_RPC_Response(0, $this->xmlrpcerr['invalid_return'],$this->xmlrpcstr['invalid_return'].' '.$this->xh[$parser]['isf_reason']); - return $r; + return new XML_RPC_Response(0, $this->xmlrpcerr['invalid_return'], $this->xmlrpcstr['invalid_return'].' '.$this->xh[$parser]['isf_reason']); } elseif ( ! is_object($this->xh[$parser]['value'])) { - $r = new XML_RPC_Response(0, $this->xmlrpcerr['invalid_return'],$this->xmlrpcstr['invalid_return'].' '.$this->xh[$parser]['isf_reason']); - return $r; + return new XML_RPC_Response(0, $this->xmlrpcerr['invalid_return'], $this->xmlrpcstr['invalid_return'].' '.$this->xh[$parser]['isf_reason']); } - //------------------------------------- - // DISPLAY XML CONTENT for DEBUGGING - //------------------------------------- - + // Display XML content for debugging if ($this->debug === TRUE) { - echo "<pre>"; + echo '<pre>'; if (count($this->xh[$parser]['headers'] > 0)) { echo "---HEADERS---\n"; foreach ($this->xh[$parser]['headers'] as $header) { - echo "$header\n"; + echo $header."\n"; } echo "---END HEADERS---\n\n"; } @@ -782,10 +865,7 @@ class XML_RPC_Message extends CI_Xmlrpc echo "\n---END PARSED---</pre>"; } - //------------------------------------- - // SEND RESPONSE - //------------------------------------- - + // Send response $v = $this->xh[$parser]['value']; if ($this->xh[$parser]['isf']) { @@ -810,6 +890,8 @@ class XML_RPC_Message extends CI_Xmlrpc return $r; } + // -------------------------------------------------------------------- + // ------------------------------------ // Begin Return Message Parsing section // ------------------------------------ @@ -824,17 +906,21 @@ class XML_RPC_Message extends CI_Xmlrpc // stack - array with parent tree of the xml element, // used to validate the nesting of elements - //------------------------------------- - // Start Element Handler - //------------------------------------- + // -------------------------------------------------------------------- - public function open_tag($the_parser, $name, $attrs) + /** + * Start Element Handler + * + * @param string + * @param string + * @return void + */ + public function open_tag($the_parser, $name) { // If invalid nesting, then return if ($this->xh[$the_parser]['isf'] > 1) return; // Evaluate and check for correct nesting of XML elements - if (count($this->xh[$the_parser]['stack']) == 0) { if ($name != 'METHODRESPONSE' && $name != 'METHODCALL') @@ -844,43 +930,37 @@ class XML_RPC_Message extends CI_Xmlrpc return; } } - else + // not top level element: see if parent is OK + elseif ( ! in_array($this->xh[$the_parser]['stack'][0], $this->valid_parents[$name], TRUE)) { - // not top level element: see if parent is OK - if ( ! in_array($this->xh[$the_parser]['stack'][0], $this->valid_parents[$name], TRUE)) - { - $this->xh[$the_parser]['isf'] = 2; - $this->xh[$the_parser]['isf_reason'] = "XML-RPC element $name cannot be child of ".$this->xh[$the_parser]['stack'][0]; - return; - } + $this->xh[$the_parser]['isf'] = 2; + $this->xh[$the_parser]['isf_reason'] = 'XML-RPC element $name cannot be child of '.$this->xh[$the_parser]['stack'][0]; + return; } - switch($name) + switch ($name) { case 'STRUCT': case 'ARRAY': // Creates array for child elements - - $cur_val = array('value' => array(), - 'type' => $name); - + $cur_val = array('value' => array(), 'type' => $name); array_unshift($this->xh[$the_parser]['valuestack'], $cur_val); - break; + break; case 'METHODNAME': case 'NAME': $this->xh[$the_parser]['ac'] = ''; - break; + break; case 'FAULT': $this->xh[$the_parser]['isf'] = 1; - break; + break; case 'PARAM': $this->xh[$the_parser]['value'] = NULL; - break; + break; case 'VALUE': $this->xh[$the_parser]['vt'] = 'value'; $this->xh[$the_parser]['ac'] = ''; $this->xh[$the_parser]['lv'] = 1; - break; + break; case 'I4': case 'INT': case 'STRING': @@ -892,66 +972,70 @@ class XML_RPC_Message extends CI_Xmlrpc { //two data elements inside a value: an error occurred! $this->xh[$the_parser]['isf'] = 2; - $this->xh[$the_parser]['isf_reason'] = "'Twas a $name element following a ".$this->xh[$the_parser]['vt']." element inside a single value"; + $this->xh[$the_parser]['isf_reason'] = "'Twas a ".$name.' element following a ' + .$this->xh[$the_parser]['vt'].' element inside a single value'; return; } $this->xh[$the_parser]['ac'] = ''; - break; + break; case 'MEMBER': // Set name of <member> to nothing to prevent errors later if no <name> is found $this->xh[$the_parser]['valuestack'][0]['name'] = ''; // Set NULL value to check to see if value passed for this param/member $this->xh[$the_parser]['value'] = NULL; - break; + break; case 'DATA': case 'METHODCALL': case 'METHODRESPONSE': case 'PARAMS': // valid elements that add little to processing - break; + break; default: /// An Invalid Element is Found, so we have trouble $this->xh[$the_parser]['isf'] = 2; - $this->xh[$the_parser]['isf_reason'] = "Invalid XML-RPC element found: $name"; - break; + $this->xh[$the_parser]['isf_reason'] = 'Invalid XML-RPC element found: '.$name; + break; } // Add current element name to stack, to allow validation of nesting array_unshift($this->xh[$the_parser]['stack'], $name); - if ($name != 'VALUE') $this->xh[$the_parser]['lv'] = 0; + $name == 'VALUE' OR $this->xh[$the_parser]['lv'] = 0; } - // END - - //------------------------------------- - // End Element Handler - //------------------------------------- + // -------------------------------------------------------------------- + /** + * End Element Handler + * + * @param string + * @param string + * @return void + */ public function closing_tag($the_parser, $name) { if ($this->xh[$the_parser]['isf'] > 1) return; // Remove current element from stack and set variable // NOTE: If the XML validates, then we do not have to worry about - // the opening and closing of elements. Nesting is checked on the opening + // the opening and closing of elements. Nesting is checked on the opening // tag so we be safe there as well. $curr_elem = array_shift($this->xh[$the_parser]['stack']); - switch($name) + switch ($name) { case 'STRUCT': case 'ARRAY': $cur_val = array_shift($this->xh[$the_parser]['valuestack']); - $this->xh[$the_parser]['value'] = ( ! isset($cur_val['values'])) ? array() : $cur_val['values']; + $this->xh[$the_parser]['value'] = isset($cur_val['values']) ? $cur_val['values'] : array(); $this->xh[$the_parser]['vt'] = strtolower($name); - break; + break; case 'NAME': $this->xh[$the_parser]['valuestack'][0]['name'] = $this->xh[$the_parser]['ac']; - break; + break; case 'BOOLEAN': case 'I4': case 'INT': @@ -965,56 +1049,39 @@ class XML_RPC_Message extends CI_Xmlrpc { $this->xh[$the_parser]['value'] = $this->xh[$the_parser]['ac']; } - elseif ($name=='DATETIME.ISO8601') + elseif ($name == 'DATETIME.ISO8601') { $this->xh[$the_parser]['vt'] = $this->xmlrpcDateTime; $this->xh[$the_parser]['value'] = $this->xh[$the_parser]['ac']; } - elseif ($name=='BASE64') + elseif ($name == 'BASE64') { $this->xh[$the_parser]['value'] = base64_decode($this->xh[$the_parser]['ac']); } - elseif ($name=='BOOLEAN') + elseif ($name == 'BOOLEAN') { // Translated BOOLEAN values to TRUE AND FALSE - if ($this->xh[$the_parser]['ac'] == '1') - { - $this->xh[$the_parser]['value'] = TRUE; - } - else - { - $this->xh[$the_parser]['value'] = FALSE; - } + $this->xh[$the_parser]['value'] = (bool) $this->xh[$the_parser]['ac']; } elseif ($name=='DOUBLE') { // we have a DOUBLE // we must check that only 0123456789-.<space> are characters here - if ( ! preg_match('/^[+-]?[eE0-9\t \.]+$/', $this->xh[$the_parser]['ac'])) - { - $this->xh[$the_parser]['value'] = 'ERROR_NON_NUMERIC_FOUND'; - } - else - { - $this->xh[$the_parser]['value'] = (double)$this->xh[$the_parser]['ac']; - } + $this->xh[$the_parser]['value'] = preg_match('/^[+-]?[eE0-9\t \.]+$/', $this->xh[$the_parser]['ac']) + ? (float) $this->xh[$the_parser]['ac'] + : 'ERROR_NON_NUMERIC_FOUND'; } else { // we have an I4/INT // we must check that only 0123456789-<space> are characters here - if ( ! preg_match('/^[+-]?[0-9\t ]+$/', $this->xh[$the_parser]['ac'])) - { - $this->xh[$the_parser]['value'] = 'ERROR_NON_NUMERIC_FOUND'; - } - else - { - $this->xh[$the_parser]['value'] = (int)$this->xh[$the_parser]['ac']; - } + $this->xh[$the_parser]['value'] = preg_match('/^[+-]?[0-9\t ]+$/', $this->xh[$the_parser]['ac']) + ? (int) $this->xh[$the_parset]['ac'] + : 'ERROR_NON_NUMERIC_FOUND'; } $this->xh[$the_parser]['ac'] = ''; $this->xh[$the_parser]['lv'] = 3; // indicate we've found a value - break; + break; case 'VALUE': // This if() detects if no scalar was inside <VALUE></VALUE> if ($this->xh[$the_parser]['vt']=='value') @@ -1036,44 +1103,49 @@ class XML_RPC_Message extends CI_Xmlrpc // Struct $this->xh[$the_parser]['value'] = $temp; } - break; + break; case 'MEMBER': - $this->xh[$the_parser]['ac']=''; + $this->xh[$the_parser]['ac'] = ''; // If value add to array in the stack for the last element built if ($this->xh[$the_parser]['value']) { $this->xh[$the_parser]['valuestack'][0]['values'][$this->xh[$the_parser]['valuestack'][0]['name']] = $this->xh[$the_parser]['value']; } - break; + break; case 'DATA': - $this->xh[$the_parser]['ac']=''; - break; + $this->xh[$the_parser]['ac'] = ''; + break; case 'PARAM': if ($this->xh[$the_parser]['value']) { $this->xh[$the_parser]['params'][] = $this->xh[$the_parser]['value']; } - break; + break; case 'METHODNAME': $this->xh[$the_parser]['method'] = ltrim($this->xh[$the_parser]['ac']); - break; + break; case 'PARAMS': case 'FAULT': case 'METHODCALL': case 'METHORESPONSE': // We're all good kids with nuthin' to do - break; + break; default: - // End of an Invalid Element. Taken care of during the opening tag though - break; + // End of an Invalid Element. Taken care of during the opening tag though + break; } } - //------------------------------------- - // Parses Character Data - //------------------------------------- + // -------------------------------------------------------------------- + /** + * Parse character data + * + * @param string + * @param string + * @return void + */ public function character_data($the_parser, $data) { if ($this->xh[$the_parser]['isf'] > 1) return; // XML Fault found already @@ -1086,7 +1158,7 @@ class XML_RPC_Message extends CI_Xmlrpc $this->xh[$the_parser]['lv'] = 2; // Found a value } - if ( ! @isset($this->xh[$the_parser]['ac'])) + if ( ! isset($this->xh[$the_parser]['ac'])) { $this->xh[$the_parser]['ac'] = ''; } @@ -1095,12 +1167,27 @@ class XML_RPC_Message extends CI_Xmlrpc } } + // -------------------------------------------------------------------- + /** + * Add parameter + * + * @param mixed + * @return void + */ public function addParam($par) { $this->params[] = $par; } + // -------------------------------------------------------------------- + + /** + * Output parameters + * + * @param array + * @return array + */ public function output_parameters($array = FALSE) { $CI =& get_instance(); @@ -1121,31 +1208,36 @@ class XML_RPC_Message extends CI_Xmlrpc } } - $parameters = $array; + return $array; } - else + + $parameters = array(); + + for ($i = 0, $c = count($this->params); $i < $c; $i++) { - $parameters = array(); + $a_param = $this->decode_message($this->params[$i]); - for ($i = 0, $c = count($this->params); $i < $c; $i++) + if (is_array($a_param)) { - $a_param = $this->decode_message($this->params[$i]); - - if (is_array($a_param)) - { - $parameters[] = $this->output_parameters($a_param); - } - else - { - $parameters[] = ($this->xss_clean) ? $CI->security->xss_clean($a_param) : $a_param; - } + $parameters[] = $this->output_parameters($a_param); + } + else + { + $parameters[] = ($this->xss_clean) ? $CI->security->xss_clean($a_param) : $a_param; } } return $parameters; } + // -------------------------------------------------------------------- + /** + * Decode message + * + * @param object + * @return mixed + */ public function decode_message($param) { $kind = $param->kindOf(); @@ -1160,7 +1252,7 @@ class XML_RPC_Message extends CI_Xmlrpc $b = current($param->me); $arr = array(); - for($i = 0, $c = count($b); $i < $c; $i++) + for ($i = 0, $c = count($b); $i < $c; $i++) { $arr[] = $this->decode_message($param->me['array'][$i]); } @@ -1181,8 +1273,7 @@ class XML_RPC_Message extends CI_Xmlrpc } } -} -// End XML_RPC_Messages class +} // END XML_RPC_Message Class /** * XML-RPC Values class @@ -1196,6 +1287,13 @@ class XML_RPC_Values extends CI_Xmlrpc public $me = array(); public $mytype = 0; + /** + * Constructor + * + * @param mixed + * @param string + * @return void + */ public function __construct($val = -1, $type = '') { parent::__construct(); @@ -1219,11 +1317,20 @@ class XML_RPC_Values extends CI_Xmlrpc } } + // -------------------------------------------------------------------- + + /** + * Add scalar value + * + * @param scalar + * @param string + * @return int + */ public function addScalar($val, $type = 'string') { $typeof = $this->xmlrpcTypes[$type]; - if ($this->mytype==1) + if ($this->mytype == 1) { echo '<strong>XML_RPC_Values</strong>: scalar can have only one value<br />'; return 0; @@ -1237,7 +1344,7 @@ class XML_RPC_Values extends CI_Xmlrpc if ($type == $this->xmlrpcBoolean) { - $val = (strcasecmp($val,'true') === 0 OR $val == 1 OR ($val == true && strcasecmp($val, 'false'))) ? 1 : 0; + $val = (int) (strcasecmp($val,'true') === 0 OR $val === 1 OR ($val === TRUE && strcasecmp($val, 'false'))); } if ($this->mytype == 2) @@ -1253,9 +1360,18 @@ class XML_RPC_Values extends CI_Xmlrpc $this->me[$type] = $val; $this->mytype = $typeof; } + return 1; } + // -------------------------------------------------------------------- + + /** + * Add array value + * + * @param array + * @return int + */ public function addArray($vals) { if ($this->mytype != 0) @@ -1269,6 +1385,14 @@ class XML_RPC_Values extends CI_Xmlrpc return 1; } + // -------------------------------------------------------------------- + + /** + * Add struct value + * + * @param object + * @return int + */ public function addStruct($vals) { if ($this->mytype != 0) @@ -1281,29 +1405,37 @@ class XML_RPC_Values extends CI_Xmlrpc return 1; } + // -------------------------------------------------------------------- + + /** + * Get value type + * + * @return string + */ public function kindOf() { - switch($this->mytype) + switch ($this->mytype) { - case 3: - return 'struct'; - break; - case 2: - return 'array'; - break; - case 1: - return 'scalar'; - break; - default: - return 'undef'; + case 3: return 'struct'; + case 2: return 'array'; + case 1: return 'scalar'; + default: return 'undef'; } } + // -------------------------------------------------------------------- + + /** + * Serialize data + * + * @param string + * @param mixed + */ public function serializedata($typ, $val) { $rs = ''; - switch($this->xmlrpcTypes[$typ]) + switch ($this->xmlrpcTypes[$typ]) { case 3: // struct @@ -1314,11 +1446,11 @@ class XML_RPC_Values extends CI_Xmlrpc $rs .= "<member>\n<name>{$key2}</name>\n".$this->serializeval($val2)."</member>\n"; } $rs .= '</struct>'; - break; + break; case 2: // array $rs .= "<array>\n<data>\n"; - for($i = 0, $c = count($val); $i < $c; $i++) + for ($i = 0, $c = count($val); $i < $c; $i++) { $rs .= $this->serializeval($val[$i]); } @@ -1329,29 +1461,45 @@ class XML_RPC_Values extends CI_Xmlrpc switch ($typ) { case $this->xmlrpcBase64: - $rs .= "<{$typ}>" . base64_encode((string)$val) . "</{$typ}>\n"; - break; + $rs .= '<'.$typ.'>'.base64_encode( (string) $val).'</'.$typ.">\n"; + break; case $this->xmlrpcBoolean: - $rs .= "<{$typ}>" . ((bool)$val ? '1' : '0') . "</{$typ}>\n"; - break; + $rs .= '<'.$typ.'>'.( (bool) $val ? '1' : '0').'</'.$typ.">\n"; + break; case $this->xmlrpcString: - $rs .= "<{$typ}>" . htmlspecialchars((string)$val). "</{$typ}>\n"; - break; + $rs .= '<'.$typ.'>'.htmlspecialchars( (string) $val).'</'.$typ.">\n"; + break; default: - $rs .= "<{$typ}>{$val}</{$typ}>\n"; - break; + $rs .= '<'.$typ.'>'.$val.'</'.$typ.">\n"; + break; } default: - break; + break; } + return $rs; } + // -------------------------------------------------------------------- + + /** + * Serialize class + * + * @return string + */ public function serialize_class() { return $this->serializeval($this); } + // -------------------------------------------------------------------- + + /** + * Serialize value + * + * @param object + * @return string + */ public function serializeval($o) { $ar = $o->me; @@ -1361,26 +1509,35 @@ class XML_RPC_Values extends CI_Xmlrpc return "<value>\n".$this->serializedata($typ, $val)."</value>\n"; } + // -------------------------------------------------------------------- + + /** + * Scalar value + * + * @return mixed + */ public function scalarval() { reset($this->me); return current($this->me); } - - //------------------------------------- - // Encode time in ISO-8601 form. - //------------------------------------- - - // Useful for sending time in XML-RPC - - public function iso8601_encode($time, $utc = 0) + // -------------------------------------------------------------------- + + /** + * Encode time in ISO-8601 form. + * Useful for sending time in XML-RPC + * + * @param int unix timestamp + * @param bool + * @return string + */ + public function iso8601_encode($time, $utc = FALSE) { return ($utc) ? strftime('%Y%m%dT%H:%i:%s', $time) : gmstrftime('%Y%m%dT%H:%i:%s', $time); } -} -// END XML_RPC_Values Class +} // END XML_RPC_Values Class /* End of file Xmlrpc.php */ -/* Location: ./system/libraries/Xmlrpc.php */ +/* Location: ./system/libraries/Xmlrpc.php */
\ No newline at end of file diff --git a/system/libraries/Zip.php b/system/libraries/Zip.php index e91e2a2ff..80438546b 100644 --- a/system/libraries/Zip.php +++ b/system/libraries/Zip.php @@ -279,7 +279,7 @@ class CI_Zip { */ public function read_dir($path, $preserve_filepath = TRUE, $root_path = NULL) { - $path = rtrim($path, '/\\').'/'; + $path = rtrim($path, '/\\').DIRECTORY_SEPARATOR; if ( ! $fp = @opendir($path)) { return FALSE; @@ -288,7 +288,7 @@ class CI_Zip { // Set the original directory root for child dir's to use as relative if ($root_path === NULL) { - $root_path = dirname($path).'/'; + $root_path = dirname($path).DIRECTORY_SEPARATOR; } while (FALSE !== ($file = readdir($fp))) @@ -300,11 +300,11 @@ class CI_Zip { if (@is_dir($path.$file)) { - $this->read_dir($path.$file.'/', $preserve_filepath, $root_path); + $this->read_dir($path.$file.DIRECTORY_SEPARATOR, $preserve_filepath, $root_path); } elseif (FALSE !== ($data = file_get_contents($path.$file))) { - $name = str_replace('\\', '/', $path); + $name = str_replace(array('\\', '/'), DIRECTORY_SEPARATOR, $path); if ($preserve_filepath === FALSE) { $name = str_replace($root_path, '', $name); |