diff options
52 files changed, 1399 insertions, 1104 deletions
diff --git a/application/config/config.php b/application/config/config.php index ab1508e7b..6867cee88 100644 --- a/application/config/config.php +++ b/application/config/config.php @@ -62,11 +62,12 @@ $config['index_page'] = 'index.php'; | URI string. The default setting of 'AUTO' works for most servers. | If your links do not seem to work, try one of the other delicious flavors: | -| 'AUTO' Default - auto detects -| 'PATH_INFO' Uses the PATH_INFO -| 'QUERY_STRING' Uses the QUERY_STRING -| 'REQUEST_URI' Uses the REQUEST_URI -| 'ORIG_PATH_INFO' Uses the ORIG_PATH_INFO +| 'AUTO' Default - auto detects +| 'CLI' or 'argv' Uses $_SERVER['argv'] (for php-cli only) +| 'REQUEST_URI' Uses $_SERVER['REQUEST_URI'] +| 'PATH_INFO' Uses $_SERVER['PATH_INFO'] +| 'QUERY_STRING' Uses $_SERVER['QUERY_STRING'] +| 'ORIG_PATH_INFO' Uses $_SERVER['ORIG_PATH_INFO'] | */ $config['uri_protocol'] = 'AUTO'; diff --git a/application/config/routes.php b/application/config/routes.php index 001198615..d1a4419b7 100644 --- a/application/config/routes.php +++ b/application/config/routes.php @@ -59,8 +59,8 @@ | | $route['404_override'] = 'errors/page_missing'; | -| This route will tell the Router what URI segments to use if those provided -| in the URL cannot be matched to a valid route. +| This route will tell the Router which controller/method to use if those +| provided in the URL cannot be matched to a valid route. | */ diff --git a/system/core/Benchmark.php b/system/core/Benchmark.php index 2fabdf46e..f94db2721 100644 --- a/system/core/Benchmark.php +++ b/system/core/Benchmark.php @@ -26,7 +26,7 @@ */ /** - * CodeIgniter Benchmark Class + * Benchmark Class * * This class enables you to mark points and calculate the time difference * between them. Memory consumption can also be displayed. @@ -40,21 +40,19 @@ class CI_Benchmark { /** - * List of all benchmark markers and when they were added + * List of all benchmark markers * - * @var array + * @var array */ - public $marker = array(); - - // -------------------------------------------------------------------- + public $marker = array(); /** * Set a benchmark marker * * Multiple calls to this function can be made so that several - * execution points can be timed + * execution points can be timed. * - * @param string $name name of the marker + * @param string $name Marker name * @return void */ public function mark($name) @@ -65,6 +63,8 @@ class CI_Benchmark { // -------------------------------------------------------------------- /** + * Elapsed time + * * Calculates the time difference between two marked points. * * If the first parameter is empty this function instead returns the @@ -72,10 +72,13 @@ class CI_Benchmark { * execution time to be shown in a template. The output class will * swap the real value for this variable. * - * @param string a particular marked point - * @param string a particular marked point - * @param integer the number of decimal places - * @return mixed + * @param string $point1 A particular marked point + * @param string $point2 A particular marked point + * @param int $decimals Number of decimal places + * + * @return string Calculated elapsed time on success, + * an '{elapsed_string}' if $point1 is empty + * or an empty string if $point1 is not found. */ public function elapsed_time($point1 = '', $point2 = '', $decimals = 4) { @@ -102,12 +105,13 @@ class CI_Benchmark { /** * Memory Usage * - * This function returns the {memory_usage} pseudo-variable. + * Simply returns the {memory_usage} marker. + * * This permits it to be put it anywhere in a template * without the memory being calculated until the end. * The output class will swap the real value for this variable. * - * @return string + * @return string '{memory_usage}' */ public function memory_usage() { diff --git a/system/core/CodeIgniter.php b/system/core/CodeIgniter.php index f3592eaf9..f27086386 100644 --- a/system/core/CodeIgniter.php +++ b/system/core/CodeIgniter.php @@ -130,9 +130,12 @@ $CFG =& load_class('Config', 'core'); // Do we have any manually set config items in the index.php file? - if (isset($assign_to_config)) + if (isset($assign_to_config) && is_array($assign_to_config)) { - $CFG->_assign_to_config($assign_to_config); + foreach ($assign_to_config as $key => $value) + { + $CFG->set_item($key, $value); + } } /* @@ -229,7 +232,6 @@ return CI_Controller::get_instance(); } - if (file_exists(APPPATH.'core/'.$CFG->config['subclass_prefix'].'Controller.php')) { require APPPATH.'core/'.$CFG->config['subclass_prefix'].'Controller.php'; diff --git a/system/core/Config.php b/system/core/Config.php index e78128c76..642cee798 100644 --- a/system/core/Config.php +++ b/system/core/Config.php @@ -26,7 +26,7 @@ */ /** - * CodeIgniter Config Class + * Config Class * * This class contains functions that enable config files to be managed * @@ -41,29 +41,31 @@ class CI_Config { /** * List of all loaded config values * - * @var array + * @var array */ public $config = array(); /** * List of all loaded config files * - * @var array + * @var array */ public $is_loaded = array(); /** * List of paths to search when trying to load a config file. - * This must be public as it's used by the Loader class. * - * @var array + * @used-by CI_Loader + * @var array */ public $_config_paths = array(APPPATH); /** - * Constructor + * Class constructor * - * Sets the $config data from the primary config.php file as a class variable + * Sets the $config data from the primary config.php file as a class variable. + * + * @return void */ public function __construct() { @@ -93,10 +95,10 @@ class CI_Config { /** * Load Config File * - * @param string the config file name - * @param bool if configuration values should be loaded into their own section - * @param bool true if errors should just return false, false if an error message should be displayed - * @return bool if the file was loaded correctly + * @param string $file Configuration file name + * @param bool $use_sections Whether configuration values should be loaded into their own section + * @param bool $fail_gracefully Whether to just return FALSE or display an error message + * @return bool TRUE if the file was loaded correctly or FALSE on failure */ public function load($file = '', $use_sections = FALSE, $fail_gracefully = FALSE) { @@ -183,9 +185,9 @@ class CI_Config { /** * Fetch a config file item * - * @param string the config item name - * @param string the index name - * @return string + * @param string $item Config item name + * @param string $index Index name + * @return string|bool The configuration item or FALSE on failure */ public function item($item, $index = '') { @@ -200,10 +202,10 @@ class CI_Config { // -------------------------------------------------------------------- /** - * Fetch a config file item - adds slash after item (if item is not empty) + * Fetch a config file item with slash appended (if not empty) * - * @param string the config item name - * @return string + * @param string $item Config item name + * @return string|bool The configuration item or FALSE on failure */ public function slash_item($item) { @@ -223,9 +225,12 @@ class CI_Config { /** * Site URL + * * Returns base_url . index_page [. uri_string] * - * @param mixed the URI string or an array of segments + * @uses CI_Config::_uri_string() + * + * @param string|string[] $uri URI string or an array of segments * @return string */ public function site_url($uri = '') @@ -264,9 +269,12 @@ class CI_Config { /** * Base URL + * * Returns base_url [. uri_string] * - * @param string $uri + * @uses CI_Config::_uri_string() + * + * @param string|string[] $uri URI string or an array of segments * @return string */ public function base_url($uri = '') @@ -277,9 +285,12 @@ class CI_Config { // ------------------------------------------------------------- /** - * Build URI string for use in Config::site_url() and Config::base_url() + * Build URI string + * + * @used-by CI_Config::site_url() + * @used-by CI_Config::base_url() * - * @param mixed $uri + * @param string|string[] $uri URI string or an array of segments * @return string */ protected function _uri_string($uri) @@ -318,8 +329,8 @@ class CI_Config { /** * Set a config file item * - * @param string the config item key - * @param string the config item value + * @param string $item Config item key + * @param string $value Config item value * @return void */ public function set_item($item, $value) @@ -327,29 +338,6 @@ class CI_Config { $this->config[$item] = $value; } - // -------------------------------------------------------------------- - - /** - * Assign to Config - * - * This function is called by the front controller (CodeIgniter.php) - * after the Config class is instantiated. It permits config items - * to be assigned or overriden by variables contained in the index.php file - * - * @param array - * @return void - */ - public function _assign_to_config($items = array()) - { - if (is_array($items)) - { - foreach ($items as $key => $val) - { - $this->set_item($key, $val); - } - } - } - } /* End of file Config.php */ diff --git a/system/core/Controller.php b/system/core/Controller.php index 9196958ae..8c2ba893e 100644 --- a/system/core/Controller.php +++ b/system/core/Controller.php @@ -26,7 +26,7 @@ */ /** - * CodeIgniter Application Controller Class + * Application Controller Class * * This class object is the super class that every library in * CodeIgniter will be assigned to. @@ -40,15 +40,14 @@ class CI_Controller { /** - * Reference to the global CI instance + * Reference to the CI singleton * - * @static * @var object */ private static $instance; /** - * Set up controller properties and methods + * Class constructor * * @return void */ @@ -69,8 +68,10 @@ class CI_Controller { log_message('debug', 'Controller Class Initialized'); } + // -------------------------------------------------------------------- + /** - * Return the CI object + * Get the CI singleton * * @static * @return object diff --git a/system/core/Exceptions.php b/system/core/Exceptions.php index bd9178dbd..556257729 100644 --- a/system/core/Exceptions.php +++ b/system/core/Exceptions.php @@ -64,7 +64,7 @@ class CI_Exceptions { ); /** - * Initialize execption class + * Class constructor * * @return void */ @@ -79,12 +79,12 @@ class CI_Exceptions { /** * Exception Logger * - * This function logs PHP generated error messages + * Logs PHP generated error messages * - * @param string the error severity - * @param string the error string - * @param string the error filepath - * @param string the error line number + * @param int $severity Log level + * @param string $message Error message + * @param string $filepath File path + * @param int $line Line number * @return void */ public function log_exception($severity, $message, $filepath, $line) @@ -96,11 +96,13 @@ class CI_Exceptions { // -------------------------------------------------------------------- /** - * 404 Page Not Found Handler + * 404 Error Handler * - * @param string the page - * @param bool log error yes/no - * @return string + * @uses CI_Exceptions::show_error() + * + * @param string $page Page URI + * @param bool $log_error Whether to log the error + * @return void */ public function show_404($page = '', $log_error = TRUE) { @@ -122,15 +124,15 @@ class CI_Exceptions { /** * General Error Page * - * This function takes an error message as input - * (either as a string or an array) and displays - * it using the specified template. + * Takes an error message as input (either as a string or an array) + * and displays it using the specified template. + * + * @param string $heading Page heading + * @param string|string[] $message Error message + * @param string $template Template name + * @param int $status_code (default: 500) * - * @param string the heading - * @param string the message - * @param string the template name - * @param int the status code - * @return string + * @return string Error page output */ public function show_error($heading, $message, $template = 'error_general', $status_code = 500) { @@ -154,11 +156,11 @@ class CI_Exceptions { /** * Native PHP error handler * - * @param string the error severity - * @param string the error string - * @param string the error filepath - * @param string the error line number - * @return string + * @param int $severity Error level + * @param string $message Error message + * @param string $filepath File path + * @param int $line Line number + * @return string Error page output */ public function show_php_error($severity, $message, $filepath, $line) { diff --git a/system/core/Hooks.php b/system/core/Hooks.php index afbf4b453..d60e9ac5d 100644 --- a/system/core/Hooks.php +++ b/system/core/Hooks.php @@ -26,7 +26,7 @@ */ /** - * CodeIgniter Hooks Class + * Hooks Class * * Provides a mechanism to extend the base system without hacking. * @@ -41,26 +41,28 @@ class CI_Hooks { /** * Determines whether hooks are enabled * - * @var bool + * @var bool */ - public $enabled = FALSE; + public $enabled = FALSE; /** * List of all hooks set in config/hooks.php * - * @var array + * @var array */ public $hooks = array(); /** + * In progress flag + * * Determines whether hook is in progress, used to prevent infinte loops * - * @var bool + * @var bool */ - public $in_progress = FALSE; + protected $_in_progress = FALSE; /** - * Initialize the Hooks Preferences + * Class constructor * * @return void */ @@ -104,8 +106,10 @@ class CI_Hooks { * * Calls a particular hook. Called by CodeIgniter.php. * - * @param string the hook name - * @return mixed + * @uses CI_Hooks::_run_hook() + * + * @param string $which Hook name + * @return bool TRUE on success or FALSE on failure */ public function call_hook($which = '') { @@ -136,8 +140,8 @@ class CI_Hooks { * * Runs a particular hook * - * @param array the hook details - * @return bool + * @param array $data Hook details + * @return bool TRUE on success or FALSE on failure */ protected function _run_hook($data) { @@ -152,7 +156,7 @@ class CI_Hooks { // If the script being called happens to have the same // hook call within it a loop can happen - if ($this->in_progress === TRUE) + if ($this->_in_progress === TRUE) { return; } @@ -173,44 +177,20 @@ class CI_Hooks { return FALSE; } - // ----------------------------------- - // Set class/function name - // ----------------------------------- - - $class = FALSE; - $function = FALSE; - $params = ''; - - if ( ! empty($data['class'])) - { - $class = $data['class']; - } - - if ( ! empty($data['function'])) - { - $function = $data['function']; - } - - if (isset($data['params'])) - { - $params = $data['params']; - } + // Determine and class and/or function names + $class = empty($data['class']) ? FALSE : $data['class']; + $function = empty($data['function']) ? FALSE : $data['function']; + $params = isset($data['params']) ? $data['params'] : ''; if ($class === FALSE && $function === FALSE) { return FALSE; } - // ----------------------------------- - // Set the in_progress flag - // ----------------------------------- - - $this->in_progress = TRUE; + // Set the _in_progress flag + $this->_in_progress = TRUE; - // ----------------------------------- // Call the requested class and/or function - // ----------------------------------- - if ($class !== FALSE) { if ( ! class_exists($class)) @@ -218,7 +198,7 @@ class CI_Hooks { require($filepath); } - $HOOK = new $class; + $HOOK = new $class(); $HOOK->$function($params); } else @@ -231,7 +211,7 @@ class CI_Hooks { $function($params); } - $this->in_progress = FALSE; + $this->_in_progress = FALSE; return TRUE; } diff --git a/system/core/Input.php b/system/core/Input.php index ec935d531..f6213c34e 100644 --- a/system/core/Input.php +++ b/system/core/Input.php @@ -41,59 +41,68 @@ class CI_Input { /** * IP address of the current user * - * @var string + * @var string */ - public $ip_address = FALSE; + public $ip_address = FALSE; /** - * user agent (web browser) being used by the current user + * User agent strin * - * @var string + * @var string */ - public $user_agent = FALSE; + public $user_agent = FALSE; /** - * If FALSE, then $_GET will be set to an empty array + * Allow GET array flag * - * @var bool + * If set to FALSE, then $_GET will be set to an empty array. + * + * @var bool */ - protected $_allow_get_array = TRUE; + protected $_allow_get_array = TRUE; /** - * If TRUE, then newlines are standardized + * Standartize new lines flag + * + * If set to TRUE, then newlines are standardized. * - * @var bool + * @var bool */ - protected $_standardize_newlines = TRUE; + protected $_standardize_newlines = TRUE; /** - * Determines whether the XSS filter is always active when GET, POST or COOKIE data is encountered - * Set automatically based on config setting + * Enable XSS flag + * + * Determines whether the XSS filter is always active when + * GET, POST or COOKIE data is encountered. + * Set automatically based on config setting. * - * @var bool + * @var bool */ - protected $_enable_xss = FALSE; + protected $_enable_xss = FALSE; /** + * Enable CSRF flag + * * Enables a CSRF cookie token to be set. - * Set automatically based on config setting + * Set automatically based on config setting. * - * @var bool + * @var bool */ - protected $_enable_csrf = FALSE; + protected $_enable_csrf = FALSE; /** * List of all HTTP request headers * * @var array */ - protected $headers = array(); + protected $headers = array(); /** - * Constructor + * Class constructor * - * Sets whether to globally enable the XSS processing - * and whether to allow the $_GET array + * Determines whether to globally enable the XSS processing + * and whether to allow the $_GET array. * * @return void */ @@ -124,12 +133,12 @@ class CI_Input { /** * Fetch from array * - * This is a helper function to retrieve values from global arrays + * Internal method used to retrieve values from global arrays. * - * @param array - * @param string - * @param bool - * @return string + * @param array &$array $_GET, $_POST, $_COOKIE, $_SERVER, etc. + * @param string $index Index for item to be fetched from $array + * @param bool $xss_clean Whether to apply XSS filtering + * @return mixed */ protected function _fetch_from_array(&$array, $index = '', $xss_clean = FALSE) { @@ -151,9 +160,9 @@ class CI_Input { /** * Fetch an item from the GET array * - * @param string - * @param bool - * @return string + * @param string $index Index for item to be fetched from $_GET + * @param bool $xss_clean Whether to apply XSS filtering + * @return mixed */ public function get($index = NULL, $xss_clean = FALSE) { @@ -178,9 +187,9 @@ class CI_Input { /** * Fetch an item from the POST array * - * @param string - * @param bool - * @return string + * @param string $index Index for item to be fetched from $_POST + * @param bool $xss_clean Whether to apply XSS filtering + * @return mixed */ public function post($index = NULL, $xss_clean = FALSE) { @@ -200,15 +209,14 @@ class CI_Input { return $this->_fetch_from_array($_POST, $index, $xss_clean); } - // -------------------------------------------------------------------- /** - * Fetch an item from either the GET array or the POST + * Fetch an item from POST data with fallback to GET * - * @param string The index key - * @param bool XSS cleaning - * @return string + * @param string $index Index for item to be fetched from $_POST or $_GET + * @param bool $xss_clean Whether to apply XSS filtering + * @return mixed */ public function get_post($index = '', $xss_clean = FALSE) { @@ -222,31 +230,45 @@ class CI_Input { /** * Fetch an item from the COOKIE array * - * @param string - * @param bool - * @return string + * @param string $index Index for item to be fetched from $_COOKIE + * @param bool $xss_clean Whether to apply XSS filtering + * @return mixed */ public function cookie($index = '', $xss_clean = FALSE) { return $this->_fetch_from_array($_COOKIE, $index, $xss_clean); } + // -------------------------------------------------------------------- + + /** + * Fetch an item from the SERVER array + * + * @param string $index Index for item to be fetched from $_SERVER + * @param bool $xss_clean Whether to apply XSS filtering + * @return mixed + */ + public function server($index = '', $xss_clean = FALSE) + { + return $this->_fetch_from_array($_SERVER, $index, $xss_clean); + } + // ------------------------------------------------------------------------ /** * Set cookie * - * Accepts seven parameters, or you can submit an associative + * Accepts an arbitrary number of parameters (up to 7) or an associative * array in the first parameter containing all the values. * - * @param mixed - * @param string the value of the cookie - * @param string the number of seconds until expiration - * @param string the cookie domain. Usually: .yourdomain.com - * @param string the cookie path - * @param string the cookie prefix - * @param bool true makes the cookie secure - * @param bool true makes the cookie accessible via http(s) only (no javascript) + * @param string|mixed[] $name Cookie name or an array containing parameters + * @param string $value Cookie value + * @param int $expire Cookie expiration time in seconds + * @param string $domain Cookie domain (e.g.: '.yourdomain.com') + * @param string $path Cookie path (default: '/') + * @param string $prefix Cookie name prefix + * @param bool $secure Whether to only transfer cookies via SSL + * @param bool $httponly Whether to only makes the cookie accessible via HTTP (no javascript) * @return void */ public function set_cookie($name = '', $value = '', $expire = '', $domain = '', $path = '/', $prefix = '', $secure = FALSE, $httponly = FALSE) @@ -303,23 +325,11 @@ class CI_Input { // -------------------------------------------------------------------- /** - * Fetch an item from the SERVER array - * - * @param string - * @param bool - * @return string - */ - public function server($index = '', $xss_clean = FALSE) - { - return $this->_fetch_from_array($_SERVER, $index, $xss_clean); - } - - // -------------------------------------------------------------------- - - /** * Fetch the IP Address * - * @return string + * Determines and validates the visitor's IP address. + * + * @return string IP address */ public function ip_address() { @@ -458,8 +468,8 @@ class CI_Input { /** * Validate IP Address * - * @param string - * @param string 'ipv4' or 'ipv6' + * @param string $ip IP address + * @param string $which IP protocol: 'ipv4' or 'ipv6' * @return bool */ public function valid_ip($ip, $which = '') @@ -483,9 +493,9 @@ class CI_Input { // -------------------------------------------------------------------- /** - * User Agent + * Fetch User Agent string * - * @return string + * @return string|null User Agent string or NULL if it doesn't exist */ public function user_agent() { @@ -494,7 +504,7 @@ class CI_Input { return $this->user_agent; } - return $this->user_agent = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : FALSE; + return $this->user_agent = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : NULL; } // -------------------------------------------------------------------- @@ -502,11 +512,12 @@ class CI_Input { /** * Sanitize Globals * - * This function does the following: + * Internal method serving for the following purposes: * - * - Unsets $_GET data (if query strings are not enabled) - * - Unsets all globals if register_globals is enabled - * - Standardizes newline characters to \n + * - Unsets $_GET data (if query strings are not enabled) + * - Unsets all globals if register_globals is enabled + * - Cleans POST, COOKIE and SERVER data + * - Standardizes newline characters to PHP_EOL * * @return void */ @@ -534,25 +545,29 @@ class CI_Input { 'IN' ); - // Unset globals for securiy. + // Unset globals for security. // This is effectively the same as register_globals = off - foreach (array($_GET, $_POST, $_COOKIE) as $global) + // PHP 5.4 no longer has the register_globals functionality. + if ( ! is_php('5.4')) { - if (is_array($global)) + foreach (array($_GET, $_POST, $_COOKIE) as $global) { - foreach ($global as $key => $val) + if (is_array($global)) { - if ( ! in_array($key, $protected)) + foreach ($global as $key => $val) { - global $$key; - $$key = NULL; + if ( ! in_array($key, $protected)) + { + global $$key; + $$key = NULL; + } } } - } - elseif ( ! in_array($global, $protected)) - { - global $$global; - $$global = NULL; + elseif ( ! in_array($global, $protected)) + { + global $$global; + $$global = NULL; + } } } @@ -613,10 +628,10 @@ class CI_Input { /** * Clean Input Data * - * This is a helper function. It escapes data and - * standardizes newline characters to \n + * Internal method that aids in escaping data and + * standardizing newline characters to PHP_EOL. * - * @param string + * @param string|string[] $str Input string(s) * @return string */ protected function _clean_input_data($str) @@ -624,9 +639,9 @@ class CI_Input { if (is_array($str)) { $new_array = array(); - foreach ($str as $key => $val) + foreach (array_keys($str) as $key) { - $new_array[$this->_clean_input_keys($key)] = $this->_clean_input_data($val); + $new_array[$this->_clean_input_keys($key)] = $this->_clean_input_data($str[$key]); } return $new_array; } @@ -670,11 +685,11 @@ class CI_Input { /** * Clean Keys * - * This is a helper function. To prevent malicious users + * Internal method that helps to prevent malicious users * from trying to exploit keys we make sure that keys are * only named with alpha-numeric text and a few other items. * - * @param string + * @param string $str Input string * @return string */ protected function _clean_input_keys($str) @@ -699,15 +714,12 @@ class CI_Input { /** * Request Headers * - * In Apache, you can simply call apache_request_headers(), however for - * people running other webservers the function is undefined. - * - * @param bool XSS cleaning + * @param bool $xss_clean Whether to apply XSS filtering * @return array */ public function request_headers($xss_clean = FALSE) { - // Look at Apache go! + // In Apache, you can simply call apache_request_headers() if (function_exists('apache_request_headers')) { $headers = apache_request_headers(); @@ -744,9 +756,9 @@ class CI_Input { * * Returns the value of a single member of the headers class member * - * @param string array key for $this->headers - * @param bool XSS Clean or not - * @return mixed FALSE on failure, string on success + * @param string $index Header name + * @param bool $xss_clean Whether to apply XSS filtering + * @return string|bool The requested header on success or FALSE on failure */ public function get_request_header($index, $xss_clean = FALSE) { @@ -768,9 +780,9 @@ class CI_Input { // -------------------------------------------------------------------- /** - * Is ajax Request? + * Is AJAX request? * - * Test to see if a request contains the HTTP_X_REQUESTED_WITH header + * Test to see if a request contains the HTTP_X_REQUESTED_WITH header. * * @return bool */ @@ -782,9 +794,9 @@ class CI_Input { // -------------------------------------------------------------------- /** - * Is cli Request? + * Is CLI request? * - * Test to see if a request was made from the command line + * Test to see if a request was made from the command line. * * @return bool */ @@ -798,10 +810,11 @@ class CI_Input { /** * Get Request Method * - * Return the Request Method + * Return the request method * - * @param bool uppercase or lowercase - * @return bool + * @param bool $upper Whether to return in upper or lower case + * (default: FALSE) + * @return string */ public function method($upper = FALSE) { diff --git a/system/core/Lang.php b/system/core/Lang.php index 601348aa4..251cf6ef1 100644 --- a/system/core/Lang.php +++ b/system/core/Lang.php @@ -39,19 +39,19 @@ class CI_Lang { /** * List of translations * - * @var array + * @var array */ public $language = array(); /** * List of loaded language files * - * @var array + * @var array */ public $is_loaded = array(); /** - * Initialize language class + * Class constructor * * @return void */ @@ -65,12 +65,13 @@ class CI_Lang { /** * Load a language file * - * @param mixed $langile the name of the language file to be loaded - * @param string $idiom = '' the language (english, etc.) - * @param bool $return = FALSE return loaded array of translations - * @param bool $add_suffix = TRUE add suffix to $langfile - * @param string $alt_path = '' alternative path to look for language file - * @return mixed + * @param mixed $langfile Language file name + * @param string $idiom Language name (english, etc.) + * @param bool $return Whether to return the loaded array of translations + * @param bool $add_suffix Whether to add suffix to $langfile + * @param string $alt_path Alternative path to look for the language file + * + * @return void|string[] Array containing translations, if $return is set to TRUE */ public function load($langfile, $idiom = '', $return = FALSE, $add_suffix = TRUE, $alt_path = '') { @@ -119,7 +120,6 @@ class CI_Lang { } } - if ( ! isset($lang) OR ! is_array($lang)) { log_message('error', 'Language file contains no data: language/'.$idiom.'/'.$langfile); @@ -146,10 +146,12 @@ class CI_Lang { // -------------------------------------------------------------------- /** - * Fetch a single line of text from the language array + * Language line + * + * Fetches a single line of text from the language array * - * @param string $line the language line - * @return string + * @param string $line Language line key + * @return string Translation */ public function line($line = '') { diff --git a/system/core/Loader.php b/system/core/Loader.php index b316c8e1b..db56ab3ae 100644 --- a/system/core/Loader.php +++ b/system/core/Loader.php @@ -28,7 +28,7 @@ /** * Loader Class * - * Loads views and files + * Loads framework components. * * @package CodeIgniter * @subpackage Libraries @@ -42,84 +42,84 @@ class CI_Loader { /** * Nesting level of the output buffering mechanism * - * @var int + * @var int */ protected $_ci_ob_level; /** * List of paths to load views from * - * @var array + * @var array */ protected $_ci_view_paths = array(); /** * List of paths to load libraries from * - * @var array + * @var array */ protected $_ci_library_paths = array(); /** * List of paths to load models from * - * @var array + * @var array */ protected $_ci_model_paths = array(); /** * List of paths to load helpers from * - * @var array + * @var array */ protected $_ci_helper_paths = array(); /** * List of loaded base classes * - * @var array + * @var array */ protected $_base_classes = array(); // Set by the controller class /** * List of cached variables * - * @var array + * @var array */ protected $_ci_cached_vars = array(); /** * List of loaded classes * - * @var array + * @var array */ protected $_ci_classes = array(); /** * List of loaded files * - * @var array + * @var array */ protected $_ci_loaded_files = array(); /** * List of loaded models * - * @var array + * @var array */ protected $_ci_models = array(); /** * List of loaded helpers * - * @var array + * @var array */ protected $_ci_helpers = array(); /** * List of class name mappings * - * @var array + * @var array */ protected $_ci_varmap = array( 'unit_test' => 'unit', @@ -127,9 +127,9 @@ class CI_Loader { ); /** - * Constructor + * Class constructor * - * Sets the path to the view files and gets the initial output buffering level + * Sets component load paths gets the initial output buffering level. * * @return void */ @@ -149,9 +149,9 @@ class CI_Loader { /** * Initialize the Loader * - * This method is called once in CI_Controller. - * - * @return object + * @used-by CI_Controller + * @uses CI_Loader::_ci_autoloader() + * @return object $this */ public function initialize() { @@ -169,14 +169,12 @@ class CI_Loader { /** * Is Loaded * - * A utility function to test if a class is in the self::$_ci_classes array. - * This function returns the object name if the class tested for is loaded, - * and returns FALSE if it isn't. + * A utility method to test if a class is in the self::$_ci_classes array. * - * It is mainly used in the form_helper -> _get_validation_object() + * @used-by Mainly used by Form Helper function _get_validation_object(). * - * @param string class being checked for - * @return mixed class object name on the CI SuperObject or FALSE + * @param string $class Class name to check for + * @return string|bool Class object name if loaded or FALSE */ public function is_loaded($class) { @@ -186,14 +184,14 @@ class CI_Loader { // -------------------------------------------------------------------- /** - * Class Loader + * Library Loader * - * This function lets users load and instantiate classes. - * It is designed to be called from a user's app controllers. + * Loads and instantiates libraries. + * Designed to be called from application controllers. * - * @param string the name of the class - * @param mixed the optional parameters - * @param string an optional object name + * @param string $library Library name + * @param array $params Optional parameters to pass to the library class constructor + * @param string $object_name An optional object name to assign to * @return void */ public function library($library = '', $params = NULL, $object_name = NULL) @@ -210,7 +208,7 @@ class CI_Loader { if ($library === '' OR isset($this->_base_classes[$library])) { - return FALSE; + return; } if ( ! is_null($params) && ! is_array($params)) @@ -226,16 +224,20 @@ class CI_Loader { /** * Model Loader * - * This function lets users load and instantiate models. + * Loads and instantiates libraries. * - * @param string the name of the class - * @param string name for the model - * @param bool database connection + * @param string $model Model name + * @param string $name An optional object name to assign to + * @param bool $db_conn An optional database connection configuration to initialize * @return void */ public function model($model, $name = '', $db_conn = FALSE) { - if (is_array($model)) + if (empty($model)) + { + return; + } + elseif (is_array($model)) { foreach ($model as $class) { @@ -244,11 +246,6 @@ class CI_Loader { return; } - if ($model === '') - { - return; - } - $path = ''; // Is the model in a sub-folder? If so, parse out the filename and path. @@ -318,10 +315,13 @@ class CI_Loader { /** * Database Loader * - * @param mixed $params = '' the DB settings - * @param bool $return = FALSE whether to return the DB object - * @param bool $query_builder = NULL whether to enable query builder (overrides the config setting) - * @return object + * @param mixed $params Database configuration options + * @param bool $return Whether to return the database object + * @param bool $query_builder Whether to enable Query Builder + * (overrides the configuration setting) + * + * @return void|object|bool Database object if $return is set to TRUE, + * FALSE on failure, void in any other case */ public function database($params = '', $return = FALSE, $query_builder = NULL) { @@ -352,9 +352,9 @@ class CI_Loader { // -------------------------------------------------------------------- /** - * Load the Utilities Class + * Load the Database Utilities Class * - * @return string + * @return void */ public function dbutil() { @@ -381,7 +381,7 @@ class CI_Loader { /** * Load the Database Forge Class * - * @return string + * @return void */ public function dbforge() { @@ -402,19 +402,15 @@ class CI_Loader { // -------------------------------------------------------------------- /** - * Load View - * - * This function is used to load a "view" file. It has three parameters: + * View Loader * - * 1. The name of the "view" file to be included. - * 2. An associative array of data to be extracted for use in the view. - * 3. TRUE/FALSE - whether to return the data or load it. In - * some cases it's advantageous to be able to return data so that - * a developer can process it in some way. + * Loads "view" files. * - * @param string - * @param array - * @param bool + * @param string $view View name + * @param array $vars An associative array of data + * to be extracted for use in the view + * @param bool $return Whether to return the view output + * or leave it to the Output class * @return void */ public function view($view, $vars = array(), $return = FALSE) @@ -425,13 +421,11 @@ class CI_Loader { // -------------------------------------------------------------------- /** - * Load File - * - * This is a generic file loader + * Generic File Loader * - * @param string - * @param bool - * @return string + * @param string $path File path + * @param bool $return Whether to return the file output + * @return void|string */ public function file($path, $return = FALSE) { @@ -446,8 +440,10 @@ class CI_Loader { * Once variables are set they become available within * the controller class and its "view" files. * - * @param array - * @param string + * @param array|object|string $vars + * An associative array or object containing values + * to be set, or a value's name if string + * @param string $val Value to set, only used if $vars is a string * @return void */ public function vars($vars = array(), $val = '') @@ -475,8 +471,8 @@ class CI_Loader { * * Check if a variable is set and retrieve it. * - * @param array - * @return void + * @param string $key Variable name + * @return mixed The variable or NULL if not found */ public function get_var($key) { @@ -488,7 +484,7 @@ class CI_Loader { /** * Get Variables * - * Retrieve all loaded variables + * Retrieves all loaded variables. * * @return array */ @@ -500,11 +496,9 @@ class CI_Loader { // -------------------------------------------------------------------- /** - * Load Helper - * - * This function loads the specified helper file. + * Helper Loader * - * @param mixed + * @param string|string[] $helpers Helper name(s) * @return void */ public function helper($helpers = array()) @@ -562,10 +556,11 @@ class CI_Loader { /** * Load Helpers * - * This is simply an alias to the above function in case the - * user has written the plural form of this function. + * An alias for the helper() method in case the developer has + * written the plural form of it. * - * @param array + * @uses CI_Loader::helper() + * @param string|string[] $helpers Helper name(s) * @return void */ public function helpers($helpers = array()) @@ -576,22 +571,21 @@ class CI_Loader { // -------------------------------------------------------------------- /** - * Loads a language file + * Language Loader * - * @param array - * @param string + * Loads language files. + * + * @param string|string[] $files List of language file names to load + * @param string Language name * @return void */ - public function language($file = array(), $lang = '') + public function language($files = array(), $lang = '') { $CI =& get_instance(); - if ( ! is_array($file)) - { - $file = array($file); - } + is_array($files) OR $files = array($files); - foreach ($file as $langfile) + foreach ($files as $langfile) { $CI->lang->load($langfile, $lang); } @@ -600,30 +594,35 @@ class CI_Loader { // -------------------------------------------------------------------- /** - * Loads a config file + * Config Loader * - * @param string - * @param bool - * @param bool - * @return void + * Loads a config file (an alias for CI_Config::load()). + * + * @uses CI_Config::load() + * @param string $file Configuration file name + * @param bool $use_sections Whether configuration values should be loaded into their own section + * @param bool $fail_gracefully Whether to just return FALSE or display an error message + * @return bool TRUE if the file was loaded correctly or FALSE on failure */ public function config($file = '', $use_sections = FALSE, $fail_gracefully = FALSE) { $CI =& get_instance(); - $CI->config->load($file, $use_sections, $fail_gracefully); + return $CI->config->load($file, $use_sections, $fail_gracefully); } // -------------------------------------------------------------------- /** - * Driver + * Driver Loader * - * Loads a driver library + * Loads a driver library. * - * @param mixed the name of the class or array of classes - * @param mixed the optional parameters - * @param string an optional object name - * @return void + * @param string|string[] $library Driver name(s) + * @param array $params Optional parameters to pass to the driver + * @param string $object_name An optional object name to assign to + * + * @return void|object|bool Object or FALSE on failure if $library is a string + * and $object_name is set. void otherwise. */ public function driver($library = '', $params = NULL, $object_name = NULL) { @@ -656,10 +655,16 @@ class CI_Loader { /** * Add Package Path * - * Prepends a parent path to the library, model, helper, and config path arrays + * Prepends a parent path to the library, model, helper and config + * path arrays. + * + * @see CI_Loader::$_ci_library_paths + * @see CI_Loader::$_ci_model_paths + * @see CI_Loader::$_ci_helper_paths + * @see CI_Config::$_config_paths * - * @param string - * @param bool + * @param string $path Path to add + * @param bool $view_cascade (default: TRUE) * @return void */ public function add_package_path($path, $view_cascade = TRUE) @@ -682,10 +687,10 @@ class CI_Loader { /** * Get Package Paths * - * Return a list of all package paths, by default it will ignore BASEPATH. + * Return a list of all package paths. * - * @param string - * @return void + * @param bool $include_base Whether to include BASEPATH (default: TRUE) + * @return array */ public function get_package_paths($include_base = FALSE) { @@ -697,14 +702,14 @@ class CI_Loader { /** * Remove Package Path * - * Remove a path from the library, model, and helper path arrays if it exists - * If no path is provided, the most recently added path is removed. + * Remove a path from the library, model, helper and/or config + * path arrays if it exists. If no path is provided, the most recently + * added path will be removed removed. * - * @param string - * @param bool + * @param string $path Path to remove * @return void */ - public function remove_package_path($path = '', $remove_config_path = TRUE) + public function remove_package_path($path = '') { $config =& $this->_ci_get_component('config'); @@ -749,13 +754,16 @@ class CI_Loader { // -------------------------------------------------------------------- /** - * Loader + * Internal CI Data Loader + * + * Used to load views and files. * - * This function is used to load views and files. * Variables are prefixed with _ci_ to avoid symbol collision with - * variables made available to view files + * variables made available to view files. * - * @param array + * @used-by CI_Loader::view() + * @used-by CI_Loader::file() + * @param array $_ci_data Data to load * @return void */ protected function _ci_load($_ci_data) @@ -883,13 +891,14 @@ class CI_Loader { // -------------------------------------------------------------------- /** - * Load class + * Internal CI Class Loader * - * This function loads the requested class. + * @used-by CI_Loader::library() + * @uses CI_Loader::_ci_init_class() * - * @param string the item that is being loaded - * @param mixed any additional parameters - * @param string an optional object name + * @param string $class Class name to load + * @param mixed $params Optional parameters to pass to the class constructor + * @param string $object_name Optional object name to assign to * @return void */ protected function _ci_load_class($class, $params = NULL, $object_name = NULL) @@ -1024,12 +1033,17 @@ class CI_Loader { // -------------------------------------------------------------------- /** - * Instantiates a class + * Internal CI Class Instantiator + * + * @used-by CI_Loader::_ci_load_class() * - * @param string - * @param string - * @param bool - * @param string an optional object name + * @param string $class Class name + * @param string $prefix Class name prefix + * @param array|null|bool $config Optional configuration to pass to the class constructor: + * FALSE to skip; + * NULL to search in config paths; + * array containing configuration data + * @param string $object_name Optional object name to assign to * @return void */ protected function _ci_init_class($class, $prefix = '', $config = FALSE, $object_name = NULL) @@ -1131,11 +1145,11 @@ class CI_Loader { // -------------------------------------------------------------------- /** - * Autoloader + * CI Autoloader * - * The config/autoload.php file contains an array that permits sub-systems, - * libraries, and helpers to be loaded automatically. + * Loads component listed in the config/autoload.php file. * + * @used-by CI_Loader::initialize() * @return void */ protected function _ci_autoloader() @@ -1218,11 +1232,12 @@ class CI_Loader { // -------------------------------------------------------------------- /** - * Object to Array + * CI Object to Array translator * - * Takes an object as input and converts the class variables to array key/vals + * Takes an object as input and converts the class variables to + * an associative array with key/value pairs. * - * @param object + * @param object $object Object data to translate * @return array */ protected function _ci_object_to_array($object) @@ -1233,9 +1248,11 @@ class CI_Loader { // -------------------------------------------------------------------- /** - * Get a reference to a specific library or model + * CI Component getter + * + * Get a reference to a specific library or model. * - * @param string + * @param string $component Component name * @return bool */ protected function &_ci_get_component($component) @@ -1249,10 +1266,11 @@ class CI_Loader { /** * Prep filename * - * This function preps the name of various items to make loading them more reliable. + * This function prepares filenames of various items to + * make their loading more reliable. * - * @param mixed - * @param string + * @param string|string[] $filename Filename(s) + * @param string $extension Filename extension * @return array */ protected function _ci_prep_filename($filename, $extension) diff --git a/system/core/Model.php b/system/core/Model.php index 9bc9f879f..5a87ab153 100644 --- a/system/core/Model.php +++ b/system/core/Model.php @@ -26,7 +26,7 @@ */ /** - * CodeIgniter Model Class + * Model Class * * @package CodeIgniter * @subpackage Libraries @@ -37,7 +37,7 @@ class CI_Model { /** - * Initialize CI_Model Class + * Class constructor * * @return void */ @@ -46,13 +46,15 @@ class CI_Model { log_message('debug', 'Model Class Initialized'); } + // -------------------------------------------------------------------- + /** - * __get + * __get magic * * Allows models to access CI's loaded classes using the same * syntax as controllers. * - * @param string + * @param string $key */ public function __get($key) { diff --git a/system/core/Output.php b/system/core/Output.php index aa0e05dc4..3bb8f8dc0 100644 --- a/system/core/Output.php +++ b/system/core/Output.php @@ -28,7 +28,7 @@ /** * Output Class * - * Responsible for sending final output to browser + * Responsible for sending final output to the browser. * * @package CodeIgniter * @subpackage Libraries @@ -39,70 +39,74 @@ class CI_Output { /** - * Current output string + * Final output string * - * @var string + * @var string */ public $final_output; /** * Cache expiration time * - * @var int + * @var int */ - public $cache_expiration = 0; + public $cache_expiration = 0; /** * List of server headers * - * @var array + * @var array */ public $headers = array(); /** * List of mime types * - * @var array + * @var array */ public $mimes = array(); /** * Mime-type for the current page * - * @var string + * @var string */ - protected $mime_type = 'text/html'; + protected $mime_type = 'text/html'; /** - * Determines whether profiler is enabled + * Enable Profiler flag * - * @var book + * @var bool */ - public $enable_profiler = FALSE; + public $enable_profiler = FALSE; /** - * Determines if output compression is enabled + * zLib output compression flag * - * @var bool + * @var bool */ protected $_zlib_oc = FALSE; /** * List of profiler sections * - * @var array + * @var array */ protected $_profiler_sections = array(); /** - * Whether or not to parse variables like {elapsed_time} and {memory_usage} + * Parse markers flag * - * @var bool + * Whether or not to parse variables like {elapsed_time} and {memory_usage}. + * + * @var bool */ public $parse_exec_vars = TRUE; /** - * Set up Output class + * Class constructor + * + * Determines whether zLib output compression will be used. * * @return void */ @@ -121,7 +125,7 @@ class CI_Output { /** * Get Output * - * Returns the current output string + * Returns the current output string. * * @return string */ @@ -135,10 +139,10 @@ class CI_Output { /** * Set Output * - * Sets the output string + * Sets the output string. * - * @param string - * @return void + * @param string $output Output data + * @return object $this */ public function set_output($output) { @@ -151,14 +155,14 @@ class CI_Output { /** * Append Output * - * Appends data onto the output string + * Appends data onto the output string. * - * @param string - * @return void + * @param string $output Data to append + * @return object $this */ public function append_output($output) { - if ($this->final_output == '') + if (empty($this->final_output)) { $this->final_output = $output; } @@ -175,14 +179,14 @@ class CI_Output { /** * Set Header * - * Lets you set a server header which will be outputted with the final display. + * Lets you set a server header which will be sent with the final output. * - * Note: If a file is cached, headers will not be sent. We need to figure out - * how to permit header data to be saved with the cache data... + * Note: If a file is cached, headers will not be sent. + * @todo We need to figure out how to permit headers to be cached. * - * @param string - * @param bool - * @return void + * @param string $header Header + * @param bool $replace Whether to replace the old header value, if already set + * @return object $this */ public function set_header($header, $replace = TRUE) { @@ -192,7 +196,7 @@ class CI_Output { // We'll just skip content-length in those cases. if ($this->_zlib_oc && strncasecmp($header, 'content-length', 14) === 0) { - return; + return $this; } $this->headers[] = array($header, $replace); @@ -202,11 +206,11 @@ class CI_Output { // -------------------------------------------------------------------- /** - * Set Content Type Header + * Set Content-Type Header * - * @param string $mime_type extension of the file we're outputting - * @param string $charset = NULL - * @return void + * @param string $mime_type Extension of the file we're outputting + * @param string $charset Character set (default: NULL) + * @return object $this */ public function set_content_type($mime_type, $charset = NULL) { @@ -243,7 +247,7 @@ class CI_Output { // -------------------------------------------------------------------- /** - * Get Current Content Type Header + * Get Current Content-Type Header * * @return string 'text/html', if not already set */ @@ -264,11 +268,13 @@ class CI_Output { /** * Set HTTP Status Header - * moved to Common procedural functions in 1.7.2 * - * @param int the status code - * @param string - * @return void + * As of version 1.7.2, this is an alias for common function + * set_status_header(). + * + * @param int $code Status code (default: 200) + * @param string $text Optional message + * @return object $this */ public function set_status_header($code = 200, $text = '') { @@ -281,8 +287,8 @@ class CI_Output { /** * Enable/disable Profiler * - * @param bool - * @return void + * @param bool $val TRUE to enable or FALSE to disable + * @return object $this */ public function enable_profiler($val = TRUE) { @@ -295,10 +301,11 @@ class CI_Output { /** * Set Profiler Sections * - * Allows override of default / config settings for Profiler section display + * Allows override of default/config settings for + * Profiler section display. * - * @param array - * @return void + * @param array $sections Profiler sections + * @return object $this */ public function set_profiler_sections($sections) { @@ -321,8 +328,8 @@ class CI_Output { /** * Set Cache * - * @param int - * @return void + * @param int $time Cache expiration time in seconds + * @return object $this */ public function cache($time) { @@ -335,16 +342,16 @@ class CI_Output { /** * Display Output * - * All "view" data is automatically put into this variable by the controller class: - * - * $this->final_output + * Processes sends the sends finalized output data to the browser along + * with any server headers and profile data. It also stops benchmark + * timers so the page rendering speed and memory usage can be shown. * - * This function sends the finalized output data to the browser along - * with any server headers and profile data. It also stops the - * benchmark timer so the page rendering speed and memory usage can be shown. + * Note: All "view" data is automatically put into $this->final_output + * by controller class. * - * @param string - * @return mixed + * @uses CI_Output::$final_output + * @param string $output Output data override + * @return void */ public function _display($output = '') { @@ -375,10 +382,9 @@ class CI_Output { $output = $this->minify($output, $this->mime_type); } - // -------------------------------------------------------------------- - // Do we need to write a cache file? Only if the controller does not have its + // Do we need to write a cache file? Only if the controller does not have its // own _output() method and we are not dealing with a cache file, which we // can determine by the existence of the $CI object above if ($this->cache_expiration > 0 && isset($CI) && ! method_exists($CI, '_output')) @@ -431,7 +437,7 @@ class CI_Output { echo $output; log_message('debug', 'Final output sent to browser'); log_message('debug', 'Total execution time: '.$elapsed); - return TRUE; + return; } // -------------------------------------------------------------------- @@ -473,9 +479,9 @@ class CI_Output { // -------------------------------------------------------------------- /** - * Write a Cache File + * Write Cache * - * @param string + * @param string $output Output data to cache * @return void */ public function _write_cache($output) @@ -526,11 +532,14 @@ class CI_Output { // -------------------------------------------------------------------- /** - * Update/serve a cached file + * Update/serve cached output + * + * @uses CI_Config + * @uses CI_URI * - * @param object config class - * @param object uri class - * @return bool + * @param object &$CFG CI_Config class instance + * @param object &$URI CI_URI class instance + * @return bool TRUE on success or FALSE on failure */ public function _display_cache(&$CFG, &$URI) { @@ -584,11 +593,13 @@ class CI_Output { // -------------------------------------------------------------------- /** + * Set Cache Header + * * Set the HTTP headers to match the server-side file cache settings * in order to reduce bandwidth. * - * @param int timestamp of when the page was last modified - * @param int timestamp of when should the requested page expire from cache + * @param int $last_modified Timestamp of when the page was last modified + * @param int $expiration Timestamp of when should the requested page expire from cache * @return void */ public function set_cache_header($last_modified, $expiration) @@ -612,11 +623,13 @@ class CI_Output { // -------------------------------------------------------------------- /** - * Reduce excessive size of HTML content. + * Minify * - * @param string - * @param string - * @return string + * Reduce excessive size of HTML/CSS/JavaScript content. + * + * @param string $output Output to minify + * @param string $type Output content MIME type + * @return string Minified output */ public function minify($output, $type = 'text/html') { diff --git a/system/core/Router.php b/system/core/Router.php index e8addf962..529cbb7c8 100644 --- a/system/core/Router.php +++ b/system/core/Router.php @@ -39,56 +39,56 @@ class CI_Router { /** - * Config class + * CI_Config class object * - * @var object + * @var object */ public $config; /** * List of routes * - * @var array + * @var array */ public $routes = array(); /** * List of error routes * - * @var array + * @var array */ public $error_routes = array(); /** * Current class name * - * @var string + * @var string */ public $class = ''; /** * Current method name * - * @var string + * @var string */ public $method = 'index'; /** * Sub-directory that contains the requested controller class * - * @var string + * @var string */ public $directory = ''; /** * Default controller (and method if specific) * - * @var string + * @var string */ public $default_controller; /** - * Constructor + * Class constructor * * Runs the route mapping function. * @@ -104,9 +104,9 @@ class CI_Router { // -------------------------------------------------------------------- /** - * Set the route mapping + * Set route mapping * - * This function determines what should be served based on the URI request, + * Determines what should be served based on the URI request, * as well as any "routes" that have been set in the routing config file. * * @return void @@ -179,7 +179,7 @@ class CI_Router { // -------------------------------------------------------------------- /** - * Set the default controller + * Set default controller * * @return void */ @@ -213,12 +213,12 @@ class CI_Router { // -------------------------------------------------------------------- /** - * Set the Route + * Set request route * - * This function takes an array of URI segments as - * input, and sets the current class/method + * Takes an array of URI segments as input and sets the class/method + * to be called. * - * @param array + * @param array $segments URI segments * @return void */ protected function _set_request($segments = array()) @@ -253,11 +253,12 @@ class CI_Router { // -------------------------------------------------------------------- /** - * Validates the supplied segments. - * Attempts to determine the path to the controller. + * Validate request * - * @param array - * @return array + * Attempts validate the URI request and determine the controller path. + * + * @param array $segments URI segments + * @return array URI segments */ protected function _validate_request($segments) { @@ -347,9 +348,8 @@ class CI_Router { /** * Parse Routes * - * This function matches any routes that may exist in - * the config/routes.php file against the URI to - * determine if the class/method need to be remapped. + * Matches any routes that may exist in the config/routes.php file + * against the URI to determine if the class/method need to be remapped. * * @return void */ @@ -368,7 +368,7 @@ class CI_Router { foreach ($this->routes as $key => $val) { // Convert wild-cards to RegEx - $key = str_replace(array(':any', ':num'), array('.+', '[0-9]+'), $key); + $key = str_replace(array(':any', ':num'), array('[^/]+', '[0-9]+'), $key); // Does the RegEx match? if (preg_match('#^'.$key.'$#', $uri, $matches)) @@ -429,9 +429,9 @@ class CI_Router { // -------------------------------------------------------------------- /** - * Set the class name + * Set class name * - * @param string + * @param string $class Class name * @return void */ public function set_class($class) @@ -454,9 +454,9 @@ class CI_Router { // -------------------------------------------------------------------- /** - * Set the method name + * Set method name * - * @param string + * @param string $method Method name * @return void */ public function set_method($method) @@ -479,9 +479,9 @@ class CI_Router { // -------------------------------------------------------------------- /** - * Set the directory name + * Set directory name * - * @param string + * @param string $dir Directory name * @return void */ public function set_directory($dir) @@ -492,7 +492,10 @@ class CI_Router { // -------------------------------------------------------------------- /** - * Fetch the sub-directory (if any) that contains the requested controller class + * Fetch directory + * + * Feches the sub-directory (if any) that contains the requested + * controller class. * * @return string */ @@ -504,9 +507,9 @@ class CI_Router { // -------------------------------------------------------------------- /** - * Set the controller overrides + * Set controller overrides * - * @param array + * @param array $routing Route overrides * @return void */ public function _set_overrides($routing) diff --git a/system/core/Security.php b/system/core/Security.php index d7c82712d..50d0ce052 100644 --- a/system/core/Security.php +++ b/system/core/Security.php @@ -37,45 +37,55 @@ class CI_Security { /** - * Random Hash for protecting URLs + * XSS Hash * - * @var string + * Random Hash for protecting URLs. + * + * @var string */ protected $_xss_hash = ''; /** - * Random Hash for Cross Site Request Forgery Protection Cookie + * CSRF Hash + * + * Random hash for Cross Site Request Forgery protection cookie * - * @var string + * @var string */ protected $_csrf_hash = ''; /** - * Expiration time for Cross Site Request Forgery Protection Cookie - * Defaults to two hours (in seconds) + * CSRF Expire time + * + * Expiration time for Cross Site Request Forgery protection cookie. + * Defaults to two hours (in seconds). * - * @var int + * @var int */ protected $_csrf_expire = 7200; /** - * Token name for Cross Site Request Forgery Protection Cookie + * CSRF Token name * - * @var string + * Token name for Cross Site Request Forgery protection cookie. + * + * @var string */ protected $_csrf_token_name = 'ci_csrf_token'; /** - * Cookie name for Cross Site Request Forgery Protection Cookie + * CSRF Cookie name + * + * Cookie name for Cross Site Request Forgery protection cookie. * - * @var string + * @var string */ protected $_csrf_cookie_name = 'ci_csrf_token'; /** * List of never allowed strings * - * @var array + * @var array */ protected $_never_allowed_str = array( 'document.cookie' => '[removed]', @@ -91,9 +101,9 @@ class CI_Security { ); /** - * List of never allowed regex replacement + * List of never allowed regex replacements * - * @var array + * @var array */ protected $_never_allowed_regex = array( 'javascript\s*:', @@ -104,7 +114,7 @@ class CI_Security { ); /** - * Initialize security class + * Class constructor * * @return void */ @@ -138,7 +148,7 @@ class CI_Security { // -------------------------------------------------------------------- /** - * Verify Cross Site Request Forgery Protection + * CSRF Verify * * @return object */ @@ -188,10 +198,10 @@ class CI_Security { // -------------------------------------------------------------------- /** - * Set Cross Site Request Forgery Protection Cookie + * CSRF Set Cookie * - * @return object * @codeCoverageIgnore + * @return object */ public function csrf_set_cookie() { @@ -234,9 +244,8 @@ class CI_Security { /** * Get CSRF Hash * - * Getter Method - * - * @return string self::_csrf_hash + * @see CI_Security::$_csrf_hash + * @return string CSRF hash */ public function get_csrf_hash() { @@ -248,9 +257,8 @@ class CI_Security { /** * Get CSRF Token Name * - * Getter Method - * - * @return string self::_csrf_token_name + * @see CI_Security::$_csrf_token_name + * @return string CSRF token name */ public function get_csrf_token_name() { @@ -263,26 +271,26 @@ class CI_Security { * XSS Clean * * Sanitizes data so that Cross Site Scripting Hacks can be - * prevented. This function does a fair amount of work but + * prevented. This method does a fair amount of work but * it is extremely thorough, designed to prevent even the * most obscure XSS attempts. Nothing is ever 100% foolproof, * of course, but I haven't been able to get anything passed * the filter. * - * Note: This function should only be used to deal with data - * upon submission. It's not something that should - * be used for general runtime processing. + * Note: Should only be used to deal with data upon submission. + * It's not something that should be used for general + * runtime processing. * - * This function was based in part on some code and ideas I - * got from Bitflux: http://channel.bitflux.ch/wiki/XSS_Prevention + * @link http://channel.bitflux.ch/wiki/XSS_Prevention + * Based in part on some code and ideas from Bitflux. * - * To help develop this script I used this great list of - * vulnerabilities along with a few other hacks I've - * harvested from examining vulnerabilities in other programs: - * http://ha.ckers.org/xss.html + * @link http://ha.ckers.org/xss.html + * To help develop this script I used this great list of + * vulnerabilities along with a few other hacks I've + * harvested from examining vulnerabilities in other programs. * - * @param mixed string or array - * @param bool + * @param string|string[] $str Input data + * @param bool $is_image Whether the input is an image * @return string */ public function xss_clean($str, $is_image = FALSE) @@ -469,9 +477,12 @@ class CI_Security { // -------------------------------------------------------------------- /** - * Random Hash for protecting URLs + * XSS Hash * - * @return string + * Generates the XSS hash if needed and returns it. + * + * @see CI_Security::$_xss_hash + * @return string XSS hash */ public function xss_hash() { @@ -489,7 +500,7 @@ class CI_Security { /** * HTML Entities Decode * - * This function is a replacement for html_entity_decode() + * A replacement for html_entity_decode() * * The reason we are not using html_entity_decode() by itself is because * while it is not technically correct to leave out the semicolon @@ -497,8 +508,10 @@ class CI_Security { * correctly. html_entity_decode() does not convert entities without * semicolons, so we are left with our own little solution here. Bummer. * - * @param string - * @param string + * @link http://php.net/html-entity-decode + * + * @param string $str Input + * @param string $charset Character set * @return string */ public function entity_decode($str, $charset = NULL) @@ -521,10 +534,10 @@ class CI_Security { // -------------------------------------------------------------------- /** - * Filename Security + * Sanitize Filename * - * @param string - * @param bool + * @param string $str Input file name + * @param bool $relative_path Whether to preserve paths * @return string */ public function sanitize_filename($str, $relative_path = FALSE) @@ -563,7 +576,7 @@ class CI_Security { /** * Strip Image Tags * - * @param string + * @param string $str * @return string */ public function strip_image_tags($str) @@ -576,10 +589,11 @@ class CI_Security { /** * Compact Exploded Words * - * Callback function for xss_clean() to remove whitespace from - * things like j a v a s c r i p t + * Callback method for xss_clean() to remove whitespace from + * things like 'j a v a s c r i p t'. * - * @param array + * @used-by CI_Security::xss_clean() + * @param array $matches * @return string */ protected function _compact_exploded_words($matches) @@ -593,16 +607,22 @@ class CI_Security { * Remove Evil HTML Attributes (like event handlers and style) * * It removes the evil attribute and either: - * - Everything up until a space - * For example, everything between the pipes: + * + * - Everything up until a space. For example, everything between the pipes: + * + * <code> * <a |style=document.write('hello');alert('world');| class=link> - * - Everything inside the quotes - * For example, everything between the pipes: + * </code> + * + * - Everything inside the quotes. For example, everything between the pipes: + * + * <code> * <a |style="document.write('hello'); alert('world');"| class="link"> + * </code> * - * @param string $str The string to check - * @param boolean $is_image TRUE if this is an image - * @return string The string with the evil attributes removed + * @param string $str The string to check + * @param bool $is_image Whether the input is an image + * @return string The string with the evil attributes removed */ protected function _remove_evil_attributes($str, $is_image) { @@ -655,9 +675,10 @@ class CI_Security { /** * Sanitize Naughty HTML * - * Callback function for xss_clean() to remove naughty HTML elements + * Callback method for xss_clean() to remove naughty HTML elements. * - * @param array + * @used-by CI_Security::xss_clean() + * @param array $matches * @return string */ protected function _sanitize_naughty_html($matches) @@ -672,12 +693,14 @@ class CI_Security { /** * JS Link Removal * - * Callback function for xss_clean() to sanitize links + * Callback method for xss_clean() to sanitize links. + * * This limits the PCRE backtracks, making it more performance friendly * and prevents PREG_BACKTRACK_LIMIT_ERROR from being triggered in - * PHP 5.2+ on link-heavy strings + * PHP 5.2+ on link-heavy strings. * - * @param array + * @used-by CI_Security::xss_clean() + * @param array $match * @return string */ protected function _js_link_removal($match) @@ -695,12 +718,14 @@ class CI_Security { /** * JS Image Removal * - * Callback function for xss_clean() to sanitize image tags + * Callback method for xss_clean() to sanitize image tags. + * * This limits the PCRE backtracks, making it more performance friendly * and prevents PREG_BACKTRACK_LIMIT_ERROR from being triggered in - * PHP 5.2+ on image tag heavy strings + * PHP 5.2+ on image tag heavy strings. * - * @param array + * @used-by CI_Security::xss_clean() + * @param array $match * @return string */ protected function _js_img_removal($match) @@ -718,9 +743,8 @@ class CI_Security { /** * Attribute Conversion * - * Used as a callback for XSS Clean - * - * @param array + * @used-by CI_Security::xss_clean() + * @param array $match * @return string */ protected function _convert_attribute($match) @@ -733,9 +757,11 @@ class CI_Security { /** * Filter Attributes * - * Filters tag attributes for consistency and safety + * Filters tag attributes for consistency and safety. * - * @param string + * @used-by CI_Security::_js_img_removal() + * @used-by CI_Security::_js_link_removal() + * @param string $str * @return string */ protected function _filter_attributes($str) @@ -757,9 +783,8 @@ class CI_Security { /** * HTML Entity Decode Callback * - * Used as a callback for XSS Clean - * - * @param array + * @used-by CI_Security::xss_clean() + * @param array $match * @return string */ protected function _decode_entity($match) @@ -772,9 +797,8 @@ class CI_Security { /** * Validate URL entities * - * Called by xss_clean() - * - * @param string + * @used-by CI_Security::xss_clean() + * @param string $str * @return string */ protected function _validate_entities($str) @@ -812,8 +836,7 @@ class CI_Security { /** * Do Never Allowed * - * A utility function for xss_clean() - * + * @used-by CI_Security::xss_clean() * @param string * @return string */ @@ -832,7 +855,7 @@ class CI_Security { // -------------------------------------------------------------------- /** - * Set Cross Site Request Forgery Protection Cookie + * Set CSRF Hash and Cookie * * @return string */ diff --git a/system/core/URI.php b/system/core/URI.php index 72f293c18..6692d07a6 100644 --- a/system/core/URI.php +++ b/system/core/URI.php @@ -39,36 +39,37 @@ class CI_URI { /** - * List of cached uri segments + * List of cached URI segments * - * @var array + * @var array */ public $keyval = array(); /** - * Current uri string + * Current URI string * - * @var string + * @var string */ public $uri_string; /** - * List of uri segments + * List of URI segments * - * @var array + * @var array */ public $segments = array(); /** - * Re-indexed list of uri segments - * Starts at 1 instead of 0 + * Re-indexed list of URI segments * - * @var array + * Starts at 1 instead of 0. + * + * @var array */ public $rsegments = array(); /** - * Constructor + * Class constructor * * Simply globalizes the $RTR object. The front * loads the Router class early on so it's not available @@ -85,10 +86,9 @@ class CI_URI { // -------------------------------------------------------------------- /** - * Get the URI String - * - * Called by CI_Router + * Fetch URI String * + * @used-by CI_Router * @return void */ public function _fetch_uri_string() @@ -98,12 +98,12 @@ class CI_URI { // Is the request coming from the command line? if ($this->_is_cli_request()) { - $this->_set_uri_string($this->_parse_cli_args()); + $this->_set_uri_string($this->_parse_argv()); return; } // Let's try the REQUEST_URI first, this will work in most situations - if ($uri = $this->_detect_uri()) + if (($uri = $this->_parse_request_uri()) !== '') { $this->_set_uri_string($uri); return; @@ -111,18 +111,17 @@ class CI_URI { // Is there a PATH_INFO variable? // Note: some servers seem to have trouble with getenv() so we'll test it two ways - $path = isset($_SERVER['PATH_INFO']) ? $_SERVER['PATH_INFO'] : @getenv('PATH_INFO'); - if (trim($path, '/') !== '' && $path !== '/'.SELF) + $uri = isset($_SERVER['PATH_INFO']) ? $_SERVER['PATH_INFO'] : @getenv('PATH_INFO'); + if (trim($uri, '/') !== '' && $uri !== '/'.SELF) { $this->_set_uri_string($path); return; } // No PATH_INFO?... What about QUERY_STRING? - $path = isset($_SERVER['QUERY_STRING']) ? $_SERVER['QUERY_STRING'] : @getenv('QUERY_STRING'); - if (trim($path, '/') !== '') + if (($uri = $this->_parse_query_string()) !== '') { - $this->_set_uri_string($path); + $this->_set_uri_string($uri); return; } @@ -140,27 +139,27 @@ class CI_URI { $uri = strtoupper($this->config->item('uri_protocol')); - if ($uri === 'REQUEST_URI') + if ($uri === 'CLI') { - $this->_set_uri_string($this->_detect_uri()); + $this->_set_uri_string($this->_parse_argv()); return; } - elseif ($uri === 'CLI') + elseif (method_exists($this, ($method = '_parse_'.strtolower($uri)))) { - $this->_set_uri_string($this->_parse_cli_args()); + $this->_set_uri_string($this->$method()); return; } - $path = isset($_SERVER[$uri]) ? $_SERVER[$uri] : @getenv($uri); - $this->_set_uri_string($path); + $uri = isset($_SERVER[$uri]) ? $_SERVER[$uri] : @getenv($uri); + $this->_set_uri_string($uri); } // -------------------------------------------------------------------- /** - * Set the URI String + * Set URI String * - * @param string + * @param string $str * @return void */ protected function _set_uri_string($str) @@ -172,60 +171,54 @@ class CI_URI { // -------------------------------------------------------------------- /** - * Detects the URI + * Parse REQUEST_URI * - * This function will detect the URI automatically - * and fix the query string if necessary. + * Will parse REQUEST_URI and automatically detect the URI from it, + * while fixing the query string if necessary. * + * @used-by CI_URI::_fetch_uri_string() * @return string */ - protected function _detect_uri() + protected function _parse_request_uri() { if ( ! isset($_SERVER['REQUEST_URI'], $_SERVER['SCRIPT_NAME'])) { return ''; } - if (strpos($_SERVER['REQUEST_URI'], $_SERVER['SCRIPT_NAME']) === 0) - { - $uri = substr($_SERVER['REQUEST_URI'], strlen($_SERVER['SCRIPT_NAME'])); - } - elseif (strpos($_SERVER['REQUEST_URI'], dirname($_SERVER['SCRIPT_NAME'])) === 0) + $uri = parse_url($_SERVER['REQUEST_URI']); + $query = isset($uri['query']) ? $uri['query'] : ''; + $uri = isset($uri['path']) ? $uri['path'] : ''; + + if (strpos($uri, $_SERVER['SCRIPT_NAME']) === 0) { - $uri = substr($_SERVER['REQUEST_URI'], strlen(dirname($_SERVER['SCRIPT_NAME']))); + $uri = (string) substr($uri, strlen($_SERVER['SCRIPT_NAME'])); } - else + elseif (strpos($uri, dirname($_SERVER['SCRIPT_NAME'])) === 0) { - $uri = $_SERVER['REQUEST_URI']; + $uri = (string) substr($uri, strlen(dirname($_SERVER['SCRIPT_NAME']))); } // This section ensures that even on servers that require the URI to be in the query string (Nginx) a correct // URI is found, and also fixes the QUERY_STRING server var and $_GET array. - if (strpos($uri, '?/') === 0) + if (trim($uri, '/') === '' && strncmp($query, '/', 1) === 0) { - $uri = substr($uri, 2); - } - - $parts = explode('?', $uri, 2); - $uri = $parts[0]; - if (isset($parts[1])) - { - $_SERVER['QUERY_STRING'] = $parts[1]; - parse_str($_SERVER['QUERY_STRING'], $_GET); + $query = explode('?', $query, 2); + $uri = $query[0]; + $_SERVER['QUERY_STRING'] = isset($query[1]) ? $query[1] : ''; } else { - $_SERVER['QUERY_STRING'] = ''; - $_GET = array(); + $_SERVER['QUERY_STRING'] = $query; } - if ($uri === '/' OR empty($uri)) + $this->_reset_query_string(); + + if ($uri === '/' OR $uri === '') { return '/'; } - $uri = parse_url('pseudo://hostname/'.$uri, PHP_URL_PATH); - // Do some final cleaning of the URI and return it return str_replace(array('//', '../'), '/', trim($uri, '/')); } @@ -233,10 +226,66 @@ class CI_URI { // -------------------------------------------------------------------- /** - * Is cli Request? + * Parse QUERY_STRING + * + * Will parse QUERY_STRING and automatically detect the URI from it. + * + * @used-by CI_URI::_fetch_uri_string() + * @return string + */ + protected function _parse_query_string() + { + $uri = isset($_SERVER['QUERY_STRING']) ? $_SERVER['QUERY_STRING'] : @getenv('QUERY_STRING'); + + if (trim($uri, '/') === '') + { + return ''; + } + elseif (strncmp($uri, '/', 1) === 0) + { + $uri = explode('?', $uri, 2); + $_SERVER['QUERY_STRING'] = isset($uri[1]) ? $uri[1] : ''; + $uri = $uri[0]; + } + $this->_reset_query_string(); + + return str_replace(array('//', '../'), '/', trim($uri, '/')); + } + + // -------------------------------------------------------------------- + + /** + * Reset QUERY_STRING * - * Duplicate of function from the Input class to test to see if a request was made from the command line + * Re-processes QUERY_STRING to and fetches the real GET values from it. + * Useful for cases where we got the URI path from it's query string. * + * @used-by CI_URI::_parse_request_uri() + * @used-by CI_URI::_parse_query_string() + * @return void + */ + protected function _reset_query_string() + { + if ($_SERVER['QUERY_STRING'] === '') + { + $_GET = array(); + } + else + { + parse_str($_SERVER['QUERY_STRING']); + } + } + + // -------------------------------------------------------------------- + + /** + * Is CLI Request? + * + * Duplicate of method from the Input class to test to see if + * a request was made from the command line. + * + * @see CI_Input::is_cli_request() + * @used-by CI_URI::_fetch_uri_string() * @return bool */ protected function _is_cli_request() @@ -247,26 +296,27 @@ class CI_URI { // -------------------------------------------------------------------- /** - * Parse cli arguments + * Parse CLI arguments * * Take each command line argument and assume it is a URI segment. * * @return string */ - protected function _parse_cli_args() + protected function _parse_argv() { $args = array_slice($_SERVER['argv'], 1); - return $args ? '/'.implode('/', $args) : ''; + return $args ? implode('/', $args) : ''; } // -------------------------------------------------------------------- /** - * Filter segments for malicious characters + * Filter URI * - * Called by CI_Router + * Filters segments for malicious characters. * - * @param string + * @used-by CI_Router + * @param string $str * @return string */ public function _filter_uri($str) @@ -291,10 +341,11 @@ class CI_URI { // -------------------------------------------------------------------- /** - * Remove the suffix from the URL if needed + * Remove URL suffix * - * Called by CI_Router + * Removes the suffix from the URL if needed. * + * @used-by CI_Router * @return void */ public function _remove_url_suffix() @@ -310,11 +361,12 @@ class CI_URI { // -------------------------------------------------------------------- /** - * Explode the URI Segments. The individual segments will - * be stored in the $this->segments array. + * Explode URI segments * - * Called by CI_Router + * The individual segments will be stored in the $this->segments array. * + * @see CI_URI::$segments + * @used-by CI_Router * @return void */ public function _explode_segments() @@ -336,13 +388,12 @@ class CI_URI { /** * Re-index Segments * - * This function re-indexes the $this->segment array so that it - * starts at 1 rather than 0. Doing so makes it simpler to - * use functions like $this->uri->segment(n) since there is - * a 1:1 relationship between the segment array and the actual segments. - * - * Called by CI_Router + * Re-indexes the CI_URI::$segment array so that it starts at 1 rather + * than 0. Doing so makes it simpler to use methods like + * CI_URI::segment(n) since there is a 1:1 relationship between the + * segment array and the actual segments. * + * @used-by CI_Router * @return void */ public function _reindex_segments() @@ -356,13 +407,12 @@ class CI_URI { // -------------------------------------------------------------------- /** - * Fetch a URI Segment - * - * This function returns the URI segment based on the number provided. + * Fetch URI Segment * - * @param int - * @param mixed - * @return string + * @see CI_URI::$segments + * @param int $n Index + * @param mixed $no_result What to return if the segment index is not found + * @return mixed */ public function segment($n, $no_result = NULL) { @@ -372,15 +422,17 @@ class CI_URI { // -------------------------------------------------------------------- /** - * Fetch a URI "routed" Segment + * Fetch URI "routed" Segment * - * This function returns the re-routed URI segment (assuming routing rules are used) - * based on the number provided. If there is no routing this function returns the - * same result as $this->segment() + * Returns the re-routed URI segment (assuming routing rules are used) + * based on the index provided. If there is no routing, will return + * the same result as CI_URI::segment(). * - * @param int - * @param mixed - * @return string + * @see CI_URI::$rsegments + * @see CI_URI::segment() + * @param int $n Index + * @param mixed $no_result What to return if the segment index is not found + * @return mixed */ public function rsegment($n, $no_result = NULL) { @@ -390,23 +442,23 @@ class CI_URI { // -------------------------------------------------------------------- /** - * Generate a key value pair from the URI string + * URI to assoc * - * This function generates and associative array of URI data starting - * at the supplied segment. For example, if this is your URI: + * Generates an associative array of URI data starting at the supplied + * segment index. For example, if this is your URI: * * example.com/user/search/name/joe/location/UK/gender/male * - * You can use this function to generate an array with this prototype: + * You can use this method to generate an array with this prototype: * - * array ( - * name => joe - * location => UK - * gender => male - * ) + * array ( + * name => joe + * location => UK + * gender => male + * ) * - * @param int the starting segment number - * @param array an array of default values + * @param int $n Index (default: 3) + * @param array $default Default values * @return array */ public function uri_to_assoc($n = 3, $default = array()) @@ -417,10 +469,14 @@ class CI_URI { // -------------------------------------------------------------------- /** - * Identical to above only it uses the re-routed segment array + * Routed URI to assoc * - * @param int the starting segment number - * @param array an array of default values + * Identical to CI_URI::uri_to_assoc(), only it uses the re-routed + * segment array. + * + * @see CI_URI::uri_to_assoc() + * @param int $n Index (default: 3) + * @param array $default Default values * @return array */ public function ruri_to_assoc($n = 3, $default = array()) @@ -431,11 +487,15 @@ class CI_URI { // -------------------------------------------------------------------- /** - * Generate a key value pair from the URI string or Re-routed URI string + * Internal URI-to-assoc + * + * Generates a key/value pair from the URI string or re-routed URI string. * - * @param int $n = 3 the starting segment number - * @param array $default = array() an array of default values - * @param string $which = 'segment' which array we should use + * @used-by CI_URI::uri_to_assoc() + * @used-by CI_URI::ruri_to_assoc() + * @param int $n Index (default: 3) + * @param array $default Default values + * @param string $which Array name ('segment' or 'rsegment') * @return array */ protected function _uri_to_assoc($n = 3, $default = array(), $which = 'segment') @@ -473,7 +533,7 @@ class CI_URI { $segments = array_slice($this->$segment_array(), ($n - 1)); $i = 0; $lastval = ''; - $retval = array(); + $retval = array(); foreach ($segments as $seg) { if ($i % 2) @@ -509,10 +569,12 @@ class CI_URI { // -------------------------------------------------------------------- /** - * Generate a URI string from an associative array + * Assoc to URI * - * @param array an associative array of key/values - * @return array + * Generates a URI string from an associative array. + * + * @param array $array Input array of key/value pairs + * @return string URI string */ public function assoc_to_uri($array) { @@ -529,10 +591,12 @@ class CI_URI { // -------------------------------------------------------------------- /** - * Fetch a URI Segment and add a trailing slash + * Slash segment * - * @param int - * @param string + * Fetches an URI segment with a slash. + * + * @param int $n Index + * @param string $where Where to add the slash ('trailing' or 'leading') * @return string */ public function slash_segment($n, $where = 'trailing') @@ -543,10 +607,12 @@ class CI_URI { // -------------------------------------------------------------------- /** - * Fetch a URI Segment and add a trailing slash + * Slash routed segment + * + * Fetches an URI routed segment with a slash. * - * @param int - * @param string + * @param int $n Index + * @param string $where Where to add the slash ('trailing' or 'leading') * @return string */ public function slash_rsegment($n, $where = 'trailing') @@ -557,11 +623,16 @@ class CI_URI { // -------------------------------------------------------------------- /** - * Fetch a URI Segment and add a trailing slash - helper function + * Internal Slash segment + * + * Fetches an URI Segment and adds a slash to it. + * + * @used-by CI_URI::slash_segment() + * @used-by CI_URI::slash_rsegment() * - * @param int - * @param string - * @param string + * @param int $n Index + * @param string $where Where to add the slash ('trailing' or 'leading') + * @param string $which Array name ('segment' or 'rsegment') * @return string */ protected function _slash_segment($n, $where = 'trailing', $which = 'segment') @@ -585,7 +656,7 @@ class CI_URI { /** * Segment Array * - * @return array + * @return array CI_URI::$segments */ public function segment_array() { @@ -597,7 +668,7 @@ class CI_URI { /** * Routed Segment Array * - * @return array + * @return array CI_URI::$rsegments */ public function rsegment_array() { @@ -631,20 +702,19 @@ class CI_URI { // -------------------------------------------------------------------- /** - * Fetch the entire URI string + * Fetch URI string * - * @return string + * @return string CI_URI::$uri_string */ public function uri_string() { return $this->uri_string; } - // -------------------------------------------------------------------- /** - * Fetch the entire Re-routed URI string + * Fetch Re-routed URI string * * @return string */ diff --git a/system/core/Utf8.php b/system/core/Utf8.php index 1ff02981b..efe3c10dc 100644 --- a/system/core/Utf8.php +++ b/system/core/Utf8.php @@ -39,9 +39,9 @@ class CI_Utf8 { /** - * Constructor + * Class constructor * - * Determines if UTF-8 support is to be enabled + * Determines if UTF-8 support is to be enabled. * * @return void */ @@ -64,7 +64,6 @@ class CI_Utf8 { define('MB_ENABLED', FALSE); } - if ( @preg_match('/./u', 'é') === 1 // PCRE must support UTF-8 && function_exists('iconv') // iconv must be installed @@ -87,9 +86,11 @@ class CI_Utf8 { /** * Clean UTF-8 strings * - * Ensures strings are UTF-8 + * Ensures strings contain only valid UTF-8 characters. + * + * @uses CI_Utf8::_is_ascii() Decide whether a conversion is needed * - * @param string + * @param string $str String to clean * @return string */ public function clean_string($str) @@ -109,9 +110,9 @@ class CI_Utf8 { * * Removes all ASCII control characters except horizontal tabs, * line feeds, and carriage returns, as all others can cause - * problems in XML + * problems in XML. * - * @param string + * @param string $str String to clean * @return string */ public function safe_ascii_for_xml($str) @@ -124,11 +125,11 @@ class CI_Utf8 { /** * Convert to UTF-8 * - * Attempts to convert a string to UTF-8 + * Attempts to convert a string to UTF-8. * - * @param string - * @param string input encoding - * @return string + * @param string $str Input string + * @param string $encoding Input encoding + * @return string $str encoded in UTF-8 or FALSE on failure */ public function convert_to_utf8($str, $encoding) { @@ -149,9 +150,9 @@ class CI_Utf8 { /** * Is ASCII? * - * Tests if a string is standard 7-bit ASCII or not + * Tests if a string is standard 7-bit ASCII or not. * - * @param string + * @param string $str String to check * @return bool */ protected function _is_ascii($str) diff --git a/system/database/DB_query_builder.php b/system/database/DB_query_builder.php index ed00510ac..a3585586e 100644 --- a/system/database/DB_query_builder.php +++ b/system/database/DB_query_builder.php @@ -1162,7 +1162,9 @@ abstract class CI_DB_query_builder extends CI_DB_driver { $this->from($table); } - $result = $this->query($this->_compile_select($this->_count_string.$this->protect_identifiers('numrows'))); + $result = ($this->qb_distinct === TRUE) + ? $this->query($this->_count_string.$this->protect_identifiers('numrows')."\nFROM (\n".$this->_compile_select()."\n) CI_count_all_results") + : $this->query($this->_compile_select($this->_count_string.$this->protect_identifiers('numrows'))); $this->_reset_select(); if ($result->num_rows() === 0) diff --git a/system/database/drivers/oci8/oci8_result.php b/system/database/drivers/oci8/oci8_result.php index a2b600e6c..ade186be7 100644 --- a/system/database/drivers/oci8/oci8_result.php +++ b/system/database/drivers/oci8/oci8_result.php @@ -157,7 +157,7 @@ class CI_DB_oci8_result extends CI_DB_result { protected function _fetch_assoc() { $id = ($this->curs_id) ? $this->curs_id : $this->stmt_id; - return oci_fetch_assoc($id); + return @oci_fetch_assoc($id); } // -------------------------------------------------------------------- diff --git a/system/database/drivers/odbc/odbc_driver.php b/system/database/drivers/odbc/odbc_driver.php index 063a04b98..f6ea412ad 100644 --- a/system/database/drivers/odbc/odbc_driver.php +++ b/system/database/drivers/odbc/odbc_driver.php @@ -50,6 +50,13 @@ class CI_DB_odbc_driver extends CI_DB { protected $_random_keyword; /** + * Database schema + * + * @var string + */ + public $schema = 'public'; + + /** * Constructor * * @param array $params @@ -234,17 +241,17 @@ class CI_DB_odbc_driver extends CI_DB { * * Generates a platform-specific query string so that the table names can be fetched * - * @param bool + * @param bool $prefix_limit = FALSE * @return string */ protected function _list_tables($prefix_limit = FALSE) { - $sql = 'SHOW TABLES FROM '.$this->database; + $sql = "SELECT table_name FROM information_schema.tables WHERE table_schema = '".$this->schema."'"; if ($prefix_limit !== FALSE && $this->dbprefix !== '') { - //$sql .= " LIKE '".$this->escape_like_str($this->dbprefix)."%' ".sprintf($this->_like_escape_str, $this->_like_escape_chr); - return FALSE; // not currently supported + return $sql." AND table_name LIKE '".$this->escape_like_str($this->dbprefix)."%' " + .sprintf($this->_like_escape_str, $this->_like_escape_chr); } return $sql; diff --git a/system/database/drivers/pdo/subdrivers/pdo_odbc_driver.php b/system/database/drivers/pdo/subdrivers/pdo_odbc_driver.php index 5944d55f4..d64e9fb36 100644 --- a/system/database/drivers/pdo/subdrivers/pdo_odbc_driver.php +++ b/system/database/drivers/pdo/subdrivers/pdo_odbc_driver.php @@ -51,6 +51,13 @@ class CI_DB_pdo_odbc_driver extends CI_DB_pdo_driver { protected $_random_keyword = ' RAND()'; /** + * Database schema + * + * @var string + */ + public $schema = 'public'; + + /** * Constructor * * Builds the DSN if not already set. @@ -122,12 +129,12 @@ class CI_DB_pdo_odbc_driver extends CI_DB_pdo_driver { * * Generates a platform-specific query string so that the table names can be fetched * - * @param bool + * @param bool $prefix_limit = FALSE * @return string */ protected function _list_tables($prefix_limit = FALSE) { - $sql = "SELECT table_name FROM information_schema.tables WHERE table_schema = 'public'"; + $sql = "SELECT table_name FROM information_schema.tables WHERE table_schema = '".$this->schema."'"; if ($prefix_limit !== FALSE && $this->dbprefix !== '') { diff --git a/system/database/drivers/pdo/subdrivers/pdo_pgsql_driver.php b/system/database/drivers/pdo/subdrivers/pdo_pgsql_driver.php index 74d56e6b8..93674b576 100644 --- a/system/database/drivers/pdo/subdrivers/pdo_pgsql_driver.php +++ b/system/database/drivers/pdo/subdrivers/pdo_pgsql_driver.php @@ -45,6 +45,13 @@ class CI_DB_pdo_pgsql_driver extends CI_DB_pdo_driver { protected $_random_keyword = ' RANDOM()'; /** + * Database schema + * + * @var string + */ + public $schema = 'public'; + + /** * Constructor * * Builds the DSN if not already set. @@ -92,12 +99,12 @@ class CI_DB_pdo_pgsql_driver extends CI_DB_pdo_driver { * * Generates a platform-specific query string so that the table names can be fetched * - * @param bool + * @param bool $prefix_limit = FALSE * @return string */ protected function _list_tables($prefix_limit = FALSE) { - $sql = 'SELECT "table_name" FROM "information_schema"."tables" WHERE "table_schema" = \'public\''; + $sql = 'SELECT "table_name" FROM "information_schema"."tables" WHERE "table_schema" = \''.$this->schema."'"; if ($prefix_limit === TRUE && $this->dbprefix !== '') { diff --git a/system/database/drivers/postgre/postgre_driver.php b/system/database/drivers/postgre/postgre_driver.php index 1b9474920..ca231f6f7 100644 --- a/system/database/drivers/postgre/postgre_driver.php +++ b/system/database/drivers/postgre/postgre_driver.php @@ -47,6 +47,13 @@ class CI_DB_postgre_driver extends CI_DB { protected $_random_keyword = ' RANDOM()'; // database specific random keyword /** + * Database schema + * + * @var string + */ + public $schema = 'public'; + + /** * Constructor * * Creates a DSN string to be used for db_connect() and db_pconnect() @@ -393,12 +400,12 @@ class CI_DB_postgre_driver extends CI_DB { * * Generates a platform-specific query string so that the table names can be fetched * - * @param bool + * @param bool $prefix_limit = FALSE * @return string */ protected function _list_tables($prefix_limit = FALSE) { - $sql = 'SELECT "table_name" FROM "information_schema"."tables" WHERE "table_schema" = \'public\''; + $sql = 'SELECT "table_name" FROM "information_schema"."tables" WHERE "table_schema" = \''.$this->schema."'"; if ($prefix_limit !== FALSE && $this->dbprefix !== '') { diff --git a/system/helpers/date_helper.php b/system/helpers/date_helper.php index 51b2b76db..5d9251526 100644 --- a/system/helpers/date_helper.php +++ b/system/helpers/date_helper.php @@ -119,19 +119,16 @@ if ( ! function_exists('standard_date')) * * As of PHP 5.2, the DateTime extension provides constants that * serve for the exact same purpose and are used with date(). - * Due to that, this function is DEPRECATED and should be removed - * in CodeIgniter 3.1+. * - * Here are two examples of how you should replace it: + * @todo Remove in version 3.1+. + * @deprecated 3.0.0 Use PHP's native date() instead. + * @link http://www.php.net/manual/en/class.datetime.php#datetime.constants.types * - * date(DATE_RFC822, now()); // default - * date(DATE_W3C, $time); // a different format and time + * @example date(DATE_RFC822, now()); // default + * @example date(DATE_W3C, $time); // a different format and time * - * Reference: http://www.php.net/manual/en/class.datetime.php#datetime.constants.types - * - * @deprecated - * @param string the chosen format - * @param int Unix timestamp + * @param string $fmt = 'DATE_RFC822' the chosen format + * @param int $time = NULL Unix timestamp * @return string */ function standard_date($fmt = 'DATE_RFC822', $time = NULL) diff --git a/system/helpers/file_helper.php b/system/helpers/file_helper.php index 441345b05..8f23a3d54 100644 --- a/system/helpers/file_helper.php +++ b/system/helpers/file_helper.php @@ -44,12 +44,10 @@ if ( ! function_exists('read_file')) * * Opens the file specfied in the path and returns it as a string. * - * This function is DEPRECATED and should be removed in - * CodeIgniter 3.1+. Use file_get_contents() instead. - * - * @deprecated - * @param string path to file - * @return string + * @todo Remove in version 3.1+. + * @deprecated 3.0.0 It is now just an alias for PHP's native file_get_contents(). + * @param string $file Path to file + * @return string File contents */ function read_file($file) { diff --git a/system/helpers/form_helper.php b/system/helpers/form_helper.php index 1bccac35c..622622c0e 100644 --- a/system/helpers/form_helper.php +++ b/system/helpers/form_helper.php @@ -149,7 +149,7 @@ if ( ! function_exists('form_hidden')) if ( ! is_array($value)) { - $form .= '<input type="hidden" name="'.$name.'" value="'.form_prep($value, $name)."\" />\n"; + $form .= '<input type="hidden" name="'.$name.'" value="'.html_escape($value)."\" />\n"; } else { @@ -263,7 +263,7 @@ if ( ! function_exists('form_textarea')) } $name = is_array($data) ? $data['name'] : $data; - return '<textarea '._parse_form_attributes($data, $defaults).$extra.'>'.form_prep($val, $name)."</textarea>\n"; + return '<textarea '._parse_form_attributes($data, $defaults).$extra.'>'.html_escape($val)."</textarea>\n"; } } @@ -298,10 +298,10 @@ if ( ! function_exists('form_dropdown')) /** * Drop-down Menu * - * @param string - * @param array - * @param string - * @param string + * @param mixed $name = '' + * @param mixed $options = array() + * @param mixed $selected = array() + * @param mixed $extra = array() * @return string */ function form_dropdown($name = '', $options = array(), $selected = array(), $extra = '') @@ -316,10 +316,7 @@ if ( ! function_exists('form_dropdown')) return form_dropdown($name['name'], $name['options'], $name['selected'], $name['extra']); } - if ( ! is_array($selected)) - { - $selected = array($selected); - } + is_array($selected) OR $selected = array($selected); // If no selected state was submitted we will attempt to set it automatically if (count($selected) === 0 && isset($_POST[$name])) @@ -352,14 +349,17 @@ if ( ! function_exists('form_dropdown')) foreach ($val as $optgroup_key => $optgroup_val) { $sel = in_array($optgroup_key, $selected) ? ' selected="selected"' : ''; - $form .= '<option value="'.$optgroup_key.'"'.$sel.'>'.(string) $optgroup_val."</option>\n"; + $form .= '<option value="'.html_escape($optgroup_key).'"'.$sel.'>' + .(string) $optgroup_val."</option>\n"; } $form .= "</optgroup>\n"; } else { - $form .= '<option value="'.$key.'"'.(in_array($key, $selected) ? ' selected="selected"' : '').'>'.(string) $val."</option>\n"; + $form .= '<option value="'.html_escape($key).'"' + .(in_array($key, $selected) ? ' selected="selected"' : '').'>' + .(string) $val."</option>\n"; } } @@ -600,44 +600,16 @@ if ( ! function_exists('form_prep')) * * Formats text so that it can be safely placed in a form field in the event it has HTML tags. * - * @param string - * @param string + * @todo Remove in version 3.1+. + * @deprecated 3.0.0 This function has been broken for a long time + * and is now just an alias for html_escape(). It's + * second argument is ignored. + * @param string $str = '' + * @param string $field_name = '' * @return string */ function form_prep($str = '', $field_name = '') { - static $prepped_fields = array(); - - // if the field name is an array we do this recursively - if (is_array($str)) - { - foreach ($str as $key => $val) - { - $str[$key] = form_prep($val); - } - - return $str; - } - - if ($str === '') - { - return ''; - } - - // we've already prepped a field with this name - // @todo need to figure out a way to namespace this so - // that we know the *exact* field and not just one with - // the same name - if (isset($prepped_fields[$field_name])) - { - return $str; - } - - if ($field_name !== '') - { - $prepped_fields[$field_name] = $field_name; - } - return html_escape($str); } } @@ -663,13 +635,13 @@ if ( ! function_exists('set_value')) { if ( ! isset($_POST[$field])) { - return $default; + return html_escape($default); } - return form_prep($_POST[$field], $field); + return html_escape($_POST[$field]); } - return form_prep($OBJ->set_value($field, $default), $field); + return html_escape($OBJ->set_value($field, $default)); } } @@ -919,7 +891,11 @@ if ( ! function_exists('_parse_form_attributes')) { if ($key === 'value') { - $val = form_prep($val, $default['name']); + $val = html_escape($val); + } + elseif ($key === 'name' && ! strlen($default['name'])) + { + continue; } $att .= $key.'="'.$val.'" '; diff --git a/system/helpers/security_helper.php b/system/helpers/security_helper.php index 5ecc960bc..8bbd06684 100644 --- a/system/helpers/security_helper.php +++ b/system/helpers/security_helper.php @@ -77,12 +77,10 @@ if ( ! function_exists('do_hash')) /** * Hash encode a string * - * This function is DEPRECATED and should be removed in - * CodeIgniter 3.1+. Use hash() instead. - * - * @deprecated - * @param string - * @param string + * @todo Remove in version 3.1+. + * @deprecated 3.0.0 Use PHP's native hash() instead. + * @param string $str + * @param string $type = 'sha1' * @return string */ function do_hash($str, $type = 'sha1') diff --git a/system/helpers/string_helper.php b/system/helpers/string_helper.php index 4eee2a262..c5c493452 100644 --- a/system/helpers/string_helper.php +++ b/system/helpers/string_helper.php @@ -276,8 +276,11 @@ if ( ! function_exists('repeater')) /** * Repeater function * - * @param string - * @param int number of repeats + * @todo Remove in version 3.1+. + * @deprecated 3.0.0 This is just an alias for PHP's native str_repeat() + * + * @param string $data String to repeat + * @param int $num Number of repeats * @return string */ function repeater($data, $num = 1) diff --git a/system/helpers/text_helper.php b/system/helpers/text_helper.php index 016a36c57..89602fc28 100644 --- a/system/helpers/text_helper.php +++ b/system/helpers/text_helper.php @@ -118,18 +118,15 @@ if ( ! function_exists('ascii_to_entities')) /** * High ASCII to Entities * - * Converts High ascii text and MS Word special characters to character entities + * Converts high ASCII text and MS Word special characters to character entities * - * @param string + * @param string $str * @return string */ function ascii_to_entities($str) { - $count = 1; - $out = ''; - $temp = array(); - - for ($i = 0, $s = strlen($str); $i < $s; $i++) + $out = ''; + for ($i = 0, $s = strlen($str), $count = 1, $temp = array(); $i < $s; $i++) { $ordinal = ord($str[$i]); diff --git a/system/libraries/Cache/Cache.php b/system/libraries/Cache/Cache.php index 4395cf411..7ec2380a5 100644 --- a/system/libraries/Cache/Cache.php +++ b/system/libraries/Cache/Cache.php @@ -41,7 +41,7 @@ class CI_Cache extends CI_Driver_Library { * * @var array */ - protected $valid_drivers = array( + protected $valid_drivers = array( 'cache_apc', 'cache_dummy', 'cache_file', @@ -67,16 +67,23 @@ class CI_Cache extends CI_Driver_Library { /** * Fallback driver * - * @param string + * @var string */ protected $_backup_driver = 'dummy'; /** + * Cache key prefix + * + * @var string + */ + public $key_prefix = ''; + + /** * Constructor * * Initialize class properties based on the configuration array. * - * @param array + * @param array $config = array() * @return void */ public function __construct($config = array()) @@ -96,12 +103,11 @@ class CI_Cache extends CI_Driver_Library { } } - if (isset($config['backup'])) + isset($config['key_prefix']) && $this->key_prefix = $config['key_prefix']; + + if (isset($config['backup']) && in_array('cache_'.$config['backup'], $this->valid_drivers)) { - if (in_array('cache_'.$config['backup'], $this->valid_drivers)) - { - $this->_backup_driver = $config['backup']; - } + $this->_backup_driver = $config['backup']; } // If the specified adapter isn't available, check the backup. @@ -129,12 +135,12 @@ class CI_Cache extends CI_Driver_Library { * Look for a value in the cache. If it exists, return the data * if not, return FALSE * - * @param string - * @return mixed value that is stored/FALSE on failure + * @param string $id + * @return mixed value matching $id or FALSE on failure */ public function get($id) { - return $this->{$this->_adapter}->get($id); + return $this->{$this->_adapter}->get($this->key_prefix.$id); } // ------------------------------------------------------------------------ @@ -142,14 +148,14 @@ class CI_Cache extends CI_Driver_Library { /** * Cache Save * - * @param string Unique Key - * @param mixed Data to store - * @param int Length of time (in seconds) to cache the data - * @return bool true on success/false on failure + * @param string $id Cache ID + * @param mixed $data Data to store + * @param int $ttl = 60 Cache TTL (in seconds) + * @return bool TRUE on success, FALSE on failure */ public function save($id, $data, $ttl = 60) { - return $this->{$this->_adapter}->save($id, $data, $ttl); + return $this->{$this->_adapter}->save($this->key_prefix.$id, $data, $ttl); } // ------------------------------------------------------------------------ @@ -157,12 +163,12 @@ class CI_Cache extends CI_Driver_Library { /** * Delete from Cache * - * @param mixed unique identifier of the item in the cache - * @return bool true on success/false on failure + * @param string $id Cache ID + * @return bool TRUE on success, FALSE on failure */ public function delete($id) { - return $this->{$this->_adapter}->delete($id); + return $this->{$this->_adapter}->delete($this->key_prefix.$id); } // ------------------------------------------------------------------------ @@ -170,7 +176,7 @@ class CI_Cache extends CI_Driver_Library { /** * Clean the cache * - * @return bool false on failure/true on success + * @return bool TRUE on success, FALSE on failure */ public function clean() { @@ -182,8 +188,8 @@ class CI_Cache extends CI_Driver_Library { /** * Cache Info * - * @param string user/filehits - * @return mixed array on success, false on failure + * @param string $type = 'user' user/filehits + * @return mixed array containing cache info on success OR FALSE on failure */ public function cache_info($type = 'user') { @@ -195,12 +201,12 @@ class CI_Cache extends CI_Driver_Library { /** * Get Cache Metadata * - * @param mixed key to get cache metadata on - * @return mixed return value from child method + * @param string $id key to get cache metadata on + * @return mixed cache item metadata */ public function get_metadata($id) { - return $this->{$this->_adapter}->get_metadata($id); + return $this->{$this->_adapter}->get_metadata($this->key_prefix.$id); } // ------------------------------------------------------------------------ @@ -208,7 +214,7 @@ class CI_Cache extends CI_Driver_Library { /** * Is the requested driver supported in this environment? * - * @param string The driver to test. + * @param string $driver The driver to test * @return array */ public function is_supported($driver) diff --git a/system/libraries/Calendar.php b/system/libraries/Calendar.php index a49f171b9..95f537e42 100644 --- a/system/libraries/Calendar.php +++ b/system/libraries/Calendar.php @@ -95,11 +95,13 @@ class CI_Calendar { public $next_prev_url = ''; /** - * Constructor + * Class constructor * - * Loads the calendar language file and sets the default time reference + * Loads the calendar language file and sets the default time reference. * - * @param array + * @uses CI_Lang::$is_loaded + * + * @param array $config Calendar options * @return void */ public function __construct($config = array()) diff --git a/system/libraries/Cart.php b/system/libraries/Cart.php index c442f88da..d4b17fa36 100644 --- a/system/libraries/Cart.php +++ b/system/libraries/Cart.php @@ -480,17 +480,34 @@ class CI_Cart { // -------------------------------------------------------------------- /** + * Get cart item + * + * Returns the details of a specific item in the cart + * + * @param string $row_id + * @return array + */ + public function get_item($row_id) + { + return (in_array($row_id, array('total_items', 'cart_total'), TRUE) OR ! isset($this->_cart_contents[$row_id])) + ? FALSE + : $this->_cart_contents[$row_id]; + } + + // -------------------------------------------------------------------- + + /** * Has options * * Returns TRUE if the rowid passed to this function correlates to an item * that has options associated with it. * - * @param mixed + * @param string $row_id = '' * @return bool */ - public function has_options($rowid = '') + public function has_options($row_id = '') { - return (isset($this->_cart_contents[$rowid]['options']) && count($this->_cart_contents[$rowid]['options']) !== 0); + return (isset($this->_cart_contents[$row_id]['options']) && count($this->_cart_contents[$row_id]['options']) !== 0); } // -------------------------------------------------------------------- @@ -500,12 +517,12 @@ class CI_Cart { * * Returns the an array of options, for a particular product row ID * - * @param int + * @param string $row_id = '' * @return array */ - public function product_options($rowid = '') + public function product_options($row_id = '') { - return isset($this->_cart_contents[$rowid]['options']) ? $this->_cart_contents[$rowid]['options'] : array(); + return isset($this->_cart_contents[$row_id]['options']) ? $this->_cart_contents[$row_id]['options'] : array(); } // -------------------------------------------------------------------- diff --git a/system/libraries/Email.php b/system/libraries/Email.php index 83b442f58..7280466a5 100644 --- a/system/libraries/Email.php +++ b/system/libraries/Email.php @@ -47,20 +47,20 @@ class CI_Email { public $smtp_port = 25; // SMTP Port public $smtp_timeout = 5; // SMTP Timeout in seconds public $smtp_crypto = ''; // SMTP Encryption. Can be null, tls or ssl. - public $wordwrap = TRUE; // TRUE/FALSE Turns word-wrap on/off + public $wordwrap = TRUE; // TRUE/FALSE - Turns word-wrap on/off public $wrapchars = 76; // Number of characters to wrap at. - public $mailtype = 'text'; // text/html Defines email formatting + public $mailtype = 'text'; // text/html - Defines email formatting public $charset = 'utf-8'; // Default char set: iso-8859-1 or us-ascii public $multipart = 'mixed'; // "mixed" (in the body) or "related" (separate) public $alt_message = ''; // Alternative message for HTML emails - public $validate = FALSE; // TRUE/FALSE. Enables email validation + public $validate = FALSE; // TRUE/FALSE - Enables email validation public $priority = 3; // Default priority (1 - 5) public $newline = "\n"; // Default newline. "\r\n" or "\n" (Use "\r\n" to comply with RFC 822) - public $crlf = "\n"; // The RFC 2045 compliant CRLF for quoted-printable is "\r\n". Apparently some servers, + public $crlf = "\n"; // The RFC 2045 compliant CRLF for quoted-printable is "\r\n". Apparently some servers, // even on the receiving end think they need to muck with CRLFs, so using "\n", while // distasteful, is the only thing that seems to work for all environments. public $dsn = FALSE; // Delivery Status Notification - public $send_multipart = TRUE; // TRUE/FALSE - Yahoo does not like multipart alternative, so this is an override. Set to FALSE for Yahoo. + public $send_multipart = TRUE; // TRUE/FALSE - Yahoo does not like multipart alternative, so this is an override. Set to FALSE for Yahoo. public $bcc_batch_mode = FALSE; // TRUE/FALSE - Turns on/off Bcc batch feature public $bcc_batch_size = 200; // If bcc_batch_mode = TRUE, sets max number of Bccs in each batch @@ -81,9 +81,7 @@ class CI_Email { protected $_cc_array = array(); protected $_bcc_array = array(); protected $_headers = array(); - protected $_attach_name = array(); - protected $_attach_type = array(); - protected $_attach_disp = array(); + protected $_attachments = array(); protected $_protocols = array('mail', 'sendmail', 'smtp'); protected $_base_charsets = array('us-ascii', 'iso-2022-'); // 7-bit charsets (excluding language suffix) protected $_bit_depths = array('7bit', '8bit'); @@ -176,9 +174,7 @@ class CI_Email { if ($clear_attachments !== FALSE) { - $this->_attach_name = array(); - $this->_attach_type = array(); - $this->_attach_disp = array(); + $this->_attachments = array(); } return $this; @@ -415,9 +411,12 @@ class CI_Email { */ public function attach($filename, $disposition = '', $newname = NULL, $mime = '') { - $this->_attach_name[] = array($filename, $newname); - $this->_attach_disp[] = empty($disposition) ? 'attachment' : $disposition; // Can also be 'inline' Not sure if it matters - $this->_attach_type[] = $mime; + $this->_attachments[] = array( + 'name' => array($filename, $newname), + 'disposition' => empty($disposition) ? 'attachment' : $disposition, // Can also be 'inline' Not sure if it matters + 'type' => $mime + ); + return $this; } @@ -635,9 +634,9 @@ class CI_Email { { if ($this->mailtype === 'html') { - return (count($this->_attach_name) === 0) ? 'html' : 'html-attach'; + return (count($this->_attachments) === 0) ? 'html' : 'html-attach'; } - elseif ($this->mailtype === 'text' && count($this->_attach_name) > 0) + elseif ($this->mailtype === 'text' && count($this->_attachments) > 0) { return 'plain-attach'; } @@ -771,6 +770,9 @@ class CI_Email { $body = str_replace(str_repeat("\n", $i), "\n\n", $body); } + // Reduce multiple spaces + $str = preg_replace('| +|', ' ', $str); + return ($this->wordwrap) ? $this->word_wrap($body, 76) : $body; @@ -793,15 +795,15 @@ class CI_Email { $charlim = empty($this->wrapchars) ? 76 : $this->wrapchars; } - // Reduce multiple spaces - $str = preg_replace('| +|', ' ', $str); - // Standardize newlines if (strpos($str, "\r") !== FALSE) { $str = str_replace(array("\r\n", "\r"), "\n", $str); } + // Reduce multiple spaces at end of line + $str = preg_replace('| +\n|', "\n", $str); + // If the current word is surrounded by {unwrap} tags we'll // strip the entire chunk and replace it with a marker. $unwrap = array(); @@ -990,7 +992,6 @@ class CI_Email { $this->_finalbody = $hdr.$this->_finalbody; } - if ($this->send_multipart !== FALSE) { $this->_finalbody .= '--'.$this->_alt_boundary.'--'; @@ -1045,14 +1046,15 @@ class CI_Email { } $attachment = array(); - for ($i = 0, $c = count($this->_attach_name), $z = 0; $i < $c; $i++) + for ($i = 0, $c = count($this->_attachments), $z = 0; $i < $c; $i++) { - $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]; + $filename = $this->_attachments[$i]['name'][0]; + $basename = is_null($this->_attachments[$i]['name'][1]) + ? basename($filename) : $this->_attachments[$i]['name'][1]; + $ctype = $this->_attachments[$i]['type']; $file_content = ''; - if ($this->_attach_type[$i] === '') + if ($ctype === '') { if ( ! file_exists($filename)) { @@ -1074,13 +1076,13 @@ class CI_Email { } else { - $file_content =& $this->_attach_content[$i]; + $file_content =& $this->_attachments[$i]['name'][0]; } $attachment[$z++] = '--'.$this->_atc_boundary.$this->newline .'Content-type: '.$ctype.'; ' .'name="'.$basename.'"'.$this->newline - .'Content-Disposition: '.$this->_attach_disp[$i].';'.$this->newline + .'Content-Disposition: '.$this->_attachments[$i]['disposition'].';'.$this->newline .'Content-Transfer-Encoding: base64'.$this->newline; $attachment[$z++] = chunk_split(base64_encode($file_content)); @@ -1661,7 +1663,7 @@ class CI_Email { // -------------------------------------------------------------------- /** - * SMTP Authenticate + * SMTP Authenticate * * @return bool */ diff --git a/system/libraries/Form_validation.php b/system/libraries/Form_validation.php index 91f46b6de..c1bf51935 100644 --- a/system/libraries/Form_validation.php +++ b/system/libraries/Form_validation.php @@ -957,15 +957,15 @@ class CI_Form_validation { /** * Match one field to another * - * @param string - * @param string field + * @param string $str string to compare against + * @param string $field * @return bool */ public function matches($str, $field) { - $validation_array = empty($this->validation_data) ? $_POST : $this->validation_data; - - return isset($validation_array[$field]) ? ($str === $validation_array[$field]) : FALSE; + return isset($this->_field_data[$field], $this->_field_data[$field]['postdata']) + ? ($str === $this->_field_data[$field]['postdata']) + : FALSE; } // -------------------------------------------------------------------- diff --git a/system/libraries/Session/Session.php b/system/libraries/Session/Session.php index 978506062..fec9b5b31 100755 --- a/system/libraries/Session/Session.php +++ b/system/libraries/Session/Session.php @@ -1,4 +1,4 @@ -<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); +<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * CodeIgniter * @@ -86,7 +86,7 @@ class CI_Session extends CI_Driver_Library { // Get valid drivers list $this->valid_drivers = array( 'Session_native', - 'Session_cookie' + 'Session_cookie' ); $key = 'sess_valid_drivers'; $drivers = isset($params[$key]) ? $params[$key] : $CI->config->item($key); @@ -243,7 +243,7 @@ class CI_Session extends CI_Driver_Library { /** * Fetch all flashdata * - * @return array Flash data array + * @return array Flash data array */ public function all_flashdata() { diff --git a/system/libraries/Session/drivers/Session_cookie.php b/system/libraries/Session/drivers/Session_cookie.php index 8617aec2d..2f1bf3531 100755 --- a/system/libraries/Session/drivers/Session_cookie.php +++ b/system/libraries/Session/drivers/Session_cookie.php @@ -223,9 +223,6 @@ class CI_Session_cookie extends CI_Session_driver { show_error('In order to use the Cookie Session driver you are required to set an encryption key in your config file.'); } - // Load the string helper so we can use the strip_slashes() function - $this->CI->load->helper('string'); - // Do we need encryption? If so, load the encryption class if ($this->sess_encrypt_cookie === TRUE) { @@ -755,7 +752,7 @@ class CI_Session_cookie extends CI_Session_driver { */ protected function _unserialize($data) { - $data = @unserialize(strip_slashes(trim($data))); + $data = @unserialize(trim($data)); if (is_array($data)) { diff --git a/system/libraries/Session/drivers/Session_native.php b/system/libraries/Session/drivers/Session_native.php index da744f39b..a837b89f6 100755 --- a/system/libraries/Session/drivers/Session_native.php +++ b/system/libraries/Session/drivers/Session_native.php @@ -1,4 +1,4 @@ -<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); +<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * CodeIgniter * diff --git a/system/libraries/javascript/Jquery.php b/system/libraries/javascript/Jquery.php index 8739d141f..ed02fadb7 100644 --- a/system/libraries/javascript/Jquery.php +++ b/system/libraries/javascript/Jquery.php @@ -700,7 +700,6 @@ class CI_Jquery extends CI_Javascript { return $updater."\t\t$($container).load('$controller'$request_options);"; } - // -------------------------------------------------------------------- // Pre-written handy stuff // -------------------------------------------------------------------- @@ -716,7 +715,7 @@ class CI_Jquery extends CI_Javascript { protected function _zebraTables($class = '', $odd = 'odd', $hover = '') { $class = ($class !== '') ? '.'.$class : ''; - $zebra = "\t\$(\"table{$class} tbody tr:nth-child(even)\").addClass(\"{$odd}\");"; + $zebra = "\t\$(\"table{$class} tbody tr:nth-child(even)\").addClass(\"{$odd}\");"; $this->jquery_code_for_compile[] = $zebra; diff --git a/tests/codeigniter/core/Common_test.php b/tests/codeigniter/core/Common_test.php index 27d48efc2..999b49cb3 100644 --- a/tests/codeigniter/core/Common_test.php +++ b/tests/codeigniter/core/Common_test.php @@ -2,8 +2,6 @@ class Common_test extends CI_TestCase { - // ------------------------------------------------------------------------ - public function test_is_php() { $this->assertEquals(TRUE, is_php('1.2.0')); @@ -16,12 +14,12 @@ class Common_test extends CI_TestCase { { $this->assertEquals(' class="foo" id="bar"', _stringify_attributes(array('class' => 'foo', 'id' => 'bar'))); - $atts = new Stdclass; + $atts = new stdClass; $atts->class = 'foo'; $atts->id = 'bar'; $this->assertEquals(' class="foo" id="bar"', _stringify_attributes($atts)); - $atts = new Stdclass; + $atts = new stdClass; $this->assertEquals('', _stringify_attributes($atts)); $this->assertEquals(' class="foo" id="bar"', _stringify_attributes('class="foo" id="bar"')); @@ -35,10 +33,20 @@ class Common_test extends CI_TestCase { { $this->assertEquals('width=800,height=600', _stringify_attributes(array('width' => '800', 'height' => '600'), TRUE)); - $atts = new Stdclass; + $atts = new stdClass; $atts->width = 800; $atts->height = 600; $this->assertEquals('width=800,height=600', _stringify_attributes($atts, TRUE)); } + // ------------------------------------------------------------------------ + + public function test_html_escape() + { + $this->assertEquals( + html_escape('Here is a string containing "quoted" text.'), + 'Here is a string containing "quoted" text.' + ); + } + }
\ No newline at end of file diff --git a/tests/codeigniter/core/Config_test.php b/tests/codeigniter/core/Config_test.php index d652a625e..be426d070 100644 --- a/tests/codeigniter/core/Config_test.php +++ b/tests/codeigniter/core/Config_test.php @@ -9,7 +9,7 @@ class Config_test extends CI_TestCase { // set predictable config values $this->cfg = array( 'index_page' => 'index.php', - 'base_url' => 'http://example.com/', + 'base_url' => 'http://example.com/', 'subclass_prefix' => 'MY_' ); $this->ci_set_config($this->cfg); @@ -38,7 +38,6 @@ class Config_test extends CI_TestCase { $this->assertFalse($this->config->item('not_yet_set')); $this->config->set_item('not_yet_set', 'is set'); - $this->assertEquals('is set', $this->config->item('not_yet_set')); } @@ -50,7 +49,6 @@ class Config_test extends CI_TestCase { $this->assertFalse($this->config->slash_item('no_good_item')); $this->assertEquals($this->cfg['base_url'], $this->config->slash_item('base_url')); - $this->assertEquals($this->cfg['subclass_prefix'].'/', $this->config->slash_item('subclass_prefix')); } @@ -124,7 +122,7 @@ class Config_test extends CI_TestCase { $q_string = $this->config->item('enable_query_strings'); $this->config->set_item('enable_query_strings', FALSE); - $uri= 'test'; + $uri = 'test'; $uri2 = '1'; $this->assertEquals($index_page.'/'.$uri, $this->config->site_url($uri)); $this->assertEquals($index_page.'/'.$uri.'/'.$uri2, $this->config->site_url(array($uri, $uri2))); @@ -137,7 +135,6 @@ class Config_test extends CI_TestCase { $this->assertEquals($index_page.'/'.$uri.$suffix.'?'.$arg, $this->config->site_url($uri.'?'.$arg)); $this->config->set_item('url_suffix', FALSE); - $this->config->set_item('enable_query_strings', TRUE); $this->assertEquals($index_page.'?'.$uri, $this->config->site_url($uri)); @@ -233,22 +230,4 @@ class Config_test extends CI_TestCase { $this->assertNull($this->config->load($file)); } - // -------------------------------------------------------------------- - - public function test_assign_to_config() - { - $key1 = 'test'; - $key2 = '1'; - $val1 = 'foo'; - $val2 = 'bar'; - $cfg = array( - $key1 => $val1, - $key2 => $val2 - ); - - $this->assertNull($this->config->_assign_to_config($cfg)); - $this->assertEquals($val1, $this->config->item($key1)); - $this->assertEquals($val2, $this->config->item($key2)); - } - }
\ No newline at end of file diff --git a/tests/codeigniter/core/Loader_test.php b/tests/codeigniter/core/Loader_test.php index f7c338a20..816587a49 100644 --- a/tests/codeigniter/core/Loader_test.php +++ b/tests/codeigniter/core/Loader_test.php @@ -36,7 +36,7 @@ class Loader_test extends CI_TestCase { $this->assertAttributeInstanceOf($class, $lib, $this->ci_obj); // Test no lib given - $this->assertFalse($this->load->library()); + $this->assertNull($this->load->library()); // Test a string given to params $this->assertNull($this->load->library($lib, ' ')); @@ -450,7 +450,7 @@ class Loader_test extends CI_TestCase { public function test_load_config() { $cfg = 'someconfig'; - $this->assertNull($this->load->config($cfg, FALSE)); + $this->assertTrue($this->load->config($cfg, FALSE)); $this->assertContains($cfg, $this->ci_obj->config->loaded); } diff --git a/tests/codeigniter/helpers/form_helper_test.php b/tests/codeigniter/helpers/form_helper_test.php index 48628d2e5..03278581d 100644 --- a/tests/codeigniter/helpers/form_helper_test.php +++ b/tests/codeigniter/helpers/form_helper_test.php @@ -7,6 +7,8 @@ class Form_helper_test extends CI_TestCase $this->helper('form'); } + // ------------------------------------------------------------------------ + public function test_form_hidden() { $expected = <<<EOH @@ -18,6 +20,8 @@ EOH; $this->assertEquals($expected, form_hidden('username', 'johndoe')); } + // ------------------------------------------------------------------------ + public function test_form_input() { $expected = <<<EOH @@ -37,6 +41,8 @@ EOH; $this->assertEquals($expected, form_input($data)); } + // ------------------------------------------------------------------------ + public function test_form_password() { $expected = <<<EOH @@ -47,6 +53,8 @@ EOH; $this->assertEquals($expected, form_password('password')); } + // ------------------------------------------------------------------------ + public function test_form_upload() { $expected = <<<EOH @@ -57,6 +65,8 @@ EOH; $this->assertEquals($expected, form_upload('attachment')); } + // ------------------------------------------------------------------------ + public function test_form_textarea() { $expected = <<<EOH @@ -67,6 +77,8 @@ EOH; $this->assertEquals($expected, form_textarea('notes', 'Notes')); } + // ------------------------------------------------------------------------ + public function test_form_dropdown() { $expected = <<<EOH @@ -130,6 +142,8 @@ EOH; $this->assertEquals($expected, form_dropdown('cars', $options, array('volvo', 'audi'))); } + // ------------------------------------------------------------------------ + public function test_form_multiselect() { $expected = <<<EOH @@ -152,6 +166,8 @@ EOH; $this->assertEquals($expected, form_multiselect('shirts[]', $options, array('med', 'large'))); } + // ------------------------------------------------------------------------ + public function test_form_fieldset() { $expected = <<<EOH @@ -163,6 +179,8 @@ EOH; $this->assertEquals($expected, form_fieldset('Address Information')); } + // ------------------------------------------------------------------------ + public function test_form_fieldset_close() { $expected = <<<EOH @@ -172,6 +190,8 @@ EOH; $this->assertEquals($expected, form_fieldset_close('</div></div>')); } + // ------------------------------------------------------------------------ + public function test_form_checkbox() { $expected = <<<EOH @@ -182,6 +202,8 @@ EOH; $this->assertEquals($expected, form_checkbox('newsletter', 'accept', TRUE)); } + // ------------------------------------------------------------------------ + public function test_form_radio() { $expected = <<<EOH @@ -192,6 +214,8 @@ EOH; $this->assertEquals($expected, form_radio('newsletter', 'accept', TRUE)); } + // ------------------------------------------------------------------------ + public function test_form_submit() { $expected = <<<EOH @@ -202,6 +226,8 @@ EOH; $this->assertEquals($expected, form_submit('mysubmit', 'Submit Post!')); } + // ------------------------------------------------------------------------ + public function test_form_label() { $expected = <<<EOH @@ -211,6 +237,8 @@ EOH; $this->assertEquals($expected, form_label('What is your Name', 'username')); } + // ------------------------------------------------------------------------ + public function test_form_reset() { $expected = <<<EOH @@ -221,6 +249,8 @@ EOH; $this->assertEquals($expected, form_reset('myreset', 'Reset')); } + // ------------------------------------------------------------------------ + public function test_form_button() { $expected = <<<EOH @@ -231,6 +261,8 @@ EOH; $this->assertEquals($expected, form_button('name', 'content')); } + // ------------------------------------------------------------------------ + public function test_form_close() { $expected = <<<EOH @@ -240,13 +272,6 @@ EOH; $this->assertEquals($expected, form_close('</div></div>')); } - public function test_form_prep() - { - $expected = 'Here is a string containing "quoted" text.'; - - $this->assertEquals($expected, form_prep('Here is a string containing "quoted" text.')); - } - } /* End of file form_helper_test.php */
\ No newline at end of file diff --git a/user_guide_src/source/changelog.rst b/user_guide_src/source/changelog.rst index 990ba1386..2df8ca7c1 100644 --- a/user_guide_src/source/changelog.rst +++ b/user_guide_src/source/changelog.rst @@ -75,7 +75,9 @@ Release Date: Not Released - Refactored ``plural()`` and ``singular()`` to avoid double pluralization and support more words. - Added an optional third parameter to ``force_download()`` that enables/disables sending the actual file MIME type in the Content-Type header (disabled by default). - Added a work-around in ``force_download()`` for a bug Android <= 2.1, where the filename extension needs to be in uppercase. - - ``form_dropdown()`` will now also take an array for unity with other form helpers. + - :doc:`Form Helper <helpers/form_helper>` changes include: + - ``form_dropdown()`` will now also take an array for unity with other form helpers. + - ``form_prep()`` is now **DEPRECATED** and only acts as an alias for :doc:`common function <general/common_functions>` ``html_escape()``. - ``do_hash()`` now uses PHP's native ``hash()`` function (supporting more algorithms) and is deprecated. - Removed previously deprecated helper function ``js_insert_smiley()`` from :doc:`Smiley Helper <helpers/smiley_helper>`. - :doc:`File Helper <helpers/file_helper>` changes include: @@ -83,6 +85,7 @@ Release Date: Not Released - Added an optional paramater to ``delete_files()`` to enable it to skip deleting files such as .htaccess and index.html. - ``read_file()`` is now a deprecated alias of ``file_get_contents()``. - :doc:`Security Helper <helpers/security_helper>` function ``strip_image_tags()`` is now an alias for the same method in the :doc:`Security Library <libraries/security>`. + - Deprecated :doc:`String Helper <helpers/string_helper>` function ``repeater()`` - it's just an alias for PHP's native ``str_repeat()``. - Database @@ -101,7 +104,8 @@ Release Date: Not Released - Server version checking is now done via ``mysqli::$server_info`` instead of running an SQL query. - Added persistent connections support for PHP >= 5.3. - Added support for ``backup()`` in :doc:`Database Utilities <database/utilities>`. - - Added *dsn* configuration setting for drivers that support DSN strings (PDO, PostgreSQL, Oracle, ODBC, CUBRID). + - Added **dsn** configuration setting for drivers that support DSN strings (PDO, PostgreSQL, Oracle, ODBC, CUBRID). + - Added **schema** configuration setting (defaults to *public*) for drivers that might need it (currently used by PostgreSQL and ODBC). - Improved PDO database support. - Added Interbase/Firebird database support via the *ibase* driver. - Added an optional database name parameter to ``db_select()``. @@ -173,9 +177,10 @@ Release Date: Not Released - Added *max_filename_increment* config setting. - Added an "index" parameter to the ``data()`` method. - :doc:`Cart library <libraries/cart>` changes include: - - It now auto-increments quantity's instead of just resetting it, this is the default behaviour of large e-commerce sites. - - Product Name strictness can be disabled via the Cart Library by switching "$product_name_safe". - - Added function remove() to remove a cart item, updating with quantity of 0 seemed like a hack but has remained to retain compatibility. + - ``insert()`` now auto-increments quantity for an item when inserted twice instead of resetting it, this is the default behaviour of large e-commerce sites. + - *Product Name* strictness can be disabled by switching the ``$product_name_safe`` property to FALSE. + - Added method ``remove()`` to remove a cart item, updating with quantity of 0 seemed like a hack but has remained to retain compatibility. + - Added method ``get_item()`` to enable retrieving data for a single cart item. - :doc:`Image Manipulation library <libraries/image_lib>` changes include: - The initialize() method now only sets existing class properties. - Added support for 3-length hex color values for *wm_font_color* and *wm_shadow_color* properties, as well as validation for them. @@ -195,8 +200,10 @@ Release Date: Not Released - Fields that have empty rules set no longer run through validation (and therefore are not considered erroneous). - Added rule *differs* to check if the value of a field differs from the value of another field. - Added support for setting :doc:`Table <libraries/table>` class defaults in a config file. - - Added a Wincache driver to the :doc:`Caching Library <libraries/caching>`. - - Added a Redis driver to the :doc:`Caching Library <libraries/caching>`. + - :doc:`Caching Library <libraries/caching>` changes include: + - Added Wincache driver. + - Added Redis driver. + - Added a *key_prefix* option for cache IDs. - :doc:`Email library <libraries/email>` changes include: - Added custom filename to ``Email::attach()`` as ``$this->email->attach($filename, $disposition, $newname)``. - Added possibility to send attachment as buffer string in ``Email::attach()`` as ``$this->email->attach($buffer, $disposition, $newname, $mime)``. @@ -223,18 +230,26 @@ Release Date: Not Released - Core - - Changed private methods in the :doc:`URI Library <libraries/uri>` to protected so MY_URI can override them. + - :doc:`URI Library <libraries/uri>` changes include: + - Changed private methods to protected so that MY_URI can override them. + - Renamed internal method ``_parse_cli_args()`` to ``_parse_argv()``. + - Renamed internal method ``_detect_uri()`` to ``_parse_request_uri()``. + - Changed ``_parse_request_uri()`` to accept absolute URIs for compatibility with HTTP/1.1 as per `RFC2616 <http://www.ietf.org/rfc/rfc2616.txt>`. + - Added protected method ``_parse_query_string()`` to URI paths in the the **QUERY_STRING** value, like ``_parse_request_uri()`` does. - Removed ``CI_CORE`` boolean constant from *CodeIgniter.php* (no longer Reactor and Core versions). - :doc:`Loader Library <libraries/loader>` changes include: - Added method ``get_vars()`` to the Loader to retrieve all variables loaded with ``$this->load->vars()``. - - ``CI_Loader::_ci_autoloader()`` is now a protected method. + - ``_ci_autoloader()`` is now a protected method. - Added autoloading of drivers with ``$autoload['drivers']``. - - ``CI_Loader::library()`` will now load drivers as well, for backward compatibility of converted libraries (like Session). - - ``$config['rewrite_short_tags']`` now has no effect when using PHP 5.4 as *<?=* will always be available. + - ``library()`` method will now load drivers as well, for backward compatibility of converted libraries (like :doc:`Session <libraries/sessions>`). + - ``$config['rewrite_short_tags']`` now has no effect when using PHP 5.4 as ``<?=`` will always be available. + - Changed method ``config()`` to return whatever ``CI_Config::load()`` returns instead of always being void. - :doc:`Input Library <libraries/input>` changes include: - Added ``method()`` to retrieve ``$_SERVER['REQUEST_METHOD']``. - - Modified ``valid_ip()`` to use PHP's ``filter_var()``. - Added support for arrays and network addresses (e.g. 192.168.1.1/24) for use with the *proxy_ips* setting. + - Changed method ``valid_ip()`` to use PHP's native ``filter_var()`` function. + - Changed internal method ``_sanitize_globals()`` to skip enforcing reversal of *register_globals* in PHP 5.4+, where this functionality no longer exists. + - Changed methods ``get()``, ``post()``, ``get_post()``, ``cookie()``, ``server()``, ``user_agent()`` to return NULL instead of FALSE when no value is found. - :doc:`Common functions <general/common_functions>` changes include: - Added function ``get_mimes()`` to return the *config/mimes.php* array. - Added support for HTTP code 303 ("See Other") in ``set_status_header()``. @@ -247,7 +262,9 @@ Release Date: Not Released - Added method ``get_content_type()``. - Added a second argument to method ``set_content_type()`` that allows setting the document charset as well. - ``$config['time_reference']`` now supports all timezone strings supported by PHP. - - Changed :doc:`Config Library <libraries/config>` method ``site_url()`` to accept an array as well. + - :doc:`Config Library <libraries/config>` changes include: + - Changed ``site_url()`` method to accept an array as well. + - Removed internal method ``_assign_to_config()`` and moved it's implementation in *CodeIgniter.php* instead. - :doc:`Security Library <libraries/security>` changes include: - Added method ``strip_image_tags()``. - Added ``$config['csrf_regeneration']``, which makes token regeneration optional. @@ -382,6 +399,14 @@ Bug fixes for 3.0 - Fixed a bug (#1255) - :doc:`User Agent Library <libraries/user_agent>` method ``is_referral()`` only checked if ``$_SERVER['HTTP_REFERER']`` exists. - Fixed a bug (#1146) - :doc:`Download Helper <helpers/download_helper>` function ``force_download()`` incorrectly sent *Cache-Control* directives *pre-check* and *post-check* to Internet Explorer. - Fixed a bug (#1811) - :doc:`URI Library <libraries/uri>` didn't properly cache segments for ``uri_to_assoc()`` and ``ruri_to_assoc()``. +- Fixed a bug (#1506) - :doc:`Form Helpers <helpers/form_helper>` set empty *name* attributes. +- Fixed a bug (#59) - :doc:`Query Builder <database/query_builder>` method ``count_all_results()`` ignored the DISTINCT clause. +- Fixed a bug (#1624) - :doc:`Form Validation Library <libraries/form_validation>` rule **matches** didn't property handle array field names. +- Fixed a bug (#1630) - :doc:`Form Helper <helpers/form_helper>` function ``set_value()`` didn't escape HTML entities. +- Fixed a bug (#142) - :doc:`Form Helper <helpers/form_helper>` function ``form_dropdown()`` didn't escape HTML entities in option values. +- Fixed a bug (#50) - :doc:`Session Library <libraries/sessions>` unnecessarily stripped slashed from serialized data, making it impossible to read objects in a namespace. +- Fixed a bug (#658) - :doc:`Routing <general/routing>` wildcard **:any** didn't work as advertised and matched multiple URI segments instead of all characters within a single segment. +- Fixed a bug (#1938) - :doc:`Email <libraries/email>` where the email library removed multiple spaces inside a pre-formatted plain text message. Version 2.1.3 ============= @@ -396,7 +421,7 @@ Bug fixes for 2.1.3 - Fixed a bug (#1543) - File-based :doc:`Caching <libraries/caching>` method ``get_metadata()`` used a non-existent array key to look for the TTL value. - Fixed a bug (#1314) - :doc:`Session Library <libraries/sessions>` method ``sess_destroy()`` didn't destroy the userdata array. -- Fixed a bug (#804) - Profiler library was trying to handle objects as strings in some cases, resulting in *E_WARNING* messages being issued by ``htmlspecialchars()``. +- Fixed a bug (#804) - :doc:`Profiler library <general/profiling>` was trying to handle objects as strings in some cases, resulting in *E_WARNING* messages being issued by ``htmlspecialchars()``. - Fixed a bug (#1699) - :doc:`Migration Library <libraries/migration>` ignored the ``$config['migration_path']`` setting. - Fixed a bug (#227) - :doc:`Input Library <libraries/input>` allowed unconditional spoofing of HTTP clients' IP addresses through the *HTTP_CLIENT_IP* header. - Fixed a bug (#907) - :doc:`Input Library <libraries/input>` ignored *HTTP_X_CLUSTER_CLIENT_IP* and *HTTP_X_CLIENT_IP* headers when checking for proxies. diff --git a/user_guide_src/source/database/configuration.rst b/user_guide_src/source/database/configuration.rst index 668496324..34cefffbd 100644 --- a/user_guide_src/source/database/configuration.rst +++ b/user_guide_src/source/database/configuration.rst @@ -182,6 +182,7 @@ Explanation of Values: customizable by the end user. **autoinit** Whether or not to automatically connect to the database when the library loads. If set to false, the connection will take place prior to executing the first query. +**schema** The database schema, defaults to 'public'. Used by PostgreSQL and ODBC drivers. **encrypt** Whether or not to use an encrypted connection. **compress** Whether or not to use client compression (MySQL only). **stricton** TRUE/FALSE (boolean) - Whether to force "Strict Mode" connections, good for ensuring strict SQL diff --git a/user_guide_src/source/database/query_builder.rst b/user_guide_src/source/database/query_builder.rst index 5380d0998..61cd7dfed 100644 --- a/user_guide_src/source/database/query_builder.rst +++ b/user_guide_src/source/database/query_builder.rst @@ -492,8 +492,8 @@ Or multiple function calls can be made if you need multiple fields. .. note:: order_by() was formerly known as orderby(), which has been removed. -.. note:: random ordering is not currently supported in Oracle or MSSQL - drivers. These will default to 'ASC'. +.. note:: Random ordering is not currently supported in Oracle and + will default to ASC instead. $this->db->limit() ================== diff --git a/user_guide_src/source/general/routing.rst b/user_guide_src/source/general/routing.rst index 144f129e8..43c181669 100644 --- a/user_guide_src/source/general/routing.rst +++ b/user_guide_src/source/general/routing.rst @@ -29,7 +29,7 @@ Setting your own routing rules Routing rules are defined in your application/config/routes.php file. In it you'll see an array called $route that permits you to specify your own routing criteria. Routes can either be specified using wildcards or -Regular Expressions +Regular Expressions. Wildcards ========= @@ -47,7 +47,11 @@ segment of the URL, and a number is found in the second segment, the You can match literal values or you can use two wildcard types: **(:num)** will match a segment containing only numbers. -**(:any)** will match a segment containing any character. +**(:any)** will match a segment containing any character (except for '/', which is the segment delimiter). + +.. note:: Wildcards are actually aliases for regular expressions, with + **:any** being translated to **[^/]+** and **:num** to **[0-9]+**, + respectively. .. note:: Routes will run in the order they are defined. Higher routes will always take precedence over lower ones. @@ -104,12 +108,28 @@ rules. Any valid regular expression is allowed, as are back-references. A typical RegEx route might look something like this:: - $route['products/([a-z]+)/(\d+)'] = "$1/id_$2"; + $route['products/([a-z]+)/(\d+)'] = '$1/id_$2'; In the above example, a URI similar to products/shirts/123 would instead -call the shirts controller class and the id_123 function. +call the shirts controller class and the id_123 method. + +With regular expressions, you can also catch a segment containing a +forward slash ('/'), which would usually represent the delimiter between +multiple segments. +For example, if a user accesses a password protected area of your web +application and you wish to be able to redirect them back to the same +page after they log in, you may find this example useful:: + + $route['login/(.+)'] = 'auth/login/$1'; + +That will call the auth controller class and its ``login()`` method, +passing everything contained in the URI after *login/* as a parameter. + +For those of you who don't know regular expressions and want to learn +more about them, `regular-expressions.info <http://www.regular-expressions.info/>` +might be a good starting point. -You can also mix and match wildcards with regular expressions. +..note:: You can also mix and match wildcards with regular expressions. Callbacks ========= diff --git a/user_guide_src/source/helpers/form_helper.rst b/user_guide_src/source/helpers/form_helper.rst index fa7b3dbf9..015bf1162 100644 --- a/user_guide_src/source/helpers/form_helper.rst +++ b/user_guide_src/source/helpers/form_helper.rst @@ -463,29 +463,6 @@ the tag. For example echo form_close($string); // Would produce: </form> </div></div> -form_prep() -=========== - -Allows you to safely use HTML and characters such as quotes within form -elements without breaking out of the form. Consider this example - -:: - - $string = 'Here is a string containing "quoted" text.'; - <input type="text" name="myform" value="$string" /> - -Since the above string contains a set of quotes it will cause the form -to break. The `form_prep()` function converts HTML so that it can be used -safely - -:: - - <input type="text" name="myform" value="<?php echo form_prep($string); ?>" /> - -.. note:: If you use any of the form helper functions listed in this page the form - values will be prepped automatically, so there is no need to call this - function. Use it only if you are creating your own form elements. - set_value() =========== @@ -546,4 +523,26 @@ This function is identical to the **set_checkbox()** function above. .. note:: If you are using the Form Validation class, you must always specify a rule for your field, even if empty, in order for the set_*() functions to work. This is because if a Form Validation object is defined, the control for set_*() is handed over to a method of the class instead of the generic helper - function.
\ No newline at end of file + function. + +Escaping field values +===================== + +You may need to use HTML and characters such as quotes within form +elements. In order to do that safely, you'll need to use +:doc:`common function <../general/common_functions>` ``html_escape()``. + +Consider the following example:: + + $string = 'Here is a string containing "quoted" text.'; + <input type="text" name="myform" value="$string" /> + +Since the above string contains a set of quotes it will cause the form +to break. The ``html_escape()`` function converts HTML so that it can be +used safely:: + + <input type="text" name="myform" value="<?php echo html_escape($string); ?>" /> + +.. note:: If you use any of the form helper functions listed in this page, the form + values will be prepped automatically, so there is no need to call this + function. Use it only if you are creating your own form elements.
\ No newline at end of file diff --git a/user_guide_src/source/helpers/string_helper.rst b/user_guide_src/source/helpers/string_helper.rst index 19500aa0d..530af2f89 100644 --- a/user_guide_src/source/helpers/string_helper.rst +++ b/user_guide_src/source/helpers/string_helper.rst @@ -96,6 +96,9 @@ Generates repeating copies of the data you submit. Example The above would generate 30 newlines. +.. note:: This function is DEPRECATED. Use the native ``str_repeat()`` + instead. + reduce_double_slashes() ======================= diff --git a/user_guide_src/source/installation/upgrade_300.rst b/user_guide_src/source/installation/upgrade_300.rst index 31a5c0761..6d99f4655 100644 --- a/user_guide_src/source/installation/upgrade_300.rst +++ b/user_guide_src/source/installation/upgrade_300.rst @@ -52,11 +52,12 @@ Step 5: Update your config/database.php *************************************** Due to 3.0.0's renaming of Active Record to Query Builder, inside your `config/database.php`, you will -need to rename the `$active_record` variable to `$query_builder`. +need to rename the `$active_record` variable to `$query_builder` +:: - $active_group = 'default'; - // $active_record = TRUE; - $query_builder = TRUE; + $active_group = 'default'; + // $active_record = TRUE; + $query_builder = TRUE; ******************************* Step 6: Move your errors folder @@ -64,16 +65,53 @@ Step 6: Move your errors folder In version 3.0.0, the errors folder has been moved from _application/errors* to _application/views/errors*. +******************************************************* +Step 7: Update your config/routes.php containing (:any) +******************************************************* + +Historically, CodeIgniter has always provided the **:any** wildcard in routing, +with the intention of providing a way to match any character **within** an URI segment. + +However, the **:any** wildcard is actually just an alias for a regular expression +and used to be executed in that manner as **.+**. This is considered a bug, as it +also matches the / (forward slash) character, which is the URI segment delimiter +and that was never the intention. In CodeIgniter 3, the **:any** wildcard will now +represent **[^/]+**, so that it will not match a forward slash. + +There are certainly many developers that have utilized this bug as an actual feature. +If you're one of them and want to match a forward slash, please use the **.+** +regular expression:: + + (.+) // matches ANYTHING + (:any) // matches any character, except for '/' + + **************************************************************************** -Step 7: Check the calls to Array Helper's element() and elements() functions +Step 8: Check the calls to Array Helper's element() and elements() functions **************************************************************************** The default return value of these functions, when the required elements don't exist, has been changed from FALSE to NULL. -*************************************************************** -Step 8: Remove usage of (previously) deprecated functionalities -*************************************************************** +********************************************************** +Step 9: Change usage of Email library with multiple emails +********************************************************** + +The :doc:`Email library <../libraries/email>` will automatically clear the +set parameters after successfully sending emails. To override this behaviour, +pass FALSE as the first parameter in the ``send()`` method: + +:: + + if ($this->email->send(FALSE)) + { + // Parameters won't be cleared + } + + +**************************************************************** +Step 10: Remove usage of (previously) deprecated functionalities +**************************************************************** In addition to the ``$autoload['core']`` configuration setting, there's a number of other functionalities that have been removed in CodeIgniter 3.0.0: @@ -118,6 +156,26 @@ CodeIgniter 3.1+. .. note:: This function is still available, but you're strongly encouraged to remove it's usage sooner rather than later. +String helper repeater() +======================== + +:doc:`String Helper <../helpers/string_helper>` function ``repeater()`` is now just an alias for +PHP's native ``str_repeat()`` function. It is deprecated and scheduled for removal in +CodeIgniter 3.1+. + +.. note:: This function is still available, but you're strongly encouraged to remove it's usage sooner + rather than later. + +Form helper form_prep() +======================= + +:doc:`Form Helper <../helpers/form_helper>` function ``form_prep()`` is now just an alias for +:doc:`common function <../general/common_functions>` ``html_escape()`` and it's second argument +is ignored. It is deprecated and scheduled for removal in CodeIgniter 3.1+. + +.. note:: This function is still available, but you're strongly encouraged to remove it's usage sooner + rather than later. + Date helper standard_date() =========================== @@ -154,17 +212,4 @@ As a result of that, the 'anchor_class' setting is now deprecated and scheduled CodeIgniter 3.1+. .. note:: This setting is still available, but you're strongly encouraged to remove its' usage sooner - rather than later. - -Email library -============= - -The :doc:`Email library <../libraries/email>` will automatically clear the set parameters after successfully sending -emails. To override this behaviour, pass FALSE as the first parameter in the ``send()`` function: - -:: - - if ($this->email->send(FALSE)) - { - // Parameters won't be cleared - } + rather than later.
\ No newline at end of file diff --git a/user_guide_src/source/libraries/caching.rst b/user_guide_src/source/libraries/caching.rst index 2f06d29f9..8d7b4c440 100644 --- a/user_guide_src/source/libraries/caching.rst +++ b/user_guide_src/source/libraries/caching.rst @@ -32,6 +32,17 @@ available in the hosting environment. echo $foo; +You can also prefix cache item names via the **key_prefix** setting, which is useful +to avoid collisions when you're running multiple applications on the same environment. + +:: + + $this->load->driver('cache', + array('adapter' => 'apc', 'backup' => 'file', 'key_prefix' => 'my_') + ); + + $this->cache->get('foo'); // Will get the cache entry named 'my_foo' + ****************** Function Reference ****************** @@ -39,7 +50,7 @@ Function Reference .. php:class:: CI_Cache is_supported() -=============== +============== .. php:method:: is_supported ( $driver ) @@ -130,7 +141,7 @@ clean() $this->cache->clean(); cache_info() -============= +============ .. php:method:: cache_info ( ) @@ -148,7 +159,7 @@ cache_info() get_metadata() -=============== +============== .. php:method:: get_metadata ( $id ) @@ -166,7 +177,6 @@ get_metadata() .. note:: The information returned and the structure of the data is dependent on which adapter is being used. - ******* Drivers ******* @@ -181,7 +191,7 @@ specific adapter to the driver loader as follows:: $this->cache->apc->save('foo', 'bar', 10); For more information on APC, please see -`http://php.net/apc <http://php.net/apc>`_ +`http://php.net/apc <http://php.net/apc>`_. File-based Caching ================== @@ -201,20 +211,49 @@ Memcached Caching ================= Multiple Memcached servers can be specified in the memcached.php -configuration file, located in the application/config/ directory. +configuration file, located in the _application/config/* directory. -All of the functions listed above can be accessed without passing a +All of the methods listed above can be accessed without passing a specific adapter to the driver loader as follows:: $this->load->driver('cache'); $this->cache->memcached->save('foo', 'bar', 10); For more information on Memcached, please see -`http://php.net/memcached <http://php.net/memcached>`_ +`http://php.net/memcached <http://php.net/memcached>`_. + +WinCache Caching +================ + +Under Windows, you can also utilize the WinCache driver. + +All of the functions listed above can be accessed without passing a +specific adapter to the driver loader as follows:: + + $this->load->driver('cache'); + $this->cache->wincache->save('foo', 'bar', 10); + +For more information on WinCache, please see +`http://php.net/wincache <http://php.net/wincache>`_. + +Redis Caching +============= + +All of the methods listed above can be accessed without passing a +specific adapter to the driver loader as follows:: + + $this->load->driver('cache'); + $this->cache->redis->save('foo', 'bar', 10); + +.. important:: Redis may require one or more of the following options: + **host**, **post**, **timeout**, **password**. + +The Redis PHP extension repository is located at +`https://github.com/nicolasff/phpredis <https://github.com/nicolasff/phpredis>`_. Dummy Cache =========== This is a caching backend that will always 'miss.' It stores no data, but lets you keep your caching code in place in environments that don't -support your chosen cache. +support your chosen cache.
\ No newline at end of file diff --git a/user_guide_src/source/libraries/cart.rst b/user_guide_src/source/libraries/cart.rst index 6594b3b9a..716e94bcb 100644 --- a/user_guide_src/source/libraries/cart.rst +++ b/user_guide_src/source/libraries/cart.rst @@ -279,16 +279,22 @@ by which this is returned by passing it "true" where the contents will be sorted from newest to oldest, by leaving this function blank, you'll automatically just get first added to the basket to last added to the basket. -$this->cart->has_options(rowid); -******************************** +$this->cart->get_item($row_id); +******************************* + +Returns an array containing data for the item matching the specified row ID, +or FALSE if no such item exists. + +$this->cart->has_options($row_id); +********************************** Returns TRUE (boolean) if a particular row in the cart contains options. This function is designed to be used in a loop with $this->cart->contents(), since you must pass the rowid to this function, as shown in the Displaying the Cart example above. -$this->cart->product_options(rowid); -************************************ +$this->cart->product_options($row_id); +************************************** Returns an array of options for a particular product. This function is designed to be used in a loop with $this->cart->contents(), since you diff --git a/user_guide_src/source/libraries/form_validation.rst b/user_guide_src/source/libraries/form_validation.rst index 6c6743d06..4d1940212 100644 --- a/user_guide_src/source/libraries/form_validation.rst +++ b/user_guide_src/source/libraries/form_validation.rst @@ -254,30 +254,30 @@ Setting Rules Using an Array Before moving on it should be noted that the rule setting function can be passed an array if you prefer to set all your rules in one action. If -you use this approach you must name your array keys as indicated:: +you use this approach, you must name your array keys as indicated:: $config = array( - array( - 'field' => 'username', - 'label' => 'Username', - 'rules' => 'required' - ), - array( - 'field' => 'password', - 'label' => 'Password', - 'rules' => 'required' - ), - array( - 'field' => 'passconf', - 'label' => 'Password Confirmation', - 'rules' => 'required' - ), - array( - 'field' => 'email', - 'label' => 'Email', - 'rules' => 'required' - ) - ); + array( + 'field' => 'username', + 'label' => 'Username', + 'rules' => 'required' + ), + array( + 'field' => 'password', + 'label' => 'Password', + 'rules' => 'required' + ), + array( + 'field' => 'passconf', + 'label' => 'Password Confirmation', + 'rules' => 'required' + ), + array( + 'field' => 'email', + 'label' => 'Email', + 'rules' => 'required' + ) + ); $this->form_validation->set_rules($config); @@ -291,7 +291,6 @@ your rules in the third parameter of rule setting function, like this:: $this->form_validation->set_rules('password', 'Password', 'required|matches[passconf]'); $this->form_validation->set_rules('passconf', 'Password Confirmation', 'required'); $this->form_validation->set_rules('email', 'Email', 'required|valid_email|is_unique[users.email]'); - The above code sets the following rules: @@ -560,11 +559,10 @@ globally, individually, or change the defaults in a config file. #. **Set delimiters in a config file** You can add your error delimiters in application/config/form_validation.php as follows:: - + $config['error_prefix'] = '<div class="error_prefix">'; $config['error_suffix'] = '</div>'; - Showing Errors Individually =========================== @@ -592,8 +590,8 @@ Try it! Change your form so that it looks like this:: If there are no errors, nothing will be shown. If there is an error, the message will appear. -**Important Note:** If you use an array as the name of a form field, you -must supply it as an array to the function. Example:: +.. important:: If you use an array as the name of a form field, you + must supply it as an array to the function. Example:: <?php echo form_error('options[size]'); ?> <input type="text" name="options[size]" value="<?php echo set_value("options[size]"); ?>" size="50" /> @@ -603,20 +601,20 @@ For more info please see the :ref:`using-arrays-as-field-names` section below. Validating an Array (other than $_POST) ======================================= -Sometimes you may want to validate an array that does not originate from $_POST data. +Sometimes you may want to validate an array that does not originate from ``$_POST`` data. In this case, you can specify the array to be validated:: - + $data = array( - 'username' => 'johndoe', - 'password' => 'mypassword', - 'passconf' => 'mypassword' - ); + 'username' => 'johndoe', + 'password' => 'mypassword', + 'passconf' => 'mypassword' + ); $this->form_validation->set_data($data); -Creating validation rules, running the validation and retrieving error messages works the same whether you are -validating $_POST data or an array. +Creating validation rules, running the validation and retrieving error messages works the +same whether you are validating ``$_POST`` data or an array. **Important Note:** If you want to validate more than one array during a single execution, then you should call the reset_validation() function before setting up rules and validating the new array. @@ -644,32 +642,32 @@ you will place an array named $config with your rules. As shown earlier, the validation array will have this prototype:: $config = array( - array( - 'field' => 'username', - 'label' => 'Username', - 'rules' => 'required' - ), - array( - 'field' => 'password', - 'label' => 'Password', - 'rules' => 'required' - ), - array( - 'field' => 'passconf', - 'label' => 'Password Confirmation', - 'rules' => 'required' - ), - array( - 'field' => 'email', - 'label' => 'Email', - 'rules' => 'required' - ) - ); + array( + 'field' => 'username', + 'label' => 'Username', + 'rules' => 'required' + ), + array( + 'field' => 'password', + 'label' => 'Password', + 'rules' => 'required' + ), + array( + 'field' => 'passconf', + 'label' => 'Password Confirmation', + 'rules' => 'required' + ), + array( + 'field' => 'email', + 'label' => 'Email', + 'rules' => 'required' + ) + ); Your validation rule file will be loaded automatically and used when you -call the run() function. +call the ``run()`` method. -Please note that you MUST name your array $config. +Please note that you MUST name your ``$config`` array. Creating Sets of Rules ====================== @@ -729,45 +727,44 @@ You can name your rules anything you want:: Calling a Specific Rule Group ============================= -In order to call a specific group you will pass its name to the run() -function. For example, to call the signup rule you will do this:: +In order to call a specific group you will pass its name to the ``run()`` +method. For example, to call the signup rule you will do this:: if ($this->form_validation->run('signup') == FALSE) { - $this->load->view('myform'); + $this->load->view('myform'); } else { - $this->load->view('formsuccess'); + $this->load->view('formsuccess'); } Associating a Controller Function with a Rule Group =================================================== An alternate (and more automatic) method of calling a rule group is to -name it according to the controller class/function you intend to use it +name it according to the controller class/method you intend to use it with. For example, let's say you have a controller named Member and a -function named signup. Here's what your class might look like:: +method named signup. Here's what your class might look like:: <?php class Member extends CI_Controller { - function signup() - { - $this->load->library('form_validation'); - - if ($this->form_validation->run() == FALSE) - { - $this->load->view('myform'); - } - else - { - $this->load->view('formsuccess'); - } - } + function signup() + { + $this->load->library('form_validation'); + + if ($this->form_validation->run() == FALSE) + { + $this->load->view('myform'); + } + else + { + $this->load->view('formsuccess'); + } + } } - ?> In your validation config file, you will name your rule group member/signup:: @@ -913,6 +910,9 @@ Rule Parameter Description to two parameters, where at least one is required (to pass the field data). +.. note:: When using the **matches** rule, the form item specified + to compare against must already be defined. + ****************** Prepping Reference ****************** @@ -945,7 +945,7 @@ The following functions are intended for use in your controller functions. $this->form_validation->set_rules(); -====================================== +==================================== .. php:method:: set_rules ($field, $label = '', $rules = '') @@ -953,7 +953,7 @@ $this->form_validation->set_rules(); :param string $label: The field label :param mixed $rules: The rules, as a string with rules separated by a pipe "|", or an array or rules. :rtype: Object - + Permits you to set validation rules, as described in the tutorial sections above: @@ -961,19 +961,19 @@ $this->form_validation->set_rules(); - :ref:`saving-groups` $this->form_validation->run(); -=============================== +============================== .. php:method:: run ($group = '') :param string $group: The name of the validation group to run :rtype: Boolean - + Runs the validation routines. Returns boolean TRUE on success and FALSE on failure. You can optionally pass the name of the validation group via the function, as described in: :ref:`saving-groups` $this->form_validation->set_message(); -======================================== +====================================== .. php:method:: set_message ($lang, $val = '') @@ -984,7 +984,7 @@ $this->form_validation->set_message(); Permits you to set custom error messages. See :ref:`setting-error-messages` $this->form_validation->set_data(); -======================================== +=================================== .. php:method:: set_data ($data = '') @@ -996,13 +996,13 @@ $this->form_validation->set_data(); $this->form_validation->reset_validation(); =========================================== - .. php:method:: reset_validation () + .. php:method:: reset_validation () - Permits you to reset the validation when you validate more than one array. - This function should be called before validating each new array. + Permits you to reset the validation when you validate more than one array. + This method should be called before validating each new array. $this->form_validation->error_array(); -======================================== +====================================== .. php:method:: error_array () @@ -1021,7 +1021,7 @@ containing your forms. Note that these are procedural functions, so they **do not** require you to prepend them with $this->form_validation. form_error() -============= +============ Shows an individual error message associated with the field name supplied to the function. Example:: @@ -1032,7 +1032,7 @@ The error delimiters can be optionally specified. See the :ref:`changing-delimiters` section above. validation_errors() -==================== +=================== Shows all error messages as a string: Example:: @@ -1042,7 +1042,7 @@ The error delimiters can be optionally specified. See the :ref:`changing-delimiters` section above. set_value() -============ +=========== Permits you to set the value of an input form or textarea. You must supply the field name via the first parameter of the function. The @@ -1054,7 +1054,7 @@ form. Example:: The above form will show "0" when loaded for the first time. set_select() -============= +============ If you use a <select> menu, this function permits you to display the menu item that was selected. The first parameter must contain the name @@ -1071,7 +1071,7 @@ Example:: </select> set_checkbox() -=============== +============== Permits you to display a checkbox in the state it was submitted. The first parameter must contain the name of the checkbox, the second @@ -1082,7 +1082,7 @@ lets you set an item as the default (use boolean TRUE/FALSE). Example:: <input type="checkbox" name="mycheck[]" value="2" <?php echo set_checkbox('mycheck[]', '2'); ?> /> set_radio() -============ +=========== Permits you to display radio buttons in the state they were submitted. This function is identical to the **set_checkbox()** function above. @@ -1090,4 +1090,4 @@ This function is identical to the **set_checkbox()** function above. :: <input type="radio" name="myradio" value="1" <?php echo set_radio('myradio', '1', TRUE); ?> /> - <input type="radio" name="myradio" value="2" <?php echo set_radio('myradio', '2'); ?> /> + <input type="radio" name="myradio" value="2" <?php echo set_radio('myradio', '2'); ?> />
\ No newline at end of file |