diff options
author | Iban Eguia <admin@razican.com> | 2012-06-08 23:01:31 +0200 |
---|---|---|
committer | Iban Eguia <admin@razican.com> | 2012-06-08 23:01:31 +0200 |
commit | 895e98c0f04f1087e8900ce8423ad3210a423770 (patch) | |
tree | 6adfe487293df38807084599f1f04157b5531e54 /system/libraries | |
parent | 0ed4f63f4268b0c98f549ffd711702fd45a761d0 (diff) | |
parent | a593c69de4ea125c096f611c78dd0839489e7ebd (diff) |
Merge remote-tracking branch 'upstream/develop' into new_date
Diffstat (limited to 'system/libraries')
31 files changed, 2640 insertions, 1669 deletions
diff --git a/system/libraries/Cache/Cache.php b/system/libraries/Cache/Cache.php index f98241617..53f9f81a7 100644 --- a/system/libraries/Cache/Cache.php +++ b/system/libraries/Cache/Cache.php @@ -36,17 +36,39 @@ */ class CI_Cache extends CI_Driver_Library { - protected $valid_drivers = array( - 'cache_apc', - 'cache_file', - 'cache_memcached', - 'cache_dummy', - 'cache_wincache' - ); - - protected $_cache_path = NULL; // Path of cache files (if file-based cache) - protected $_adapter = 'dummy'; - protected $_backup_driver; + /** + * Valid cache drivers + * + * @var array + */ + protected $valid_drivers = array( + 'cache_apc', + 'cache_file', + 'cache_memcached', + 'cache_dummy', + 'cache_wincache' + ); + + /** + * Path of cache files (if file-based cache) + * + * @var string + */ + protected $_cache_path = NULL; + + /** + * Reference to the driver + * + * @var mixed + */ + protected $_adapter = 'dummy'; + + /** + * Fallback driver + * + * @param string + */ + protected $_backup_driver = 'dummy'; /** * Constructor @@ -59,9 +81,9 @@ class CI_Cache extends CI_Driver_Library { public function __construct($config = array()) { $default_config = array( - 'adapter', - 'memcached' - ); + 'adapter', + 'memcached' + ); foreach ($default_config as $key) { @@ -80,6 +102,22 @@ class CI_Cache extends CI_Driver_Library { $this->_backup_driver = $config['backup']; } } + + // If the specified adapter isn't available, check the backup. + if ( ! $this->is_supported($this->_adapter)) + { + if ( ! $this->is_supported($this->_backup_driver)) + { + // Backup isn't supported either. Default to 'Dummy' driver. + log_message('error', 'Cache adapter "'.$this->_adapter.'" and backup "'.$this->_backup_driver.'" are both unavailable. Cache is now using "Dummy" adapter.'); + $this->_adapter = 'dummy'; + } + else + { + // Backup is supported. Set it to primary. + $this->_adapter = $this->_backup_driver; + } + } } // ------------------------------------------------------------------------ @@ -184,26 +222,6 @@ class CI_Cache extends CI_Driver_Library { return $support[$driver]; } - // ------------------------------------------------------------------------ - - /** - * __get() - * - * @param child - * @return object - */ - public function __get($child) - { - $obj = parent::__get($child); - - if ( ! $this->is_supported($child)) - { - $this->_adapter = $this->_backup_driver; - } - - return $obj; - } - } /* End of file Cache.php */ diff --git a/system/libraries/Cache/drivers/Cache_apc.php b/system/libraries/Cache/drivers/Cache_apc.php index 59ab67533..c85034f95 100644 --- a/system/libraries/Cache/drivers/Cache_apc.php +++ b/system/libraries/Cache/drivers/Cache_apc.php @@ -75,7 +75,7 @@ class CI_Cache_apc extends CI_Driver { * Delete from Cache * * @param mixed unique identifier of the item in the cache - * @param bool true on success/false on failure + * @return bool true on success/false on failure */ public function delete($id) { diff --git a/system/libraries/Cache/drivers/Cache_dummy.php b/system/libraries/Cache/drivers/Cache_dummy.php index e8b791c5b..3f2b4b956 100644 --- a/system/libraries/Cache/drivers/Cache_dummy.php +++ b/system/libraries/Cache/drivers/Cache_dummy.php @@ -70,7 +70,7 @@ class CI_Cache_dummy extends CI_Driver { * Delete from Cache * * @param mixed unique identifier of the item in the cache - * @param bool TRUE, simulating success + * @return bool TRUE, simulating success */ public function delete($id) { diff --git a/system/libraries/Cache/drivers/Cache_file.php b/system/libraries/Cache/drivers/Cache_file.php index dd27aa90e..5170de821 100644 --- a/system/libraries/Cache/drivers/Cache_file.php +++ b/system/libraries/Cache/drivers/Cache_file.php @@ -36,14 +36,24 @@ */ class CI_Cache_file extends CI_Driver { + /** + * Directory in which to save cache files + * + * @var string + */ protected $_cache_path; + /** + * Initialize file-based cache + * + * @return void + */ public function __construct() { $CI =& get_instance(); $CI->load->helper('file'); $path = $CI->config->item('cache_path'); - $this->_cache_path = ($path == '') ? APPPATH.'cache/' : $path; + $this->_cache_path = ($path === '') ? APPPATH.'cache/' : $path; } // ------------------------------------------------------------------------ @@ -61,7 +71,7 @@ class CI_Cache_file extends CI_Driver { return FALSE; } - $data = unserialize(read_file($this->_cache_path.$id)); + $data = unserialize(file_get_contents($this->_cache_path.$id)); if (time() > $data['time'] + $data['ttl']) { @@ -86,10 +96,10 @@ class CI_Cache_file extends CI_Driver { public function save($id, $data, $ttl = 60) { $contents = array( - 'time' => time(), - 'ttl' => $ttl, - 'data' => $data - ); + 'time' => time(), + 'ttl' => $ttl, + 'data' => $data + ); if (write_file($this->_cache_path.$id, serialize($contents))) { @@ -155,7 +165,7 @@ class CI_Cache_file extends CI_Driver { return FALSE; } - $data = unserialize(read_file($this->_cache_path.$id)); + $data = unserialize(file_get_contents($this->_cache_path.$id)); if (is_array($data)) { diff --git a/system/libraries/Cache/drivers/Cache_memcached.php b/system/libraries/Cache/drivers/Cache_memcached.php index 1028c8fd5..bf90f6197 100644 --- a/system/libraries/Cache/drivers/Cache_memcached.php +++ b/system/libraries/Cache/drivers/Cache_memcached.php @@ -36,15 +36,25 @@ */ class CI_Cache_memcached extends CI_Driver { - protected $_memcached; // Holds the memcached object + /** + * Holds the memcached object + * + * @var object + */ + protected $_memcached; + /** + * Memcached configuration + * + * @var array + */ protected $_memcache_conf = array( - 'default' => array( - 'default_host' => '127.0.0.1', - 'default_port' => 11211, - 'default_weight' => 1 - ) - ); + 'default' => array( + 'default_host' => '127.0.0.1', + 'default_port' => 11211, + 'default_weight' => 1 + ) + ); /** * Fetch from cache @@ -67,7 +77,7 @@ class CI_Cache_memcached extends CI_Driver { * @param string unique identifier * @param mixed data being cached * @param int time to live - * @return bool true on success, false on failure + * @return bool true on success, false on failure */ public function save($id, $data, $ttl = 60) { @@ -89,7 +99,7 @@ class CI_Cache_memcached extends CI_Driver { * Delete from Cache * * @param mixed key to be deleted. - * @return bool true on success, false on failure + * @return bool true on success, false on failure */ public function delete($id) { @@ -189,20 +199,20 @@ class CI_Cache_memcached extends CI_Driver { { if ( ! array_key_exists('hostname', $cache_server)) { - $cache_server['hostname'] = $this->_default_options['default_host']; + $cache_server['hostname'] = $this->_memcache_conf['default']['default_host']; } if ( ! array_key_exists('port', $cache_server)) { - $cache_server['port'] = $this->_default_options['default_port']; + $cache_server['port'] = $this->_memcache_conf['default']['default_port']; } if ( ! array_key_exists('weight', $cache_server)) { - $cache_server['weight'] = $this->_default_options['default_weight']; + $cache_server['weight'] = $this->_memcache_conf['default']['default_weight']; } - if (get_class($this->_memcached) == 'Memcache') + if (get_class($this->_memcached) === 'Memcache') { // Third parameter is persistance and defaults to TRUE. $this->_memcached->addServer( diff --git a/system/libraries/Cache/drivers/Cache_wincache.php b/system/libraries/Cache/drivers/Cache_wincache.php index b32e66a46..74048d564 100644 --- a/system/libraries/Cache/drivers/Cache_wincache.php +++ b/system/libraries/Cache/drivers/Cache_wincache.php @@ -78,7 +78,7 @@ class CI_Cache_wincache extends CI_Driver { * Delete from Cache * * @param mixed unique identifier of the item in the cache - * @param bool true on success/false on failure + * @return bool true on success/false on failure */ public function delete($id) { diff --git a/system/libraries/Calendar.php b/system/libraries/Calendar.php index b6f145d95..969a7610a 100644 --- a/system/libraries/Calendar.php +++ b/system/libraries/Calendar.php @@ -38,15 +38,61 @@ */ class CI_Calendar { + /** + * Reference to CodeIgniter instance + * + * @var object + */ protected $CI; - public $lang; + + /** + * Current local time + * + * @var int + */ public $local_time; + + /** + * Calendar layout template + * + * @var string + */ public $template = ''; + + /** + * Day of the week to start the calendar on + * + * @var string + */ public $start_day = 'sunday'; + + /** + * How to display months + * + * @var string + */ public $month_type = 'long'; + + /** + * How to display names of days + * + * @var string + */ public $day_type = 'abr'; - public $show_next_prev = FALSE; - public $next_prev_url = ''; + + /** + * Whether to show next/prev month links + * + * @var bool + */ + public $show_next_prev = FALSE; + + /** + * Url base to use for next/prev month links + * + * @var bool + */ + public $next_prev_url = ''; /** * Constructor @@ -109,7 +155,7 @@ class CI_Calendar { public function generate($year = '', $month = '', $data = array()) { // Set and validate the supplied month/year - if ($year == '') + if ($year === '') { $year = date('Y', $this->local_time); } @@ -122,7 +168,7 @@ class CI_Calendar { $year = '20'.$year; } - if ($month == '') + if ($month === '') { $month = date('m', $this->local_time); } @@ -141,7 +187,7 @@ class CI_Calendar { // Set the starting day of the week $start_days = array('sunday' => 0, 'monday' => 1, 'tuesday' => 2, 'wednesday' => 3, 'thursday' => 4, 'friday' => 5, 'saturday' => 6); - $start_day = ( ! isset($start_days[$this->start_day])) ? 0 : $start_days[$this->start_day]; + $start_day = isset($start_days[$this->start_day]) ? $start_days[$this->start_day] : 0; // Set the starting day number $local_date = mktime(12, 0, 0, $month, 1, $year); @@ -168,7 +214,7 @@ class CI_Calendar { $out = $this->temp['table_open']."\n\n".$this->temp['heading_row_start']."\n"; // "previous" month link - if ($this->show_next_prev == TRUE) + if ($this->show_next_prev === TRUE) { // Add a trailing slash to the URL if needed $this->next_prev_url = preg_replace('/(.+?)\/*$/', '\\1/', $this->next_prev_url); @@ -178,7 +224,7 @@ class CI_Calendar { } // Heading containing the month/year - $colspan = ($this->show_next_prev == TRUE) ? 5 : 7; + $colspan = ($this->show_next_prev === TRUE) ? 5 : 7; $this->temp['heading_title_cell'] = str_replace('{colspan}', $colspan, str_replace('{heading}', $this->get_month_name($month).' '.$year, $this->temp['heading_title_cell'])); @@ -186,7 +232,7 @@ class CI_Calendar { $out .= $this->temp['heading_title_cell']."\n"; // "next" month link - if ($this->show_next_prev == TRUE) + if ($this->show_next_prev === TRUE) { $adjusted_date = $this->adjust_date($month + 1, $year); $out .= str_replace('{next_url}', $this->next_prev_url.$adjusted_date['year'].'/'.$adjusted_date['month'], $this->temp['heading_next_cell']); @@ -244,9 +290,7 @@ class CI_Calendar { $out .= "\n".$this->temp['cal_row_end']."\n"; } - $out .= "\n".$this->temp['table_close']; - - return $out; + return $out .= "\n".$this->temp['table_close']; } // -------------------------------------------------------------------- @@ -262,7 +306,7 @@ class CI_Calendar { */ public function get_month_name($month) { - if ($this->month_type == 'short') + if ($this->month_type === 'short') { $month_names = array('01' => 'cal_jan', '02' => 'cal_feb', '03' => 'cal_mar', '04' => 'cal_apr', '05' => 'cal_may', '06' => 'cal_jun', '07' => 'cal_jul', '08' => 'cal_aug', '09' => 'cal_sep', '10' => 'cal_oct', '11' => 'cal_nov', '12' => 'cal_dec'); } @@ -271,14 +315,9 @@ class CI_Calendar { $month_names = array('01' => 'cal_january', '02' => 'cal_february', '03' => 'cal_march', '04' => 'cal_april', '05' => 'cal_mayl', '06' => 'cal_june', '07' => 'cal_july', '08' => 'cal_august', '09' => 'cal_september', '10' => 'cal_october', '11' => 'cal_november', '12' => 'cal_december'); } - $month = $month_names[$month]; - - if ($this->CI->lang->line($month) === FALSE) - { - return ucfirst(substr($month, 4)); - } - - return $this->CI->lang->line($month); + return ($this->CI->lang->line($month_names[$month]) === FALSE) + ? ucfirst(substr($month_names[$month], 4)) + : $this->CI->lang->line($month_names[$month]); } // -------------------------------------------------------------------- @@ -294,16 +333,16 @@ class CI_Calendar { */ public function get_day_names($day_type = '') { - if ($day_type != '') + if ($day_type !== '') { $this->day_type = $day_type; } - if ($this->day_type == 'long') + if ($this->day_type === 'long') { $day_names = array('sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday'); } - elseif ($this->day_type == 'short') + elseif ($this->day_type === 'short') { $day_names = array('sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'); } @@ -382,7 +421,7 @@ class CI_Calendar { // Is the year a leap year? if ($month == 2) { - if ($year % 400 == 0 OR ($year % 4 == 0 && $year % 100 != 0)) + if ($year % 400 === 0 OR ($year % 4 === 0 && $year % 100 !== 0)) { return 29; } @@ -402,29 +441,29 @@ class CI_Calendar { */ public function default_template() { - return array ( - 'table_open' => '<table border="0" cellpadding="4" cellspacing="0">', - 'heading_row_start' => '<tr>', - 'heading_previous_cell' => '<th><a href="{previous_url}"><<</a></th>', - 'heading_title_cell' => '<th colspan="{colspan}">{heading}</th>', - 'heading_next_cell' => '<th><a href="{next_url}">>></a></th>', - 'heading_row_end' => '</tr>', - 'week_row_start' => '<tr>', - 'week_day_cell' => '<td>{week_day}</td>', - 'week_row_end' => '</tr>', - 'cal_row_start' => '<tr>', - 'cal_cell_start' => '<td>', - 'cal_cell_start_today' => '<td>', - 'cal_cell_content' => '<a href="{content}">{day}</a>', - 'cal_cell_content_today' => '<a href="{content}"><strong>{day}</strong></a>', - 'cal_cell_no_content' => '{day}', - 'cal_cell_no_content_today' => '<strong>{day}</strong>', - 'cal_cell_blank' => ' ', - 'cal_cell_end' => '</td>', - 'cal_cell_end_today' => '</td>', - 'cal_row_end' => '</tr>', - 'table_close' => '</table>' - ); + return array( + 'table_open' => '<table border="0" cellpadding="4" cellspacing="0">', + 'heading_row_start' => '<tr>', + 'heading_previous_cell' => '<th><a href="{previous_url}"><<</a></th>', + 'heading_title_cell' => '<th colspan="{colspan}">{heading}</th>', + 'heading_next_cell' => '<th><a href="{next_url}">>></a></th>', + 'heading_row_end' => '</tr>', + 'week_row_start' => '<tr>', + 'week_day_cell' => '<td>{week_day}</td>', + 'week_row_end' => '</tr>', + 'cal_row_start' => '<tr>', + 'cal_cell_start' => '<td>', + 'cal_cell_start_today' => '<td>', + 'cal_cell_content' => '<a href="{content}">{day}</a>', + 'cal_cell_content_today' => '<a href="{content}"><strong>{day}</strong></a>', + 'cal_cell_no_content' => '{day}', + 'cal_cell_no_content_today' => '<strong>{day}</strong>', + 'cal_cell_blank' => ' ', + 'cal_cell_end' => '</td>', + 'cal_cell_end_today' => '</td>', + 'cal_row_end' => '</tr>', + 'table_close' => '</table>' + ); } // -------------------------------------------------------------------- @@ -441,7 +480,7 @@ class CI_Calendar { { $this->temp = $this->default_template(); - if ($this->template == '') + if ($this->template === '') { return; } diff --git a/system/libraries/Cart.php b/system/libraries/Cart.php index ca7be555e..c442f88da 100644 --- a/system/libraries/Cart.php +++ b/system/libraries/Cart.php @@ -36,19 +36,54 @@ */ class CI_Cart { - // These are the regular expression rules that we use to validate the product ID and product name - public $product_id_rules = '\.a-z0-9_-'; // alpha-numeric, dashes, underscores, or periods - public $product_name_rules = '\.\:\-_ a-z0-9'; // alpha-numeric, dashes, underscores, colons or periods - public $product_name_safe = TRUE; // only allow safe product names + /** + * These are the regular expression rules that we use to validate the product ID and product name + * alpha-numeric, dashes, underscores, or periods + * + * @var string + */ + public $product_id_rules = '\.a-z0-9_-'; + + /** + * These are the regular expression rules that we use to validate the product ID and product name + * alpha-numeric, dashes, underscores, colons or periods + * + * @var string + */ + public $product_name_rules = '\.\:\-_ a-z0-9'; + /** + * only allow safe product names + * + * @var bool + */ + public $product_name_safe = TRUE; + + // -------------------------------------------------------------------------- // Protected variables. Do not change! + // -------------------------------------------------------------------------- + + /** + * Reference to CodeIgniter instance + * + * @var object + */ protected $CI; + + /** + * Contents of the cart + * + * @var array + */ protected $_cart_contents = array(); /** * Shopping Class Constructor * * The constructor loads the Session class, used to store the shopping cart contents. + * + * @param array + * @return void */ public function __construct($params = array()) { @@ -146,7 +181,7 @@ class CI_Cart { // -------------------------------------------------------------------- // Does the $items array contain an id, quantity, price, and name? These are required - if ( ! isset($items['id']) OR ! isset($items['qty']) OR ! isset($items['price']) OR ! isset($items['name'])) + if ( ! isset($items['id'], $items['qty'], $items['price'], $items['name'])) { log_message('error', 'The cart array must contain a product ID, quantity, price, and name.'); return FALSE; @@ -210,7 +245,7 @@ class CI_Cart { // This becomes the unique "row ID" if (isset($items['options']) && count($items['options']) > 0) { - $rowid = md5($items['id'].implode('', $items['options'])); + $rowid = md5($items['id'].serialize($items['options'])); } else { @@ -245,7 +280,6 @@ class CI_Cart { * product ID and quantity for each item. * * @param array - * @param string * @return bool */ public function update($items = array()) @@ -308,7 +342,7 @@ class CI_Cart { protected function _update($items = array()) { // Without these array indexes there is nothing we can do - if ( ! isset($items['qty']) OR ! isset($items['rowid']) OR ! isset($this->_cart_contents[$items['rowid']])) + if ( ! isset($items['qty'], $items['rowid'], $this->_cart_contents[$items['rowid']])) { return FALSE; } @@ -350,7 +384,7 @@ class CI_Cart { foreach ($this->_cart_contents as $key => $val) { // We make sure the array contains the proper indexes - if ( ! is_array($val) OR ! isset($val['price']) OR ! isset($val['qty'])) + if ( ! is_array($val) OR ! isset($val['price'], $val['qty'])) { continue; } @@ -360,7 +394,7 @@ class CI_Cart { $this->_cart_contents[$key]['subtotal'] = ($this->_cart_contents[$key]['price'] * $this->_cart_contents[$key]['qty']); } - // Is our cart empty? If so we delete it from the session + // Is our cart empty? If so we delete it from the session if (count($this->_cart_contents) <= 2) { $this->CI->session->unset_userdata('cart_contents'); @@ -396,6 +430,7 @@ class CI_Cart { * * Removes an item from the cart * + * @param int * @return bool */ public function remove($rowid) @@ -427,6 +462,7 @@ class CI_Cart { * * Returns the entire cart array * + * @param bool * @return array */ public function contents($newest_first = FALSE) @@ -449,11 +485,12 @@ class CI_Cart { * Returns TRUE if the rowid passed to this function correlates to an item * that has options associated with it. * + * @param mixed * @return bool */ public function has_options($rowid = '') { - return (isset($this->_cart_contents[$rowid]['options']) && count($this->_cart_contents[$rowid]['options']) !== 0) ? TRUE : FALSE; + return (isset($this->_cart_contents[$rowid]['options']) && count($this->_cart_contents[$rowid]['options']) !== 0); } // -------------------------------------------------------------------- @@ -483,15 +520,7 @@ class CI_Cart { */ public function format_number($n = '') { - if ($n == '') - { - return ''; - } - - // Remove anything that isn't a number or decimal point. - $n = (float) $n; - - return number_format($n, 2, '.', ','); + return ($n === '') ? '' : number_format( (float) $n, 2, '.', ','); } // -------------------------------------------------------------------- diff --git a/system/libraries/Driver.php b/system/libraries/Driver.php index f409f47d4..d67ee2549 100644 --- a/system/libraries/Driver.php +++ b/system/libraries/Driver.php @@ -39,11 +39,27 @@ */ class CI_Driver_Library { - protected $valid_drivers = array(); - protected static $lib_name; + /** + * Array of drivers that are available to use with the driver class + * + * @var array + */ + protected $valid_drivers = array(); + + /** + * Name of the current class - usually the driver class + * + * @var string + */ + protected $lib_name; - // The first time a child is used it won't exist, so we instantiate it - // subsequents calls will go straight to the proper child. + /** + * The first time a child is used it won't exist, so we instantiate it + * subsequents calls will go straight to the proper child. + * + * @param mixed $child + * @return mixed + */ public function __get($child) { if ( ! isset($this->lib_name)) @@ -100,6 +116,8 @@ class CI_Driver_Library { } +// -------------------------------------------------------------------------- + /** * CodeIgniter Driver Class * @@ -114,11 +132,32 @@ class CI_Driver_Library { */ class CI_Driver { + /** + * Instance of the parent class + * + * @var object + */ protected $_parent; + /** + * List of methods in the parent class + * + * @var array + */ protected $_methods = array(); + + /** + * List of properties in the parent class + * + * @var array + */ protected $_properties = array(); + /** + * Array of methods and properties for the parent class(es) + * + * @var array + */ protected static $_reflections = array(); /** diff --git a/system/libraries/Email.php b/system/libraries/Email.php index 8f383c939..c70144f7c 100644 --- a/system/libraries/Email.php +++ b/system/libraries/Email.php @@ -93,6 +93,8 @@ class CI_Email { * Constructor - Sets Email Preferences * * The constructor can be passed an array of config values + * + * @return void */ public function __construct($config = array()) { @@ -102,7 +104,7 @@ class CI_Email { } else { - $this->_smtp_auth = ! ($this->smtp_user == '' && $this->smtp_pass == ''); + $this->_smtp_auth = ! ($this->smtp_user === '' && $this->smtp_pass === ''); $this->_safe_mode = (bool) @ini_get('safe_mode'); } @@ -137,7 +139,7 @@ class CI_Email { } $this->clear(); - $this->_smtp_auth = ! ($this->smtp_user == '' && $this->smtp_pass == ''); + $this->_smtp_auth = ! ($this->smtp_user === '' && $this->smtp_pass === ''); $this->_safe_mode = (bool) @ini_get('safe_mode'); return $this; @@ -164,8 +166,8 @@ class CI_Email { $this->_headers = array(); $this->_debug_msg = array(); - $this->_set_header('User-Agent', $this->useragent); - $this->_set_header('Date', $this->_set_date()); + $this->set_header('User-Agent', $this->useragent); + $this->set_header('Date', $this->_set_date()); if ($clear_attachments !== FALSE) { @@ -199,7 +201,7 @@ class CI_Email { } // prepare the display name - if ($name != '') + if ($name !== '') { // only use Q encoding if there are characters that would require it if ( ! preg_match('/[\200-\377]/', $name)) @@ -213,8 +215,8 @@ class CI_Email { } } - $this->_set_header('From', $name.' <'.$from.'>'); - $this->_set_header('Return-Path', '<'.$from.'>'); + $this->set_header('From', $name.' <'.$from.'>'); + $this->set_header('Return-Path', '<'.$from.'>'); return $this; } @@ -240,7 +242,7 @@ class CI_Email { $this->validate_email($this->_str_to_array($replyto)); } - if ($name == '') + if ($name === '') { $name = $replyto; } @@ -250,7 +252,7 @@ class CI_Email { $name = '"'.$name.'"'; } - $this->_set_header('Reply-To', $name.' <'.$replyto.'>'); + $this->set_header('Reply-To', $name.' <'.$replyto.'>'); $this->_replyto_flag = TRUE; return $this; @@ -276,7 +278,7 @@ class CI_Email { if ($this->_get_protocol() !== 'mail') { - $this->_set_header('To', implode(', ', $to)); + $this->set_header('To', implode(', ', $to)); } switch ($this->_get_protocol()) @@ -303,15 +305,14 @@ class CI_Email { */ public function cc($cc) { - $cc = $this->_str_to_array($cc); - $cc = $this->clean_email($cc); + $cc = $this->clean_email($this->_str_to_array($cc)); if ($this->validate) { $this->validate_email($cc); } - $this->_set_header('Cc', implode(', ', $cc)); + $this->set_header('Cc', implode(', ', $cc)); if ($this->_get_protocol() === 'smtp') { @@ -332,14 +333,13 @@ class CI_Email { */ public function bcc($bcc, $limit = '') { - if ($limit != '' && is_numeric($limit)) + if ($limit !== '' && is_numeric($limit)) { $this->bcc_batch_mode = TRUE; $this->bcc_batch_size = $limit; } - $bcc = $this->_str_to_array($bcc); - $bcc = $this->clean_email($bcc); + $bcc = $this->clean_email($this->_str_to_array($bcc)); if ($this->validate) { @@ -352,7 +352,7 @@ class CI_Email { } else { - $this->_set_header('Bcc', implode(', ', $bcc)); + $this->set_header('Bcc', implode(', ', $bcc)); } return $this; @@ -369,7 +369,7 @@ class CI_Email { public function subject($subject) { $subject = $this->_prep_q_encoding($subject); - $this->_set_header('Subject', $subject); + $this->set_header('Subject', $subject); return $this; } @@ -407,11 +407,11 @@ class CI_Email { * @param string * @return object */ - public function attach($filename, $disposition = '', $newname = NULL) + public function attach($filename, $disposition = '', $newname = NULL, $mime = '') { $this->_attach_name[] = array($filename, $newname); - $this->_attach_type[] = $this->_mime_types(pathinfo($filename, PATHINFO_EXTENSION)); $this->_attach_disp[] = empty($disposition) ? 'attachment' : $disposition; // Can also be 'inline' Not sure if it matters + $this->_attach_type[] = $mime; return $this; } @@ -424,7 +424,7 @@ class CI_Email { * @param string * @return void */ - protected function _set_header($header, $value) + public function set_header($header, $value) { $this->_headers[$header] = $value; } @@ -441,15 +441,11 @@ class CI_Email { { if ( ! is_array($email)) { - if (strpos($email, ',') !== FALSE) - { - $email = preg_split('/[\s,]/', $email, -1, PREG_SPLIT_NO_EMPTY); - } - else - { - $email = (array) trim($email); - } + return (strpos($email, ',') !== FALSE) + ? preg_split('/[\s,]/', $email, -1, PREG_SPLIT_NO_EMPTY) + : (array) trim($email); } + return $email; } @@ -477,7 +473,7 @@ class CI_Email { */ public function set_mailtype($type = 'text') { - $this->mailtype = ($type == 'html') ? 'html' : 'text'; + $this->mailtype = ($type === 'html') ? 'html' : 'text'; return $this; } @@ -574,7 +570,7 @@ class CI_Email { protected function _get_message_id() { $from = str_replace(array('>', '<'), '', $this->_headers['Return-Path']); - return '<'.uniqid('').strstr($from, '@').'>'; + return '<'.uniqid('').strstr($from, '@').'>'; } // -------------------------------------------------------------------- @@ -590,7 +586,7 @@ class CI_Email { $this->protocol = strtolower($this->protocol); in_array($this->protocol, $this->_protocols, TRUE) OR $this->protocol = 'mail'; - if ($return == TRUE) + if ($return === TRUE) { return $this->protocol; } @@ -616,7 +612,7 @@ class CI_Email { } } - if ($return == TRUE) + if ($return === TRUE) { return $this->_encoding; } @@ -631,13 +627,9 @@ class CI_Email { */ protected function _get_content_type() { - if ($this->mailtype === 'html' && count($this->_attach_name) === 0) + if ($this->mailtype === 'html') { - return 'html'; - } - elseif ($this->mailtype === 'html' && count($this->_attach_name) > 0) - { - return 'html-attach'; + return (count($this->_attach_name) === 0) ? 'html' : 'html-attach'; } elseif ($this->mailtype === 'text' && count($this->_attach_name) > 0) { @@ -731,7 +723,7 @@ class CI_Email { { if ( ! is_array($email)) { - return (preg_match('/\<(.*)\>/', $email, $match)) ? $match[1] : $email; + return preg_match('/\<(.*)\>/', $email, $match) ? $match[1] : $email; } $clean_email = array(); @@ -758,12 +750,12 @@ class CI_Email { */ protected function _get_alt_message() { - if ($this->alt_message != '') + if ($this->alt_message !== '') { return $this->word_wrap($this->alt_message, '76'); } - $body = (preg_match('/\<body.*?\>(.*)\<\/body\>/si', $this->_body, $match)) ? $match[1] : $this->_body; + $body = preg_match('/\<body.*?\>(.*)\<\/body\>/si', $this->_body, $match) ? $match[1] : $this->_body; $body = str_replace("\t", '', preg_replace('#<!--(.*)--\>#', '', trim(strip_tags($body)))); for ($i = 20; $i >= 3; $i--) @@ -786,13 +778,13 @@ class CI_Email { public function word_wrap($str, $charlim = '') { // Se the character limit - if ($charlim == '') + if ($charlim === '') { - $charlim = ($this->wrapchars == "") ? 76 : $this->wrapchars; + $charlim = ($this->wrapchars === '') ? 76 : $this->wrapchars; } // Reduce multiple spaces - $str = preg_replace("| +|", " ", $str); + $str = preg_replace('| +|', ' ', $str); // Standardize newlines if (strpos($str, "\r") !== FALSE) @@ -803,22 +795,22 @@ class CI_Email { // If the current word is surrounded by {unwrap} tags we'll // strip the entire chunk and replace it with a marker. $unwrap = array(); - if (preg_match_all("|(\{unwrap\}.+?\{/unwrap\})|s", $str, $matches)) + if (preg_match_all('|(\{unwrap\}.+?\{/unwrap\})|s', $str, $matches)) { for ($i = 0, $c = count($matches[0]); $i < $c; $i++) { $unwrap[] = $matches[1][$i]; - $str = str_replace($matches[1][$i], "{{unwrapped".$i."}}", $str); + $str = str_replace($matches[1][$i], '{{unwrapped'.$i.'}}', $str); } } // Use PHP's native public function to do the initial wordwrap. // We set the cut flag to FALSE so that any individual words that are - // too long get left alone. In the next step we'll deal with them. + // too long get left alone. In the next step we'll deal with them. $str = wordwrap($str, $charlim, "\n", FALSE); // Split the string into individual lines of text and cycle through them - $output = ""; + $output = ''; foreach (explode("\n", $str) as $line) { // Is the line within the allowed character count? @@ -833,7 +825,7 @@ class CI_Email { do { // If the over-length word is a URL we won't wrap it - if (preg_match("!\[url.+\]|://|wwww.!", $line)) + if (preg_match('!\[url.+\]|://|wwww.!', $line)) { break; } @@ -846,7 +838,7 @@ class CI_Email { // If $temp contains data it means we had to split up an over-length // word into smaller chunks so we'll add it back to our current line - if ($temp != '') + if ($temp !== '') { $output .= $temp.$this->newline; } @@ -859,7 +851,7 @@ class CI_Email { { foreach ($unwrap as $key => $val) { - $output = str_replace("{{unwrapped".$key."}}", $val, $output); + $output = str_replace('{{unwrapped'.$key.'}}', $val, $output); } } @@ -875,11 +867,11 @@ class CI_Email { */ protected function _build_headers() { - $this->_set_header('X-Sender', $this->clean_email($this->_headers['From'])); - $this->_set_header('X-Mailer', $this->useragent); - $this->_set_header('X-Priority', $this->_priorities[$this->priority - 1]); - $this->_set_header('Message-ID', $this->_get_message_id()); - $this->_set_header('Mime-Version', '1.0'); + $this->set_header('X-Sender', $this->clean_email($this->_headers['From'])); + $this->set_header('X-Mailer', $this->useragent); + $this->set_header('X-Priority', $this->_priorities[$this->priority - 1]); + $this->set_header('Message-ID', $this->_get_message_id()); + $this->set_header('Mime-Version', '1.0'); } // -------------------------------------------------------------------- @@ -898,15 +890,15 @@ class CI_Email { } reset($this->_headers); - $this->_header_str = ""; + $this->_header_str = ''; foreach ($this->_headers as $key => $val) { $val = trim($val); - if ($val != "") + if ($val !== '') { - $this->_header_str .= $key.": ".$val.$this->newline; + $this->_header_str .= $key.': '.$val.$this->newline; } } @@ -940,8 +932,8 @@ class CI_Email { { case 'plain' : - $hdr .= "Content-Type: text/plain; charset=" . $this->charset . $this->newline - . "Content-Transfer-Encoding: " . $this->_get_encoding(); + $hdr .= 'Content-Type: text/plain; charset='.$this->charset.$this->newline + .'Content-Transfer-Encoding: '.$this->_get_encoding(); if ($this->_get_protocol() === 'mail') { @@ -959,25 +951,25 @@ class CI_Email { if ($this->send_multipart === FALSE) { - $hdr .= "Content-Type: text/html; charset=" . $this->charset . $this->newline - . "Content-Transfer-Encoding: quoted-printable"; + $hdr .= 'Content-Type: text/html; charset='.$this->charset.$this->newline + .'Content-Transfer-Encoding: quoted-printable'; } else { - $hdr .= "Content-Type: multipart/alternative; boundary=\"" . $this->_alt_boundary . "\"" . $this->newline . $this->newline; + $hdr .= 'Content-Type: multipart/alternative; boundary="'.$this->_alt_boundary.'"'.$this->newline.$this->newline; - $body .= $this->_get_mime_message() . $this->newline . $this->newline - . "--" . $this->_alt_boundary . $this->newline + $body .= $this->_get_mime_message().$this->newline.$this->newline + .'--'.$this->_alt_boundary.$this->newline - . "Content-Type: text/plain; charset=" . $this->charset . $this->newline - . "Content-Transfer-Encoding: " . $this->_get_encoding() . $this->newline . $this->newline - . $this->_get_alt_message() . $this->newline . $this->newline . "--" . $this->_alt_boundary . $this->newline + .'Content-Type: text/plain; charset='.$this->charset.$this->newline + .'Content-Transfer-Encoding: '.$this->_get_encoding().$this->newline.$this->newline + .$this->_get_alt_message().$this->newline.$this->newline.'--'.$this->_alt_boundary.$this->newline - . "Content-Type: text/html; charset=" . $this->charset . $this->newline - . "Content-Transfer-Encoding: quoted-printable" . $this->newline . $this->newline; + .'Content-Type: text/html; charset='.$this->charset.$this->newline + .'Content-Transfer-Encoding: quoted-printable'.$this->newline.$this->newline; } - $this->_finalbody = $body . $this->_prep_quoted_printable($this->_body) . $this->newline . $this->newline; + $this->_finalbody = $body.$this->_prep_quoted_printable($this->_body).$this->newline.$this->newline; if ($this->_get_protocol() === 'mail') @@ -986,59 +978,59 @@ class CI_Email { } else { - $this->_finalbody = $hdr . $this->_finalbody; + $this->_finalbody = $hdr.$this->_finalbody; } if ($this->send_multipart !== FALSE) { - $this->_finalbody .= "--" . $this->_alt_boundary . "--"; + $this->_finalbody .= '--'.$this->_alt_boundary.'--'; } return; case 'plain-attach' : - $hdr .= "Content-Type: multipart/".$this->multipart."; boundary=\"" . $this->_atc_boundary."\"" . $this->newline . $this->newline; + $hdr .= 'Content-Type: multipart/'.$this->multipart.'; boundary="'.$this->_atc_boundary.'"'.$this->newline.$this->newline; if ($this->_get_protocol() === 'mail') { $this->_header_str .= $hdr; } - $body .= $this->_get_mime_message() . $this->newline . $this->newline - . "--" . $this->_atc_boundary . $this->newline + $body .= $this->_get_mime_message().$this->newline.$this->newline + .'--'.$this->_atc_boundary.$this->newline - . "Content-Type: text/plain; charset=" . $this->charset . $this->newline - . "Content-Transfer-Encoding: " . $this->_get_encoding() . $this->newline . $this->newline + .'Content-Type: text/plain; charset='.$this->charset.$this->newline + .'Content-Transfer-Encoding: '.$this->_get_encoding().$this->newline.$this->newline - . $this->_body . $this->newline . $this->newline; + .$this->_body.$this->newline.$this->newline; break; case 'html-attach' : - $hdr .= "Content-Type: multipart/".$this->multipart."; boundary=\"" . $this->_atc_boundary."\"" . $this->newline . $this->newline; + $hdr .= 'Content-Type: multipart/'.$this->multipart.'; boundary="'.$this->_atc_boundary.'"'.$this->newline.$this->newline; if ($this->_get_protocol() === 'mail') { $this->_header_str .= $hdr; } - $body .= $this->_get_mime_message() . $this->newline . $this->newline - . "--" . $this->_atc_boundary . $this->newline + $body .= $this->_get_mime_message().$this->newline.$this->newline + .'--'.$this->_atc_boundary.$this->newline - . "Content-Type: multipart/alternative; boundary=\"" . $this->_alt_boundary . "\"" . $this->newline .$this->newline - . "--" . $this->_alt_boundary . $this->newline + .'Content-Type: multipart/alternative; boundary="'.$this->_alt_boundary.'"'.$this->newline.$this->newline + .'--'.$this->_alt_boundary.$this->newline - . "Content-Type: text/plain; charset=" . $this->charset . $this->newline - . "Content-Transfer-Encoding: " . $this->_get_encoding() . $this->newline . $this->newline - . $this->_get_alt_message() . $this->newline . $this->newline . "--" . $this->_alt_boundary . $this->newline + .'Content-Type: text/plain; charset='.$this->charset.$this->newline + .'Content-Transfer-Encoding: '.$this->_get_encoding().$this->newline.$this->newline + .$this->_get_alt_message().$this->newline.$this->newline.'--'.$this->_alt_boundary.$this->newline - . "Content-Type: text/html; charset=" . $this->charset . $this->newline - . "Content-Transfer-Encoding: quoted-printable" . $this->newline . $this->newline + .'Content-Type: text/html; charset='.$this->charset.$this->newline + .'Content-Transfer-Encoding: quoted-printable'.$this->newline.$this->newline - . $this->_prep_quoted_printable($this->_body) . $this->newline . $this->newline - . "--" . $this->_alt_boundary . "--" . $this->newline . $this->newline; + .$this->_prep_quoted_printable($this->_body).$this->newline.$this->newline + .'--'.$this->_alt_boundary.'--'.$this->newline.$this->newline; break; } @@ -1047,35 +1039,46 @@ class CI_Email { for ($i = 0, $c = count($this->_attach_name), $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]; + $basename = is_null($this->_attach_name[$i][1]) ? basename($filename) : $this->_attach_name[$i][1]; $ctype = $this->_attach_type[$i]; + $file_content = ''; - if ( ! file_exists($filename)) + if ($this->_attach_type[$i] === '') { - $this->_set_error_message('lang:email_attachment_missing', $filename); - return FALSE; - } + if ( ! file_exists($filename)) + { + $this->_set_error_message('lang:email_attachment_missing', $filename); + return FALSE; + } - $attachment[$z++] = "--".$this->_atc_boundary.$this->newline - . "Content-type: ".$ctype."; " - . "name=\"".$basename."\"".$this->newline - . "Content-Disposition: ".$this->_attach_disp[$i].";".$this->newline - . "Content-Transfer-Encoding: base64".$this->newline; + $file = filesize($filename) +1; - $file = filesize($filename) +1; + if ( ! $fp = fopen($filename, FOPEN_READ)) + { + $this->_set_error_message('lang:email_attachment_unreadable', $filename); + return FALSE; + } - if ( ! $fp = fopen($filename, FOPEN_READ)) + $ctype = $this->_mime_types(pathinfo($filename, PATHINFO_EXTENSION)); + $file_content = fread($fp, $file); + fclose($fp); + } + else { - $this->_set_error_message('lang:email_attachment_unreadable', $filename); - return FALSE; + $file_content =& $this->_attach_content[$i]; } - $attachment[$z++] = chunk_split(base64_encode(fread($fp, $file))); - fclose($fp); + $attachment[$z++] = '--'.$this->_atc_boundary.$this->newline + .'Content-type: '.$ctype.'; ' + .'name="'.$basename.'"'.$this->newline + .'Content-Disposition: '.$this->_attach_disp[$i].';'.$this->newline + .'Content-Transfer-Encoding: base64'.$this->newline; + + $attachment[$z++] = chunk_split(base64_encode($file_content)); } - $body .= implode($this->newline, $attachment).$this->newline."--".$this->_atc_boundary."--"; - $this->_finalbody = ($this->_get_protocol() === 'mail') ? $body : $hdr . $body; + $body .= implode($this->newline, $attachment).$this->newline.'--'.$this->_atc_boundary.'--'; + $this->_finalbody = ($this->_get_protocol() === 'mail') ? $body : $hdr.$body; return; } @@ -1096,13 +1099,13 @@ class CI_Email { // Set the character limit // Don't allow over 76, as that will make servers and MUAs barf // all over quoted-printable data - if ($charlim == '' OR $charlim > 76) + if ($charlim === '' OR $charlim > 76) { $charlim = 76; } // Reduce multiple spaces & remove nulls - $str = preg_replace(array("| +|", '/\x00+/'), array(' ', ''), $str); + $str = preg_replace(array('| +|', '/\x00+/'), array(' ', ''), $str); // Standardize newlines if (strpos($str, "\r") !== FALSE) @@ -1223,11 +1226,9 @@ class CI_Email { $temp .= $char; } - $str = $output.$temp; - // wrap each line with the shebang, charset, and transfer encoding // the preceding space on successive lines is required for header "folding" - return trim(preg_replace('/^(.*)$/m', ' =?'.$this->charset.'?Q?$1?=', $str)); + return trim(preg_replace('/^(.*)$/m', ' =?'.$this->charset.'?Q?$1?=', $output.$temp)); } // -------------------------------------------------------------------- @@ -1239,7 +1240,7 @@ class CI_Email { */ public function send() { - if ($this->_replyto_flag == FALSE) + if ($this->_replyto_flag === FALSE) { $this->reply_to($this->_headers['From']); } @@ -1283,7 +1284,7 @@ class CI_Email { $set .= ', '.$this->_bcc_array[$i]; } - if ($i == $float) + if ($i === $float) { $chunk[] = substr($set, 1); $float += $this->bcc_batch_size; @@ -1304,7 +1305,7 @@ class CI_Email { if ($this->protocol !== 'smtp') { - $this->_set_header('Bcc', implode(', ', $bcc)); + $this->set_header('Bcc', implode(', ', $bcc)); } else { @@ -1325,7 +1326,7 @@ class CI_Email { */ protected function _unwrap_specials() { - $this->_finalbody = preg_replace_callback("/\{unwrap\}(.*?)\{\/unwrap\}/si", array($this, '_remove_nl_callback'), $this->_finalbody); + $this->_finalbody = preg_replace_callback('/\{unwrap\}(.*?)\{\/unwrap\}/si', array($this, '_remove_nl_callback'), $this->_finalbody); } // -------------------------------------------------------------------- @@ -1356,10 +1357,10 @@ class CI_Email { { $this->_unwrap_specials(); - $method = '_send_with_' . $this->_get_protocol(); + $method = '_send_with_'.$this->_get_protocol(); if ( ! $this->$method()) { - $this->_set_error_message('lang:email_send_failure_' . ($this->_get_protocol() === 'mail' ? 'phpmail' : $this->_get_protocol())); + $this->_set_error_message('lang:email_send_failure_'.($this->_get_protocol() === 'mail' ? 'phpmail' : $this->_get_protocol())); return FALSE; } @@ -1376,7 +1377,7 @@ class CI_Email { */ protected function _send_with_mail() { - if ($this->_safe_mode == TRUE) + if ($this->_safe_mode === TRUE) { return mail($this->_recipients, $this->_subject, $this->_finalbody, $this->_header_str); } @@ -1384,7 +1385,7 @@ class CI_Email { { // most documentation of sendmail using the "-f" flag lacks a space after it, however // we've encountered servers that seem to require it to be in place. - return mail($this->_recipients, $this->_subject, $this->_finalbody, $this->_header_str, "-f ".$this->clean_email($this->_headers['From'])); + return mail($this->_recipients, $this->_subject, $this->_finalbody, $this->_header_str, '-f '.$this->clean_email($this->_headers['From'])); } } @@ -1397,7 +1398,7 @@ class CI_Email { */ protected function _send_with_sendmail() { - $fp = @popen($this->mailpath . " -oi -f ".$this->clean_email($this->_headers['From'])." -t", 'w'); + $fp = @popen($this->mailpath.' -oi -f '.$this->clean_email($this->_headers['From']).' -t', 'w'); if ($fp === FALSE OR $fp === NULL) { @@ -1429,7 +1430,7 @@ class CI_Email { */ protected function _send_with_smtp() { - if ($this->smtp_host == '') + if ($this->smtp_host === '') { $this->_set_error_message('lang:email_no_hostname'); return FALSE; @@ -1451,7 +1452,7 @@ class CI_Email { { foreach ($this->_cc_array as $val) { - if ($val != "") + if ($val !== '') { $this->_send_command('to', $val); } @@ -1462,7 +1463,7 @@ class CI_Email { { foreach ($this->_bcc_array as $val) { - if ($val != "") + if ($val !== '') { $this->_send_command('to', $val); } @@ -1472,7 +1473,7 @@ class CI_Email { $this->_send_command('data'); // perform dot transformation on any lines that begin with a dot - $this->_send_data($this->_header_str . preg_replace('/^\./m', '..$1', $this->_finalbody)); + $this->_send_data($this->_header_str.preg_replace('/^\./m', '..$1', $this->_finalbody)); $this->_send_data('.'); @@ -1500,23 +1501,23 @@ class CI_Email { */ protected function _smtp_connect() { - $ssl = ($this->smtp_crypto == 'ssl') ? 'ssl://' : NULL; + $ssl = ($this->smtp_crypto === 'ssl') ? 'ssl://' : NULL; $this->_smtp_connect = fsockopen($ssl.$this->smtp_host, - $this->smtp_port, - $errno, - $errstr, - $this->smtp_timeout); + $this->smtp_port, + $errno, + $errstr, + $this->smtp_timeout); if ( ! is_resource($this->_smtp_connect)) { - $this->_set_error_message('lang:email_smtp_error', $errno." ".$errstr); + $this->_set_error_message('lang:email_smtp_error', $errno.' '.$errstr); return FALSE; } $this->_set_error_message($this->_get_smtp_data()); - if ($this->smtp_crypto == 'tls') + if ($this->smtp_crypto === 'tls') { $this->_send_command('hello'); $this->_send_command('starttls'); @@ -1548,27 +1549,29 @@ class CI_Email { { case 'hello' : - if ($this->_smtp_auth OR $this->_get_encoding() == '8bit') - $this->_send_data('EHLO '.$this->_get_hostname()); - else - $this->_send_data('HELO '.$this->_get_hostname()); + if ($this->_smtp_auth OR $this->_get_encoding() === '8bit') + { + $this->_send_data('EHLO '.$this->_get_hostname()); + } + else + { + $this->_send_data('HELO '.$this->_get_hostname()); + } $resp = 250; break; case 'starttls' : $this->_send_data('STARTTLS'); - $resp = 220; break; case 'from' : $this->_send_data('MAIL FROM:<'.$data.'>'); - $resp = 250; break; - case 'to' : - + case 'to' : + if ($this->dsn) { $this->_send_data('RCPT TO:<'.$data.'> NOTIFY=SUCCESS,DELAY,FAILURE ORCPT=rfc822;'.$data); @@ -1577,33 +1580,32 @@ class CI_Email { { $this->_send_data('RCPT TO:<'.$data.'>'); } + $resp = 250; break; case 'data' : $this->_send_data('DATA'); - $resp = 354; break; case 'quit' : $this->_send_data('QUIT'); - $resp = 221; break; } $reply = $this->_get_smtp_data(); - $this->_debug_msg[] = "<pre>".$cmd.": ".$reply."</pre>"; + $this->_debug_msg[] = '<pre>'.$cmd.': '.$reply.'</pre>'; - if (substr($reply, 0, 3) != $resp) + if (substr($reply, 0, 3) !== $resp) { $this->_set_error_message('lang:email_smtp_error', $reply); return FALSE; } - if ($cmd == 'quit') + if ($cmd === 'quit') { fclose($this->_smtp_connect); } @@ -1625,7 +1627,7 @@ class CI_Email { return TRUE; } - if ($this->smtp_user == '' && $this->smtp_pass == '') + if ($this->smtp_user === '' && $this->smtp_pass === '') { $this->_set_error_message('lang:email_no_smtp_unpw'); return FALSE; @@ -1691,13 +1693,13 @@ class CI_Email { */ protected function _get_smtp_data() { - $data = ""; + $data = ''; while ($str = fgets($this->_smtp_connect, 512)) { $data .= $str; - if ($str[3] == " ") + if ($str[3] === ' ') { break; } @@ -1796,11 +1798,11 @@ class CI_Email { if (substr($msg, 0, 5) !== 'lang:' OR FALSE === ($line = $CI->lang->line(substr($msg, 5)))) { - $this->_debug_msg[] = str_replace('%s', $val, $msg)."<br />"; + $this->_debug_msg[] = str_replace('%s', $val, $msg).'<br />'; } else { - $this->_debug_msg[] = str_replace('%s', $val, $line)."<br />"; + $this->_debug_msg[] = str_replace('%s', $val, $line).'<br />'; } } @@ -1814,100 +1816,26 @@ class CI_Email { */ protected function _mime_types($ext = '') { - $mimes = array( - 'hqx' => 'application/mac-binhex40', - 'cpt' => 'application/mac-compactpro', - 'doc' => 'application/msword', - 'bin' => 'application/macbinary', - 'dms' => 'application/octet-stream', - 'lha' => 'application/octet-stream', - 'lzh' => 'application/octet-stream', - 'exe' => 'application/octet-stream', - 'class' => 'application/octet-stream', - 'psd' => 'application/octet-stream', - 'so' => 'application/octet-stream', - 'sea' => 'application/octet-stream', - 'dll' => 'application/octet-stream', - 'oda' => 'application/oda', - 'pdf' => 'application/pdf', - 'ai' => 'application/postscript', - 'eps' => 'application/postscript', - 'ps' => 'application/postscript', - 'smi' => 'application/smil', - 'smil' => 'application/smil', - 'mif' => 'application/vnd.mif', - 'xls' => 'application/vnd.ms-excel', - 'ppt' => 'application/vnd.ms-powerpoint', - 'wbxml' => 'application/vnd.wap.wbxml', - 'wmlc' => 'application/vnd.wap.wmlc', - 'dcr' => 'application/x-director', - 'dir' => 'application/x-director', - 'dxr' => 'application/x-director', - 'dvi' => 'application/x-dvi', - 'gtar' => 'application/x-gtar', - 'php' => 'application/x-httpd-php', - 'php4' => 'application/x-httpd-php', - 'php3' => 'application/x-httpd-php', - 'phtml' => 'application/x-httpd-php', - 'phps' => 'application/x-httpd-php-source', - 'js' => 'application/x-javascript', - 'swf' => 'application/x-shockwave-flash', - 'sit' => 'application/x-stuffit', - 'tar' => 'application/x-tar', - 'tgz' => 'application/x-tar', - 'xhtml' => 'application/xhtml+xml', - 'xht' => 'application/xhtml+xml', - 'zip' => 'application/zip', - 'mid' => 'audio/midi', - 'midi' => 'audio/midi', - 'mpga' => 'audio/mpeg', - 'mp2' => 'audio/mpeg', - 'mp3' => 'audio/mpeg', - 'aif' => 'audio/x-aiff', - 'aiff' => 'audio/x-aiff', - 'aifc' => 'audio/x-aiff', - 'ram' => 'audio/x-pn-realaudio', - 'rm' => 'audio/x-pn-realaudio', - 'rpm' => 'audio/x-pn-realaudio-plugin', - 'ra' => 'audio/x-realaudio', - 'rv' => 'video/vnd.rn-realvideo', - 'wav' => 'audio/x-wav', - 'bmp' => 'image/bmp', - 'gif' => 'image/gif', - 'jpeg' => 'image/jpeg', - 'jpg' => 'image/jpeg', - 'jpe' => 'image/jpeg', - 'png' => 'image/png', - 'tiff' => 'image/tiff', - 'tif' => 'image/tiff', - 'css' => 'text/css', - 'html' => 'text/html', - 'htm' => 'text/html', - 'shtml' => 'text/html', - 'txt' => 'text/plain', - 'text' => 'text/plain', - 'log' => 'text/plain', - 'rtx' => 'text/richtext', - 'rtf' => 'text/rtf', - 'xml' => 'text/xml', - 'xsl' => 'text/xml', - 'mpeg' => 'video/mpeg', - 'mpg' => 'video/mpeg', - 'mpe' => 'video/mpeg', - 'qt' => 'video/quicktime', - 'mov' => 'video/quicktime', - 'avi' => 'video/x-msvideo', - 'movie' => 'video/x-sgi-movie', - 'doc' => 'application/msword', - 'word' => 'application/msword', - 'xl' => 'application/excel', - 'eml' => 'message/rfc822' - ); - - return isset($mimes[strtolower($ext)]) ? $mimes[strtolower($ext)] : 'application/x-unknown-content-type'; + static $mimes; + + $ext = strtolower($ext); + + if ( ! is_array($mimes)) + { + $mimes =& get_mimes(); + } + + if (isset($mimes[$ext])) + { + return is_array($mimes[$ext]) + ? current($mimes[$ext]) + : $mimes[$ext]; + } + + return 'application/x-unknown-content-type'; } } /* End of file Email.php */ -/* Location: ./system/libraries/Email.php */ +/* Location: ./system/libraries/Email.php */
\ No newline at end of file diff --git a/system/libraries/Encrypt.php b/system/libraries/Encrypt.php index b29eb470e..ce5e030b0 100644 --- a/system/libraries/Encrypt.php +++ b/system/libraries/Encrypt.php @@ -38,15 +38,49 @@ */ class CI_Encrypt { - public $encryption_key = ''; - protected $_hash_type = 'sha1'; - protected $_mcrypt_exists = FALSE; + /** + * Reference to the user's encryption key + * + * @var string + */ + public $encryption_key = ''; + + /** + * Type of hash operation + * + * @var string + */ + protected $_hash_type = 'sha1'; + + /** + * Flag for the existance of mcrypt + * + * @var bool + */ + protected $_mcrypt_exists = FALSE; + + /** + * Current cipher to be used with mcrypt + * + * @var string + */ protected $_mcrypt_cipher; + + /** + * Method for encrypting/decrypting data + * + * @var int + */ protected $_mcrypt_mode; + /** + * Initialize Encryption class + * + * @return void + */ public function __construct() { - $this->_mcrypt_exists = ( ! function_exists('mcrypt_encrypt')) ? FALSE : TRUE; + $this->_mcrypt_exists = function_exists('mcrypt_encrypt'); log_message('debug', 'Encrypt Class Initialized'); } @@ -63,15 +97,14 @@ class CI_Encrypt { */ public function get_key($key = '') { - if ($key == '') + if ($key === '') { - if ($this->encryption_key != '') + if ($this->encryption_key !== '') { return $this->encryption_key; } - $CI =& get_instance(); - $key = $CI->config->item('encryption_key'); + $key = config_item('encryption_key'); if ($key === FALSE) { @@ -349,8 +382,9 @@ class CI_Encrypt { * * Function description * - * @param type - * @return type + * @param string $data + * @param string $key + * @return string */ protected function _remove_cipher_noise($data, $key) { @@ -382,8 +416,8 @@ class CI_Encrypt { /** * Set the Mcrypt Cipher * - * @param constant - * @return string + * @param int + * @return object */ public function set_cipher($cipher) { @@ -396,8 +430,8 @@ class CI_Encrypt { /** * Set the Mcrypt Mode * - * @param constant - * @return string + * @param int + * @return object */ public function set_mode($mode) { @@ -410,11 +444,11 @@ class CI_Encrypt { /** * Get Mcrypt cipher Value * - * @return string + * @return int */ protected function _get_cipher() { - if ($this->_mcrypt_cipher == '') + if ($this->_mcrypt_cipher === NULL) { return $this->_mcrypt_cipher = MCRYPT_RIJNDAEL_256; } @@ -427,11 +461,11 @@ class CI_Encrypt { /** * Get Mcrypt Mode Value * - * @return string + * @return int */ protected function _get_mode() { - if ($this->_mcrypt_mode == '') + if ($this->_mcrypt_mode === NULL) { return $this->_mcrypt_mode = MCRYPT_MODE_CBC; } @@ -464,7 +498,8 @@ class CI_Encrypt { { return ($this->_hash_type === 'sha1') ? sha1($str) : md5($str); } + } /* End of file Encrypt.php */ -/* Location: ./system/libraries/Encrypt.php */ +/* Location: ./system/libraries/Encrypt.php */
\ No newline at end of file diff --git a/system/libraries/Form_validation.php b/system/libraries/Form_validation.php index 3e0c72e84..225325d6f 100644 --- a/system/libraries/Form_validation.php +++ b/system/libraries/Form_validation.php @@ -25,8 +25,6 @@ * @filesource */ -// ------------------------------------------------------------------------ - /** * Form Validation Class * @@ -38,17 +36,82 @@ */ class CI_Form_validation { + /** + * Reference to the CodeIgniter instance + * + * @var object + */ protected $CI; - protected $_field_data = array(); - protected $_config_rules = array(); - protected $_error_array = array(); - protected $_error_messages = array(); - protected $_error_prefix = '<p>'; - protected $_error_suffix = '</p>'; - protected $error_string = ''; - protected $_safe_form_data = FALSE; - protected $validation_data = array(); + /** + * Validation data for the current form submission + * + * @var array + */ + protected $_field_data = array(); + + /** + * Validation rules for the current form + * + * @var array + */ + protected $_config_rules = array(); + + /** + * Array of validation errors + * + * @var array + */ + protected $_error_array = array(); + + /** + * Array of custom error messages + * + * @var array + */ + protected $_error_messages = array(); + + /** + * Start tag for error wrapping + * + * @var string + */ + protected $_error_prefix = '<p>'; + + /** + * End tag for error wrapping + * + * @var string + */ + protected $_error_suffix = '</p>'; + + /** + * Custom error message + * + * @var string + */ + protected $error_string = ''; + + /** + * Whether the form data has been validated as safe + * + * @var bool + */ + protected $_safe_form_data = FALSE; + + /** + * Custom data to validate + * + * @var array + */ + protected $validation_data = array(); + + /** + * Initialize Form_Validation class + * + * @param array $rules + * @return void + */ public function __construct($rules = array()) { $this->CI =& get_instance(); @@ -64,7 +127,7 @@ class CI_Form_validation { $this->_error_suffix = $rules['error_suffix']; unset($rules['error_suffix']); } - + // Validation rules can be stored in a config file. $this->_config_rules = $rules; @@ -88,9 +151,10 @@ class CI_Form_validation { * This function takes an array of field names and validation * rules as input, validates the info, and stores it * - * @param mixed - * @param string - * @return void + * @param mixed $field + * @param string $label + * @param mixed $rules + * @return object */ public function set_rules($field, $label = '', $rules = '') { @@ -108,28 +172,29 @@ class CI_Form_validation { foreach ($field as $row) { // Houston, we have a problem... - if ( ! isset($row['field']) OR ! isset($row['rules'])) + if ( ! isset($row['field'], $row['rules'])) { continue; } // If the field label wasn't passed we use the field name - $label = ( ! isset($row['label'])) ? $row['field'] : $row['label']; + $label = isset($row['label']) ? $row['label'] : $row['field']; // Here we go! $this->set_rules($row['field'], $label, $row['rules']); } + return $this; } // No fields? Nothing to do... - if ( ! is_string($field) OR ! is_string($rules) OR $field == '') + if ( ! is_string($field) OR ! is_string($rules) OR $field === '') { return $this; } // If the field label wasn't passed we use the field name - $label = ($label == '') ? $field : $label; + $label = ($label === '') ? $field : $label; // Is the field name an array? If it is an array, we break it apart // into its components so that we can fetch the corresponding POST data later @@ -142,7 +207,7 @@ class CI_Form_validation { for ($i = 0, $c = count($matches[0]); $i < $c; $i++) { - if ($matches[1][$i] != '') + if ($matches[1][$i] !== '') { $indexes[] = $matches[1][$i]; } @@ -158,13 +223,13 @@ class CI_Form_validation { // Build our master array $this->_field_data[$field] = array( - 'field' => $field, - 'label' => $label, - 'rules' => $rules, - 'is_array' => $is_array, - 'keys' => $indexes, - 'postdata' => NULL, - 'error' => '' + 'field' => $field, + 'label' => $label, + 'rules' => $rules, + 'is_array' => $is_array, + 'keys' => $indexes, + 'postdata' => NULL, + 'error' => '' ); return $this; @@ -198,12 +263,12 @@ class CI_Form_validation { /** * Set Error Message * - * Lets users set their own error messages on the fly. Note: The key - * name has to match the function name that it corresponds to. + * Lets users set their own error messages on the fly. Note: + * The key name has to match the function name that it corresponds to. * + * @param array * @param string - * @param string - * @return string + * @return object */ public function set_message($lang, $val = '') { @@ -213,7 +278,6 @@ class CI_Form_validation { } $this->_error_messages = array_merge($this->_error_messages, $lang); - return $this; } @@ -226,13 +290,12 @@ class CI_Form_validation { * * @param string * @param string - * @return void + * @return object */ public function set_error_delimiters($prefix = '<p>', $suffix = '</p>') { $this->_error_prefix = $prefix; $this->_error_suffix = $suffix; - return $this; } @@ -244,21 +307,23 @@ class CI_Form_validation { * Gets the error message associated with a particular field * * @param string the field name - * @return void + * @param string the html start tag + * @param strign the html end tag + * @return string */ public function error($field = '', $prefix = '', $suffix = '') { - if ( ! isset($this->_field_data[$field]['error']) OR $this->_field_data[$field]['error'] == '') + if (empty($this->_field_data[$field]['error'])) { return ''; } - if ($prefix == '') + if ($prefix === '') { $prefix = $this->_error_prefix; } - if ($suffix == '') + if ($suffix === '') { $suffix = $this->_error_suffix; } @@ -289,7 +354,7 @@ class CI_Form_validation { * * @param string * @param string - * @return str + * @return string */ public function error_string($prefix = '', $suffix = '') { @@ -299,12 +364,12 @@ class CI_Form_validation { return ''; } - if ($prefix == '') + if ($prefix === '') { $prefix = $this->_error_prefix; } - if ($suffix == '') + if ($suffix === '') { $suffix = $this->_error_suffix; } @@ -313,7 +378,7 @@ class CI_Form_validation { $str = ''; foreach ($this->_error_array as $val) { - if ($val != '') + if ($val !== '') { $str .= $prefix.$val.$suffix."\n"; } @@ -329,12 +394,13 @@ class CI_Form_validation { * * This function does all the work. * + * @param string $group * @return bool */ public function run($group = '') { // Do we even have any data to process? Mm? - $validation_array = ( ! empty($this->validation_data)) ? $this->validation_data : $_POST; + $validation_array = empty($this->validation_data) ? $_POST : $this->validation_data; if (count($validation_array) === 0) { return FALSE; @@ -351,9 +417,9 @@ class CI_Form_validation { } // Is there a validation rule for the particular URI being accessed? - $uri = ($group == '') ? trim($this->CI->uri->ruri_string(), '/') : $group; + $uri = ($group === '') ? trim($this->CI->uri->ruri_string(), '/') : $group; - if ($uri != '' AND isset($this->_config_rules[$uri])) + if ($uri !== '' && isset($this->_config_rules[$uri])) { $this->set_rules($this->_config_rules[$uri]); } @@ -362,10 +428,10 @@ class CI_Form_validation { $this->set_rules($this->_config_rules); } - // We're we able to set the rules correctly? + // Were we able to set the rules correctly? if (count($this->_field_data) === 0) { - log_message('debug', "Unable to find validation rules"); + log_message('debug', 'Unable to find validation rules'); return FALSE; } } @@ -379,17 +445,13 @@ class CI_Form_validation { { // Fetch the data from the corresponding $_POST or validation array and cache it in the _field_data array. // Depending on whether the field name is an array or a string will determine where we get it from. - if ($row['is_array'] === TRUE) { $this->_field_data[$field]['postdata'] = $this->_reduce_array($validation_array, $row['keys']); } - else + elseif (isset($validation_array[$field]) && $validation_array[$field] !== '') { - if (isset($validation_array[$field]) AND $validation_array[$field] != "") - { - $this->_field_data[$field]['postdata'] = $validation_array[$field]; - } + $this->_field_data[$field]['postdata'] = $validation_array[$field]; } $this->_execute($row, explode('|', $row['rules']), $this->_field_data[$field]['postdata']); @@ -397,7 +459,6 @@ class CI_Form_validation { // Did we end up with any errors? $total_errors = count($this->_error_array); - if ($total_errors > 0) { $this->_safe_form_data = TRUE; @@ -416,7 +477,7 @@ class CI_Form_validation { * * @param array * @param array - * @param integer + * @param int * @return mixed */ protected function _reduce_array($array, $keys, $i = 0) @@ -434,7 +495,7 @@ class CI_Form_validation { /** * Re-populate the _POST array with our finalized and processed data * - * @return null + * @return void */ protected function _reset_post_array() { @@ -494,7 +555,7 @@ class CI_Form_validation { * @param array * @param array * @param mixed - * @param integer + * @param int * @return mixed */ protected function _execute($row, $rules, $postdata = NULL, $cycles = 0) @@ -511,17 +572,15 @@ class CI_Form_validation { return; } - // -------------------------------------------------------------------- - // If the field is blank, but NOT required, no further tests are necessary $callback = FALSE; - if ( ! in_array('required', $rules) AND is_null($postdata)) + if ( ! in_array('required', $rules) && is_null($postdata)) { // Before we bail out, does the rule contain a callback? - if (preg_match("/(callback_\w+(\[.*?\])?)/", implode(' ', $rules), $match)) + if (preg_match('/(callback_\w+(\[.*?\])?)/', implode(' ', $rules), $match)) { $callback = TRUE; - $rules = (array('1' => $match[1])); + $rules = array(1 => $match[1]); } else { @@ -529,26 +588,21 @@ class CI_Form_validation { } } - // -------------------------------------------------------------------- - // Isset Test. Typically this rule will only apply to checkboxes. - if (is_null($postdata) AND $callback === FALSE) + if (is_null($postdata) && $callback === FALSE) { if (in_array('isset', $rules, TRUE) OR in_array('required', $rules)) { // Set the message type - $type = (in_array('required', $rules)) ? 'required' : 'isset'; + $type = in_array('required', $rules) ? 'required' : 'isset'; - if ( ! isset($this->_error_messages[$type])) + if (isset($this->_error_messages[$type])) { - if (FALSE === ($line = $this->CI->lang->line($type))) - { - $line = 'The field was not set'; - } + $line = $this->_error_messages[$type]; } - else + elseif (FALSE === ($line = $this->CI->lang->line($type))) { - $line = $this->_error_messages[$type]; + $line = 'The field was not set'; } // Build the error message @@ -569,13 +623,13 @@ class CI_Form_validation { // -------------------------------------------------------------------- // Cycle through each rule and run it - foreach ($rules As $rule) + foreach ($rules as $rule) { $_in_array = FALSE; // We set the $postdata variable with the current data in our master array so that // each cycle of the loop is dealing with the processed data from the last cycle - if ($row['is_array'] == TRUE AND is_array($this->_field_data[$row['field']]['postdata'])) + if ($row['is_array'] === TRUE && is_array($this->_field_data[$row['field']]['postdata'])) { // We shouldn't need this safety, but just in case there isn't an array index // associated with this cycle we'll bail out @@ -592,11 +646,9 @@ class CI_Form_validation { $postdata = $this->_field_data[$row['field']]['postdata']; } - // -------------------------------------------------------------------- - // Is the rule a callback? $callback = FALSE; - if (substr($rule, 0, 9) == 'callback_') + if (strpos($rule, 'callback_') === 0) { $rule = substr($rule, 9); $callback = TRUE; @@ -605,7 +657,7 @@ class CI_Form_validation { // Strip the parameter (if exists) from the rule // Rules can contain a parameter: max_length[5] $param = FALSE; - if (preg_match("/(.*?)\[(.*)\]/", $rule, $match)) + if (preg_match('/(.*?)\[(.*)\]/', $rule, $match)) { $rule = $match[1]; $param = $match[2]; @@ -616,68 +668,69 @@ class CI_Form_validation { { if ( ! method_exists($this->CI, $rule)) { - continue; + log_message('debug', 'Unable to find callback validation rule: '.$rule); + $result = FALSE; + } + else + { + // Run the function and grab the result + $result = $this->CI->$rule($postdata, $param); } - - // Run the function and grab the result - $result = $this->CI->$rule($postdata, $param); // Re-assign the result to the master data array if ($_in_array === TRUE) { - $this->_field_data[$row['field']]['postdata'][$cycles] = (is_bool($result)) ? $postdata : $result; + $this->_field_data[$row['field']]['postdata'][$cycles] = is_bool($result) ? $postdata : $result; } else { - $this->_field_data[$row['field']]['postdata'] = (is_bool($result)) ? $postdata : $result; + $this->_field_data[$row['field']]['postdata'] = is_bool($result) ? $postdata : $result; } // If the field isn't required and we just processed a callback we'll move on... - if ( ! in_array('required', $rules, TRUE) AND $result !== FALSE) + if ( ! in_array('required', $rules, TRUE) && $result !== FALSE) { continue; } } - else + elseif ( ! method_exists($this, $rule)) { - if ( ! method_exists($this, $rule)) + // If our own wrapper function doesn't exist we see if a native PHP function does. + // Users can use any native PHP function call that has one param. + if (function_exists($rule)) { - // If our own wrapper function doesn't exist we see if a native PHP function does. - // Users can use any native PHP function call that has one param. - if (function_exists($rule)) - { - $result = $rule($postdata); + $result = ($param !== FALSE) ? $rule($postdata, $param) : $rule($postdata); - if ($_in_array === TRUE) - { - $this->_field_data[$row['field']]['postdata'][$cycles] = (is_bool($result)) ? $postdata : $result; - } - else - { - $this->_field_data[$row['field']]['postdata'] = (is_bool($result)) ? $postdata : $result; - } + if ($_in_array === TRUE) + { + $this->_field_data[$row['field']]['postdata'][$cycles] = is_bool($result) ? $postdata : $result; } else { - log_message('debug', "Unable to find validation rule: ".$rule); + $this->_field_data[$row['field']]['postdata'] = is_bool($result) ? $postdata : $result; } - - continue; } - + else + { + log_message('debug', 'Unable to find validation rule: '.$rule); + $result = FALSE; + } + } + else + { $result = $this->$rule($postdata, $param); if ($_in_array === TRUE) { - $this->_field_data[$row['field']]['postdata'][$cycles] = (is_bool($result)) ? $postdata : $result; + $this->_field_data[$row['field']]['postdata'][$cycles] = is_bool($result) ? $postdata : $result; } else { - $this->_field_data[$row['field']]['postdata'] = (is_bool($result)) ? $postdata : $result; + $this->_field_data[$row['field']]['postdata'] = is_bool($result) ? $postdata : $result; } } - // Did the rule test negatively? If so, grab the error. + // Did the rule test negatively? If so, grab the error. if ($result === FALSE) { if ( ! isset($this->_error_messages[$rule])) @@ -693,7 +746,7 @@ class CI_Form_validation { } // Is the parameter we are inserting into the error message the name - // of another field? If so we need to grab its "field label" + // of another field? If so we need to grab its "field label" if (isset($this->_field_data[$param], $this->_field_data[$param]['label'])) { $param = $this->_translate_fieldname($this->_field_data[$param]['label']); @@ -727,7 +780,7 @@ class CI_Form_validation { { // Do we need to translate the field name? // We look for the prefix lang: to determine this - if (substr($fieldname, 0, 5) === 'lang:') + if (strpos($fieldname, 'lang:') === 0) { // Grab the variable $line = substr($fieldname, 5); @@ -781,6 +834,7 @@ class CI_Form_validation { * * @param string * @param string + * @param bool * @return string */ public function set_select($field = '', $value = '', $default = FALSE) @@ -791,7 +845,6 @@ class CI_Form_validation { } $field = $this->_field_data[$field]['postdata']; - if (is_array($field)) { if ( ! in_array($value, $field)) @@ -799,7 +852,7 @@ class CI_Form_validation { return ''; } } - elseif (($field == '' OR $value == '') OR ($field != $value)) + elseif (($field === '' OR $value === '') OR ($field !== $value)) { return ''; } @@ -817,6 +870,7 @@ class CI_Form_validation { * * @param string * @param string + * @param bool * @return string */ public function set_radio($field = '', $value = '', $default = FALSE) @@ -827,7 +881,6 @@ class CI_Form_validation { } $field = $this->_field_data[$field]['postdata']; - if (is_array($field)) { if ( ! in_array($value, $field)) @@ -835,12 +888,9 @@ class CI_Form_validation { return ''; } } - else + elseif (($field === '' OR $value === '') OR ($field !== $value)) { - if (($field == '' OR $value == '') OR ($field != $value)) - { - return ''; - } + return ''; } return ' checked="checked"'; @@ -856,6 +906,7 @@ class CI_Form_validation { * * @param string * @param string + * @param bool * @return string */ public function set_checkbox($field = '', $value = '', $default = FALSE) @@ -874,7 +925,7 @@ class CI_Form_validation { */ public function required($str) { - return ( ! is_array($str)) ? (trim($str) !== '') : ( ! empty($str)); + return is_array($str) ? (bool) count($str) : (trim($str) !== ''); } // -------------------------------------------------------------------- @@ -883,7 +934,7 @@ class CI_Form_validation { * Performs a Regular Expression match test. * * @param string - * @param regex + * @param string regex * @return bool */ public function regex_match($str, $regex) @@ -897,18 +948,14 @@ class CI_Form_validation { * Match one field to another * * @param string - * @param field + * @param string field * @return bool */ public function matches($str, $field) { - $validation_array = ( ! empty($this->validation_data)) ? $this->validation_data : $_POST; - if ( ! isset($validation_array[$field])) - { - return FALSE; - } + $validation_array = empty($this->validation_data) ? $_POST : $this->validation_data; - return ($str === $validation_array[$field]); + return isset($validation_array[$field]) ? ($str === $validation_array[$field]) : FALSE; } // -------------------------------------------------------------------- @@ -920,7 +967,7 @@ class CI_Form_validation { * in the specified database field. * * @param string - * @param field + * @param string field * @return bool */ public function is_unique($str, $field) @@ -940,7 +987,7 @@ class CI_Form_validation { * Minimum Length * * @param string - * @param value + * @param int * @return bool */ public function min_length($str, $val) @@ -950,12 +997,9 @@ class CI_Form_validation { return FALSE; } - if (MB_ENABLED === TRUE) - { - return ! (mb_strlen($str) < $val); - } - - return ! (strlen($str) < $val); + return (MB_ENABLED === TRUE) + ? ($val <= mb_strlen($str)) + : ($val <= strlen($str)); } // -------------------------------------------------------------------- @@ -964,7 +1008,7 @@ class CI_Form_validation { * Max Length * * @param string - * @param value + * @param int * @return bool */ public function max_length($str, $val) @@ -974,12 +1018,9 @@ class CI_Form_validation { return FALSE; } - if (MB_ENABLED === TRUE) - { - return ! (mb_strlen($str) > $val); - } - - return ! (strlen($str) > $val); + return (MB_ENABLED === TRUE) + ? ($val >= mb_strlen($str)) + : ($val >= strlen($str)); } // -------------------------------------------------------------------- @@ -988,7 +1029,7 @@ class CI_Form_validation { * Exact Length * * @param string - * @param value + * @param int * @return bool */ public function exact_length($str, $val) @@ -998,12 +1039,9 @@ class CI_Form_validation { return FALSE; } - if (MB_ENABLED === TRUE) - { - return (mb_strlen($str) == $val); - } - - return (strlen($str) == $val); + return (MB_ENABLED === TRUE) + ? (mb_strlen($str) === $val) + : (strlen($str) === $val); } // -------------------------------------------------------------------- @@ -1114,19 +1152,6 @@ class CI_Form_validation { // -------------------------------------------------------------------- /** - * Is Numeric - * - * @param string - * @return bool - */ - public function is_numeric($str) - { - return is_numeric($str); - } - - // -------------------------------------------------------------------- - - /** * Integer * * @param string @@ -1156,15 +1181,12 @@ class CI_Form_validation { * Greater than * * @param string + * @param int * @return bool */ public function greater_than($str, $min) { - if ( ! is_numeric($str)) - { - return FALSE; - } - return $str > $min; + return is_numeric($str) ? ($str > $min) : FALSE; } // -------------------------------------------------------------------- @@ -1173,15 +1195,12 @@ class CI_Form_validation { * Equal to or Greater than * * @param string + * @param int * @return bool */ public function greater_than_equal_to($str, $min) { - if ( ! is_numeric($str)) - { - return FALSE; - } - return $str >= $min; + return is_numeric($str) ? ($str >= $min) : FALSE; } // -------------------------------------------------------------------- @@ -1190,15 +1209,12 @@ class CI_Form_validation { * Less than * * @param string + * @param int * @return bool */ public function less_than($str, $max) { - if ( ! is_numeric($str)) - { - return FALSE; - } - return $str < $max; + return is_numeric($str) ? ($str < $max) : FALSE; } // -------------------------------------------------------------------- @@ -1207,15 +1223,12 @@ class CI_Form_validation { * Equal to or Less than * * @param string + * @param int * @return bool */ public function less_than_equal_to($str, $max) { - if ( ! is_numeric($str)) - { - return FALSE; - } - return $str <= $max; + return is_numeric($str) ? ($str <= $max) : FALSE; } // -------------------------------------------------------------------- @@ -1241,7 +1254,7 @@ class CI_Form_validation { */ public function is_natural_no_zero($str) { - return ($str != 0 && preg_match('/^[0-9]+$/', $str)); + return ($str !== 0 && preg_match('/^[0-9]+$/', $str)); } // -------------------------------------------------------------------- @@ -1257,7 +1270,7 @@ class CI_Form_validation { */ public function valid_base64($str) { - return (bool) ! preg_match('/[^a-zA-Z0-9\/\+=]/', $str); + return ! preg_match('/[^a-zA-Z0-9\/\+=]/', $str); } // -------------------------------------------------------------------- @@ -1283,7 +1296,7 @@ class CI_Form_validation { return $data; } - if ($this->_safe_form_data == FALSE OR $data === '') + if ($this->_safe_form_data === FALSE OR $data === '') { return $data; } @@ -1301,14 +1314,14 @@ class CI_Form_validation { */ public function prep_url($str = '') { - if ($str == 'http://' OR $str == '') + if ($str === 'http://' OR $str === '') { return ''; } - if (substr($str, 0, 7) !== 'http://' && substr($str, 0, 8) !== 'https://') + if (strpos($str, 'http://') !== 0 && strpos($str, 'https://') !== 0) { - $str = 'http://'.$str; + return 'http://'.$str; } return $str; @@ -1375,4 +1388,4 @@ class CI_Form_validation { } /* End of file Form_validation.php */ -/* Location: ./system/libraries/Form_validation.php */ +/* Location: ./system/libraries/Form_validation.php */
\ No newline at end of file diff --git a/system/libraries/Ftp.php b/system/libraries/Ftp.php index 8aa1650d2..461e884fb 100644 --- a/system/libraries/Ftp.php +++ b/system/libraries/Ftp.php @@ -44,7 +44,6 @@ class CI_FTP { public $debug = FALSE; public $conn_id = FALSE; - public function __construct($config = array()) { if (count($config) > 0) @@ -94,7 +93,7 @@ class CI_FTP { if (FALSE === ($this->conn_id = @ftp_connect($this->hostname, $this->port))) { - if ($this->debug == TRUE) + if ($this->debug === TRUE) { $this->_error('ftp_unable_to_connect'); } @@ -103,7 +102,7 @@ class CI_FTP { if ( ! $this->_login()) { - if ($this->debug == TRUE) + if ($this->debug === TRUE) { $this->_error('ftp_unable_to_login'); } @@ -111,7 +110,7 @@ class CI_FTP { } // Set passive mode if needed - if ($this->passive == TRUE) + if ($this->passive === TRUE) { ftp_pasv($this->conn_id, TRUE); } @@ -142,7 +141,7 @@ class CI_FTP { { if ( ! is_resource($this->conn_id)) { - if ($this->debug == TRUE) + if ($this->debug === TRUE) { $this->_error('ftp_no_connection'); } @@ -168,7 +167,7 @@ class CI_FTP { */ public function changedir($path = '', $supress_debug = FALSE) { - if ($path == '' OR ! $this->_is_conn()) + if ($path === '' OR ! $this->_is_conn()) { return FALSE; } @@ -177,7 +176,7 @@ class CI_FTP { if ($result === FALSE) { - if ($this->debug == TRUE && $supress_debug == FALSE) + if ($this->debug === TRUE && $supress_debug === FALSE) { $this->_error('ftp_unable_to_changedir'); } @@ -198,7 +197,7 @@ class CI_FTP { */ public function mkdir($path = '', $permissions = NULL) { - if ($path == '' OR ! $this->_is_conn()) + if ($path === '' OR ! $this->_is_conn()) { return FALSE; } @@ -207,7 +206,7 @@ class CI_FTP { if ($result === FALSE) { - if ($this->debug == TRUE) + if ($this->debug === TRUE) { $this->_error('ftp_unable_to_makdir'); } @@ -261,7 +260,7 @@ class CI_FTP { if ($result === FALSE) { - if ($this->debug == TRUE) + if ($this->debug === TRUE) { $this->_error('ftp_unable_to_upload'); } @@ -308,7 +307,7 @@ class CI_FTP { if ($result === FALSE) { - if ($this->debug == TRUE) + if ($this->debug === TRUE) { $this->_error('ftp_unable_to_download'); } @@ -339,9 +338,9 @@ class CI_FTP { if ($result === FALSE) { - if ($this->debug == TRUE) + if ($this->debug === TRUE) { - $this->_error('ftp_unable_to_' . ($move == FALSE ? 'rename' : 'move')); + $this->_error('ftp_unable_to_' . ($move === FALSE ? 'rename' : 'move')); } return FALSE; } @@ -382,7 +381,7 @@ class CI_FTP { if ($result === FALSE) { - if ($this->debug == TRUE) + if ($this->debug === TRUE) { $this->_error('ftp_unable_to_delete'); } @@ -430,7 +429,7 @@ class CI_FTP { if ($result === FALSE) { - if ($this->debug == TRUE) + if ($this->debug === TRUE) { $this->_error('ftp_unable_to_delete'); } @@ -460,7 +459,7 @@ class CI_FTP { if ($result === FALSE) { - if ($this->debug == TRUE) + if ($this->debug === TRUE) { $this->_error('ftp_unable_to_chmod'); } @@ -539,7 +538,6 @@ class CI_FTP { return FALSE; } - // -------------------------------------------------------------------- /** diff --git a/system/libraries/Image_lib.php b/system/libraries/Image_lib.php index 86b77bf07..4735dfd08 100644 --- a/system/libraries/Image_lib.php +++ b/system/libraries/Image_lib.php @@ -36,56 +36,336 @@ */ class CI_Image_lib { - public $image_library = 'gd2'; // Can be: imagemagick, netpbm, gd, gd2 + /** + * PHP extension/library to use for image manipulation + * Can be: imagemagick, netpbm, gd, gd2 + * + * @var string + */ + public $image_library = 'gd2'; + + /** + * Path to the graphic library (if applicable) + * + * @var string + */ public $library_path = ''; - public $dynamic_output = FALSE; // Whether to send to browser or write to disk + + /** + * Whether to send to browser or write to disk + * + * @var bool + */ + public $dynamic_output = FALSE; + + /** + * Path to original image + * + * @var string + */ public $source_image = ''; - public $new_image = ''; - public $width = ''; - public $height = ''; - public $quality = '90'; + + /** + * Path to the modified image + * + * @var string + */ + public $new_image = ''; + + /** + * Image width + * + * @var int + */ + public $width = ''; + + /** + * Image height + * + * @var int + */ + public $height = ''; + + /** + * Quality percentage of new image + * + * @var int + */ + public $quality = 90; + + /** + * Whether to create a thumbnail + * + * @var bool + */ public $create_thumb = FALSE; + + /** + * String to add to thumbnail version of image + * + * @var string + */ public $thumb_marker = '_thumb'; - public $maintain_ratio = TRUE; // Whether to maintain aspect ratio when resizing or use hard values - public $master_dim = 'auto'; // auto, height, or width. Determines what to use as the master dimension + + /** + * Whether to maintain aspect ratio when resizing or use hard values + * + * @var bool + */ + public $maintain_ratio = TRUE; + + /** + * auto, height, or width. Determines what to use as the master dimension + * + * @var string + */ + public $master_dim = 'auto'; + + /** + * Angle at to rotate image + * + * @var string + */ public $rotation_angle = ''; - public $x_axis = ''; - public $y_axis = ''; + /** + * X Coordinate for manipulation of the current image + * + * @var int + */ + public $x_axis = ''; + + /** + * Y Coordinate for manipulation of the current image + * + * @var int + */ + public $y_axis = ''; + + // -------------------------------------------------------------------------- // Watermark Vars - public $wm_text = ''; // Watermark text if graphic is not used - public $wm_type = 'text'; // Type of watermarking. Options: text/overlay + // -------------------------------------------------------------------------- + + /** + * Watermark text if graphic is not used + * + * @var string + */ + public $wm_text = ''; + + /** + * Type of watermarking. Options: text/overlay + * + * @var string + */ + public $wm_type = 'text'; + + /** + * Default transparency for watermark + * + * @var int + */ public $wm_x_transp = 4; + + /** + * Default transparency for watermark + * + * @var int + */ public $wm_y_transp = 4; - public $wm_overlay_path = ''; // Watermark image path - public $wm_font_path = ''; // TT font - public $wm_font_size = 17; // Font size (different versions of GD will either use points or pixels) - public $wm_vrt_alignment = 'B'; // Vertical alignment: T M B - public $wm_hor_alignment = 'C'; // Horizontal alignment: L R C - public $wm_padding = 0; // Padding around text - public $wm_hor_offset = 0; // Lets you push text to the right - public $wm_vrt_offset = 0; // Lets you push text down - protected $wm_font_color = '#ffffff'; // Text color - protected $wm_shadow_color = ''; // Dropshadow color - public $wm_shadow_distance = 2; // Dropshadow distance - public $wm_opacity = 50; // Image opacity: 1 - 100 Only works with image + /** + * Watermark image path + * + * @var string + */ + public $wm_overlay_path = ''; + + /** + * TT font + * + * @var string + */ + public $wm_font_path = ''; + + /** + * Font size (different versions of GD will either use points or pixels) + * + * @var int + */ + public $wm_font_size = 17; + + /** + * Vertical alignment: T M B + * + * @var string + */ + public $wm_vrt_alignment = 'B'; + + /** + * Horizontal alignment: L R C + * + * @var string + */ + public $wm_hor_alignment = 'C'; + + /** + * Padding around text + * + * @var int + */ + public $wm_padding = 0; + + /** + * Lets you push text to the right + * + * @var int + */ + public $wm_hor_offset = 0; + + /** + * Lets you push text down + * + * @var int + */ + public $wm_vrt_offset = 0; + + /** + * Text color + * + * @var string + */ + protected $wm_font_color = '#ffffff'; + + /** + * Dropshadow color + * + * @var string + */ + protected $wm_shadow_color = ''; + + /** + * Dropshadow distance + * + * @var int + */ + public $wm_shadow_distance = 2; + + /** + * Image opacity: 1 - 100 Only works with image + * + * @var int + */ + public $wm_opacity = 50; + + // -------------------------------------------------------------------------- // Private Vars + // -------------------------------------------------------------------------- + + /** + * Source image folder + * + * @var string + */ public $source_folder = ''; + + /** + * Destination image folder + * + * @var string + */ public $dest_folder = ''; - public $mime_type = ''; - public $orig_width = ''; + + /** + * Image mime-type + * + * @var string + */ + public $mime_type = ''; + + /** + * Original image width + * + * @var int + */ + public $orig_width = ''; + + /** + * Original image height + * + * @var int + */ public $orig_height = ''; - public $image_type = ''; - public $size_str = ''; + + /** + * Image format + * + * @var string + */ + public $image_type = ''; + + /** + * Size of current image + * + * @var string + */ + public $size_str = ''; + + /** + * Full path to source image + * + * @var string + */ public $full_src_path = ''; + + /** + * Full path to destination image + * + * @var string + */ public $full_dst_path = ''; - public $create_fnc = 'imagecreatetruecolor'; - public $copy_fnc = 'imagecopyresampled'; - public $error_msg = array(); + + /** + * Name of function to create image + * + * @var string + */ + public $create_fnc = 'imagecreatetruecolor'; + + /** + * Name of function to copy image + * + * @var string + */ + public $copy_fnc = 'imagecopyresampled'; + + /** + * Error messages + * + * @var array + */ + public $error_msg = array(); + + /** + * Whether to have a drop shadow on watermark + * + * @var bool + */ protected $wm_use_drop_shadow = FALSE; + + /** + * Whether to use truetype fonts + * + * @var bool + */ public $wm_use_truetype = FALSE; + /** + * Initialize Image Library + * + * @param array $props + * @return void + */ public function __construct($props = array()) { if (count($props) > 0) @@ -116,7 +396,7 @@ class CI_Image_lib { $this->image_library = 'gd2'; $this->dynamic_output = FALSE; - $this->quality = '90'; + $this->quality = 90; $this->create_thumb = FALSE; $this->thumb_marker = '_thumb'; $this->maintain_ratio = TRUE; @@ -186,7 +466,7 @@ class CI_Image_lib { } // Is there a source image? If not, there's no reason to continue - if ($this->source_image == '') + if ($this->source_image === '') { $this->set_error('imglib_source_image_required'); return FALSE; @@ -239,7 +519,7 @@ class CI_Image_lib { * it means we are altering the original. We'll * set the destination filename and path accordingly. */ - if ($this->new_image == '') + if ($this->new_image === '') { $this->dest_image = $this->source_image; $this->dest_folder = $this->source_folder; @@ -251,7 +531,7 @@ class CI_Image_lib { } else { - if (strpos($this->new_image, '/') === FALSE AND strpos($this->new_image, '\\') === FALSE) + if (strpos($this->new_image, '/') === FALSE && strpos($this->new_image, '\\') === FALSE) { $full_dest_path = str_replace('\\', '/', realpath($this->new_image)); } @@ -282,7 +562,7 @@ class CI_Image_lib { * We'll also split the destination image name * so we can insert the thumbnail marker if needed. */ - if ($this->create_thumb === FALSE OR $this->thumb_marker == '') + if ($this->create_thumb === FALSE OR $this->thumb_marker === '') { $this->thumb_marker = ''; } @@ -301,7 +581,7 @@ class CI_Image_lib { * might not be in correct proportion with the source * image's width/height. We'll recalculate it here. */ - if ($this->maintain_ratio === TRUE && ($this->width != 0 OR $this->height != 0)) + if ($this->maintain_ratio === TRUE && ($this->width !== 0 OR $this->height !== 0)) { $this->image_reproportion(); } @@ -311,12 +591,12 @@ class CI_Image_lib { * If the destination width/height was not submitted we * will use the values from the actual file */ - if ($this->width == '') + if ($this->width === '') { $this->width = $this->orig_width; } - if ($this->height == '') + if ($this->height === '') { $this->height = $this->orig_height; } @@ -324,31 +604,31 @@ class CI_Image_lib { // Set the quality $this->quality = trim(str_replace('%', '', $this->quality)); - if ($this->quality == '' OR $this->quality == 0 OR ! preg_match('/^[0-9]+$/', $this->quality)) + if ($this->quality === '' OR $this->quality === 0 OR ! preg_match('/^[0-9]+$/', $this->quality)) { $this->quality = 90; } // Set the x/y coordinates - $this->x_axis = ($this->x_axis == '' OR ! preg_match('/^[0-9]+$/', $this->x_axis)) ? 0 : $this->x_axis; - $this->y_axis = ($this->y_axis == '' OR ! preg_match('/^[0-9]+$/', $this->y_axis)) ? 0 : $this->y_axis; + is_numeric($this->x_axis) OR $this->x_axis = 0; + is_numeric($this->y_axis) OR $this->y_axis = 0; // Watermark-related Stuff... - if ($this->wm_overlay_path != '') + if ($this->wm_overlay_path !== '') { $this->wm_overlay_path = str_replace('\\', '/', realpath($this->wm_overlay_path)); } - if ($this->wm_shadow_color != '') + if ($this->wm_shadow_color !== '') { $this->wm_use_drop_shadow = TRUE; } - elseif ($this->wm_use_drop_shadow == TRUE && $this->wm_shadow_color == '') + elseif ($this->wm_use_drop_shadow === TRUE && $this->wm_shadow_color === '') { $this->wm_use_drop_shadow = FALSE; } - if ($this->wm_font_path != '') + if ($this->wm_font_path !== '') { $this->wm_use_truetype = TRUE; } @@ -403,14 +683,14 @@ class CI_Image_lib { // Allowed rotation values $degs = array(90, 180, 270, 'vrt', 'hor'); - if ($this->rotation_angle == '' OR ! in_array($this->rotation_angle, $degs)) + if ($this->rotation_angle === '' OR ! in_array($this->rotation_angle, $degs)) { $this->set_error('imglib_rotation_angle_required'); return FALSE; } // Reassign the width and height - if ($this->rotation_angle == 90 OR $this->rotation_angle == 270) + if ($this->rotation_angle === 90 OR $this->rotation_angle === 270) { $this->width = $this->orig_height; $this->height = $this->orig_width; @@ -449,9 +729,9 @@ class CI_Image_lib { // If the target width/height match the source, AND if the new file name is not equal to the old file name // we'll simply make a copy of the original with the new name... assuming dynamic rendering is off. - if ($this->dynamic_output === FALSE && $this->orig_width == $this->width && $this->orig_height == $this->height) + if ($this->dynamic_output === FALSE && $this->orig_width === $this->width && $this->orig_height === $this->height) { - if ($this->source_image != $this->new_image && @copy($this->full_src_path, $this->full_dst_path)) + if ($this->source_image !== $this->new_image && @copy($this->full_src_path, $this->full_dst_path)) { @chmod($this->full_dst_path, FILE_WRITE_MODE); } @@ -460,7 +740,7 @@ class CI_Image_lib { } // Let's set up our values based on the action - if ($action == 'crop') + if ($action === 'crop') { // Reassign the source width/height if cropping $this->orig_width = $this->width; @@ -470,7 +750,7 @@ class CI_Image_lib { if ($this->gd_version() !== FALSE) { $gd_version = str_replace('0', '', $this->gd_version()); - $v2_override = ($gd_version == 2) ? TRUE : FALSE; + $v2_override = ($gd_version === 2); } } else @@ -492,7 +772,7 @@ class CI_Image_lib { * it appears that this is no longer the issue that it was in 2004, so we've removed it, retaining it in the comment * below should that ever prove inaccurate. * - * if ($this->image_library === 'gd2' && function_exists('imagecreatetruecolor') && $v2_override == FALSE) + * if ($this->image_library === 'gd2' && function_exists('imagecreatetruecolor') && $v2_override === FALSE) */ if ($this->image_library === 'gd2' && function_exists('imagecreatetruecolor')) { @@ -507,7 +787,7 @@ class CI_Image_lib { $dst_img = $create($this->width, $this->height); - if ($this->image_type == 3) // png we can actually preserve transparency + if ($this->image_type === 3) // png we can actually preserve transparency { imagealphablending($dst_img, FALSE); imagesavealpha($dst_img, TRUE); @@ -516,7 +796,7 @@ class CI_Image_lib { $copy($dst_img, $src_img, 0, 0, $this->x_axis, $this->y_axis, $this->width, $this->height, $this->orig_width, $this->orig_height); // Show the image - if ($this->dynamic_output == TRUE) + if ($this->dynamic_output === TRUE) { $this->image_display_gd($dst_img); } @@ -548,7 +828,7 @@ class CI_Image_lib { public function image_process_imagemagick($action = 'resize') { // Do we have a vaild library path? - if ($this->library_path == '') + if ($this->library_path === '') { $this->set_error('imglib_libpath_invalid'); return FALSE; @@ -562,11 +842,11 @@ class CI_Image_lib { // Execute the command $cmd = $this->library_path.' -quality '.$this->quality; - if ($action == 'crop') + if ($action === 'crop') { $cmd .= ' -crop '.$this->width.'x'.$this->height.'+'.$this->x_axis.'+'.$this->y_axis.' "'.$this->full_src_path.'" "'.$this->full_dst_path .'" 2>&1'; } - elseif ($action == 'rotate') + elseif ($action === 'rotate') { $angle = ($this->rotation_angle === 'hor' OR $this->rotation_angle === 'vrt') ? '-flop' : '-rotate '.$this->rotation_angle; @@ -606,7 +886,7 @@ class CI_Image_lib { */ public function image_process_netpbm($action = 'resize') { - if ($this->library_path == '') + if ($this->library_path === '') { $this->set_error('imglib_libpath_invalid'); return FALSE; @@ -616,36 +896,36 @@ class CI_Image_lib { switch ($this->image_type) { case 1 : - $cmd_in = 'giftopnm'; - $cmd_out = 'ppmtogif'; + $cmd_in = 'giftopnm'; + $cmd_out = 'ppmtogif'; break; case 2 : - $cmd_in = 'jpegtopnm'; - $cmd_out = 'ppmtojpeg'; + $cmd_in = 'jpegtopnm'; + $cmd_out = 'ppmtojpeg'; break; case 3 : - $cmd_in = 'pngtopnm'; - $cmd_out = 'ppmtopng'; + $cmd_in = 'pngtopnm'; + $cmd_out = 'ppmtopng'; break; } - if ($action == 'crop') + if ($action === 'crop') { $cmd_inner = 'pnmcut -left '.$this->x_axis.' -top '.$this->y_axis.' -width '.$this->width.' -height '.$this->height; } - elseif ($action == 'rotate') + elseif ($action === 'rotate') { switch ($this->rotation_angle) { - case 90 : $angle = 'r270'; + case 90: $angle = 'r270'; break; - case 180 : $angle = 'r180'; + case 180: $angle = 'r180'; break; - case 270 : $angle = 'r90'; + case 270: $angle = 'r90'; break; - case 'vrt' : $angle = 'tb'; + case 'vrt': $angle = 'tb'; break; - case 'hor' : $angle = 'lr'; + case 'hor': $angle = 'lr'; break; } @@ -704,7 +984,7 @@ class CI_Image_lib { $dst_img = imagerotate($src_img, $this->rotation_angle, $white); // Show the image - if ($this->dynamic_output == TRUE) + if ($this->dynamic_output === TRUE) { $this->image_display_gd($dst_img); } @@ -778,7 +1058,7 @@ class CI_Image_lib { } // Show the image - if ($this->dynamic_output == TRUE) + if ($this->dynamic_output === TRUE) { $this->image_display_gd($src_img); } @@ -804,7 +1084,6 @@ class CI_Image_lib { * This is a wrapper function that chooses the type * of watermarking based on the specified preference. * - * @param string * @return bool */ public function watermark() @@ -850,10 +1129,10 @@ class CI_Image_lib { $this->wm_vrt_alignment = strtoupper($this->wm_vrt_alignment[0]); $this->wm_hor_alignment = strtoupper($this->wm_hor_alignment[0]); - if ($this->wm_vrt_alignment == 'B') + if ($this->wm_vrt_alignment === 'B') $this->wm_vrt_offset = $this->wm_vrt_offset * -1; - if ($this->wm_hor_alignment == 'R') + if ($this->wm_hor_alignment === 'R') $this->wm_hor_offset = $this->wm_hor_offset * -1; // Set the base x and y axis values @@ -881,7 +1160,7 @@ class CI_Image_lib { } // Build the finalized image - if ($wm_img_type == 3 && function_exists('imagealphablending')) + if ($wm_img_type === 3 && function_exists('imagealphablending')) { @imagealphablending($src_img, TRUE); } @@ -904,7 +1183,7 @@ class CI_Image_lib { } // Output the image - if ($this->dynamic_output == TRUE) + if ($this->dynamic_output === TRUE) { $this->image_display_gd($src_img); } @@ -933,7 +1212,7 @@ class CI_Image_lib { return FALSE; } - if ($this->wm_use_truetype == TRUE && ! file_exists($this->wm_font_path)) + if ($this->wm_use_truetype === TRUE && ! file_exists($this->wm_font_path)) { $this->set_error('imglib_missing_font'); return FALSE; @@ -949,18 +1228,18 @@ class CI_Image_lib { // invert the offset. Note: The horizontal // offset flips itself automatically - if ($this->wm_vrt_alignment == 'B') + if ($this->wm_vrt_alignment === 'B') $this->wm_vrt_offset = $this->wm_vrt_offset * -1; - if ($this->wm_hor_alignment == 'R') + if ($this->wm_hor_alignment === 'R') $this->wm_hor_offset = $this->wm_hor_offset * -1; // Set font width and height // These are calculated differently depending on // whether we are using the true type font or not - if ($this->wm_use_truetype == TRUE) + if ($this->wm_use_truetype === TRUE) { - if ($this->wm_font_size == '') + if ($this->wm_font_size === '') { $this->wm_font_size = 17; } @@ -979,7 +1258,7 @@ class CI_Image_lib { $x_axis = $this->wm_hor_offset + $this->wm_padding; $y_axis = $this->wm_vrt_offset + $this->wm_padding; - if ($this->wm_use_drop_shadow == FALSE) + if ($this->wm_use_drop_shadow === FALSE) $this->wm_shadow_distance = 0; $this->wm_vrt_alignment = strtoupper(substr($this->wm_vrt_alignment, 0, 1)); @@ -1037,7 +1316,7 @@ class CI_Image_lib { } // Output the final image - if ($this->dynamic_output == TRUE) + if ($this->dynamic_output === TRUE) { $this->image_display_gd($src_img); } @@ -1060,14 +1339,15 @@ class CI_Image_lib { * based on the type of image being processed * * @param string + * @param string * @return resource */ public function image_create_gd($path = '', $image_type = '') { - if ($path == '') + if ($path === '') $path = $this->full_src_path; - if ($image_type == '') + if ($image_type === '') $image_type = $this->image_type; @@ -1122,49 +1402,49 @@ class CI_Image_lib { { switch ($this->image_type) { - case 1 : - if ( ! function_exists('imagegif')) - { - $this->set_error(array('imglib_unsupported_imagecreate', 'imglib_gif_not_supported')); - return FALSE; - } + case 1: + if ( ! function_exists('imagegif')) + { + $this->set_error(array('imglib_unsupported_imagecreate', 'imglib_gif_not_supported')); + return FALSE; + } - if ( ! @imagegif($resource, $this->full_dst_path)) - { - $this->set_error('imglib_save_failed'); - return FALSE; - } - break; - case 2 : - if ( ! function_exists('imagejpeg')) - { - $this->set_error(array('imglib_unsupported_imagecreate', 'imglib_jpg_not_supported')); - return FALSE; - } + if ( ! @imagegif($resource, $this->full_dst_path)) + { + $this->set_error('imglib_save_failed'); + return FALSE; + } + break; + case 2: + if ( ! function_exists('imagejpeg')) + { + $this->set_error(array('imglib_unsupported_imagecreate', 'imglib_jpg_not_supported')); + return FALSE; + } - if ( ! @imagejpeg($resource, $this->full_dst_path, $this->quality)) - { - $this->set_error('imglib_save_failed'); - return FALSE; - } - break; - case 3 : - if ( ! function_exists('imagepng')) - { - $this->set_error(array('imglib_unsupported_imagecreate', 'imglib_png_not_supported')); - return FALSE; - } + if ( ! @imagejpeg($resource, $this->full_dst_path, $this->quality)) + { + $this->set_error('imglib_save_failed'); + return FALSE; + } + break; + case 3: + if ( ! function_exists('imagepng')) + { + $this->set_error(array('imglib_unsupported_imagecreate', 'imglib_png_not_supported')); + return FALSE; + } - if ( ! @imagepng($resource, $this->full_dst_path)) - { - $this->set_error('imglib_save_failed'); - return FALSE; - } - break; - default : - $this->set_error(array('imglib_unsupported_imagecreate')); - return FALSE; - break; + if ( ! @imagepng($resource, $this->full_dst_path)) + { + $this->set_error('imglib_save_failed'); + return FALSE; + } + break; + default: + $this->set_error(array('imglib_unsupported_imagecreate')); + return FALSE; + break; } return TRUE; @@ -1187,13 +1467,13 @@ class CI_Image_lib { switch ($this->image_type) { - case 1 : imagegif($resource); + case 1 : imagegif($resource); break; - case 2 : imagejpeg($resource, '', $this->quality); + case 2 : imagejpeg($resource, '', $this->quality); break; - case 3 : imagepng($resource); + case 3 : imagepng($resource); break; - default : echo 'Unable to display the image'; + default: echo 'Unable to display the image'; break; } } @@ -1214,7 +1494,7 @@ class CI_Image_lib { */ public function image_reproportion() { - if (($this->width == 0 && $this->height == 0) OR $this->orig_width == 0 OR $this->orig_height == 0 + if (($this->width === 0 && $this->height === 0) OR $this->orig_width === 0 OR $this->orig_height === 0 OR ( ! preg_match('/^[0-9]+$/', $this->width) && ! preg_match('/^[0-9]+$/', $this->height)) OR ! preg_match('/^[0-9]+$/', $this->orig_width) OR ! preg_match('/^[0-9]+$/', $this->orig_height)) { @@ -1261,6 +1541,7 @@ class CI_Image_lib { * A helper function that gets info about the file * * @param string + * @param bool * @return mixed */ public function get_image_properties($path = '', $return = FALSE) @@ -1268,7 +1549,7 @@ class CI_Image_lib { // For now we require GD but we should // find a way to determine this using IM or NetPBM - if ($path == '') + if ($path === '') { $path = $this->full_src_path; } @@ -1283,7 +1564,7 @@ class CI_Image_lib { $types = array(1 => 'gif', 2 => 'jpeg', 3 => 'png'); $mime = (isset($types[$vals[2]])) ? 'image/'.$types[$vals[2]] : 'image/jpg'; - if ($return == TRUE) + if ($return === TRUE) { return array( 'width' => $vals[0], @@ -1333,20 +1614,22 @@ class CI_Image_lib { foreach ($allowed as $item) { - if ( ! isset($vals[$item]) OR $vals[$item] == '') + if (empty($vals[$item])) + { $vals[$item] = 0; + } } - if ($vals['width'] == 0 OR $vals['height'] == 0) + if ($vals['width'] === 0 OR $vals['height'] === 0) { return $vals; } - if ($vals['new_width'] == 0) + if ($vals['new_width'] === 0) { $vals['new_width'] = ceil($vals['width']*$vals['new_height']/$vals['height']); } - elseif ($vals['new_height'] == 0) + elseif ($vals['new_height'] === 0) { $vals['new_height'] = ceil($vals['new_width']*$vals['height']/$vals['width']); } @@ -1432,15 +1715,14 @@ class CI_Image_lib { { foreach ($msg as $val) { - - $msg = ($CI->lang->line($val) == FALSE) ? $val : $CI->lang->line($val); + $msg = ($CI->lang->line($val) === FALSE) ? $val : $CI->lang->line($val); $this->error_msg[] = $msg; log_message('error', $msg); } } else { - $msg = ($CI->lang->line($msg) == FALSE) ? $msg : $CI->lang->line($msg); + $msg = ($CI->lang->line($msg) === FALSE) ? $msg : $CI->lang->line($msg); $this->error_msg[] = $msg; log_message('error', $msg); } @@ -1452,6 +1734,7 @@ class CI_Image_lib { * Show error messages * * @param string + * @param string * @return string */ public function display_errors($open = '<p>', $close = '</p>') @@ -1462,4 +1745,4 @@ class CI_Image_lib { } /* End of file Image_lib.php */ -/* Location: ./system/libraries/Image_lib.php */ +/* Location: ./system/libraries/Image_lib.php */
\ No newline at end of file diff --git a/system/libraries/Javascript.php b/system/libraries/Javascript.php index 9ba93000b..98fec61d3 100644 --- a/system/libraries/Javascript.php +++ b/system/libraries/Javascript.php @@ -25,8 +25,6 @@ * @filesource */ -// ------------------------------------------------------------------------ - /** * Javascript Class * @@ -46,7 +44,7 @@ class CI_Javascript { foreach ($defaults as $key => $val) { - if (isset($params[$key]) && $params[$key] !== "") + if (isset($params[$key]) && $params[$key] !== '') { $defaults[$key] = $params[$key]; } @@ -61,7 +59,7 @@ class CI_Javascript { // make js to refer to current library $this->js =& $this->CI->$js_library_driver; - log_message('debug', "Javascript Class Initialized and loaded. Driver used: $js_library_driver"); + log_message('debug', 'Javascript Class Initialized and loaded. Driver used: '.$js_library_driver); } // -------------------------------------------------------------------- @@ -107,7 +105,7 @@ class CI_Javascript { * * @param string The element to attach the event to * @param string The code to execute - * @param boolean whether or not to return false + * @param bool whether or not to return false * @return string */ public function click($element = 'this', $js = '', $ret_false = TRUE) @@ -375,7 +373,6 @@ class CI_Javascript { // Effects // -------------------------------------------------------------------- - /** * Add Class * @@ -618,12 +615,9 @@ class CI_Javascript { { $this->_javascript_location = $external_file; } - else + elseif ($this->CI->config->item('javascript_location') !== '') { - if ($this->CI->config->item('javascript_location') != '') - { - $this->_javascript_location = $this->CI->config->item('javascript_location'); - } + $this->_javascript_location = $this->CI->config->item('javascript_location'); } if ($relative === TRUE OR strncmp($external_file, 'http://', 7) === 0 OR strncmp($external_file, 'https://', 8) === 0) @@ -650,13 +644,13 @@ class CI_Javascript { * Outputs a <script> tag * * @param string The element to attach the event to - * @param boolean If a CDATA section should be added + * @param bool If a CDATA section should be added * @return string */ public function inline($script, $cdata = TRUE) { return $this->_open_script() - . ($cdata ? "\n// <![CDATA[\n{$script}\n// ]]>\n" : "\n{$script}\n") + . ($cdata ? "\n// <![CDATA[\n".$script."\n// ]]>\n" : "\n".$script."\n") . $this->_close_script(); } @@ -673,7 +667,7 @@ class CI_Javascript { protected function _open_script($src = '') { return '<script type="text/javascript" charset="'.strtolower($this->CI->config->item('charset')).'"' - . ($src == '' ? '>' : ' src="'.$src.'">'); + .($src === '' ? '>' : ' src="'.$src.'">'); } // -------------------------------------------------------------------- @@ -688,15 +682,12 @@ class CI_Javascript { */ protected function _close_script($extra = "\n") { - return "</script>$extra"; + return '</script>'.$extra; } - - // -------------------------------------------------------------------- // -------------------------------------------------------------------- // AJAX-Y STUFF - still a testbed // -------------------------------------------------------------------- - // -------------------------------------------------------------------- /** * Update @@ -732,7 +723,7 @@ class CI_Javascript { { if (is_object($result)) { - $json_result = $result->result_array(); + $json_result = is_callable(array($result, 'result_array')) ? $result->result_array() : (array) $result; } elseif (is_array($result)) { @@ -751,9 +742,9 @@ class CI_Javascript { $json = array(); $_is_assoc = TRUE; - if ( ! is_array($json_result) AND empty($json_result)) + if ( ! is_array($json_result) && empty($json_result)) { - show_error("Generate JSON Failed - Illegal key, value pair."); + show_error('Generate JSON Failed - Illegal key, value pair.'); } elseif ($match_array_type) { @@ -774,7 +765,7 @@ class CI_Javascript { $json = implode(',', $json); - return $_is_assoc ? "{".$json."}" : "[".$json."]"; + return $_is_assoc ? '{'.$json.'}' : '['.$json.']'; } @@ -785,8 +776,8 @@ class CI_Javascript { * * Checks for an associative array * - * @param type - * @return type + * @param array + * @return bool */ protected function _is_associative_array($arr) { @@ -808,8 +799,8 @@ class CI_Javascript { * * Ensures a standard json value and escapes values * - * @param type - * @return type + * @param mixed + * @return string */ protected function _prep_args($result, $is_key = FALSE) { @@ -831,9 +822,7 @@ class CI_Javascript { } } - // -------------------------------------------------------------------- } -// END Javascript Class /* End of file Javascript.php */ -/* Location: ./system/libraries/Javascript.php */ +/* Location: ./system/libraries/Javascript.php */
\ No newline at end of file diff --git a/system/libraries/Log.php b/system/libraries/Log.php index 955277acc..baac80121 100644 --- a/system/libraries/Log.php +++ b/system/libraries/Log.php @@ -25,8 +25,6 @@ * @filesource */ -// ------------------------------------------------------------------------ - /** * Logging Class * @@ -38,22 +36,65 @@ */ class CI_Log { + /** + * Path to save log files + * + * @var string + */ protected $_log_path; + + /** + * Level of logging + * + * @var int + */ protected $_threshold = 1; + + /** + * Highest level of logging + * + * @var int + */ protected $_threshold_max = 0; + + /** + * Array of threshold levels to log + * + * @var array + */ protected $_threshold_array = array(); + + /** + * Format of timestamp for log files + * + * @var string + */ protected $_date_fmt = 'Y-m-d H:i:s'; - protected $_enabled = TRUE; - protected $_levels = array('ERROR' => 1, 'DEBUG' => 2, 'INFO' => 3, 'ALL' => 4); /** - * Constructor + * Whether or not the logger can write to the log files + * + * @var bool + */ + protected $_enabled = TRUE; + + /** + * Predefined logging levels + * + * @var array + */ + protected $_levels = array('ERROR' => 1, 'DEBUG' => 2, 'INFO' => 3, 'ALL' => 4); + + /** + * Initialize Logging class + * + * @return void */ public function __construct() { $config =& get_config(); - $this->_log_path = ($config['log_path'] != '') ? $config['log_path'] : APPPATH.'logs/'; + $this->_log_path = ($config['log_path'] !== '') ? $config['log_path'] : APPPATH.'logs/'; if ( ! is_dir($this->_log_path) OR ! is_really_writable($this->_log_path)) { @@ -70,7 +111,7 @@ class CI_Log { $this->_threshold_array = array_flip($config['log_threshold']); } - if ($config['log_date_format'] != '') + if ($config['log_date_format'] !== '') { $this->_date_fmt = $config['log_date_format']; } @@ -98,7 +139,7 @@ class CI_Log { $level = strtoupper($level); if (( ! isset($this->_levels[$level]) OR ($this->_levels[$level] > $this->_threshold)) - AND ! isset($this->_threshold_array[$this->_levels[$level]])) + && ! isset($this->_threshold_array[$this->_levels[$level]])) { return FALSE; } @@ -110,7 +151,7 @@ class CI_Log { if ( ! file_exists($filepath)) { $newfile = TRUE; - $message .= "<"."?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); ?".">\n\n"; + $message .= '<'."?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); ?".">\n\n"; } if ( ! $fp = @fopen($filepath, FOPEN_WRITE_CREATE)) @@ -118,22 +159,22 @@ class CI_Log { return FALSE; } - $message .= $level.' '.(($level == 'INFO') ? ' -' : '-').' '.date($this->_date_fmt). ' --> '.$msg."\n"; + $message .= $level.' '.($level === 'INFO' ? ' -' : '-').' '.date($this->_date_fmt).' --> '.$msg."\n"; flock($fp, LOCK_EX); fwrite($fp, $message); flock($fp, LOCK_UN); fclose($fp); - if (isset($newfile) AND $newfile === TRUE) + if (isset($newfile) && $newfile === TRUE) { @chmod($filepath, FILE_WRITE_MODE); } + return TRUE; } } -// END Log Class /* End of file Log.php */ -/* Location: ./system/libraries/Log.php */ +/* Location: ./system/libraries/Log.php */
\ No newline at end of file diff --git a/system/libraries/Migration.php b/system/libraries/Migration.php index a18fcb9f1..4391b235d 100644 --- a/system/libraries/Migration.php +++ b/system/libraries/Migration.php @@ -39,14 +39,54 @@ */ class CI_Migration { + /** + * Whether the library is enabled + * + * @var bool + */ protected $_migration_enabled = FALSE; + + /** + * Path to migration classes + * + * @var string + */ protected $_migration_path = NULL; + + /** + * Current migration version + * + * @var mixed + */ protected $_migration_version = 0; + + /** + * Database table with migration info + * + * @var string + */ protected $_migration_table = 'migrations'; + + /** + * Whether to automatically run migrations + * + * @var bool + */ protected $_migration_auto_latest = FALSE; + /** + * Error message + * + * @var string + */ protected $_error_string = ''; + /** + * Initialize Migration Class + * + * @param array + * @return void + */ public function __construct($config = array()) { # Only run this constructor on main library load @@ -57,7 +97,7 @@ class CI_Migration { foreach ($config as $key => $val) { - $this->{'_' . $key} = $val; + $this->{'_'.$key} = $val; } log_message('debug', 'Migrations class initialized'); @@ -69,7 +109,7 @@ class CI_Migration { } // If not set, set it - $this->_migration_path != '' OR $this->_migration_path = APPPATH.'migrations/'; + $this->_migration_path !== '' OR $this->_migration_path = APPPATH.'migrations/'; // Add trailing slash if not set $this->_migration_path = rtrim($this->_migration_path, '/').'/'; @@ -139,7 +179,7 @@ class CI_Migration { // We now prepare to actually DO the migrations // But first let's make sure that everything is the way it should be - for ($i = $start; $i != $stop; $i += $step) + for ($i = $start; $i !== $stop; $i += $step) { $f = glob(sprintf($this->_migration_path.'%03d_*.php', $i)); @@ -301,7 +341,6 @@ class CI_Migration { } sort($files); - return $files; } @@ -345,6 +384,7 @@ class CI_Migration { { return get_instance()->$var; } + } /* End of file Migration.php */ diff --git a/system/libraries/Pagination.php b/system/libraries/Pagination.php index 0fe73d69f..a91159c98 100644 --- a/system/libraries/Pagination.php +++ b/system/libraries/Pagination.php @@ -73,6 +73,7 @@ class CI_Pagination { * Constructor * * @param array initialization parameters + * @return void */ public function __construct($params = array()) { @@ -94,17 +95,16 @@ class CI_Pagination { { foreach ($params as $key => $val) { - if (isset($this->$key)) + if ($key === 'anchor_class') + { + $this->anchor_class = ($val !== '') ? 'class="'.$val.'" ' : ''; + } + elseif (isset($this->$key)) { $this->$key = $val; } } } - - if ($this->anchor_class != '') - { - $this->anchor_class = 'class="'.$this->anchor_class.'" '; - } } // -------------------------------------------------------------------- @@ -117,7 +117,7 @@ class CI_Pagination { public function create_links() { // If our item count or per-page total is zero there is no need to continue. - if ($this->total_rows == 0 OR $this->per_page == 0) + if ($this->total_rows === 0 OR $this->per_page === 0) { return ''; } @@ -138,25 +138,25 @@ class CI_Pagination { $CI =& get_instance(); // See if we are using a prefix or suffix on links - if ($this->prefix != '' OR $this->suffix != '') + if ($this->prefix !== '' OR $this->suffix !== '') { $this->cur_page = (int) str_replace(array($this->prefix, $this->suffix), '', $CI->uri->segment($this->uri_segment)); } if ($CI->config->item('enable_query_strings') === TRUE OR $this->page_query_string === TRUE) { - if ($CI->input->get($this->query_string_segment) != $base_page) + if ($CI->input->get($this->query_string_segment) !== $base_page) { $this->cur_page = (int) $CI->input->get($this->query_string_segment); } } - elseif ( ! $this->cur_page && $CI->uri->segment($this->uri_segment) != $base_page) + elseif ( ! $this->cur_page && $CI->uri->segment($this->uri_segment) !== $base_page) { $this->cur_page = (int) $CI->uri->segment($this->uri_segment); } // Set current page to 1 if it's not valid or if using page numbers instead of offset - if ( ! is_numeric($this->cur_page) OR ($this->use_page_numbers && $this->cur_page == 0)) + if ( ! is_numeric($this->cur_page) OR ($this->use_page_numbers && $this->cur_page === 0)) { $this->cur_page = $base_page; } @@ -211,22 +211,22 @@ class CI_Pagination { // Render the "First" link if ($this->first_link !== FALSE && $this->cur_page > ($this->num_links + 1)) { - $first_url = ($this->first_url == '') ? $this->base_url : $this->first_url; + $first_url = ($this->first_url === '') ? $this->base_url : $this->first_url; $output .= $this->first_tag_open.'<a '.$this->anchor_class.'href="'.$first_url.'">'.$this->first_link.'</a>'.$this->first_tag_close; } // Render the "previous" link - if ($this->prev_link !== FALSE && $this->cur_page != 1) + if ($this->prev_link !== FALSE && $this->cur_page !== 1) { $i = ($this->use_page_numbers) ? $uri_page_number - 1 : $uri_page_number - $this->per_page; - if ($i == $base_page && $this->first_url != '') + if ($i === $base_page && $this->first_url !== '') { $output .= $this->prev_tag_open.'<a '.$this->anchor_class.'href="'.$this->first_url.'">'.$this->prev_link.'</a>'.$this->prev_tag_close; } else { - $i = ($i == $base_page) ? '' : $this->prefix.$i.$this->suffix; + $i = ($i === $base_page) ? '' : $this->prefix.$i.$this->suffix; $output .= $this->prev_tag_open.'<a '.$this->anchor_class.'href="'.$this->base_url.$i.'">'.$this->prev_link.'</a>'.$this->prev_tag_close; } @@ -242,21 +242,21 @@ class CI_Pagination { if ($i >= $base_page) { - if ($this->cur_page == $loop) + if ($this->cur_page === $loop) { $output .= $this->cur_tag_open.$loop.$this->cur_tag_close; // Current page } else { - $n = ($i == $base_page) ? '' : $i; + $n = ($i === $base_page) ? '' : $i; - if ($n == '' && $this->first_url != '') + if ($n === '' && $this->first_url !== '') { $output .= $this->num_tag_open.'<a '.$this->anchor_class.'href="'.$this->first_url.'">'.$loop.'</a>'.$this->num_tag_close; } else { - $n = ($n == '') ? '' : $this->prefix.$n.$this->suffix; + $n = ($n === '') ? '' : $this->prefix.$n.$this->suffix; $output .= $this->num_tag_open.'<a '.$this->anchor_class.'href="'.$this->base_url.$n.'">'.$loop.'</a>'.$this->num_tag_close; } diff --git a/system/libraries/Parser.php b/system/libraries/Parser.php index d1b5b764b..b64c78254 100644 --- a/system/libraries/Parser.php +++ b/system/libraries/Parser.php @@ -36,9 +36,25 @@ */ class CI_Parser { + /** + * Left delimeter character for psuedo vars + * + * @var string + */ public $l_delim = '{'; + + /** + * Right delimeter character for psuedo vars + * + * @var string + */ public $r_delim = '}'; - public $object; + + /** + * Reference to CodeIgniter instance + * + * @var object + */ protected $CI; /** @@ -93,24 +109,19 @@ class CI_Parser { */ protected function _parse($template, $data, $return = FALSE) { - if ($template == '') + if ($template === '') { return FALSE; } foreach ($data as $key => $val) { - if (is_array($val)) - { - $template = $this->_parse_pair($key, $val, $template); - } - else - { - $template = $this->_parse_single($key, (string)$val, $template); - } + $template = is_array($val) + ? $this->_parse_pair($key, $val, $template) + : $template = $this->_parse_single($key, (string) $val, $template); } - if ($return == FALSE) + if ($return === FALSE) { $this->CI->output->append_output($template); } @@ -173,14 +184,9 @@ class CI_Parser { $temp = $match[1]; foreach ($row as $key => $val) { - if ( ! is_array($val)) - { - $temp = $this->_parse_single($key, $val, $temp); - } - else - { - $temp = $this->_parse_pair($key, $val, $temp); - } + $temp = is_array($val) + ? $this->_parse_pair($key, $val, $temp) + : $this->_parse_single($key, $val, $temp); } $str .= $temp; diff --git a/system/libraries/Profiler.php b/system/libraries/Profiler.php index d84e5d3fc..d96088c14 100644 --- a/system/libraries/Profiler.php +++ b/system/libraries/Profiler.php @@ -25,8 +25,6 @@ * @filesource */ -// ------------------------------------------------------------------------ - /** * CodeIgniter Profiler Class * @@ -44,25 +42,45 @@ */ class CI_Profiler { + /** + * List of profiler sections available to show + * + * @var array + */ protected $_available_sections = array( - 'benchmarks', - 'get', - 'memory_usage', - 'post', - 'uri_string', - 'controller_info', - 'queries', - 'http_headers', - 'session_data', - 'config' - ); + 'benchmarks', + 'get', + 'memory_usage', + 'post', + 'uri_string', + 'controller_info', + 'queries', + 'http_headers', + 'session_data', + 'config' + ); + /** + * Number of queries to show before making the additional queries togglable + * + * @var int + */ protected $_query_toggle_count = 25; + /** + * Reference to the CodeIgniter singleton + * + * @var object + */ protected $CI; - // -------------------------------------------------------------------- - + /** + * Constructor + * + * Initialize Profiler + * + * @param array $config + */ public function __construct($config = array()) { $this->CI =& get_instance(); @@ -102,7 +120,7 @@ class CI_Profiler { { if (in_array($method, $this->_available_sections)) { - $this->_compile_{$method} = ($enable !== FALSE) ? TRUE : FALSE; + $this->_compile_{$method} = ($enable !== FALSE); } } } @@ -127,7 +145,7 @@ class CI_Profiler { // We match the "end" marker so that the list ends // up in the order that it was defined if (preg_match('/(.+?)_end/i', $key, $match) - AND isset($this->CI->benchmark->marker[$match[1].'_end'], $this->CI->benchmark->marker[$match[1].'_start'])) + && isset($this->CI->benchmark->marker[$match[1].'_end'], $this->CI->benchmark->marker[$match[1].'_start'])) { $profile[$match[1]] = $this->CI->benchmark->elapsed_time($match[1].'_start', $key); } @@ -135,18 +153,20 @@ class CI_Profiler { // Build a table containing the profile data. // Note: At some point we should turn this into a template that can - // be modified. We also might want to make this data available to be logged + // be modified. We also might want to make this data available to be logged $output = "\n\n" - . '<fieldset id="ci_profiler_benchmarks" style="border:1px solid #900;padding:6px 10px 10px 10px;margin:20px 0 20px 0;background-color:#eee">' - . "\n" - . '<legend style="color:#900;"> '.$this->CI->lang->line('profiler_benchmarks').' </legend>' - . "\n\n\n<table style='width:100%'>\n"; + .'<fieldset id="ci_profiler_benchmarks" style="border:1px solid #900;padding:6px 10px 10px 10px;margin:20px 0 20px 0;background-color:#eee;">' + ."\n" + .'<legend style="color:#900;"> '.$this->CI->lang->line('profiler_benchmarks')." </legend>" + ."\n\n\n<table style=\"width:100%;\">\n"; foreach ($profile as $key => $val) { $key = ucwords(str_replace(array('_', '-'), ' ', $key)); - $output .= "<tr><td style='padding:5px;width:50%;color:#000;font-weight:bold;background-color:#ddd;'>".$key." </td><td style='padding:5px;width:50%;color:#900;font-weight:normal;background-color:#ddd;'>".$val."</td></tr>\n"; + $output .= '<tr><td style="padding:5px;width:50%;color:#000;font-weight:bold;background-color:#ddd;">' + .$key.' </td><td style="padding:5px;width:50%;color:#900;font-weight:normal;background-color:#ddd;">' + .$val."</td></tr>\n"; } return $output."</table>\n</fieldset>"; @@ -166,7 +186,7 @@ class CI_Profiler { // Let's determine which databases are currently connected to foreach (get_object_vars($this->CI) as $CI_object) { - if (is_object($CI_object) && is_subclass_of(get_class($CI_object), 'CI_DB') ) + if (is_object($CI_object) && is_subclass_of(get_class($CI_object), 'CI_DB')) { $dbs[] = $CI_object; } @@ -175,13 +195,13 @@ class CI_Profiler { if (count($dbs) === 0) { return "\n\n" - . '<fieldset id="ci_profiler_queries" style="border:1px solid #0000FF;padding:6px 10px 10px 10px;margin:20px 0 20px 0;background-color:#eee;">' - . "\n" - . '<legend style="color:#0000FF;"> '.$this->CI->lang->line('profiler_queries').' </legend>' - . "\n\n\n<table style='border:none; width:100%;'>\n" - . '<tr><td style="width:100%;color:#0000FF;font-weight:normal;background-color:#eee;padding:5px;">' - . $this->CI->lang->line('profiler_no_db') - . "</td></tr>\n</table>\n</fieldset>"; + .'<fieldset id="ci_profiler_queries" style="border:1px solid #0000FF;padding:6px 10px 10px 10px;margin:20px 0 20px 0;background-color:#eee;">' + ."\n" + .'<legend style="color:#0000FF;"> '.$this->CI->lang->line('profiler_queries').' </legend>' + ."\n\n\n<table style=\"border:none; width:100%;\">\n" + .'<tr><td style="width:100%;color:#0000FF;font-weight:normal;background-color:#eee;padding:5px;">' + .$this->CI->lang->line('profiler_no_db') + ."</td></tr>\n</table>\n</fieldset>"; } // Load the text helper so we can highlight the SQL @@ -191,7 +211,6 @@ class CI_Profiler { $highlight = array('SELECT', 'DISTINCT', 'FROM', 'WHERE', 'AND', 'LEFT JOIN', 'ORDER BY', 'GROUP BY', 'LIMIT', 'INSERT', 'INTO', 'VALUES', 'UPDATE', 'OR ', 'HAVING', 'OFFSET', 'NOT IN', 'IN', 'LIKE', 'NOT LIKE', 'COUNT', 'MAX', 'MIN', 'ON', 'AS', 'AVG', 'SUM', '(', ')'); $output = "\n\n"; - $count = 0; foreach ($dbs as $db) @@ -200,26 +219,28 @@ class CI_Profiler { $show_hide_js = '(<span style="cursor: pointer;" onclick="var s=document.getElementById(\'ci_profiler_queries_db_'.$count.'\').style;s.display=s.display==\'none\'?\'\':\'none\';this.innerHTML=this.innerHTML==\''.$this->CI->lang->line('profiler_section_hide').'\'?\''.$this->CI->lang->line('profiler_section_show').'\':\''.$this->CI->lang->line('profiler_section_hide').'\';">'.$this->CI->lang->line('profiler_section_hide').'</span>)'; - if ($hide_queries != '') + if ($hide_queries !== '') { $show_hide_js = '(<span style="cursor: pointer;" onclick="var s=document.getElementById(\'ci_profiler_queries_db_'.$count.'\').style;s.display=s.display==\'none\'?\'\':\'none\';this.innerHTML=this.innerHTML==\''.$this->CI->lang->line('profiler_section_show').'\'?\''.$this->CI->lang->line('profiler_section_hide').'\':\''.$this->CI->lang->line('profiler_section_show').'\';">'.$this->CI->lang->line('profiler_section_show').'</span>)'; } - $output .= '<fieldset style="border:1px solid #0000FF;padding:6px 10px 10px 10px;margin:20px 0 20px 0;background-color:#eee">' - . "\n" - . '<legend style="color:#0000FF;"> '.$this->CI->lang->line('profiler_database').': '.$db->database.' '.$this->CI->lang->line('profiler_queries').': '.count($db->queries).' '.$show_hide_js.'</legend>' - . "\n\n\n<table style='width:100%;{$hide_queries}' id='ci_profiler_queries_db_{$count}'>\n"; + $output .= '<fieldset style="border:1px solid #0000FF;padding:6px 10px 10px 10px;margin:20px 0 20px 0;background-color:#eee;">' + ."\n" + .'<legend style="color:#0000FF;"> '.$this->CI->lang->line('profiler_database') + .': '.$db->database.' '.$this->CI->lang->line('profiler_queries') + .': '.count($db->queries).' '.$show_hide_js."</legend>\n\n\n" + .'<table style="width:100%;'.$hide_queries.'" id="ci_profiler_queries_db_'.$count."\">\n"; if (count($db->queries) === 0) { - $output .= "<tr><td style='width:100%;color:#0000FF;font-weight:normal;background-color:#eee;padding:5px;'>".$this->CI->lang->line('profiler_no_queries')."</td></tr>\n"; + $output .= '<tr><td style="width:100%;color:#0000FF;font-weight:normal;background-color:#eee;padding:5px;">' + .$this->CI->lang->line('profiler_no_queries')."</td></tr>\n"; } else { foreach ($db->queries as $key => $val) { $time = number_format($db->query_times[$key], 4); - $val = highlight_code($val, ENT_QUOTES); foreach ($highlight as $bold) @@ -227,18 +248,18 @@ class CI_Profiler { $val = str_replace($bold, '<strong>'.$bold.'</strong>', $val); } - $output .= "<tr><td style='padding:5px; vertical-align: top;width:1%;color:#900;font-weight:normal;background-color:#ddd;'>".$time." </td><td style='padding:5px; color:#000;font-weight:normal;background-color:#ddd;'>".$val."</td></tr>\n"; + $output .= '<tr><td style="padding:5px;vertical-align:top;width:1%;color:#900;font-weight:normal;background-color:#ddd;">' + .$time.' </td><td style="padding:5px;color:#000;font-weight:normal;background-color:#ddd;">' + .$val."</td></tr>\n"; } } $output .= "</table>\n</fieldset>"; - } return $output; } - // -------------------------------------------------------------------- /** @@ -248,19 +269,18 @@ class CI_Profiler { */ protected function _compile_get() { - $output = "\n\n" - . '<fieldset id="ci_profiler_get" style="border:1px solid #cd6e00;padding:6px 10px 10px 10px;margin:20px 0 20px 0;background-color:#eee">' - . "\n" - . '<legend style="color:#cd6e00;"> '.$this->CI->lang->line('profiler_get_data').' </legend>' - . "\n"; + $output = "\n\n" + .'<fieldset id="ci_profiler_get" style="border:1px solid #cd6e00;padding:6px 10px 10px 10px;margin:20px 0 20px 0;background-color:#eee;">' + ."\n" + .'<legend style="color:#cd6e00;"> '.$this->CI->lang->line('profiler_get_data')." </legend>\n"; if (count($_GET) === 0) { - $output .= "<div style='color:#cd6e00;font-weight:normal;padding:4px 0 4px 0'>".$this->CI->lang->line('profiler_no_get')."</div>"; + $output .= '<div style="color:#cd6e00;font-weight:normal;padding:4px 0 4px 0;">'.$this->CI->lang->line('profiler_no_get').'</div>'; } else { - $output .= "\n\n<table style='width:100%; border:none'>\n"; + $output .= "\n\n<table style=\"width:100%;border:none;\">\n"; foreach ($_GET as $key => $val) { @@ -269,9 +289,10 @@ class CI_Profiler { $key = "'".$key."'"; } - $output .= "<tr><td style='width:50%;color:#000;background-color:#ddd;padding:5px'>$_GET[".$key."] </td><td style='width:50%;padding:5px;color:#cd6e00;font-weight:normal;background-color:#ddd;'>" - . ((is_array($val) OR is_object($val)) ? "<pre>" . htmlspecialchars(stripslashes(print_r($val, true))) . "</pre>" : htmlspecialchars(stripslashes($val))) - . "</td></tr>\n"; + $output .= '<tr><td style="width:50%;color:#000;background-color:#ddd;padding:5px;">$_GET[' + .$key.'] </td><td style="width:50%;padding:5px;color:#cd6e00;font-weight:normal;background-color:#ddd;">' + .((is_array($val) OR is_object($val)) ? '<pre>'.htmlspecialchars(stripslashes(print_r($val, TRUE))).'</pre>' : htmlspecialchars(stripslashes($val))) + ."</td></tr>\n"; } $output .= "</table>\n"; @@ -290,18 +311,17 @@ class CI_Profiler { protected function _compile_post() { $output = "\n\n" - . '<fieldset id="ci_profiler_post" style="border:1px solid #009900;padding:6px 10px 10px 10px;margin:20px 0 20px 0;background-color:#eee">' - . "\n" - . '<legend style="color:#009900;"> '.$this->CI->lang->line('profiler_post_data').' </legend>' - . "\n"; + .'<fieldset id="ci_profiler_post" style="border:1px solid #009900;padding:6px 10px 10px 10px;margin:20px 0 20px 0;background-color:#eee;">' + ."\n" + .'<legend style="color:#009900;"> '.$this->CI->lang->line('profiler_post_data')." </legend>\n"; - if (count($_POST) == 0) + if (count($_POST) === 0) { - $output .= "<div style='color:#009900;font-weight:normal;padding:4px 0 4px 0'>".$this->CI->lang->line('profiler_no_post')."</div>"; + $output .= '<div style="color:#009900;font-weight:normal;padding:4px 0 4px 0;">'.$this->CI->lang->line('profiler_no_post').'</div>'; } else { - $output .= "\n\n<table style='width:100%'>\n"; + $output .= "\n\n<table style=\"width:100%;\">\n"; foreach ($_POST as $key => $val) { @@ -310,15 +330,18 @@ class CI_Profiler { $key = "'".$key."'"; } - $output .= "<tr><td style='width:50%;padding:5px;color:#000;background-color:#ddd;'>$_POST[".$key."] </td><td style='width:50%;padding:5px;color:#009900;font-weight:normal;background-color:#ddd;'>"; + $output .= '<tr><td style="width:50%;padding:5px;color:#000;background-color:#ddd;">$_POST[' + .$key.'] </td><td style="width:50%;padding:5px;color:#009900;font-weight:normal;background-color:#ddd;">'; + if (is_array($val) OR is_object($val)) { - $output .= "<pre>" . htmlspecialchars(stripslashes(print_r($val, TRUE))) . "</pre>"; + $output .= '<pre>'.htmlspecialchars(stripslashes(print_r($val, TRUE))).'</pre>'; } else { $output .= htmlspecialchars(stripslashes($val)); } + $output .= "</td></tr>\n"; } @@ -338,12 +361,12 @@ class CI_Profiler { protected function _compile_uri_string() { return "\n\n" - . '<fieldset id="ci_profiler_uri_string" style="border:1px solid #000;padding:6px 10px 10px 10px;margin:20px 0 20px 0;background-color:#eee">' - . "\n" - . '<legend style="color:#000;"> '.$this->CI->lang->line('profiler_uri_string').' </legend>' - . "\n<div style='color:#000;font-weight:normal;padding:4px 0 4px 0'>" - . ($this->CI->uri->uri_string == '' ? $this->CI->lang->line('profiler_no_uri') : $this->CI->uri->uri_string) - . '</div></fieldset>'; + .'<fieldset id="ci_profiler_uri_string" style="border:1px solid #000;padding:6px 10px 10px 10px;margin:20px 0 20px 0;background-color:#eee;">' + ."\n" + .'<legend style="color:#000;"> '.$this->CI->lang->line('profiler_uri_string')." </legend>\n" + .'<div style="color:#000;font-weight:normal;padding:4px 0 4px 0;">' + .($this->CI->uri->uri_string === '' ? $this->CI->lang->line('profiler_no_uri') : $this->CI->uri->uri_string) + .'</div></fieldset>'; } // -------------------------------------------------------------------- @@ -356,11 +379,11 @@ class CI_Profiler { protected function _compile_controller_info() { return "\n\n" - . '<fieldset id="ci_profiler_controller_info" style="border:1px solid #995300;padding:6px 10px 10px 10px;margin:20px 0 20px 0;background-color:#eee">' - . "\n" - . '<legend style="color:#995300;"> '.$this->CI->lang->line('profiler_controller_info').' </legend>' - . "\n<div style='color:#995300;font-weight:normal;padding:4px 0 4px 0'>".$this->CI->router->fetch_class().'/'.$this->CI->router->fetch_method() - . '</div></fieldset>'; + .'<fieldset id="ci_profiler_controller_info" style="border:1px solid #995300;padding:6px 10px 10px 10px;margin:20px 0 20px 0;background-color:#eee;">' + ."\n" + .'<legend style="color:#995300;"> '.$this->CI->lang->line('profiler_controller_info')." </legend>\n" + .'<div style="color:#995300;font-weight:normal;padding:4px 0 4px 0;">'.$this->CI->router->fetch_class().'/'.$this->CI->router->fetch_method() + .'</div></fieldset>'; } // -------------------------------------------------------------------- @@ -375,12 +398,12 @@ class CI_Profiler { protected function _compile_memory_usage() { return "\n\n" - . '<fieldset id="ci_profiler_memory_usage" style="border:1px solid #5a0099;padding:6px 10px 10px 10px;margin:20px 0 20px 0;background-color:#eee">' - . "\n" - . '<legend style="color:#5a0099;"> '.$this->CI->lang->line('profiler_memory_usage').' </legend>' - . "\n<div style='color:#5a0099;font-weight:normal;padding:4px 0 4px 0'>" - . ((function_exists('memory_get_usage') && ($usage = memory_get_usage()) != '') ? number_format($usage).' bytes' : $this->CI->lang->line('profiler_no_memory')) - . '</div></fieldset>'; + .'<fieldset id="ci_profiler_memory_usage" style="border:1px solid #5a0099;padding:6px 10px 10px 10px;margin:20px 0 20px 0;background-color:#eee;">' + ."\n" + .'<legend style="color:#5a0099;"> '.$this->CI->lang->line('profiler_memory_usage')." </legend>\n" + .'<div style="color:#5a0099;font-weight:normal;padding:4px 0 4px 0;">' + .(($usage = memory_get_usage()) != '' ? number_format($usage).' bytes' : $this->CI->lang->line('profiler_no_memory')) + .'</div></fieldset>'; } // -------------------------------------------------------------------- @@ -395,15 +418,17 @@ class CI_Profiler { protected function _compile_http_headers() { $output = "\n\n" - . '<fieldset id="ci_profiler_http_headers" style="border:1px solid #000;padding:6px 10px 10px 10px;margin:20px 0 20px 0;background-color:#eee">' - . "\n" - . '<legend style="color:#000;"> '.$this->CI->lang->line('profiler_headers').' (<span style="cursor: pointer;" onclick="var s=document.getElementById(\'ci_profiler_httpheaders_table\').style;s.display=s.display==\'none\'?\'\':\'none\';this.innerHTML=this.innerHTML==\''.$this->CI->lang->line('profiler_section_show').'\'?\''.$this->CI->lang->line('profiler_section_hide').'\':\''.$this->CI->lang->line('profiler_section_show').'\';">'.$this->CI->lang->line('profiler_section_show').'</span>)</legend>' - . "\n\n\n<table style='width:100%;display:none' id='ci_profiler_httpheaders_table'>\n"; + .'<fieldset id="ci_profiler_http_headers" style="border:1px solid #000;padding:6px 10px 10px 10px;margin:20px 0 20px 0;background-color:#eee;">' + ."\n" + .'<legend style="color:#000;"> '.$this->CI->lang->line('profiler_headers') + .' (<span style="cursor: pointer;" onclick="var s=document.getElementById(\'ci_profiler_httpheaders_table\').style;s.display=s.display==\'none\'?\'\':\'none\';this.innerHTML=this.innerHTML==\''.$this->CI->lang->line('profiler_section_show').'\'?\''.$this->CI->lang->line('profiler_section_hide').'\':\''.$this->CI->lang->line('profiler_section_show').'\';">'.$this->CI->lang->line('profiler_section_show')."</span>)</legend>\n\n\n" + .'<table style="width:100%;display:none;" id="ci_profiler_httpheaders_table">'."\n"; foreach (array('HTTP_ACCEPT', 'HTTP_USER_AGENT', 'HTTP_CONNECTION', 'SERVER_PORT', 'SERVER_NAME', 'REMOTE_ADDR', 'SERVER_SOFTWARE', 'HTTP_ACCEPT_LANGUAGE', 'SCRIPT_NAME', 'REQUEST_METHOD',' HTTP_HOST', 'REMOTE_HOST', 'CONTENT_TYPE', 'SERVER_PROTOCOL', 'QUERY_STRING', 'HTTP_ACCEPT_ENCODING', 'HTTP_X_FORWARDED_FOR') as $header) { - $val = (isset($_SERVER[$header])) ? $_SERVER[$header] : ''; - $output .= "<tr><td style='vertical-align: top;width:50%;padding:5px;color:#900;background-color:#ddd;'>".$header." </td><td style='width:50%;padding:5px;color:#000;background-color:#ddd;'>".$val."</td></tr>\n"; + $val = isset($_SERVER[$header]) ? $_SERVER[$header] : ''; + $output .= '<tr><td style="vertical-align:top;width:50%;padding:5px;color:#900;background-color:#ddd;">' + .$header.' </td><td style="width:50%;padding:5px;color:#000;background-color:#ddd;">'.$val."</td></tr>\n"; } return $output."</table>\n</fieldset>"; @@ -421,10 +446,10 @@ class CI_Profiler { protected function _compile_config() { $output = "\n\n" - . '<fieldset id="ci_profiler_config" style="border:1px solid #000;padding:6px 10px 10px 10px;margin:20px 0 20px 0;background-color:#eee">' - . "\n" - . '<legend style="color:#000;"> '.$this->CI->lang->line('profiler_config').' (<span style="cursor: pointer;" onclick="var s=document.getElementById(\'ci_profiler_config_table\').style;s.display=s.display==\'none\'?\'\':\'none\';this.innerHTML=this.innerHTML==\''.$this->CI->lang->line('profiler_section_show').'\'?\''.$this->CI->lang->line('profiler_section_hide').'\':\''.$this->CI->lang->line('profiler_section_show').'\';">'.$this->CI->lang->line('profiler_section_show').'</span>)</legend>' - . "\n\n\n<table style='width:100%; display:none' id='ci_profiler_config_table'>\n"; + .'<fieldset id="ci_profiler_config" style="border:1px solid #000;padding:6px 10px 10px 10px;margin:20px 0 20px 0;background-color:#eee;">' + ."\n" + .'<legend style="color:#000;"> '.$this->CI->lang->line('profiler_config').' (<span style="cursor: pointer;" onclick="var s=document.getElementById(\'ci_profiler_config_table\').style;s.display=s.display==\'none\'?\'\':\'none\';this.innerHTML=this.innerHTML==\''.$this->CI->lang->line('profiler_section_show').'\'?\''.$this->CI->lang->line('profiler_section_hide').'\':\''.$this->CI->lang->line('profiler_section_show').'\';">'.$this->CI->lang->line('profiler_section_show')."</span>)</legend>\n\n\n" + .'<table style="width:100%;display:none;" id="ci_profiler_config_table">'."\n"; foreach ($this->CI->config->config as $config => $val) { @@ -433,7 +458,8 @@ class CI_Profiler { $val = print_r($val, TRUE); } - $output .= "<tr><td style='padding:5px; vertical-align: top;color:#900;background-color:#ddd;'>".$config." </td><td style='padding:5px; color:#000;background-color:#ddd;'>".htmlspecialchars($val)."</td></tr>\n"; + $output .= '<tr><td style="padding:5px;vertical-align:top;color:#900;background-color:#ddd;">' + .$config.' </td><td style="padding:5px;color:#000;background-color:#ddd;">'.htmlspecialchars($val)."</td></tr>\n"; } return $output."</table>\n</fieldset>"; @@ -453,9 +479,9 @@ class CI_Profiler { return; } - $output = '<fieldset id="ci_profiler_csession" style="border:1px solid #000;padding:6px 10px 10px 10px;margin:20px 0 20px 0;background-color:#eee">' - . '<legend style="color:#000;"> '.$this->CI->lang->line('profiler_session_data').' (<span style="cursor: pointer;" onclick="var s=document.getElementById(\'ci_profiler_session_data\').style;s.display=s.display==\'none\'?\'\':\'none\';this.innerHTML=this.innerHTML==\''.$this->CI->lang->line('profiler_section_show').'\'?\''.$this->CI->lang->line('profiler_section_hide').'\':\''.$this->CI->lang->line('profiler_section_show').'\';">'.$this->CI->lang->line('profiler_section_show').'</span>)</legend>' - . "<table style='width:100%;display:none' id='ci_profiler_session_data'>"; + $output = '<fieldset id="ci_profiler_csession" style="border:1px solid #000;padding:6px 10px 10px 10px;margin:20px 0 20px 0;background-color:#eee;">' + .'<legend style="color:#000;"> '.$this->CI->lang->line('profiler_session_data').' (<span style="cursor: pointer;" onclick="var s=document.getElementById(\'ci_profiler_session_data\').style;s.display=s.display==\'none\'?\'\':\'none\';this.innerHTML=this.innerHTML==\''.$this->CI->lang->line('profiler_section_show').'\'?\''.$this->CI->lang->line('profiler_section_hide').'\':\''.$this->CI->lang->line('profiler_section_show').'\';">'.$this->CI->lang->line('profiler_section_show').'</span>)</legend>' + .'<table style="width:100%;display:none;" id="ci_profiler_session_data">'; foreach ($this->CI->session->all_userdata() as $key => $val) { @@ -464,7 +490,8 @@ class CI_Profiler { $val = print_r($val, TRUE); } - $output .= "<tr><td style='padding:5px; vertical-align: top;color:#900;background-color:#ddd;'>".$key." </td><td style='padding:5px; color:#000;background-color:#ddd;'>".htmlspecialchars($val)."</td></tr>\n"; + $output .= '<tr><td style="padding:5px;vertical-align:top;color:#900;background-color:#ddd;">' + .$key.' </td><td style="padding:5px;color:#000;background-color:#ddd;">'.htmlspecialchars($val)."</td></tr>\n"; } return $output."</table>\n</fieldset>"; @@ -479,14 +506,14 @@ class CI_Profiler { */ public function run() { - $output = "<div id='codeigniter_profiler' style='clear:both;background-color:#fff;padding:10px;'>"; + $output = '<div id="codeigniter_profiler" style="clear:both;background-color:#fff;padding:10px;">'; $fields_displayed = 0; foreach ($this->_available_sections as $section) { if ($this->_compile_{$section} !== FALSE) { - $func = "_compile_{$section}"; + $func = '_compile_'.$section; $output .= $this->{$func}(); $fields_displayed++; } @@ -494,12 +521,14 @@ class CI_Profiler { if ($fields_displayed === 0) { - $output .= '<p style="border:1px solid #5a0099;padding:10px;margin:20px 0;background-color:#eee">'.$this->CI->lang->line('profiler_no_profiles').'</p>'; + $output .= '<p style="border:1px solid #5a0099;padding:10px;margin:20px 0;background-color:#eee;">' + .$this->CI->lang->line('profiler_no_profiles').'</p>'; } return $output.'</div>'; } + } /* End of file Profiler.php */ -/* Location: ./system/libraries/Profiler.php */ +/* Location: ./system/libraries/Profiler.php */
\ No newline at end of file diff --git a/system/libraries/Session.php b/system/libraries/Session.php index 3a80c1626..7beedd96b 100644 --- a/system/libraries/Session.php +++ b/system/libraries/Session.php @@ -36,26 +36,151 @@ */ class CI_Session { + /** + * Whether to encrypt the session cookie + * + * @var bool + */ public $sess_encrypt_cookie = FALSE; + + /** + * Whether to use to the database for session storage + * + * @var bool + */ public $sess_use_database = FALSE; + + /** + * Name of the database table in which to store sessions + * + * @var string + */ public $sess_table_name = ''; + + /** + * Length of time (in seconds) for sessions to expire + * + * @var int + */ public $sess_expiration = 7200; + + /** + * Whether to kill session on close of browser window + * + * @var bool + */ public $sess_expire_on_close = FALSE; + + /** + * Whether to match session on ip address + * + * @var bool + */ public $sess_match_ip = FALSE; + + /** + * Whether to match session on user-agent + * + * @var bool + */ public $sess_match_useragent = TRUE; + + /** + * Name of session cookie + * + * @var string + */ public $sess_cookie_name = 'ci_session'; + + /** + * Session cookie prefix + * + * @var string + */ public $cookie_prefix = ''; + + /** + * Session cookie path + * + * @var string + */ public $cookie_path = ''; + + /** + * Session cookie domain + * + * @var string + */ public $cookie_domain = ''; + + /** + * Whether to set the cookie only on HTTPS connections + * + * @var bool + */ public $cookie_secure = FALSE; + + /** + * Whether cookie should be allowed only to be sent by the server + * + * @var bool + */ public $cookie_httponly = FALSE; + + /** + * Interval at which to update session + * + * @var int + */ public $sess_time_to_update = 300; + + /** + * Key with which to encrypt the session cookie + * + * @var string + */ public $encryption_key = ''; + + /** + * String to indicate flash data cookies + * + * @var string + */ public $flashdata_key = 'flash'; + + /** + * Function to use to get the current time + * + * @var string + */ public $time_reference = 'time'; + + /** + * Probablity level of garbage collection of old sessions + * + * @var int + */ public $gc_probability = 5; + + /** + * Session data + * + * @var array + */ public $userdata = array(); + + /** + * Reference to CodeIgniter instance + * + * @var object + */ public $CI; + + /** + * Current time + * + * @var int + */ public $now; /** @@ -63,6 +188,9 @@ class CI_Session { * * The constructor runs the session routines automatically * whenever the class is instantiated. + * + * @param array + * @return void */ public function __construct($params = array()) { @@ -78,7 +206,7 @@ class CI_Session { $this->$key = (isset($params[$key])) ? $params[$key] : $this->CI->config->item($key); } - if ($this->encryption_key == '') + if ($this->encryption_key === '') { show_error('In order to use the Session class you are required to set an encryption key in your config file.'); } @@ -87,13 +215,13 @@ class CI_Session { $this->CI->load->helper('string'); // Do we need encryption? If so, load the encryption class - if ($this->sess_encrypt_cookie == TRUE) + if ($this->sess_encrypt_cookie === TRUE) { $this->CI->load->library('encrypt'); } // Are we using a database? If so, load it - if ($this->sess_use_database === TRUE && $this->sess_table_name != '') + if ($this->sess_use_database === TRUE && $this->sess_table_name !== '') { $this->CI->load->database(); } @@ -104,7 +232,7 @@ class CI_Session { // Set the session length. If the session expiration is // set to zero we'll set the expiration two years from now. - if ($this->sess_expiration == 0) + if ($this->sess_expiration === 0) { $this->sess_expiration = (60*60*24*365*2); } @@ -148,14 +276,14 @@ class CI_Session { $session = $this->CI->input->cookie($this->sess_cookie_name); // No cookie? Goodbye cruel world!... - if ($session === FALSE) + if ($session === NULL) { log_message('debug', 'A session cookie was not found.'); return FALSE; } // Decrypt the cookie data - if ($this->sess_encrypt_cookie == TRUE) + if ($this->sess_encrypt_cookie === TRUE) { $session = $this->CI->encrypt->decode($session); } @@ -192,14 +320,14 @@ class CI_Session { } // Does the IP match? - if ($this->sess_match_ip == TRUE && $session['ip_address'] !== $this->CI->input->ip_address()) + if ($this->sess_match_ip === TRUE && $session['ip_address'] !== $this->CI->input->ip_address()) { $this->sess_destroy(); return FALSE; } // Does the User Agent Match? - if ($this->sess_match_useragent == TRUE && trim($session['user_agent']) !== trim(substr($this->CI->input->user_agent(), 0, 120))) + if ($this->sess_match_useragent === TRUE && trim($session['user_agent']) !== trim(substr($this->CI->input->user_agent(), 0, 120))) { $this->sess_destroy(); return FALSE; @@ -210,12 +338,12 @@ class CI_Session { { $this->CI->db->where('session_id', $session['session_id']); - if ($this->sess_match_ip == TRUE) + if ($this->sess_match_ip === TRUE) { $this->CI->db->where('ip_address', $session['ip_address']); } - if ($this->sess_match_useragent == TRUE) + if ($this->sess_match_useragent === TRUE) { $this->CI->db->where('user_agent', $session['user_agent']); } @@ -231,7 +359,7 @@ class CI_Session { // Is there custom data? If so, add it to the main session array $row = $query->row(); - if (isset($row->user_data) && $row->user_data != '') + if ( ! empty($row->user_data)) { $custom_data = $this->_unserialize($row->user_data); @@ -443,6 +571,9 @@ class CI_Session { $this->cookie_domain, 0 ); + + // Kill session data + $this->userdata = array(); } // -------------------------------------------------------------------- @@ -455,7 +586,7 @@ class CI_Session { */ public function userdata($item) { - return isset($this->userdata[$item]) ? $this->userdata[$item] : FALSE; + return isset($this->userdata[$item]) ? $this->userdata[$item] : NULL; } // -------------------------------------------------------------------- @@ -469,21 +600,21 @@ class CI_Session { { return $this->userdata; } - + // -------------------------------------------------------------------------- - + /** * Fetch all flashdata - * + * * @return array */ public function all_flashdata() { $out = array(); - + // loop through all userdata foreach ($this->all_userdata() as $key => $val) - { + { // if it contains flashdata, add it if (strpos($key, 'flash:old:') !== FALSE) { @@ -525,6 +656,7 @@ class CI_Session { /** * Delete a session variable from the "userdata" array * + * @param array * @return void */ public function unset_userdata($newdata = array()) @@ -583,7 +715,7 @@ class CI_Session { { // 'old' flashdata gets removed. Here we mark all // flashdata as 'new' to preserve it from _flashdata_sweep() - // Note the function will return FALSE if the $key + // Note the function will return NULL if the $key // provided cannot be found $value = $this->userdata($this->flashdata_key.':old:'.$key); @@ -664,6 +796,7 @@ class CI_Session { /** * Write the session cookie * + * @param mixed * @return void */ protected function _set_cookie($cookie_data = NULL) @@ -676,7 +809,7 @@ class CI_Session { // Serialize the userdata for the cookie $cookie_data = $this->_serialize($cookie_data); - if ($this->sess_encrypt_cookie == TRUE) + if ($this->sess_encrypt_cookie === TRUE) { $cookie_data = $this->CI->encrypt->encode($cookie_data); } @@ -796,7 +929,7 @@ class CI_Session { */ protected function _sess_gc() { - if ($this->sess_use_database != TRUE) + if ($this->sess_use_database !== TRUE) { return; } @@ -816,4 +949,4 @@ class CI_Session { } /* End of file Session.php */ -/* Location: ./system/libraries/Session.php */ +/* Location: ./system/libraries/Session.php */
\ No newline at end of file diff --git a/system/libraries/Table.php b/system/libraries/Table.php index 11a4858a9..0f8404d85 100644 --- a/system/libraries/Table.php +++ b/system/libraries/Table.php @@ -38,14 +38,61 @@ */ class CI_Table { - public $rows = array(); - public $heading = array(); - public $auto_heading = TRUE; - public $caption = NULL; - public $template = NULL; - public $newline = "\n"; - public $empty_cells = ''; - public $function = FALSE; + /** + * Data for table rows + * + * @var array + */ + public $rows = array(); + + /** + * Data for table heading + * + * @var array + */ + public $heading = array(); + + /** + * Whether or not to automatically create the table header + * + * @var bool + */ + public $auto_heading = TRUE; + + /** + * Table caption + * + * @var string + */ + public $caption = NULL; + + /** + * Table layout template + * + * @var array + */ + public $template = NULL; + + /** + * Newline setting + * + * @var string + */ + public $newline = "\n"; + + /** + * Contents of empty cells + * + * @var string + */ + public $empty_cells = ''; + + /** + * Callback for custom table layout + * + * @var function + */ + public $function = FALSE; /** * Set the template from the table config file if it exists @@ -55,13 +102,13 @@ class CI_Table { */ public function __construct($config = array()) { - log_message('debug', 'Table Class Initialized'); - // initialize config foreach ($config as $key => $val) { $this->template[$key] = $val; } + + log_message('debug', 'Table Class Initialized'); } // -------------------------------------------------------------------- @@ -70,7 +117,7 @@ class CI_Table { * Set the template * * @param array - * @return void + * @return bool */ public function set_template($template) { @@ -80,6 +127,7 @@ class CI_Table { } $this->template = $template; + return TRUE; } // -------------------------------------------------------------------- @@ -92,7 +140,7 @@ class CI_Table { * @param mixed * @return void */ - public function set_heading() + public function set_heading($args = array()) { $args = func_get_args(); $this->heading = $this->_prep_args($args); @@ -101,9 +149,9 @@ class CI_Table { // -------------------------------------------------------------------- /** - * Set columns. Takes a one-dimensional array as input and creates + * Set columns. Takes a one-dimensional array as input and creates * a multi-dimensional array with a depth equal to the number of - * columns. This allows a single array with many elements to be + * columns. This allows a single array with many elements to be * displayed in a table that has a fixed column count. * * @param array @@ -121,7 +169,7 @@ class CI_Table { // will want headings from a one-dimensional array $this->auto_heading = FALSE; - if ($col_limit == 0) + if ($col_limit === 0) { return $array; } @@ -171,7 +219,7 @@ class CI_Table { * @param mixed * @return void */ - public function add_row() + public function add_row($args = array()) { $args = func_get_args(); $this->rows[] = $this->_prep_args($args); @@ -184,29 +232,22 @@ class CI_Table { * * Ensures a standard associative array format for all cell data * - * @param type - * @return type + * @param array + * @return array */ protected function _prep_args($args) { // If there is no $args[0], skip this and treat as an associative array // This can happen if there is only a single key, for example this is passed to table->generate // array(array('foo'=>'bar')) - if (isset($args[0]) AND (count($args) === 1 && is_array($args[0]))) + if (isset($args[0]) && count($args) === 1 && is_array($args[0])) { // args sent as indexed array if ( ! isset($args[0]['data'])) { foreach ($args[0] as $key => $val) { - if (is_array($val) && isset($val['data'])) - { - $args[$key] = $val; - } - else - { - $args[$key] = array('data' => $val); - } + $args[$key] = (is_array($val) && isset($val['data'])) ? $val : array('data' => $val); } } } @@ -257,13 +298,13 @@ class CI_Table { } elseif (is_array($table_data)) { - $set_heading = (count($this->heading) === 0 AND $this->auto_heading == FALSE) ? FALSE : TRUE; + $set_heading = (count($this->heading) !== 0 OR $this->auto_heading !== FALSE); $this->_set_from_array($table_data, $set_heading); } } - // Is there anything to display? No? Smite them! - if (count($this->heading) === 0 AND count($this->rows) === 0) + // Is there anything to display? No? Smite them! + if (count($this->heading) === 0 && count($this->rows) === 0) { return 'Undefined table data'; } @@ -295,9 +336,9 @@ class CI_Table { foreach ($heading as $key => $val) { - if ($key != 'data') + if ($key !== 'data') { - $temp = str_replace('<th', "<th $key='$val'", $temp); + $temp = str_replace('<th', '<th '.$key.'="'.$val.'"', $temp); } } @@ -321,7 +362,7 @@ class CI_Table { } // We use modulus to alternate the row colors - $name = (fmod($i++, 2)) ? '' : 'alt_'; + $name = fmod($i++, 2) ? '' : 'alt_'; $out .= $this->template['row_'.$name.'start'].$this->newline; @@ -333,27 +374,24 @@ class CI_Table { { if ($key !== 'data') { - $temp = str_replace('<td', "<td $key='$val'", $temp); + $temp = str_replace('<td', '<td '.$key.'="'.$val.'"', $temp); } } $cell = isset($cell['data']) ? $cell['data'] : ''; $out .= $temp; - if ($cell === "" OR $cell === NULL) + if ($cell === '' OR $cell === NULL) { $out .= $this->empty_cells; } + elseif ($function !== FALSE && is_callable($function)) + { + $out .= call_user_func($function, $cell); + } else { - if ($function !== FALSE && is_callable($function)) - { - $out .= call_user_func($function, $cell); - } - else - { - $out .= $cell; - } + $out .= $cell; } $out .= $this->template['cell_'.$name.'end']; @@ -382,9 +420,9 @@ class CI_Table { */ public function clear() { - $this->rows = array(); - $this->heading = array(); - $this->auto_heading = TRUE; + $this->rows = array(); + $this->heading = array(); + $this->auto_heading = TRUE; } // -------------------------------------------------------------------- @@ -399,7 +437,7 @@ class CI_Table { { if ( ! is_object($query)) { - return FALSE; + return; } // First generate the headings from the table column names @@ -407,14 +445,13 @@ class CI_Table { { if ( ! is_callable(array($query, 'list_fields'))) { - return FALSE; + return; } $this->heading = $this->_prep_args($query->list_fields()); } // Next blast through the result array and build out the rows - if ($query->num_rows() > 0) { foreach ($query->result_array() as $row) @@ -430,6 +467,7 @@ class CI_Table { * Set table data from an array * * @param array + * @param bool * @return void */ protected function _set_from_array($data, $set_heading = TRUE) @@ -443,7 +481,7 @@ class CI_Table { foreach ($data as $row) { // If a heading hasn't already been set we'll use the first row of the array as the heading - if ($i++ === 0 AND count($data) > 1 AND count($this->heading) === 0 AND $set_heading == TRUE) + if ($i++ === 0 && count($data) > 1 && count($this->heading) === 0 && $set_heading === TRUE) { $this->heading = $this->_prep_args($row); } @@ -463,7 +501,7 @@ class CI_Table { */ protected function _compile_template() { - if ($this->template == NULL) + if ($this->template === NULL) { $this->template = $this->_default_template(); return; @@ -488,36 +526,35 @@ class CI_Table { */ protected function _default_template() { - return array ( - 'table_open' => '<table border="0" cellpadding="4" cellspacing="0">', + return array( + 'table_open' => '<table border="0" cellpadding="4" cellspacing="0">', - 'thead_open' => '<thead>', - 'thead_close' => '</thead>', + 'thead_open' => '<thead>', + 'thead_close' => '</thead>', - 'heading_row_start' => '<tr>', - 'heading_row_end' => '</tr>', - 'heading_cell_start' => '<th>', - 'heading_cell_end' => '</th>', + 'heading_row_start' => '<tr>', + 'heading_row_end' => '</tr>', + 'heading_cell_start' => '<th>', + 'heading_cell_end' => '</th>', - 'tbody_open' => '<tbody>', - 'tbody_close' => '</tbody>', + 'tbody_open' => '<tbody>', + 'tbody_close' => '</tbody>', - 'row_start' => '<tr>', - 'row_end' => '</tr>', - 'cell_start' => '<td>', - 'cell_end' => '</td>', + 'row_start' => '<tr>', + 'row_end' => '</tr>', + 'cell_start' => '<td>', + 'cell_end' => '</td>', - 'row_alt_start' => '<tr>', - 'row_alt_end' => '</tr>', - 'cell_alt_start' => '<td>', - 'cell_alt_end' => '</td>', + 'row_alt_start' => '<tr>', + 'row_alt_end' => '</tr>', + 'cell_alt_start' => '<td>', + 'cell_alt_end' => '</td>', - 'table_close' => '</table>' - ); + 'table_close' => '</table>' + ); } - } /* End of file Table.php */ -/* Location: ./system/libraries/Table.php */ +/* Location: ./system/libraries/Table.php */
\ No newline at end of file diff --git a/system/libraries/Trackback.php b/system/libraries/Trackback.php index be1de6f3f..9a680dc2a 100644 --- a/system/libraries/Trackback.php +++ b/system/libraries/Trackback.php @@ -25,8 +25,6 @@ * @filesource */ -// ------------------------------------------------------------------------ - /** * Trackback Class * @@ -49,7 +47,7 @@ class CI_Trackback { public function __construct() { - log_message('debug', "Trackback Class Initialized"); + log_message('debug', 'Trackback Class Initialized'); } // -------------------------------------------------------------------- @@ -90,16 +88,17 @@ class CI_Trackback { } // Convert High ASCII Characters - if ($this->convert_ascii == TRUE && in_array($item, array('excerpt', 'title', 'blog_name'))) + if ($this->convert_ascii === TRUE && in_array($item, array('excerpt', 'title', 'blog_name'))) { $$item = $this->convert_ascii($$item); } } // Build the Trackback data string - $charset = ( ! isset($tb_data['charset'])) ? $this->charset : $tb_data['charset']; + $charset = isset($tb_data['charset']) ? $tb_data['charset'] : $this->charset; - $data = "url=".rawurlencode($url)."&title=".rawurlencode($title)."&blog_name=".rawurlencode($blog_name)."&excerpt=".rawurlencode($excerpt)."&charset=".rawurlencode($charset); + $data = 'url='.rawurlencode($url).'&title='.rawurlencode($title).'&blog_name='.rawurlencode($blog_name) + .'&excerpt='.rawurlencode($excerpt).'&charset='.rawurlencode($charset); // Send Trackback(s) $return = TRUE; @@ -107,7 +106,7 @@ class CI_Trackback { { foreach ($ping_url as $url) { - if ($this->process($url, $data) == FALSE) + if ($this->process($url, $data) === FALSE) { $return = FALSE; } @@ -133,22 +132,22 @@ class CI_Trackback { { foreach (array('url', 'title', 'blog_name', 'excerpt') as $val) { - if ( ! isset($_POST[$val]) OR $_POST[$val] == '') + if (empty($_POST[$val])) { $this->set_error('The following required POST variable is missing: '.$val); return FALSE; } - $this->data['charset'] = ( ! isset($_POST['charset'])) ? 'auto' : strtoupper(trim($_POST['charset'])); + $this->data['charset'] = isset($_POST['charset']) ? strtoupper(trim($_POST['charset'])) : 'auto'; - if ($val != 'url' && MB_ENABLED === TRUE) + if ($val !== 'url' && MB_ENABLED === TRUE) { $_POST[$val] = mb_convert_encoding($_POST[$val], $this->charset, $this->data['charset']); } - $_POST[$val] = ($val != 'url') ? $this->convert_xml(strip_tags($_POST[$val])) : strip_tags($_POST[$val]); + $_POST[$val] = ($val !== 'url') ? $this->convert_xml(strip_tags($_POST[$val])) : strip_tags($_POST[$val]); - if ($val == 'excerpt') + if ($val === 'excerpt') { $_POST['excerpt'] = $this->limit_characters($_POST['excerpt']); } @@ -164,7 +163,7 @@ class CI_Trackback { /** * Send Trackback Error Message * - * Allows custom errors to be set. By default it + * Allows custom errors to be set. By default it * sends the "incomplete information" error, as that's * the most common one. * @@ -173,7 +172,7 @@ class CI_Trackback { */ public function send_error($message = 'Incomplete Information') { - echo "<?xml version=\"1.0\" encoding=\"utf-8\"?".">\n<response>\n<error>1</error>\n<message>".$message."</message>\n</response>"; + echo '<?xml version="1.0" encoding="utf-8"?'.">\n<response>\n<error>1</error>\n<message>".$message."</message>\n</response>"; exit; } @@ -189,7 +188,7 @@ class CI_Trackback { */ public function send_success() { - echo "<?xml version=\"1.0\" encoding=\"utf-8\"?".">\n<response>\n<error>0</error>\n</response>"; + echo '<?xml version="1.0" encoding="utf-8"?'.">\n<response>\n<error>0</error>\n</response>"; exit; } @@ -203,7 +202,7 @@ class CI_Trackback { */ public function data($item) { - return ( ! isset($this->data[$item])) ? '' : $this->data[$item]; + return isset($this->data[$item]) ? $this->data[$item] : ''; } // -------------------------------------------------------------------- @@ -212,7 +211,7 @@ class CI_Trackback { * Process Trackback * * Opens a socket connection and passes the data to - * the server. Returns TRUE on success, FALSE on failure + * the server. Returns TRUE on success, FALSE on failure * * @param string * @param string @@ -230,37 +229,36 @@ class CI_Trackback { } // Build the path - $ppath = ( ! isset($target['path'])) ? $url : $target['path']; + $ppath = isset($target['path']) ? $target['path'] : $url; - $path = (isset($target['query']) && $target['query'] != "") ? $ppath.'?'.$target['query'] : $ppath; + $path = empty($target['query']) ? $ppath : $ppath.'?'.$target['query']; // Add the Trackback ID to the data string if ($id = $this->get_id($url)) { - $data = "tb_id=".$id."&".$data; + $data = 'tb_id='.$id.'&'.$data; } // Transfer the data - fputs ($fp, "POST " . $path . " HTTP/1.0\r\n" ); - fputs ($fp, "Host: " . $target['host'] . "\r\n" ); - fputs ($fp, "Content-type: application/x-www-form-urlencoded\r\n" ); - fputs ($fp, "Content-length: " . strlen($data) . "\r\n" ); - fputs ($fp, "Connection: close\r\n\r\n" ); - fputs ($fp, $data); + fputs($fp, 'POST '.$path." HTTP/1.0\r\n"); + fputs($fp, 'Host: '.$target['host']."\r\n"); + fputs($fp, "Content-type: application/x-www-form-urlencoded\r\n"); + fputs($fp, 'Content-length: '.strlen($data)."\r\n"); + fputs($fp, "Connection: close\r\n\r\n"); + fputs($fp, $data); // Was it successful? - $this->response = ""; + $this->response = ''; while ( ! feof($fp)) { $this->response .= fgets($fp, 128); } @fclose($fp); - if (stripos($this->response, '<error>0</error>') === FALSE) { - $message = (preg_match('/<message>(.*?)<\/message>/is', $this->response, $match)) ? trim($match[1]) : 'An unknown error was encountered'; + $message = preg_match('/<message>(.*?)<\/message>/is', $this->response, $match) ? trim($match[1]) : 'An unknown error was encountered'; $this->set_error($message); return FALSE; } @@ -282,11 +280,8 @@ class CI_Trackback { */ public function extract_urls($urls) { - // Remove the pesky white space and replace with a comma. - $urls = preg_replace("/\s*(\S+)\s*/", "\\1,", $urls); - - // If they use commas get rid of the doubles. - $urls = str_replace(",,", ",", $urls); + // Remove the pesky white space and replace with a comma, then replace doubles. + $urls = str_replace(',,', ',', preg_replace('/\s*(\S+)\s*/', '\\1,', $urls)); // Remove any comma that might be at the end if (substr($urls, -1) === ',') @@ -294,11 +289,8 @@ class CI_Trackback { $urls = substr($urls, 0, -1); } - // Break into an array via commas - $urls = preg_split('/[,]/', $urls); - - // Removes duplicates - $urls = array_unique($urls); + // Break into an array via commas and remove duplicates + $urls = array_unique(preg_split('/[,]/', $urls)); array_walk($urls, array($this, 'validate_url')); @@ -313,9 +305,9 @@ class CI_Trackback { * Simply adds "http://" if missing * * @param string - * @return string + * @return void */ - public function validate_url($url) + public function validate_url(&$url) { $url = trim($url); @@ -335,7 +327,7 @@ class CI_Trackback { */ public function get_id($url) { - $tb_id = ""; + $tb_id = ''; if (strpos($url, '?') !== FALSE) { @@ -359,18 +351,11 @@ class CI_Trackback { if ( ! is_numeric($tb_id)) { - $tb_id = $tb_array[count($tb_array)-2]; + $tb_id = $tb_array[count($tb_array)-2]; } } - if ( ! preg_match ("/^([0-9]+)$/", $tb_id)) - { - return FALSE; - } - else - { - return $tb_id; - } + return preg_match('/^[0-9]+$/', $tb_id) ? $tb_id : FALSE; } // -------------------------------------------------------------------- @@ -385,15 +370,13 @@ class CI_Trackback { { $temp = '__TEMP_AMPERSANDS__'; - $str = preg_replace(array('/&#(\d+);/', '/&(\w+);/'), "$temp\\1;", $str); - - $str = str_replace(array("&","<",">","\"", "'", "-"), - array("&", "<", ">", """, "'", "-"), - $str); + $str = preg_replace(array('/&#(\d+);/', '/&(\w+);/'), $temp.'\\1;', $str); - $str = preg_replace(array("/$temp(\d+);/", "/$temp(\w+);/"), array('&#\\1;', '&\\1;'), $str); + $str = str_replace(array('&', '<', '>', '"', "'", '-'), + array('&', '<', '>', '"', ''', '-'), + $str); - return $str; + return preg_replace(array('/'.$temp.'(\d+);/', '/'.$temp.'(\w+);/'), array('&#\\1;', '&\\1;'), $str); } // -------------------------------------------------------------------- @@ -404,7 +387,7 @@ class CI_Trackback { * Limits the string based on the character count. Will preserve complete words. * * @param string - * @param integer + * @param int * @param string * @return string */ @@ -415,7 +398,7 @@ class CI_Trackback { return $str; } - $str = preg_replace("/\s+/", ' ', str_replace(array("\r\n", "\r", "\n"), ' ', $str)); + $str = preg_replace('/\s+/', ' ', str_replace(array("\r\n", "\r", "\n"), ' ', $str)); if (strlen($str) <= $n) { @@ -469,7 +452,9 @@ class CI_Trackback { if (count($temp) === $count) { - $number = ($count == 3) ? (($temp[0] % 16) * 4096) + (($temp[1] % 64) * 64) + ($temp[2] % 64) : (($temp[0] % 32) * 64) + ($temp[1] % 64); + $number = ($count === 3) + ? (($temp[0] % 16) * 4096) + (($temp[1] % 64) * 64) + ($temp[2] % 64) + : (($temp[0] % 32) * 64) + ($temp[1] % 64); $out .= '&#'.$number.';'; $count = 1; @@ -506,11 +491,10 @@ class CI_Trackback { */ public function display_errors($open = '<p>', $close = '</p>') { - return (count($this->error_msg) > 0) ? $open . implode($close . $open, $this->error_msg) . $close : ''; + return (count($this->error_msg) > 0) ? $open.implode($close.$open, $this->error_msg).$close : ''; } } -// END Trackback Class /* End of file Trackback.php */ -/* Location: ./system/libraries/Trackback.php */ +/* Location: ./system/libraries/Trackback.php */
\ No newline at end of file diff --git a/system/libraries/Typography.php b/system/libraries/Typography.php index 21bbad038..a50934f2c 100644 --- a/system/libraries/Typography.php +++ b/system/libraries/Typography.php @@ -36,22 +36,46 @@ */ class CI_Typography { - // Block level elements that should not be wrapped inside <p> tags + /** + * Block level elements that should not be wrapped inside <p> tags + * + * @var string + */ public $block_elements = 'address|blockquote|div|dl|fieldset|form|h\d|hr|noscript|object|ol|p|pre|script|table|ul'; - // Elements that should not have <p> and <br /> tags within them. + /** + * Elements that should not have <p> and <br /> tags within them. + * + * @var string + */ public $skip_elements = 'p|pre|ol|ul|dl|object|table|h\d'; - // Tags we want the parser to completely ignore when splitting the string. + /** + * Tags we want the parser to completely ignore when splitting the string. + * + * @var string + */ public $inline_elements = 'a|abbr|acronym|b|bdo|big|br|button|cite|code|del|dfn|em|i|img|ins|input|label|map|kbd|q|samp|select|small|span|strong|sub|sup|textarea|tt|var'; - // array of block level elements that require inner content to be within another block level element + /** + * array of block level elements that require inner content to be within another block level element + * + * @var array + */ public $inner_block_required = array('blockquote'); - // the last block element parsed + /** + * the last block element parsed + * + * @var string + */ public $last_block_element = ''; - // whether or not to protect quotes within { curly braces } + /** + * whether or not to protect quotes within { curly braces } + * + * @var bool + */ public $protect_braced_quotes = FALSE; /** @@ -71,7 +95,7 @@ class CI_Typography { */ public function auto_typography($str, $reduce_linebreaks = FALSE) { - if ($str == '') + if ($str === '') { return ''; } @@ -149,7 +173,7 @@ class CI_Typography { $process = ($match[1] === '/'); } - if ($match[1] == '') + if ($match[1] === '') { $this->last_block_element = $match[2]; } @@ -320,7 +344,7 @@ class CI_Typography { */ protected function _format_newlines($str) { - if ($str == '' OR (strpos($str, "\n") === FALSE && ! in_array($this->last_block_element, $this->inner_block_required))) + if ($str === '' OR (strpos($str, "\n") === FALSE && ! in_array($this->last_block_element, $this->inner_block_required))) { return $str; } @@ -332,7 +356,7 @@ class CI_Typography { $str = preg_replace("/([^\n])(\n)([^\n])/", '\\1<br />\\2\\3', $str); // Wrap the whole enchilada in enclosing paragraphs - if ($str != "\n") + if ($str !== "\n") { // We trim off the right-side new line so that the closing </p> tag // will be positioned immediately following the string, matching diff --git a/system/libraries/Unit_test.php b/system/libraries/Unit_test.php index 2eb8df356..70ad8dc41 100644 --- a/system/libraries/Unit_test.php +++ b/system/libraries/Unit_test.php @@ -25,8 +25,6 @@ * @filesource */ -// ------------------------------------------------------------------------ - /** * Unit Testing Class * @@ -60,7 +58,7 @@ class CI_Unit_test { 'notes' ); - log_message('debug', "Unit Testing Class Initialized"); + log_message('debug', 'Unit Testing Class Initialized'); } // -------------------------------------------------------------------- @@ -75,7 +73,7 @@ class CI_Unit_test { */ public function set_test_items($items = array()) { - if ( ! empty($items) AND is_array($items)) + if ( ! empty($items) && is_array($items)) { $this->_test_items_visible = $items; } @@ -95,20 +93,20 @@ class CI_Unit_test { */ public function run($test, $expected = TRUE, $test_name = 'undefined', $notes = '') { - if ($this->active == FALSE) + if ($this->active === FALSE) { return FALSE; } if (in_array($expected, array('is_object', 'is_string', 'is_bool', 'is_true', 'is_false', 'is_int', 'is_numeric', 'is_float', 'is_double', 'is_array', 'is_null'), TRUE)) { - $expected = str_replace('is_float', 'is_double', $expected); - $result = ($expected($test)) ? TRUE : FALSE; + $expected = str_replace('is_double', 'is_float', $expected); + $result = $expected($test); $extype = str_replace(array('true', 'false'), 'bool', str_replace('is_', '', $expected)); } else { - $result = ($this->strict == TRUE) ? ($test === $expected) : ($test == $expected); + $result = ($this->strict === TRUE) ? ($test === $expected) : ($test === $expected); $extype = gettype($expected); } @@ -126,7 +124,7 @@ class CI_Unit_test { $this->results[] = $report; - return($this->report($this->result($report))); + return $this->report($this->result($report)); } // -------------------------------------------------------------------- @@ -157,13 +155,13 @@ class CI_Unit_test { foreach ($res as $key => $val) { - if ($key == $CI->lang->line('ut_result')) + if ($key === $CI->lang->line('ut_result')) { - if ($val == $CI->lang->line('ut_passed')) + if ($val === $CI->lang->line('ut_passed')) { $val = '<span style="color: #0C0;">'.$val.'</span>'; } - elseif ($val == $CI->lang->line('ut_failed')) + elseif ($val === $CI->lang->line('ut_failed')) { $val = '<span style="color: #C00;">'.$val.'</span>'; } @@ -186,7 +184,7 @@ class CI_Unit_test { * Causes the evaluation to use === rather than == * * @param bool - * @return null + * @return void */ public function use_strict($state = TRUE) { @@ -201,7 +199,7 @@ class CI_Unit_test { * Enables/disables unit testing * * @param bool - * @return null + * @return void */ public function active($state = TRUE) { @@ -291,15 +289,11 @@ class CI_Unit_test { */ protected function _backtrace() { - if (function_exists('debug_backtrace')) - { - $back = debug_backtrace(); - return array( - 'file' => (isset($back[1]['file']) ? $back[1]['file'] : ''), - 'line' => (isset($back[1]['line']) ? $back[1]['line'] : '') - ); - } - return array('file' => 'Unknown', 'line' => 'Unknown'); + $back = debug_backtrace(); + return array( + 'file' => (isset($back[1]['file']) ? $back[1]['file'] : ''), + 'line' => (isset($back[1]['line']) ? $back[1]['line'] : '') + ); } // -------------------------------------------------------------------- @@ -311,10 +305,10 @@ class CI_Unit_test { */ protected function _default_template() { - $this->_template = "\n".'<table style="width:100%; font-size:small; margin:10px 0; border-collapse:collapse; border:1px solid #CCC;">{rows}'."\n".'</table>'; + $this->_template = "\n".'<table style="width:100%; font-size:small; margin:10px 0; border-collapse:collapse; border:1px solid #CCC;">{rows}'."\n</table>"; $this->_template_rows = "\n\t<tr>\n\t\t".'<th style="text-align: left; border-bottom:1px solid #CCC;">{item}</th>' - . "\n\t\t".'<td style="border-bottom:1px solid #CCC;">{result}</td>'."\n\t</tr>"; + ."\n\t\t".'<td style="border-bottom:1px solid #CCC;">{result}</td>'."\n\t</tr>"; } // -------------------------------------------------------------------- @@ -333,7 +327,7 @@ class CI_Unit_test { return; } - if (is_null($this->_template) OR ! preg_match("/\{rows\}(.*?)\{\/rows\}/si", $this->_template, $match)) + if (is_null($this->_template) OR ! preg_match('/\{rows\}(.*?)\{\/rows\}/si', $this->_template, $match)) { $this->_default_template(); return; @@ -344,7 +338,6 @@ class CI_Unit_test { } } -// END Unit_test Class /** * Helper functions to test boolean true/false @@ -353,13 +346,12 @@ class CI_Unit_test { */ function is_true($test) { - return (is_bool($test) AND $test === TRUE) ? TRUE : FALSE; + return ($test === TRUE); } function is_false($test) { - return (is_bool($test) AND $test === FALSE) ? TRUE : FALSE; + return ($test === FALSE); } - /* End of file Unit_test.php */ -/* Location: ./system/libraries/Unit_test.php */ +/* Location: ./system/libraries/Unit_test.php */
\ No newline at end of file diff --git a/system/libraries/Upload.php b/system/libraries/Upload.php index 8ad67050d..1f6aeeb6b 100644 --- a/system/libraries/Upload.php +++ b/system/libraries/Upload.php @@ -78,6 +78,8 @@ class CI_Upload { $this->initialize($props); } + $this->mimes =& get_mimes(); + log_message('debug', 'Upload Class Initialized'); } @@ -113,7 +115,6 @@ class CI_Upload { 'image_type' => '', 'image_size_str' => '', 'error_msg' => array(), - 'mimes' => array(), 'remove_spaces' => TRUE, 'xss_clean' => FALSE, 'temp_prefix' => 'temp_file_', @@ -223,7 +224,7 @@ class CI_Upload { } // if we're overriding, let's now make sure the new name and type is allowed - if ($this->_file_name_override != '') + if ($this->_file_name_override !== '') { $this->file_name = $this->_prep_filename($this->_file_name_override); @@ -276,7 +277,7 @@ class CI_Upload { } // Remove white spaces in the name - if ($this->remove_spaces == TRUE) + if ($this->remove_spaces === TRUE) { $this->file_name = preg_replace('/\s+/', '_', $this->file_name); } @@ -289,7 +290,7 @@ class CI_Upload { */ $this->orig_name = $this->file_name; - if ($this->overwrite == FALSE) + if ($this->overwrite === FALSE) { $this->file_name = $this->set_filename($this->upload_path, $this->file_name); @@ -397,7 +398,7 @@ class CI_Upload { */ public function set_filename($path, $filename) { - if ($this->encrypt_name == TRUE) + if ($this->encrypt_name === TRUE) { mt_srand(); $filename = md5(uniqid(mt_rand())).$this->file_ext; @@ -420,7 +421,7 @@ class CI_Upload { } } - if ($new_filename == '') + if ($new_filename === '') { $this->set_error('upload_bad_filename'); return FALSE; @@ -545,7 +546,7 @@ class CI_Upload { */ public function set_xss_clean($flag = FALSE) { - $this->xss_clean = ($flag == TRUE); + $this->xss_clean = ($flag === TRUE); } // -------------------------------------------------------------------- @@ -641,7 +642,7 @@ class CI_Upload { */ public function is_allowed_filesize() { - return ($this->max_size == 0 OR $this->max_size > $this->file_size); + return ($this->max_size === 0 OR $this->max_size > $this->file_size); } // -------------------------------------------------------------------- @@ -687,13 +688,13 @@ class CI_Upload { */ public function validate_upload_path() { - if ($this->upload_path == '') + if ($this->upload_path === '') { $this->set_error('upload_no_filepath'); return FALSE; } - if (function_exists('realpath') && @realpath($this->upload_path) !== FALSE) + if (@realpath($this->upload_path) !== FALSE) { $this->upload_path = str_replace('\\', '/', realpath($this->upload_path)); } @@ -725,7 +726,7 @@ class CI_Upload { public function get_extension($filename) { $x = explode('.', $filename); - return '.'.end($x); + return (count($x) !== 1) ? '.'.end($x) : ''; } // -------------------------------------------------------------------- @@ -747,6 +748,8 @@ class CI_Upload { ';', '?', '/', + '!', + '#', '%20', '%22', '%3c', // < @@ -812,17 +815,17 @@ class CI_Upload { return FALSE; } - if (function_exists('memory_get_usage') && memory_get_usage() && ini_get('memory_limit') != '') + if (memory_get_usage() && ($memory_limit = ini_get('memory_limit'))) { - $current = ini_get('memory_limit') * 1024 * 1024; + $memory_limit *= 1024 * 1024; // There was a bug/behavioural change in PHP 5.2, where numbers over one million get output // into scientific notation. number_format() ensures this number is an integer // http://bugs.php.net/bug.php?id=43053 - $new_memory = number_format(ceil(filesize($file) + $current), 0, '.', ''); + $memory_limit = number_format(ceil(filesize($file) + $memory_limit), 0, '.', ''); - ini_set('memory_limit', $new_memory); // When an integer is used, the value is measured in bytes. - PHP.net + ini_set('memory_limit', $memory_limit); // When an integer is used, the value is measured in bytes. - PHP.net } // If the file being uploaded is an image, then we should have no problem with XSS attacks (in theory), but @@ -846,10 +849,8 @@ class CI_Upload { // <a, <body, <head, <html, <img, <plaintext, <pre, <script, <table, <title // title is basically just in SVG, but we filter it anyhow - if ( ! preg_match('/<(a|body|head|html|img|plaintext|pre|script|table|title)[\s>]/i', $opening_bytes)) - { - return TRUE; // its an image, no "triggers" detected in the first 256 bytes, we're good - } + // if its an image or no "triggers" detected in the first 256 bytes - we're good + return ! preg_match('/<(a|body|head|html|img|plaintext|pre|script|table|title)[\s>]/i', $opening_bytes); } if (($data = @file_get_contents($file)) === FALSE) @@ -878,14 +879,14 @@ class CI_Upload { { foreach ($msg as $val) { - $msg = ($CI->lang->line($val) == FALSE) ? $val : $CI->lang->line($val); + $msg = ($CI->lang->line($val) === FALSE) ? $val : $CI->lang->line($val); $this->error_msg[] = $msg; log_message('error', $msg); } } else { - $msg = ($CI->lang->line($msg) == FALSE) ? $msg : $CI->lang->line($msg); + $msg = ($CI->lang->line($msg) === FALSE) ? $msg : $CI->lang->line($msg); $this->error_msg[] = $msg; log_message('error', $msg); } @@ -918,26 +919,6 @@ class CI_Upload { */ public function mimes_types($mime) { - global $mimes; - - if (count($this->mimes) == 0) - { - if (defined('ENVIRONMENT') && is_file(APPPATH.'config/'.ENVIRONMENT.'/mimes.php')) - { - include(APPPATH.'config/'.ENVIRONMENT.'/mimes.php'); - } - elseif (is_file(APPPATH.'config/mimes.php')) - { - include(APPPATH.'config/mimes.php'); - } - else - { - return FALSE; - } - - $this->mimes = $mimes; - } - return isset($this->mimes[$mime]) ? $this->mimes[$mime] : FALSE; } @@ -954,7 +935,7 @@ class CI_Upload { */ protected function _prep_filename($filename) { - if (strpos($filename, '.') === FALSE OR $this->allowed_types == '*') + if (strpos($filename, '.') === FALSE OR $this->allowed_types === '*') { return $filename; } @@ -1032,7 +1013,7 @@ class CI_Upload { */ if (DIRECTORY_SEPARATOR !== '\\') { - $cmd = 'file --brief --mime ' . escapeshellarg($file['tmp_name']) . ' 2>&1'; + $cmd = 'file --brief --mime '.escapeshellarg($file['tmp_name']).' 2>&1'; if (function_exists('exec')) { diff --git a/system/libraries/User_agent.php b/system/libraries/User_agent.php index 9109edd0f..ff596f04b 100644 --- a/system/libraries/User_agent.php +++ b/system/libraries/User_agent.php @@ -25,8 +25,6 @@ * @filesource */ -// ------------------------------------------------------------------------ - /** * User Agent Class * @@ -40,25 +38,110 @@ */ class CI_User_agent { - public $agent = NULL; + /** + * Current user-agent + * + * @var string + */ + public $agent = NULL; + + /** + * Flag for if the user-agent belongs to a browser + * + * @var bool + */ + public $is_browser = FALSE; + + /** + * Flag for if the user-agent is a robot + * + * @var bool + */ + public $is_robot = FALSE; + + /** + * Flag for if the user-agent is a mobile browser + * + * @var bool + */ + public $is_mobile = FALSE; + + /** + * Languages accepted by the current user agent + * + * @var array + */ + public $languages = array(); + + /** + * Character sets accepted by the current user agent + * + * @var array + */ + public $charsets = array(); + + /** + * List of platforms to compare against current user agent + * + * @var array + */ + public $platforms = array(); + + /** + * List of browsers to compare against current user agent + * + * @var array + */ + public $browsers = array(); + + /** + * List of mobile browsers to compare against current user agent + * + * @var array + */ + public $mobiles = array(); + + /** + * List of robots to compare against current user agent + * + * @var array + */ + public $robots = array(); + + /** + * Current user-agent platform + * + * @var string + */ + public $platform = ''; - public $is_browser = FALSE; - public $is_robot = FALSE; - public $is_mobile = FALSE; + /** + * Current user-agent browser + * + * @var string + */ + public $browser = ''; - public $languages = array(); - public $charsets = array(); + /** + * Current user-agent version + * + * @var string + */ + public $version = ''; - public $platforms = array(); - public $browsers = array(); - public $mobiles = array(); - public $robots = array(); + /** + * Current user-agent mobile name + * + * @var string + */ + public $mobile = ''; - public $platform = ''; - public $browser = ''; - public $version = ''; - public $mobile = ''; - public $robot = ''; + /** + * Current user-agent robot name + * + * @var string + */ + public $robot = ''; /** * Constructor @@ -74,15 +157,12 @@ class CI_User_agent { $this->agent = trim($_SERVER['HTTP_USER_AGENT']); } - if ( ! is_null($this->agent)) + if ( ! is_null($this->agent) && $this->_load_agent_file()) { - if ($this->_load_agent_file()) - { - $this->_compile_data(); - } + $this->_compile_data(); } - log_message('debug', "User Agent Class Initialized"); + log_message('debug', 'User Agent Class Initialized'); } // -------------------------------------------------------------------- @@ -94,7 +174,7 @@ class CI_User_agent { */ protected function _load_agent_file() { - if (defined('ENVIRONMENT') AND is_file(APPPATH.'config/'.ENVIRONMENT.'/user_agents.php')) + if (defined('ENVIRONMENT') && is_file(APPPATH.'config/'.ENVIRONMENT.'/user_agents.php')) { include(APPPATH.'config/'.ENVIRONMENT.'/user_agents.php'); } @@ -165,22 +245,24 @@ class CI_User_agent { /** * Set the Platform * - * @return mixed + * @return bool */ protected function _set_platform() { - if (is_array($this->platforms) AND count($this->platforms) > 0) + if (is_array($this->platforms) && count($this->platforms) > 0) { foreach ($this->platforms as $key => $val) { - if (preg_match("|".preg_quote($key)."|i", $this->agent)) + if (preg_match('|'.preg_quote($key).'|i', $this->agent)) { $this->platform = $val; return TRUE; } } } + $this->platform = 'Unknown Platform'; + return FALSE; } // -------------------------------------------------------------------- @@ -192,11 +274,11 @@ class CI_User_agent { */ protected function _set_browser() { - if (is_array($this->browsers) AND count($this->browsers) > 0) + if (is_array($this->browsers) && count($this->browsers) > 0) { foreach ($this->browsers as $key => $val) { - if (preg_match("|".preg_quote($key).".*?([0-9\.]+)|i", $this->agent, $match)) + if (preg_match('|'.preg_quote($key).'.*?([0-9\.]+)|i', $this->agent, $match)) { $this->is_browser = TRUE; $this->version = $match[1]; @@ -206,6 +288,7 @@ class CI_User_agent { } } } + return FALSE; } @@ -218,11 +301,11 @@ class CI_User_agent { */ protected function _set_robot() { - if (is_array($this->robots) AND count($this->robots) > 0) + if (is_array($this->robots) && count($this->robots) > 0) { foreach ($this->robots as $key => $val) { - if (preg_match("|".preg_quote($key)."|i", $this->agent)) + if (preg_match('|'.preg_quote($key).'|i', $this->agent)) { $this->is_robot = TRUE; $this->robot = $val; @@ -230,6 +313,7 @@ class CI_User_agent { } } } + return FALSE; } @@ -242,11 +326,11 @@ class CI_User_agent { */ protected function _set_mobile() { - if (is_array($this->mobiles) AND count($this->mobiles) > 0) + if (is_array($this->mobiles) && count($this->mobiles) > 0) { foreach ($this->mobiles as $key => $val) { - if (FALSE !== (strpos(strtolower($this->agent), $key))) + if (FALSE !== (stripos($this->agent, $key))) { $this->is_mobile = TRUE; $this->mobile = $val; @@ -254,6 +338,7 @@ class CI_User_agent { } } } + return FALSE; } @@ -266,7 +351,7 @@ class CI_User_agent { */ protected function _set_languages() { - if ((count($this->languages) === 0) AND isset($_SERVER['HTTP_ACCEPT_LANGUAGE']) AND $_SERVER['HTTP_ACCEPT_LANGUAGE'] != '') + if ((count($this->languages) === 0) && ! empty($_SERVER['HTTP_ACCEPT_LANGUAGE'])) { $this->languages = explode(',', preg_replace('/(;q=[0-9\.]+)/i', '', strtolower(trim($_SERVER['HTTP_ACCEPT_LANGUAGE'])))); } @@ -286,7 +371,7 @@ class CI_User_agent { */ protected function _set_charsets() { - if ((count($this->charsets) === 0) AND isset($_SERVER['HTTP_ACCEPT_CHARSET']) AND $_SERVER['HTTP_ACCEPT_CHARSET'] != '') + if ((count($this->charsets) === 0) && ! empty($_SERVER['HTTP_ACCEPT_CHARSET'])) { $this->charsets = explode(',', preg_replace('/(;q=.+)/i', '', strtolower(trim($_SERVER['HTTP_ACCEPT_CHARSET'])))); } @@ -302,6 +387,7 @@ class CI_User_agent { /** * Is Browser * + * @param string $key * @return bool */ public function is_browser($key = NULL) @@ -318,7 +404,7 @@ class CI_User_agent { } // Check for a specific browser - return array_key_exists($key, $this->browsers) AND $this->browser === $this->browsers[$key]; + return (isset($this->browsers[$key]) && $this->browser === $this->browsers[$key]); } // -------------------------------------------------------------------- @@ -326,6 +412,7 @@ class CI_User_agent { /** * Is Robot * + * @param string $key * @return bool */ public function is_robot($key = NULL) @@ -342,7 +429,7 @@ class CI_User_agent { } // Check for a specific robot - return array_key_exists($key, $this->robots) AND $this->robot === $this->robots[$key]; + return (isset($this->robots[$key]) && $this->robot === $this->robots[$key]); } // -------------------------------------------------------------------- @@ -350,6 +437,7 @@ class CI_User_agent { /** * Is Mobile * + * @param string $key * @return bool */ public function is_mobile($key = NULL) @@ -366,7 +454,7 @@ class CI_User_agent { } // Check for a specific robot - return array_key_exists($key, $this->mobiles) AND $this->mobile === $this->mobiles[$key]; + return (isset($this->mobiles[$key]) && $this->mobile === $this->mobiles[$key]); } // -------------------------------------------------------------------- @@ -378,7 +466,7 @@ class CI_User_agent { */ public function is_referral() { - return ( ! isset($_SERVER['HTTP_REFERER']) OR $_SERVER['HTTP_REFERER'] == '') ? FALSE : TRUE; + return ! empty($_SERVER['HTTP_REFERER']); } // -------------------------------------------------------------------- @@ -461,7 +549,7 @@ class CI_User_agent { */ public function referrer() { - return ( ! isset($_SERVER['HTTP_REFERER']) OR $_SERVER['HTTP_REFERER'] == '') ? '' : trim($_SERVER['HTTP_REFERER']); + return empty($_SERVER['HTTP_REFERER']) ? '' : trim($_SERVER['HTTP_REFERER']); } // -------------------------------------------------------------------- @@ -503,11 +591,12 @@ class CI_User_agent { /** * Test for a particular language * + * @param string $lang * @return bool */ public function accept_lang($lang = 'en') { - return (in_array(strtolower($lang), $this->languages(), TRUE)); + return in_array(strtolower($lang), $this->languages(), TRUE); } // -------------------------------------------------------------------- @@ -515,14 +604,15 @@ class CI_User_agent { /** * Test for a particular character set * + * @param string $charset * @return bool */ public function accept_charset($charset = 'utf-8') { - return (in_array(strtolower($charset), $this->charsets(), TRUE)); + return in_array(strtolower($charset), $this->charsets(), TRUE); } } /* End of file User_agent.php */ -/* Location: ./system/libraries/User_agent.php */ +/* Location: ./system/libraries/User_agent.php */
\ No newline at end of file diff --git a/system/libraries/Xmlrpc.php b/system/libraries/Xmlrpc.php index 32e2e523b..6f3542333 100644 --- a/system/libraries/Xmlrpc.php +++ b/system/libraries/Xmlrpc.php @@ -25,14 +25,6 @@ * @filesource */ -if ( ! function_exists('xml_parser_create')) -{ - show_error('Your PHP installation does not support XML'); -} - - -// ------------------------------------------------------------------------ - /** * XML-RPC request handler class * @@ -42,6 +34,14 @@ if ( ! function_exists('xml_parser_create')) * @author EllisLab Dev Team * @link http://codeigniter.com/user_guide/libraries/xmlrpc.html */ + +if ( ! function_exists('xml_parser_create')) +{ + show_error('Your PHP installation does not support XML'); +} + +// ------------------------------------------------------------------------ + class CI_Xmlrpc { public $debug = FALSE; // Debugging on or off @@ -77,13 +77,17 @@ class CI_Xmlrpc { public $xss_clean = TRUE; - //------------------------------------- - // VALUES THAT MULTIPLE CLASSES NEED - //------------------------------------- + /** + * Constructor + * + * Initializes property default values + * + * @param array + * @return void + */ public function __construct($config = array()) { - $this->xmlrpcName = $this->xmlrpcName; $this->xmlrpc_backslash = chr(92).chr(92); // Types for info sent back and forth @@ -100,24 +104,24 @@ class CI_Xmlrpc { ); // Array of Valid Parents for Various XML-RPC elements - $this->valid_parents = array('BOOLEAN' => array('VALUE'), - 'I4' => array('VALUE'), - 'INT' => array('VALUE'), - 'STRING' => array('VALUE'), - 'DOUBLE' => array('VALUE'), - 'DATETIME.ISO8601' => array('VALUE'), - 'BASE64' => array('VALUE'), - 'ARRAY' => array('VALUE'), - 'STRUCT' => array('VALUE'), - 'PARAM' => array('PARAMS'), - 'METHODNAME' => array('METHODCALL'), - 'PARAMS' => array('METHODCALL', 'METHODRESPONSE'), - 'MEMBER' => array('STRUCT'), - 'NAME' => array('MEMBER'), - 'DATA' => array('ARRAY'), - 'FAULT' => array('METHODRESPONSE'), - 'VALUE' => array('MEMBER', 'DATA', 'PARAM', 'FAULT') - ); + $this->valid_parents = array('BOOLEAN' => array('VALUE'), + 'I4' => array('VALUE'), + 'INT' => array('VALUE'), + 'STRING' => array('VALUE'), + 'DOUBLE' => array('VALUE'), + 'DATETIME.ISO8601' => array('VALUE'), + 'BASE64' => array('VALUE'), + 'ARRAY' => array('VALUE'), + 'STRUCT' => array('VALUE'), + 'PARAM' => array('PARAMS'), + 'METHODNAME' => array('METHODCALL'), + 'PARAMS' => array('METHODCALL', 'METHODRESPONSE'), + 'MEMBER' => array('STRUCT'), + 'NAME' => array('MEMBER'), + 'DATA' => array('ARRAY'), + 'FAULT' => array('METHODRESPONSE'), + 'VALUE' => array('MEMBER', 'DATA', 'PARAM', 'FAULT') + ); // XML-RPC Responses @@ -136,14 +140,17 @@ class CI_Xmlrpc { $this->initialize($config); - log_message('debug', "XML-RPC Class Initialized"); + log_message('debug', 'XML-RPC Class Initialized'); } + // -------------------------------------------------------------------- - //------------------------------------- - // Initialize Prefs - //------------------------------------- - + /** + * Initialize + * + * @param array + * @return void + */ public function initialize($config = array()) { if (count($config) > 0) @@ -157,36 +164,43 @@ class CI_Xmlrpc { } } } - // END - //------------------------------------- - // Take URL and parse it - //------------------------------------- + // -------------------------------------------------------------------- - public function server($url, $port=80) + /** + * Parse server URL + * + * @param string url + * @param int port + * @return void + */ + public function server($url, $port = 80) { if (strpos($url, 'http') !== 0) { - $url = "http://".$url; + $url = 'http://'.$url; } $parts = parse_url($url); - $path = ( ! isset($parts['path'])) ? '/' : $parts['path']; + $path = isset($parts['path']) ? $parts['path'] : '/'; - if (isset($parts['query']) && $parts['query'] != '') + if ( ! empty($parts['query'])) { $path .= '?'.$parts['query']; } $this->client = new XML_RPC_Client($path, $parts['host'], $port); } - // END - //------------------------------------- - // Set Timeout - //------------------------------------- + // -------------------------------------------------------------------- + /** + * Set Timeout + * + * @param int seconds + * @return void + */ public function timeout($seconds = 5) { if ( ! is_null($this->client) && is_int($seconds)) @@ -194,27 +208,34 @@ class CI_Xmlrpc { $this->client->timeout = $seconds; } } - // END - //------------------------------------- - // Set Methods - //------------------------------------- + // -------------------------------------------------------------------- + /** + * Set Methods + * + * @param string method name + * @return void + */ public function method($function) { $this->method = $function; } - // END - //------------------------------------- - // Take Array of Data and Create Objects - //------------------------------------- + // -------------------------------------------------------------------- + /** + * Take Array of Data and Create Objects + * + * @param array + * @return void + */ public function request($incoming) { if ( ! is_array($incoming)) { // Send Error + return; } $this->data = array(); @@ -224,33 +245,39 @@ class CI_Xmlrpc { $this->data[$key] = $this->values_parsing($value); } } - // END - - //------------------------------------- - // Set Debug - //------------------------------------- + // -------------------------------------------------------------------- + /** + * Set Debug + * + * @param bool + * @return void + */ public function set_debug($flag = TRUE) { - $this->debug = ($flag == TRUE); + $this->debug = ($flag === TRUE); } - //------------------------------------- - // Values Parsing - //------------------------------------- + // -------------------------------------------------------------------- - public function values_parsing($value, $return = FALSE) + /** + * Values Parsing + * + * @param mixed + * @return object + */ + public function values_parsing($value) { if (is_array($value) && array_key_exists(0, $value)) { - if ( ! isset($value[1]) OR ( ! isset($this->xmlrpcTypes[$value[1]]))) + if ( ! isset($value[1], $this->xmlrpcTypes[$value[1]])) { $temp = new XML_RPC_Values($value[0], (is_array($value[0]) ? 'array' : 'string')); } else { - if (is_array($value[0]) && ($value[1] == 'struct' OR $value[1] == 'array')) + if (is_array($value[0]) && ($value[1] === 'struct' OR $value[1] === 'array')) { while (list($k) = each($value[0])) { @@ -268,16 +295,17 @@ class CI_Xmlrpc { return $temp; } - // END - - //------------------------------------- - // Sends XML-RPC Request - //------------------------------------- + // -------------------------------------------------------------------- + /** + * Sends XML-RPC Request + * + * @return bool + */ public function send_request() { - $this->message = new XML_RPC_Message($this->method,$this->data); + $this->message = new XML_RPC_Message($this->method, $this->data); $this->message->debug = $this->debug; if ( ! $this->result = $this->client->send($this->message) OR ! is_object($this->result->val)) @@ -289,55 +317,62 @@ class CI_Xmlrpc { $this->response = $this->result->decode(); return TRUE; } - // END - //------------------------------------- - // Returns Error - //------------------------------------- + // -------------------------------------------------------------------- + /** + * Returns Error + * + * @return string + */ public function display_error() { return $this->error; } - // END - //------------------------------------- - // Returns Remote Server Response - //------------------------------------- + // -------------------------------------------------------------------- + /** + * Returns Remote Server Response + * + * @return string + */ public function display_response() { return $this->response; } - // END - //------------------------------------- - // Sends an Error Message for Server Request - //------------------------------------- + // -------------------------------------------------------------------- + /** + * Sends an Error Message for Server Request + * + * @param int + * @param string + * @return object + */ public function send_error_message($number, $message) { return new XML_RPC_Response(0, $number, $message); } - // END + // -------------------------------------------------------------------- - //------------------------------------- - // Send Response for Server Request - //------------------------------------- - + /** + * Send Response for Server Request + * + * @param array + * @return object + */ public function send_response($response) { // $response should be array of values, which will be parsed // based on their data and type into a valid group of XML-RPC values return new XML_RPC_Response($this->values_parsing($response)); } - // END } // END XML_RPC Class - - /** * XML-RPC Client class * @@ -355,7 +390,15 @@ class XML_RPC_Client extends CI_Xmlrpc public $timeout = 5; public $no_multicall = FALSE; - public function __construct($path, $server, $port=80) + /** + * Constructor + * + * @param string + * @param object + * @param int + * @return void + */ + public function __construct($path, $server, $port = 80) { parent::__construct(); @@ -364,27 +407,41 @@ class XML_RPC_Client extends CI_Xmlrpc $this->path = $path; } + // -------------------------------------------------------------------- + + /** + * Send message + * + * @param mixed + * @return object + */ public function send($msg) { if (is_array($msg)) { // Multi-call disabled - $r = new XML_RPC_Response(0, $this->xmlrpcerr['multicall_recursion'],$this->xmlrpcstr['multicall_recursion']); - return $r; + return new XML_RPC_Response(0, $this->xmlrpcerr['multicall_recursion'], $this->xmlrpcstr['multicall_recursion']); } return $this->sendPayload($msg); } + // -------------------------------------------------------------------- + + /** + * Send payload + * + * @param object + * @return object + */ public function sendPayload($msg) { - $fp = @fsockopen($this->server, $this->port,$this->errno, $this->errstr, $this->timeout); + $fp = @fsockopen($this->server, $this->port,$this->errno, $this->errstring, $this->timeout); if ( ! is_resource($fp)) { error_log($this->xmlrpcstr['http_error']); - $r = new XML_RPC_Response(0, $this->xmlrpcerr['http_error'],$this->xmlrpcstr['http_error']); - return $r; + return new XML_RPC_Response(0, $this->xmlrpcerr['http_error'], $this->xmlrpcstr['http_error']); } if (empty($msg->payload)) @@ -394,27 +451,25 @@ class XML_RPC_Client extends CI_Xmlrpc } $r = "\r\n"; - $op = "POST {$this->path} HTTP/1.0$r" - . "Host: {$this->server}$r" - . "Content-Type: text/xml$r" - . "User-Agent: {$this->xmlrpcName}$r" - . "Content-Length: ".strlen($msg->payload)."$r$r" - . $msg->payload; - - - if ( ! fputs($fp, $op, strlen($op))) + $op = 'POST '.$this->path.' HTTP/1.0'.$r + .'Host: '.$this->server.$r + .'Content-Type: text/xml'.$r + .'User-Agent: '.$this->xmlrpcName.$r + .'Content-Length: '.strlen($msg->payload).$r.$r + .$msg->payload; + + if ( ! fwrite($fp, $op, strlen($op))) { error_log($this->xmlrpcstr['http_error']); - $r = new XML_RPC_Response(0, $this->xmlrpcerr['http_error'], $this->xmlrpcstr['http_error']); - return $r; + return new XML_RPC_Response(0, $this->xmlrpcerr['http_error'], $this->xmlrpcstr['http_error']); } + $resp = $msg->parseResponse($fp); fclose($fp); return $resp; } -} -// end class XML_RPC_Client +} // END XML_RPC_Client Class /** * XML-RPC Response class @@ -425,31 +480,34 @@ class XML_RPC_Client extends CI_Xmlrpc */ class XML_RPC_Response { - public $val = 0; - public $errno = 0; - public $errstr = ''; - public $headers = array(); - public $xss_clean = TRUE; - + public $val = 0; + public $errno = 0; + public $errstr = ''; + public $headers = array(); + public $xss_clean = TRUE; + + /** + * Constructor + * + * @param mixed + * @param int + * @param string + * @return void + */ public function __construct($val, $code = 0, $fstr = '') { - if ($code != 0) + if ($code !== 0) { // error $this->errno = $code; - if ( ! is_php('5.4')) - { - $this->errstr = htmlspecialchars($fstr, ENT_NOQUOTES, 'UTF-8'); - } - else - { - $this->errstr = htmlspecialchars($fstr, ENT_XML1 | ENT_NOQUOTES, 'UTF-8'); - } + $this->errstr = htmlspecialchars($fstr, + (is_php('5.4') ? ENT_XML1 | ENT_NOQUOTES : ENT_NOQUOTES), + 'UTF-8'); } - else if ( ! is_object($val)) + elseif ( ! is_object($val)) { // programmer error, not an object - error_log("Invalid type '" . gettype($val) . "' (value: $val) passed to XML_RPC_Response. Defaulting to empty value."); + error_log("Invalid type '".gettype($val)."' (value: ".$val.') passed to XML_RPC_Response. Defaulting to empty value.'); $this->val = new XML_RPC_Values(); } else @@ -458,43 +516,79 @@ class XML_RPC_Response } } + // -------------------------------------------------------------------- + + /** + * Fault code + * + * @return int + */ public function faultCode() { return $this->errno; } + // -------------------------------------------------------------------- + + /** + * Fault string + * + * @return string + */ public function faultString() { return $this->errstr; } + // -------------------------------------------------------------------- + + /** + * Value + * + * @return mixed + */ public function value() { return $this->val; } + // -------------------------------------------------------------------- + + /** + * Prepare response + * + * @return string xml + */ public function prepare_response() { return "<methodResponse>\n" - . ($this->errno - ? '<fault> + .($this->errno + ? '<fault> <value> <struct> <member> <name>faultCode</name> - <value><int>' . $this->errno . '</int></value> + <value><int>'.$this->errno.'</int></value> </member> <member> <name>faultString</name> - <value><string>' . $this->errstr . '</string></value> + <value><string>'.$this->errstr.'</string></value> </member> </struct> </value> </fault>' - : "<params>\n<param>\n".$this->val->serialize_class()."</param>\n</params>") - . "\n</methodResponse>"; + : "<params>\n<param>\n".$this->val->serialize_class()."</param>\n</params>") + ."\n</methodResponse>"; } + // -------------------------------------------------------------------- + + /** + * Decode + * + * @param mixed + * @return array + */ public function decode($array = FALSE) { $CI =& get_instance(); @@ -513,40 +607,40 @@ class XML_RPC_Response } } - $result = $array; + return $array; + } + + $result = $this->xmlrpc_decoder($this->val); + + if (is_array($result)) + { + $result = $this->decode($result); } else { - $result = $this->xmlrpc_decoder($this->val); - - if (is_array($result)) - { - $result = $this->decode($result); - } - else - { - $result = ($this->xss_clean) ? $CI->security->xss_clean($result) : $result; - } + $result = ($this->xss_clean) ? $CI->security->xss_clean($result) : $result; } return $result; } + // -------------------------------------------------------------------- - - //------------------------------------- - // XML-RPC Object to PHP Types - //------------------------------------- - + /** + * XML-RPC Object to PHP Types + * + * @param object + * @return array + */ public function xmlrpc_decoder($xmlrpc_val) { $kind = $xmlrpc_val->kindOf(); - if ($kind == 'scalar') + if ($kind === 'scalar') { return $xmlrpc_val->scalarval(); } - elseif ($kind == 'array') + elseif ($kind === 'array') { reset($xmlrpc_val->me); $b = current($xmlrpc_val->me); @@ -558,7 +652,7 @@ class XML_RPC_Response } return $arr; } - elseif ($kind == 'struct') + elseif ($kind === 'struct') { reset($xmlrpc_val->me['struct']); $arr = array(); @@ -571,25 +665,28 @@ class XML_RPC_Response } } + // -------------------------------------------------------------------- - //------------------------------------- - // ISO-8601 time to server or UTC time - //------------------------------------- - - public function iso8601_decode($time, $utc = 0) + /** + * ISO-8601 time to server or UTC time + * + * @param string + * @param bool + * @return int unix timestamp + */ + public function iso8601_decode($time, $utc = FALSE) { - // return a timet in the localtime, or UTC + // return a time in the localtime, or UTC $t = 0; if (preg_match('/([0-9]{4})([0-9]{2})([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})/', $time, $regs)) { - $fnc = ($utc == 1) ? 'gmmktime' : 'mktime'; + $fnc = ($utc === TRUE) ? 'gmmktime' : 'mktime'; $t = $fnc($regs[4], $regs[5], $regs[6], $regs[2], $regs[3], $regs[1]); } return $t; } -} -// End Response Class +} // END XML_RPC_Response Class /** * XML-RPC Message class @@ -602,10 +699,17 @@ class XML_RPC_Message extends CI_Xmlrpc { public $payload; public $method_name; - public $params = array(); - public $xh = array(); - - public function __construct($method, $pars=0) + public $params = array(); + public $xh = array(); + + /** + * Constructor + * + * @param string method name + * @param array + * @return void + */ + public function __construct($method, $pars = FALSE) { parent::__construct(); @@ -620,15 +724,18 @@ class XML_RPC_Message extends CI_Xmlrpc } } - //------------------------------------- - // Create Payload to Send - //------------------------------------- + // -------------------------------------------------------------------- + /** + * Create Payload to Send + * + * @return void + */ public function createPayload() { - $this->payload = "<?xml version=\"1.0\"?".">\r\n<methodCall>\r\n" - . '<methodName>'.$this->method_name."</methodName>\r\n" - . "<params>\r\n"; + $this->payload = '<?xml version="1.0"?'.">\r\n<methodCall>\r\n" + .'<methodName>'.$this->method_name."</methodName>\r\n" + ."<params>\r\n"; for ($i = 0, $c = count($this->params); $i < $c; $i++) { @@ -640,10 +747,14 @@ class XML_RPC_Message extends CI_Xmlrpc $this->payload .= "</params>\r\n</methodCall>\r\n"; } - //------------------------------------- - // Parse External XML-RPC Server's Response - //------------------------------------- + // -------------------------------------------------------------------- + /** + * Parse External XML-RPC Server's Response + * + * @param resource + * @return object + */ public function parseResponse($fp) { $data = ''; @@ -653,36 +764,24 @@ class XML_RPC_Message extends CI_Xmlrpc $data .= $datum; } - //------------------------------------- - // DISPLAY HTTP CONTENT for DEBUGGING - //------------------------------------- - + // Display HTTP content for debugging if ($this->debug === TRUE) { echo "<pre>---DATA---\n".htmlspecialchars($data)."\n---END DATA---\n\n</pre>"; } - //------------------------------------- - // Check for data - //------------------------------------- - + // Check for data if ($data === '') { error_log($this->xmlrpcstr['no_data']); - $r = new XML_RPC_Response(0, $this->xmlrpcerr['no_data'], $this->xmlrpcstr['no_data']); - return $r; + return new XML_RPC_Response(0, $this->xmlrpcerr['no_data'], $this->xmlrpcstr['no_data']); } - - //------------------------------------- - // Check for HTTP 200 Response - //------------------------------------- - + // Check for HTTP 200 Response if (strncmp($data, 'HTTP', 4) === 0 && ! preg_match('/^HTTP\/[0-9\.]+ 200 /', $data)) { - $errstr= substr($data, 0, strpos($data, "\n")-1); - $r = new XML_RPC_Response(0, $this->xmlrpcerr['http_error'], $this->xmlrpcstr['http_error']. ' (' . $errstr . ')'); - return $r; + $errstr = substr($data, 0, strpos($data, "\n")-1); + return new XML_RPC_Response(0, $this->xmlrpcerr['http_error'], $this->xmlrpcstr['http_error'].' ('.$errstr.')'); } //------------------------------------- @@ -692,25 +791,21 @@ class XML_RPC_Message extends CI_Xmlrpc $parser = xml_parser_create($this->xmlrpc_defencoding); $this->xh[$parser] = array( - 'isf' => 0, - 'ac' => '', - 'headers' => array(), - 'stack' => array(), - 'valuestack' => array(), - 'isf_reason' => 0 + 'isf' => 0, + 'ac' => '', + 'headers' => array(), + 'stack' => array(), + 'valuestack' => array(), + 'isf_reason' => 0 ); xml_set_object($parser, $this); - xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, true); + xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, TRUE); xml_set_element_handler($parser, 'open_tag', 'closing_tag'); xml_set_character_data_handler($parser, 'character_data'); //xml_set_default_handler($parser, 'default_handler'); - - //------------------------------------- - // GET HEADERS - //------------------------------------- - + // Get headers $lines = explode("\r\n", $data); while (($line = array_shift($lines))) { @@ -722,16 +817,12 @@ class XML_RPC_Message extends CI_Xmlrpc } $data = implode("\r\n", $lines); - - //------------------------------------- - // PARSE XML DATA - //------------------------------------- - + // Parse XML data if ( ! xml_parse($parser, $data, count($data))) { $errstr = sprintf('XML error: %s at line %d', - xml_error_string(xml_get_error_code($parser)), - xml_get_current_line_number($parser)); + xml_error_string(xml_get_error_code($parser)), + xml_get_current_line_number($parser)); //error_log($errstr); $r = new XML_RPC_Response(0, $this->xmlrpcerr['invalid_return'], $this->xmlrpcstr['invalid_return']); xml_parser_free($parser); @@ -739,10 +830,7 @@ class XML_RPC_Message extends CI_Xmlrpc } xml_parser_free($parser); - // --------------------------------------- - // Got Ourselves Some Badness, It Seems - // --------------------------------------- - + // Got ourselves some badness, it seems if ($this->xh[$parser]['isf'] > 1) { if ($this->debug === TRUE) @@ -750,29 +838,24 @@ class XML_RPC_Message extends CI_Xmlrpc echo "---Invalid Return---\n".$this->xh[$parser]['isf_reason']."---Invalid Return---\n\n"; } - $r = new XML_RPC_Response(0, $this->xmlrpcerr['invalid_return'],$this->xmlrpcstr['invalid_return'].' '.$this->xh[$parser]['isf_reason']); - return $r; + return new XML_RPC_Response(0, $this->xmlrpcerr['invalid_return'], $this->xmlrpcstr['invalid_return'].' '.$this->xh[$parser]['isf_reason']); } elseif ( ! is_object($this->xh[$parser]['value'])) { - $r = new XML_RPC_Response(0, $this->xmlrpcerr['invalid_return'],$this->xmlrpcstr['invalid_return'].' '.$this->xh[$parser]['isf_reason']); - return $r; + return new XML_RPC_Response(0, $this->xmlrpcerr['invalid_return'], $this->xmlrpcstr['invalid_return'].' '.$this->xh[$parser]['isf_reason']); } - //------------------------------------- - // DISPLAY XML CONTENT for DEBUGGING - //------------------------------------- - + // Display XML content for debugging if ($this->debug === TRUE) { - echo "<pre>"; + echo '<pre>'; if (count($this->xh[$parser]['headers'] > 0)) { echo "---HEADERS---\n"; foreach ($this->xh[$parser]['headers'] as $header) { - echo "$header\n"; + echo $header."\n"; } echo "---END HEADERS---\n\n"; } @@ -782,10 +865,7 @@ class XML_RPC_Message extends CI_Xmlrpc echo "\n---END PARSED---</pre>"; } - //------------------------------------- - // SEND RESPONSE - //------------------------------------- - + // Send response $v = $this->xh[$parser]['value']; if ($this->xh[$parser]['isf']) { @@ -793,7 +873,7 @@ class XML_RPC_Message extends CI_Xmlrpc $errstr_v = $v->me['struct']['faultString']; $errno = $errno_v->scalarval(); - if ($errno == 0) + if ($errno === 0) { // FAULT returned, errno needs to reflect that $errno = -1; @@ -810,6 +890,8 @@ class XML_RPC_Message extends CI_Xmlrpc return $r; } + // -------------------------------------------------------------------- + // ------------------------------------ // Begin Return Message Parsing section // ------------------------------------ @@ -824,63 +906,61 @@ class XML_RPC_Message extends CI_Xmlrpc // stack - array with parent tree of the xml element, // used to validate the nesting of elements - //------------------------------------- - // Start Element Handler - //------------------------------------- + // -------------------------------------------------------------------- - public function open_tag($the_parser, $name, $attrs) + /** + * Start Element Handler + * + * @param string + * @param string + * @return void + */ + public function open_tag($the_parser, $name) { // If invalid nesting, then return if ($this->xh[$the_parser]['isf'] > 1) return; // Evaluate and check for correct nesting of XML elements - - if (count($this->xh[$the_parser]['stack']) == 0) + if (count($this->xh[$the_parser]['stack']) === 0) { - if ($name != 'METHODRESPONSE' && $name != 'METHODCALL') + if ($name !== 'METHODRESPONSE' && $name !== 'METHODCALL') { $this->xh[$the_parser]['isf'] = 2; $this->xh[$the_parser]['isf_reason'] = 'Top level XML-RPC element is missing'; return; } } - else + // not top level element: see if parent is OK + elseif ( ! in_array($this->xh[$the_parser]['stack'][0], $this->valid_parents[$name], TRUE)) { - // not top level element: see if parent is OK - if ( ! in_array($this->xh[$the_parser]['stack'][0], $this->valid_parents[$name], TRUE)) - { - $this->xh[$the_parser]['isf'] = 2; - $this->xh[$the_parser]['isf_reason'] = "XML-RPC element $name cannot be child of ".$this->xh[$the_parser]['stack'][0]; - return; - } + $this->xh[$the_parser]['isf'] = 2; + $this->xh[$the_parser]['isf_reason'] = 'XML-RPC element $name cannot be child of '.$this->xh[$the_parser]['stack'][0]; + return; } - switch($name) + switch ($name) { case 'STRUCT': case 'ARRAY': // Creates array for child elements - - $cur_val = array('value' => array(), - 'type' => $name); - + $cur_val = array('value' => array(), 'type' => $name); array_unshift($this->xh[$the_parser]['valuestack'], $cur_val); - break; + break; case 'METHODNAME': case 'NAME': $this->xh[$the_parser]['ac'] = ''; - break; + break; case 'FAULT': $this->xh[$the_parser]['isf'] = 1; - break; + break; case 'PARAM': $this->xh[$the_parser]['value'] = NULL; - break; + break; case 'VALUE': $this->xh[$the_parser]['vt'] = 'value'; $this->xh[$the_parser]['ac'] = ''; $this->xh[$the_parser]['lv'] = 1; - break; + break; case 'I4': case 'INT': case 'STRING': @@ -888,70 +968,74 @@ class XML_RPC_Message extends CI_Xmlrpc case 'DOUBLE': case 'DATETIME.ISO8601': case 'BASE64': - if ($this->xh[$the_parser]['vt'] != 'value') + if ($this->xh[$the_parser]['vt'] !== 'value') { //two data elements inside a value: an error occurred! $this->xh[$the_parser]['isf'] = 2; - $this->xh[$the_parser]['isf_reason'] = "'Twas a $name element following a ".$this->xh[$the_parser]['vt']." element inside a single value"; + $this->xh[$the_parser]['isf_reason'] = "'Twas a ".$name.' element following a ' + .$this->xh[$the_parser]['vt'].' element inside a single value'; return; } $this->xh[$the_parser]['ac'] = ''; - break; + break; case 'MEMBER': // Set name of <member> to nothing to prevent errors later if no <name> is found $this->xh[$the_parser]['valuestack'][0]['name'] = ''; // Set NULL value to check to see if value passed for this param/member $this->xh[$the_parser]['value'] = NULL; - break; + break; case 'DATA': case 'METHODCALL': case 'METHODRESPONSE': case 'PARAMS': // valid elements that add little to processing - break; + break; default: /// An Invalid Element is Found, so we have trouble $this->xh[$the_parser]['isf'] = 2; - $this->xh[$the_parser]['isf_reason'] = "Invalid XML-RPC element found: $name"; - break; + $this->xh[$the_parser]['isf_reason'] = 'Invalid XML-RPC element found: '.$name; + break; } // Add current element name to stack, to allow validation of nesting array_unshift($this->xh[$the_parser]['stack'], $name); - if ($name != 'VALUE') $this->xh[$the_parser]['lv'] = 0; + $name === 'VALUE' OR $this->xh[$the_parser]['lv'] = 0; } - // END - - //------------------------------------- - // End Element Handler - //------------------------------------- + // -------------------------------------------------------------------- + /** + * End Element Handler + * + * @param string + * @param string + * @return void + */ public function closing_tag($the_parser, $name) { if ($this->xh[$the_parser]['isf'] > 1) return; // Remove current element from stack and set variable // NOTE: If the XML validates, then we do not have to worry about - // the opening and closing of elements. Nesting is checked on the opening + // the opening and closing of elements. Nesting is checked on the opening // tag so we be safe there as well. $curr_elem = array_shift($this->xh[$the_parser]['stack']); - switch($name) + switch ($name) { case 'STRUCT': case 'ARRAY': $cur_val = array_shift($this->xh[$the_parser]['valuestack']); - $this->xh[$the_parser]['value'] = ( ! isset($cur_val['values'])) ? array() : $cur_val['values']; + $this->xh[$the_parser]['value'] = isset($cur_val['values']) ? $cur_val['values'] : array(); $this->xh[$the_parser]['vt'] = strtolower($name); - break; + break; case 'NAME': $this->xh[$the_parser]['valuestack'][0]['name'] = $this->xh[$the_parser]['ac']; - break; + break; case 'BOOLEAN': case 'I4': case 'INT': @@ -961,60 +1045,43 @@ class XML_RPC_Message extends CI_Xmlrpc case 'BASE64': $this->xh[$the_parser]['vt'] = strtolower($name); - if ($name == 'STRING') + if ($name === 'STRING') { $this->xh[$the_parser]['value'] = $this->xh[$the_parser]['ac']; } - elseif ($name=='DATETIME.ISO8601') + elseif ($name === 'DATETIME.ISO8601') { $this->xh[$the_parser]['vt'] = $this->xmlrpcDateTime; $this->xh[$the_parser]['value'] = $this->xh[$the_parser]['ac']; } - elseif ($name=='BASE64') + elseif ($name === 'BASE64') { $this->xh[$the_parser]['value'] = base64_decode($this->xh[$the_parser]['ac']); } - elseif ($name=='BOOLEAN') + elseif ($name === 'BOOLEAN') { // Translated BOOLEAN values to TRUE AND FALSE - if ($this->xh[$the_parser]['ac'] == '1') - { - $this->xh[$the_parser]['value'] = TRUE; - } - else - { - $this->xh[$the_parser]['value'] = FALSE; - } + $this->xh[$the_parser]['value'] = (bool) $this->xh[$the_parser]['ac']; } elseif ($name=='DOUBLE') { // we have a DOUBLE // we must check that only 0123456789-.<space> are characters here - if ( ! preg_match('/^[+-]?[eE0-9\t \.]+$/', $this->xh[$the_parser]['ac'])) - { - $this->xh[$the_parser]['value'] = 'ERROR_NON_NUMERIC_FOUND'; - } - else - { - $this->xh[$the_parser]['value'] = (double)$this->xh[$the_parser]['ac']; - } + $this->xh[$the_parser]['value'] = preg_match('/^[+-]?[eE0-9\t \.]+$/', $this->xh[$the_parser]['ac']) + ? (float) $this->xh[$the_parser]['ac'] + : 'ERROR_NON_NUMERIC_FOUND'; } else { // we have an I4/INT // we must check that only 0123456789-<space> are characters here - if ( ! preg_match('/^[+-]?[0-9\t ]+$/', $this->xh[$the_parser]['ac'])) - { - $this->xh[$the_parser]['value'] = 'ERROR_NON_NUMERIC_FOUND'; - } - else - { - $this->xh[$the_parser]['value'] = (int)$this->xh[$the_parser]['ac']; - } + $this->xh[$the_parser]['value'] = preg_match('/^[+-]?[0-9\t ]+$/', $this->xh[$the_parser]['ac']) + ? (int) $this->xh[$the_parser]['ac'] + : 'ERROR_NON_NUMERIC_FOUND'; } $this->xh[$the_parser]['ac'] = ''; $this->xh[$the_parser]['lv'] = 3; // indicate we've found a value - break; + break; case 'VALUE': // This if() detects if no scalar was inside <VALUE></VALUE> if ($this->xh[$the_parser]['vt']=='value') @@ -1026,7 +1093,7 @@ class XML_RPC_Message extends CI_Xmlrpc // build the XML-RPC value out of the data received, and substitute it $temp = new XML_RPC_Values($this->xh[$the_parser]['value'], $this->xh[$the_parser]['vt']); - if (count($this->xh[$the_parser]['valuestack']) && $this->xh[$the_parser]['valuestack'][0]['type'] == 'ARRAY') + if (count($this->xh[$the_parser]['valuestack']) && $this->xh[$the_parser]['valuestack'][0]['type'] === 'ARRAY') { // Array $this->xh[$the_parser]['valuestack'][0]['values'][] = $temp; @@ -1036,57 +1103,62 @@ class XML_RPC_Message extends CI_Xmlrpc // Struct $this->xh[$the_parser]['value'] = $temp; } - break; + break; case 'MEMBER': - $this->xh[$the_parser]['ac']=''; + $this->xh[$the_parser]['ac'] = ''; // If value add to array in the stack for the last element built if ($this->xh[$the_parser]['value']) { $this->xh[$the_parser]['valuestack'][0]['values'][$this->xh[$the_parser]['valuestack'][0]['name']] = $this->xh[$the_parser]['value']; } - break; + break; case 'DATA': - $this->xh[$the_parser]['ac']=''; - break; + $this->xh[$the_parser]['ac'] = ''; + break; case 'PARAM': if ($this->xh[$the_parser]['value']) { $this->xh[$the_parser]['params'][] = $this->xh[$the_parser]['value']; } - break; + break; case 'METHODNAME': $this->xh[$the_parser]['method'] = ltrim($this->xh[$the_parser]['ac']); - break; + break; case 'PARAMS': case 'FAULT': case 'METHODCALL': case 'METHORESPONSE': // We're all good kids with nuthin' to do - break; + break; default: - // End of an Invalid Element. Taken care of during the opening tag though - break; + // End of an Invalid Element. Taken care of during the opening tag though + break; } } - //------------------------------------- - // Parses Character Data - //------------------------------------- + // -------------------------------------------------------------------- + /** + * Parse character data + * + * @param string + * @param string + * @return void + */ public function character_data($the_parser, $data) { if ($this->xh[$the_parser]['isf'] > 1) return; // XML Fault found already // If a value has not been found - if ($this->xh[$the_parser]['lv'] != 3) + if ($this->xh[$the_parser]['lv'] !== 3) { - if ($this->xh[$the_parser]['lv'] == 1) + if ($this->xh[$the_parser]['lv'] === 1) { $this->xh[$the_parser]['lv'] = 2; // Found a value } - if ( ! @isset($this->xh[$the_parser]['ac'])) + if ( ! isset($this->xh[$the_parser]['ac'])) { $this->xh[$the_parser]['ac'] = ''; } @@ -1095,12 +1167,27 @@ class XML_RPC_Message extends CI_Xmlrpc } } + // -------------------------------------------------------------------- + /** + * Add parameter + * + * @param mixed + * @return void + */ public function addParam($par) { $this->params[] = $par; } + // -------------------------------------------------------------------- + + /** + * Output parameters + * + * @param array + * @return array + */ public function output_parameters($array = FALSE) { $CI =& get_instance(); @@ -1117,57 +1204,62 @@ class XML_RPC_Message extends CI_Xmlrpc { // 'bits' is for the MetaWeblog API image bits // @todo - this needs to be made more general purpose - $array[$key] = ($key == 'bits' OR $this->xss_clean == FALSE) ? $array[$key] : $CI->security->xss_clean($array[$key]); + $array[$key] = ($key === 'bits' OR $this->xss_clean === FALSE) ? $array[$key] : $CI->security->xss_clean($array[$key]); } } - $parameters = $array; + return $array; } - else + + $parameters = array(); + + for ($i = 0, $c = count($this->params); $i < $c; $i++) { - $parameters = array(); + $a_param = $this->decode_message($this->params[$i]); - for ($i = 0, $c = count($this->params); $i < $c; $i++) + if (is_array($a_param)) { - $a_param = $this->decode_message($this->params[$i]); - - if (is_array($a_param)) - { - $parameters[] = $this->output_parameters($a_param); - } - else - { - $parameters[] = ($this->xss_clean) ? $CI->security->xss_clean($a_param) : $a_param; - } + $parameters[] = $this->output_parameters($a_param); + } + else + { + $parameters[] = ($this->xss_clean) ? $CI->security->xss_clean($a_param) : $a_param; } } return $parameters; } + // -------------------------------------------------------------------- + /** + * Decode message + * + * @param object + * @return mixed + */ public function decode_message($param) { $kind = $param->kindOf(); - if ($kind == 'scalar') + if ($kind === 'scalar') { return $param->scalarval(); } - elseif ($kind == 'array') + elseif ($kind === 'array') { reset($param->me); $b = current($param->me); $arr = array(); - for($i = 0, $c = count($b); $i < $c; $i++) + for ($i = 0, $c = count($b); $i < $c; $i++) { $arr[] = $this->decode_message($param->me['array'][$i]); } return $arr; } - elseif ($kind == 'struct') + elseif ($kind === 'struct') { reset($param->me['struct']); $arr = array(); @@ -1181,8 +1273,7 @@ class XML_RPC_Message extends CI_Xmlrpc } } -} -// End XML_RPC_Messages class +} // END XML_RPC_Message Class /** * XML-RPC Values class @@ -1196,51 +1287,67 @@ class XML_RPC_Values extends CI_Xmlrpc public $me = array(); public $mytype = 0; + /** + * Constructor + * + * @param mixed + * @param string + * @return void + */ public function __construct($val = -1, $type = '') { parent::__construct(); - if ($val != -1 OR $type != '') + if ($val !== -1 OR $type !== '') { - $type = $type == '' ? 'string' : $type; + $type = $type === '' ? 'string' : $type; - if ($this->xmlrpcTypes[$type] == 1) + if ($this->xmlrpcTypes[$type] === 1) { $this->addScalar($val,$type); } - elseif ($this->xmlrpcTypes[$type] == 2) + elseif ($this->xmlrpcTypes[$type] === 2) { $this->addArray($val); } - elseif ($this->xmlrpcTypes[$type] == 3) + elseif ($this->xmlrpcTypes[$type] === 3) { $this->addStruct($val); } } } + // -------------------------------------------------------------------- + + /** + * Add scalar value + * + * @param scalar + * @param string + * @return int + */ public function addScalar($val, $type = 'string') { $typeof = $this->xmlrpcTypes[$type]; - if ($this->mytype==1) + if ($this->mytype === 1) { echo '<strong>XML_RPC_Values</strong>: scalar can have only one value<br />'; return 0; } - if ($typeof != 1) + if ($typeof !== 1) { echo '<strong>XML_RPC_Values</strong>: not a scalar type (${typeof})<br />'; return 0; } - if ($type == $this->xmlrpcBoolean) + if ($type === $this->xmlrpcBoolean) { - $val = (strcasecmp($val,'true') === 0 OR $val == 1 OR ($val == true && strcasecmp($val, 'false'))) ? 1 : 0; + $val = (int) (strcasecmp($val,'true') === 0 OR $val === 1 OR ($val === TRUE && strcasecmp($val, 'false'))); } - if ($this->mytype == 2) + if ($this->mytype === 2) { // adding to an array here $ar = $this->me['array']; @@ -1253,12 +1360,21 @@ class XML_RPC_Values extends CI_Xmlrpc $this->me[$type] = $val; $this->mytype = $typeof; } + return 1; } + // -------------------------------------------------------------------- + + /** + * Add array value + * + * @param array + * @return int + */ public function addArray($vals) { - if ($this->mytype != 0) + if ($this->mytype !== 0) { echo '<strong>XML_RPC_Values</strong>: already initialized as a [' . $this->kindOf() . ']<br />'; return 0; @@ -1269,9 +1385,17 @@ class XML_RPC_Values extends CI_Xmlrpc return 1; } + // -------------------------------------------------------------------- + + /** + * Add struct value + * + * @param object + * @return int + */ public function addStruct($vals) { - if ($this->mytype != 0) + if ($this->mytype !== 0) { echo '<strong>XML_RPC_Values</strong>: already initialized as a [' . $this->kindOf() . ']<br />'; return 0; @@ -1281,29 +1405,37 @@ class XML_RPC_Values extends CI_Xmlrpc return 1; } + // -------------------------------------------------------------------- + + /** + * Get value type + * + * @return string + */ public function kindOf() { - switch($this->mytype) + switch ($this->mytype) { - case 3: - return 'struct'; - break; - case 2: - return 'array'; - break; - case 1: - return 'scalar'; - break; - default: - return 'undef'; + case 3: return 'struct'; + case 2: return 'array'; + case 1: return 'scalar'; + default: return 'undef'; } } + // -------------------------------------------------------------------- + + /** + * Serialize data + * + * @param string + * @param mixed + */ public function serializedata($typ, $val) { $rs = ''; - switch($this->xmlrpcTypes[$typ]) + switch ($this->xmlrpcTypes[$typ]) { case 3: // struct @@ -1314,11 +1446,11 @@ class XML_RPC_Values extends CI_Xmlrpc $rs .= "<member>\n<name>{$key2}</name>\n".$this->serializeval($val2)."</member>\n"; } $rs .= '</struct>'; - break; + break; case 2: // array $rs .= "<array>\n<data>\n"; - for($i = 0, $c = count($val); $i < $c; $i++) + for ($i = 0, $c = count($val); $i < $c; $i++) { $rs .= $this->serializeval($val[$i]); } @@ -1329,29 +1461,45 @@ class XML_RPC_Values extends CI_Xmlrpc switch ($typ) { case $this->xmlrpcBase64: - $rs .= "<{$typ}>" . base64_encode((string)$val) . "</{$typ}>\n"; - break; + $rs .= '<'.$typ.'>'.base64_encode( (string) $val).'</'.$typ.">\n"; + break; case $this->xmlrpcBoolean: - $rs .= "<{$typ}>" . ((bool)$val ? '1' : '0') . "</{$typ}>\n"; - break; + $rs .= '<'.$typ.'>'.( (bool) $val ? '1' : '0').'</'.$typ.">\n"; + break; case $this->xmlrpcString: - $rs .= "<{$typ}>" . htmlspecialchars((string)$val). "</{$typ}>\n"; - break; + $rs .= '<'.$typ.'>'.htmlspecialchars( (string) $val).'</'.$typ.">\n"; + break; default: - $rs .= "<{$typ}>{$val}</{$typ}>\n"; - break; + $rs .= '<'.$typ.'>'.$val.'</'.$typ.">\n"; + break; } default: - break; + break; } + return $rs; } + // -------------------------------------------------------------------- + + /** + * Serialize class + * + * @return string + */ public function serialize_class() { return $this->serializeval($this); } + // -------------------------------------------------------------------- + + /** + * Serialize value + * + * @param object + * @return string + */ public function serializeval($o) { $ar = $o->me; @@ -1361,26 +1509,35 @@ class XML_RPC_Values extends CI_Xmlrpc return "<value>\n".$this->serializedata($typ, $val)."</value>\n"; } + // -------------------------------------------------------------------- + + /** + * Scalar value + * + * @return mixed + */ public function scalarval() { reset($this->me); return current($this->me); } - - //------------------------------------- - // Encode time in ISO-8601 form. - //------------------------------------- - - // Useful for sending time in XML-RPC - - public function iso8601_encode($time, $utc = 0) + // -------------------------------------------------------------------- + + /** + * Encode time in ISO-8601 form. + * Useful for sending time in XML-RPC + * + * @param int unix timestamp + * @param bool + * @return string + */ + public function iso8601_encode($time, $utc = FALSE) { return ($utc) ? strftime('%Y%m%dT%H:%i:%s', $time) : gmstrftime('%Y%m%dT%H:%i:%s', $time); } -} -// END XML_RPC_Values Class +} // END XML_RPC_Values Class /* End of file Xmlrpc.php */ -/* Location: ./system/libraries/Xmlrpc.php */ +/* Location: ./system/libraries/Xmlrpc.php */
\ No newline at end of file diff --git a/system/libraries/Xmlrpcs.php b/system/libraries/Xmlrpcs.php index 6d270c2ea..be930b0f9 100644 --- a/system/libraries/Xmlrpcs.php +++ b/system/libraries/Xmlrpcs.php @@ -48,12 +48,40 @@ if ( ! class_exists('CI_Xmlrpc')) */ class CI_Xmlrpcs extends CI_Xmlrpc { - public $methods = array(); //array of methods mapped to function names and signatures - public $debug_msg = ''; // Debug Message - public $system_methods = array(); // XML RPC Server methods - public $controller_obj; - public $object = FALSE; + /** + * array of methods mapped to function names and signatures + * + * @var array + */ + public $methods = array(); + + /** + * Debug Message + * + * @var string + */ + public $debug_msg = ''; + /** + * XML RPC Server methods + * + * @var array + */ + public $system_methods = array(); + + /** + * Configuration object + * + * @var object + */ + public $object = FALSE; + + /** + * Initialize XMLRPC class + * + * @param array $config + * @return void + */ public function __construct($config = array()) { parent::__construct(); @@ -180,7 +208,7 @@ class CI_Xmlrpcs extends CI_Xmlrpc // Get Data //------------------------------------- - if ($data == '') + if ($data === '') { $data = $HTTP_RAW_POST_DATA; } @@ -277,7 +305,7 @@ class CI_Xmlrpcs extends CI_Xmlrpc // Check to see if it is a system call $system_call = (strncmp($methName, 'system', 5) === 0); - if ($this->xss_clean == FALSE) + if ($this->xss_clean === FALSE) { $m->xss_clean = FALSE; } @@ -296,7 +324,7 @@ class CI_Xmlrpcs extends CI_Xmlrpc //------------------------------------- $method_parts = explode('.', $this->methods[$methName]['function']); - $objectCall = (isset($method_parts[1]) && $method_parts[1] != ''); + $objectCall = (isset($method_parts[1]) && $method_parts[1] !== ''); if ($system_call === TRUE) { @@ -328,9 +356,9 @@ class CI_Xmlrpcs extends CI_Xmlrpc for ($n = 0, $mc = count($m->params); $n < $mc; $n++) { $p = $m->params[$n]; - $pt = ($p->kindOf() == 'scalar') ? $p->scalarval() : $p->kindOf(); + $pt = ($p->kindOf() === 'scalar') ? $p->scalarval() : $p->kindOf(); - if ($pt != $current_sig[$n+1]) + if ($pt !== $current_sig[$n+1]) { $pno = $n+1; $wanted = $current_sig[$n+1]; @@ -499,7 +527,7 @@ class CI_Xmlrpcs extends CI_Xmlrpc $attempt = $this->_execute($m); - if ($attempt->faultCode() != 0) + if ($attempt->faultCode() !== 0) { return $attempt; } @@ -539,7 +567,7 @@ class CI_Xmlrpcs extends CI_Xmlrpc */ public function do_multicall($call) { - if ($call->kindOf() != 'struct') + if ($call->kindOf() !== 'struct') { return $this->multicall_error('notstruct'); } @@ -549,13 +577,13 @@ class CI_Xmlrpcs extends CI_Xmlrpc } list($scalar_type,$scalar_value)=each($methName->me); - $scalar_type = $scalar_type == $this->xmlrpcI4 ? $this->xmlrpcInt : $scalar_type; + $scalar_type = $scalar_type === $this->xmlrpcI4 ? $this->xmlrpcInt : $scalar_type; - if ($methName->kindOf() != 'scalar' OR $scalar_type != 'string') + if ($methName->kindOf() !== 'scalar' OR $scalar_type !== 'string') { return $this->multicall_error('notstring'); } - elseif ($scalar_value == 'system.multicall') + elseif ($scalar_value === 'system.multicall') { return $this->multicall_error('recursion'); } @@ -563,7 +591,7 @@ class CI_Xmlrpcs extends CI_Xmlrpc { return $this->multicall_error('noparams'); } - elseif ($params->kindOf() != 'array') + elseif ($params->kindOf() !== 'array') { return $this->multicall_error('notarray'); } @@ -578,7 +606,7 @@ class CI_Xmlrpcs extends CI_Xmlrpc $result = $this->_execute($msg); - if ($result->faultCode() != 0) + if ($result->faultCode() !== 0) { return $this->multicall_error($result); } diff --git a/system/libraries/Zip.php b/system/libraries/Zip.php index e91e2a2ff..e0dc637ad 100644 --- a/system/libraries/Zip.php +++ b/system/libraries/Zip.php @@ -42,13 +42,53 @@ */ class CI_Zip { + /** + * Zip data in string form + * + * @var string + */ public $zipdata = ''; + + /** + * Zip data for a directory in string form + * + * @var string + */ public $directory = ''; + + /** + * Number of files/folder in zip file + * + * @var int + */ public $entries = 0; + + /** + * Number of files in zip + * + * @var int + */ public $file_num = 0; + + /** + * relative offset of local header + * + * @var int + */ public $offset = 0; + + /** + * Reference to time at init + * + * @var int + */ public $now; + /** + * Initialize zip compression class + * + * @return void + */ public function __construct() { $this->now = time(); @@ -279,7 +319,7 @@ class CI_Zip { */ public function read_dir($path, $preserve_filepath = TRUE, $root_path = NULL) { - $path = rtrim($path, '/\\').'/'; + $path = rtrim($path, '/\\').DIRECTORY_SEPARATOR; if ( ! $fp = @opendir($path)) { return FALSE; @@ -288,7 +328,7 @@ class CI_Zip { // Set the original directory root for child dir's to use as relative if ($root_path === NULL) { - $root_path = dirname($path).'/'; + $root_path = dirname($path).DIRECTORY_SEPARATOR; } while (FALSE !== ($file = readdir($fp))) @@ -300,11 +340,11 @@ class CI_Zip { if (@is_dir($path.$file)) { - $this->read_dir($path.$file.'/', $preserve_filepath, $root_path); + $this->read_dir($path.$file.DIRECTORY_SEPARATOR, $preserve_filepath, $root_path); } elseif (FALSE !== ($data = file_get_contents($path.$file))) { - $name = str_replace('\\', '/', $path); + $name = str_replace(array('\\', '/'), DIRECTORY_SEPARATOR, $path); if ($preserve_filepath === FALSE) { $name = str_replace($root_path, '', $name); diff --git a/system/libraries/javascript/Jquery.php b/system/libraries/javascript/Jquery.php index f30d7c639..44c16b578 100644 --- a/system/libraries/javascript/Jquery.php +++ b/system/libraries/javascript/Jquery.php @@ -25,8 +25,6 @@ * @filesource */ -// ------------------------------------------------------------------------ - /** * Jquery Class * @@ -57,7 +55,7 @@ class CI_Jquery extends CI_Javascript { $this->script(); } - log_message('debug', "Jquery Class Initialized"); + log_message('debug', 'Jquery Class Initialized'); } // -------------------------------------------------------------------- @@ -115,7 +113,7 @@ class CI_Jquery extends CI_Javascript { if ($ret_false) { - $js[] = "return false;"; + $js[] = 'return false;'; } return $this->_add_event($element, $js, 'click'); @@ -183,7 +181,7 @@ class CI_Jquery extends CI_Javascript { */ protected function _hover($element = 'this', $over, $out) { - $event = "\n\t$(" . $this->_prep_element($element) . ").hover(\n\t\tfunction()\n\t\t{\n\t\t\t{$over}\n\t\t}, \n\t\tfunction()\n\t\t{\n\t\t\t{$out}\n\t\t});\n"; + $event = "\n\t$(".$this->_prep_element($element).").hover(\n\t\tfunction()\n\t\t{\n\t\t\t{$over}\n\t\t}, \n\t\tfunction()\n\t\t{\n\t\t\t{$out}\n\t\t});\n"; $this->jquery_code_for_compile[] = $event; @@ -322,7 +320,7 @@ class CI_Jquery extends CI_Javascript { foreach ($array_js as $js) { - $this->jquery_code_for_compile[] = "\t$js\n"; + $this->jquery_code_for_compile[] = "\t".$js."\n"; } } @@ -389,7 +387,7 @@ class CI_Jquery extends CI_Javascript { protected function _addClass($element = 'this', $class='') { $element = $this->_prep_element($element); - return "$({$element}).addClass(\"$class\");"; + return '$('.$element.').addClass("'.$class.'");'; } // -------------------------------------------------------------------- @@ -411,24 +409,24 @@ class CI_Jquery extends CI_Javascript { $animations = "\t\t\t"; - foreach ($params as $param=>$value) + foreach ($params as $param => $value) { - $animations .= $param.': \''.$value.'\', '; + $animations .= $param.": '".$value."', "; } $animations = substr($animations, 0, -2); // remove the last ", " - if ($speed != '') + if ($speed !== '') { $speed = ', '.$speed; } - if ($extra != '') + if ($extra !== '') { $extra = ', '.$extra; } - return "$({$element}).animate({\n$animations\n\t\t}".$speed.$extra.");"; + return "$({$element}).animate({\n$animations\n\t\t}".$speed.$extra.');'; } // -------------------------------------------------------------------- @@ -448,7 +446,7 @@ class CI_Jquery extends CI_Javascript { $element = $this->_prep_element($element); $speed = $this->_validate_speed($speed); - if ($callback != '') + if ($callback !== '') { $callback = ", function(){\n{$callback}\n}"; } @@ -473,12 +471,12 @@ class CI_Jquery extends CI_Javascript { $element = $this->_prep_element($element); $speed = $this->_validate_speed($speed); - if ($callback != '') + if ($callback !== '') { $callback = ", function(){\n{$callback}\n}"; } - return "$({$element}).fadeOut({$speed}{$callback});"; + return '$('.$element.').fadeOut('.$speed.$callback.');'; } // -------------------------------------------------------------------- @@ -498,7 +496,7 @@ class CI_Jquery extends CI_Javascript { $element = $this->_prep_element($element); $speed = $this->_validate_speed($speed); - if ($callback != '') + if ($callback !== '') { $callback = ", function(){\n{$callback}\n}"; } @@ -519,7 +517,7 @@ class CI_Jquery extends CI_Javascript { protected function _removeClass($element = 'this', $class='') { $element = $this->_prep_element($element); - return "$({$element}).removeClass(\"$class\");"; + return '$('.$element.').removeClass("'.$class.'");'; } // -------------------------------------------------------------------- @@ -539,12 +537,12 @@ class CI_Jquery extends CI_Javascript { $element = $this->_prep_element($element); $speed = $this->_validate_speed($speed); - if ($callback != '') + if ($callback !== '') { $callback = ", function(){\n{$callback}\n}"; } - return "$({$element}).slideUp({$speed}{$callback});"; + return '$('.$element.').slideUp('.$speed.$callback.');'; } // -------------------------------------------------------------------- @@ -564,12 +562,12 @@ class CI_Jquery extends CI_Javascript { $element = $this->_prep_element($element); $speed = $this->_validate_speed($speed); - if ($callback != '') + if ($callback !== '') { $callback = ", function(){\n{$callback}\n}"; } - return "$({$element}).slideDown({$speed}{$callback});"; + return '$('.$element.').slideDown('.$speed.$callback.');'; } // -------------------------------------------------------------------- @@ -589,12 +587,12 @@ class CI_Jquery extends CI_Javascript { $element = $this->_prep_element($element); $speed = $this->_validate_speed($speed); - if ($callback != '') + if ($callback !== '') { $callback = ", function(){\n{$callback}\n}"; } - return "$({$element}).slideToggle({$speed}{$callback});"; + return '$('.$element.').slideToggle('.$speed.$callback.');'; } // -------------------------------------------------------------------- @@ -610,7 +608,7 @@ class CI_Jquery extends CI_Javascript { protected function _toggle($element = 'this') { $element = $this->_prep_element($element); - return "$({$element}).toggle();"; + return '$('.$element.').toggle();'; } // -------------------------------------------------------------------- @@ -626,7 +624,7 @@ class CI_Jquery extends CI_Javascript { protected function _toggleClass($element = 'this', $class='') { $element = $this->_prep_element($element); - return "$({$element}).toggleClass(\"$class\");"; + return '$('.$element.').toggleClass("'.$class.'");'; } // -------------------------------------------------------------------- @@ -646,12 +644,12 @@ class CI_Jquery extends CI_Javascript { $element = $this->_prep_element($element); $speed = $this->_validate_speed($speed); - if ($callback != '') + if ($callback !== '') { $callback = ", function(){\n{$callback}\n}"; } - return "$({$element}).show({$speed}{$callback});"; + return '$('.$element.').show('.$speed.$callback.');'; } // -------------------------------------------------------------------- @@ -674,24 +672,24 @@ class CI_Jquery extends CI_Javascript { $controller = (strpos('://', $controller) === FALSE) ? $controller : $this->CI->config->site_url($controller); // ajaxStart and ajaxStop are better choices here... but this is a stop gap - if ($this->CI->config->item('javascript_ajax_img') == '') + if ($this->CI->config->item('javascript_ajax_img') === '') { - $loading_notifier = "Loading..."; + $loading_notifier = 'Loading...'; } else { - $loading_notifier = '<img src=\''.$this->CI->config->slash_item('base_url').$this->CI->config->item('javascript_ajax_img').'\' alt=\'Loading\' />'; + $loading_notifier = '<img src="'.$this->CI->config->slash_item('base_url').$this->CI->config->item('javascript_ajax_img').'" alt="Loading" />'; } - $updater = "$($container).empty();\n" // anything that was in... get it out - . "\t\t$($container).prepend(\"$loading_notifier\");\n"; // to replace with an image + $updater = '$('.$container.").empty();\n" // anything that was in... get it out + ."\t\t$(".$container.').prepend("'.$loading_notifier."\");\n"; // to replace with an image $request_options = ''; - if ($options != '') + if ($options !== '') { $request_options .= ', {' - . (is_array($options) ? "'".implode("', '", $options)."'" : "'".str_replace(":", "':'", $options)."'") - . '}'; + .(is_array($options) ? "'".implode("', '", $options)."'" : "'".str_replace(':', "':'", $options)."'") + .'}'; } return $updater."\t\t$($container).load('$controller'$request_options);"; @@ -711,12 +709,12 @@ class CI_Jquery extends CI_Javascript { */ protected function _zebraTables($class = '', $odd = 'odd', $hover = '') { - $class = ($class != '') ? '.'.$class : ''; + $class = ($class !== '') ? '.'.$class : ''; $zebra = "\t\$(\"table{$class} tbody tr:nth-child(even)\").addClass(\"{$odd}\");"; $this->jquery_code_for_compile[] = $zebra; - if ($hover != '') + if ($hover !== '') { $hover = $this->hover("table{$class} tbody tr", "$(this).addClass('hover');", "$(this).removeClass('hover');"); } @@ -741,12 +739,12 @@ class CI_Jquery extends CI_Javascript { // may want to make this configurable down the road $corner_location = '/plugins/jquery.corner.js'; - if ($corner_style != '') + if ($corner_style !== '') { $corner_style = '"'.$corner_style.'"'; } - return "$(" . $this->_prep_element($element) . ").corner(".$corner_style.");"; + return '$('.$this->_prep_element($element).').corner('.$corner_style.');'; } // -------------------------------------------------------------------- @@ -821,16 +819,16 @@ class CI_Jquery extends CI_Javascript { $sort_options = array(); foreach ($options as $k=>$v) { - $sort_options[] = "\n\t\t".$k.': '.$v.""; + $sort_options[] = "\n\t\t".$k.': '.$v; } - $sort_options = implode(",", $sort_options); + $sort_options = implode(',', $sort_options); } else { $sort_options = ''; } - return "$(" . $this->_prep_element($element) . ").sortable({".$sort_options."\n\t});"; + return '$('.$this->_prep_element($element).').sortable({'.$sort_options."\n\t});"; } // -------------------------------------------------------------------- @@ -844,7 +842,7 @@ class CI_Jquery extends CI_Javascript { */ public function tablesorter($table = '', $options = '') { - $this->jquery_code_for_compile[] = "\t$(" . $this->_prep_element($table) . ").tablesorter($options);\n"; + $this->jquery_code_for_compile[] = "\t$(".$this->_prep_element($table).').tablesorter('.$options.");\n"; } // -------------------------------------------------------------------- @@ -869,7 +867,7 @@ class CI_Jquery extends CI_Javascript { } - $event = "\n\t$(" . $this->_prep_element($element) . ").{$event}(function(){\n\t\t{$js}\n\t});\n"; + $event = "\n\t$(".$this->_prep_element($element).').'.$event."(function(){\n\t\t{$js}\n\t});\n"; $this->jquery_code_for_compile[] = $event; return $event; } @@ -898,8 +896,8 @@ class CI_Jquery extends CI_Javascript { // Inline references $script = '$(document).ready(function() {'."\n" - . implode('', $this->jquery_code_for_compile) - . '});'; + .implode('', $this->jquery_code_for_compile) + .'});'; $output = ($script_tags === FALSE) ? $script : $this->inline($script); @@ -974,7 +972,7 @@ class CI_Jquery extends CI_Javascript { */ protected function _prep_element($element) { - if ($element != 'this') + if ($element !== 'this') { $element = '"'.$element.'"'; } @@ -998,7 +996,7 @@ class CI_Jquery extends CI_Javascript { { return '"'.$speed.'"'; } - elseif (preg_match("/[^0-9]/", $speed)) + elseif (preg_match('/[^0-9]/', $speed)) { return ''; } @@ -1009,4 +1007,4 @@ class CI_Jquery extends CI_Javascript { } /* End of file Jquery.php */ -/* Location: ./system/libraries/Jquery.php */ +/* Location: ./system/libraries/Jquery.php */
\ No newline at end of file |