summaryrefslogtreecommitdiffstats
path: root/system/libraries
diff options
context:
space:
mode:
authordchill42 <dchill42@gmail.com>2012-07-23 16:53:47 +0200
committerdchill42 <dchill42@gmail.com>2012-07-23 16:53:47 +0200
commitc5079de78e5141330c07e990811ef15e998e95aa (patch)
tree0f39d8c4fc7614246fc185810bfeaa7fad88a33a /system/libraries
parent00fcb545109d4e61bc14e403ec828749c34a54b3 (diff)
parentede49ba66b127535f3430e20aac72ceed2c4611a (diff)
Merge branch develop of github.com:/EllisLab/CodeIgniter into session
Diffstat (limited to 'system/libraries')
-rw-r--r--system/libraries/Cache/Cache.php209
-rw-r--r--system/libraries/Cache/drivers/Cache_apc.php80
-rw-r--r--system/libraries/Cache/drivers/Cache_dummy.php57
-rw-r--r--system/libraries/Cache/drivers/Cache_file.php122
-rw-r--r--system/libraries/Cache/drivers/Cache_memcached.php114
-rw-r--r--system/libraries/Cache/drivers/Cache_redis.php236
-rw-r--r--system/libraries/Cache/drivers/Cache_wincache.php162
-rw-r--r--system/libraries/Calendar.php335
-rw-r--r--system/libraries/Cart.php292
-rw-r--r--system/libraries/Driver.php106
-rw-r--r--system/libraries/Email.php1067
-rw-r--r--system/libraries/Encrypt.php287
-rw-r--r--system/libraries/Form_validation.php755
-rw-r--r--system/libraries/Ftp.php237
-rw-r--r--system/libraries/Image_lib.php1304
-rw-r--r--system/libraries/Javascript.php215
-rw-r--r--system/libraries/Log.php101
-rw-r--r--system/libraries/Migration.php155
-rw-r--r--system/libraries/Pagination.php338
-rw-r--r--system/libraries/Parser.php135
-rw-r--r--system/libraries/Profiler.php370
-rwxr-xr-xsystem/libraries/Session/Session.php25
-rwxr-xr-xsystem/libraries/Session/drivers/Session_cookie.php413
-rw-r--r--system/libraries/Sha1.php251
-rw-r--r--system/libraries/Table.php305
-rw-r--r--system/libraries/Trackback.php234
-rw-r--r--system/libraries/Typography.php206
-rw-r--r--system/libraries/Unit_test.php158
-rw-r--r--system/libraries/Upload.php562
-rw-r--r--system/libraries/User_agent.php261
-rw-r--r--system/libraries/Xmlrpc.php1269
-rw-r--r--system/libraries/Xmlrpcs.php262
-rw-r--r--system/libraries/Zip.php222
-rw-r--r--system/libraries/javascript/Jquery.php487
34 files changed, 6077 insertions, 5255 deletions
diff --git a/system/libraries/Cache/Cache.php b/system/libraries/Cache/Cache.php
index 61e7aa761..4395cf411 100644
--- a/system/libraries/Cache/Cache.php
+++ b/system/libraries/Cache/Cache.php
@@ -2,66 +2,138 @@
/**
* CodeIgniter
*
- * An open source application development framework for PHP 4.3.2 or newer
+ * An open source application development framework for PHP 5.2.4 or newer
+ *
+ * NOTICE OF LICENSE
+ *
+ * Licensed under the Open Software License version 3.0
+ *
+ * This source file is subject to the Open Software License (OSL 3.0) that is
+ * bundled with this package in the files license.txt / license.rst. It is
+ * also available through the world wide web at this URL:
+ * http://opensource.org/licenses/OSL-3.0
+ * If you did not receive a copy of the license and are unable to obtain it
+ * through the world wide web, please send an email to
+ * licensing@ellislab.com so we can send you a copy immediately.
*
* @package CodeIgniter
- * @author ExpressionEngine Dev Team
- * @copyright Copyright (c) 2006 - 2011 EllisLab, Inc.
- * @license http://codeigniter.com/user_guide/license.html
+ * @author EllisLab Dev Team
+ * @copyright Copyright (c) 2006 - 2012 EllisLab, Inc.
+ * @license http://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
* @link http://codeigniter.com
* @since Version 2.0
- * @filesource
+ * @filesource
*/
-// ------------------------------------------------------------------------
-
/**
- * CodeIgniter Caching Class
+ * CodeIgniter Caching Class
*
* @package CodeIgniter
* @subpackage Libraries
* @category Core
- * @author ExpressionEngine Dev Team
- * @link
+ * @author EllisLab Dev Team
+ * @link
*/
class CI_Cache extends CI_Driver_Library {
-
+
+ /**
+ * Valid cache drivers
+ *
+ * @var array
+ */
protected $valid_drivers = array(
- 'cache_apc', 'cache_file', 'cache_memcached', 'cache_dummy'
+ 'cache_apc',
+ 'cache_dummy',
+ 'cache_file',
+ 'cache_memcached',
+ 'cache_redis',
+ 'cache_wincache'
);
- protected $_cache_path = NULL; // Path of cache files (if file-based cache)
- protected $_adapter = 'dummy';
- protected $_backup_driver;
-
- // ------------------------------------------------------------------------
+ /**
+ * 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
*
- * @param array
+ * Initialize class properties based on the configuration array.
+ *
+ * @param array
+ * @return void
*/
public function __construct($config = array())
{
- if ( ! empty($config))
+ $default_config = array(
+ 'adapter',
+ 'memcached'
+ );
+
+ foreach ($default_config as $key)
+ {
+ if (isset($config[$key]))
+ {
+ $param = '_'.$key;
+
+ $this->{$param} = $config[$key];
+ }
+ }
+
+ if (isset($config['backup']))
{
- $this->_initialize($config);
+ if (in_array('cache_'.$config['backup'], $this->valid_drivers))
+ {
+ $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;
+ }
}
}
// ------------------------------------------------------------------------
/**
- * Get
+ * Get
*
- * Look for a value in the cache. If it exists, return the data
+ * Look for a value in the cache. If it exists, return the data
* if not, return FALSE
*
- * @param string
- * @return mixed value that is stored/FALSE on failure
+ * @param string
+ * @return mixed value that is stored/FALSE on failure
*/
public function get($id)
- {
+ {
return $this->{$this->_adapter}->get($id);
}
@@ -70,11 +142,10 @@ class CI_Cache extends CI_Driver_Library {
/**
* Cache Save
*
- * @param string Unique Key
- * @param mixed Data to store
- * @param int Length of time (in seconds) to cache the data
- *
- * @return boolean true on success/false on failure
+ * @param string Unique Key
+ * @param mixed Data to store
+ * @param int Length of time (in seconds) to cache the data
+ * @return bool true on success/false on failure
*/
public function save($id, $data, $ttl = 60)
{
@@ -86,8 +157,8 @@ class CI_Cache extends CI_Driver_Library {
/**
* Delete from Cache
*
- * @param mixed unique identifier of the item in the cache
- * @return boolean true on success/false on failure
+ * @param mixed unique identifier of the item in the cache
+ * @return bool true on success/false on failure
*/
public function delete($id)
{
@@ -99,7 +170,7 @@ class CI_Cache extends CI_Driver_Library {
/**
* Clean the cache
*
- * @return boolean false on failure/true on success
+ * @return bool false on failure/true on success
*/
public function clean()
{
@@ -111,8 +182,8 @@ class CI_Cache extends CI_Driver_Library {
/**
* Cache Info
*
- * @param string user/filehits
- * @return mixed array on success, false on failure
+ * @param string user/filehits
+ * @return mixed array on success, false on failure
*/
public function cache_info($type = 'user')
{
@@ -120,61 +191,25 @@ class CI_Cache extends CI_Driver_Library {
}
// ------------------------------------------------------------------------
-
+
/**
* Get Cache Metadata
*
- * @param mixed key to get cache metadata on
- * @return mixed return value from child method
+ * @param mixed key to get cache metadata on
+ * @return mixed return value from child method
*/
public function get_metadata($id)
{
return $this->{$this->_adapter}->get_metadata($id);
}
-
- // ------------------------------------------------------------------------
-
- /**
- * Initialize
- *
- * Initialize class properties based on the configuration array.
- *
- * @param array
- * @return void
- */
- private function _initialize($config)
- {
- $default_config = array(
- 'adapter',
- 'memcached'
- );
-
- foreach ($default_config as $key)
- {
- if (isset($config[$key]))
- {
- $param = '_'.$key;
-
- $this->{$param} = $config[$key];
- }
- }
-
- if (isset($config['backup']))
- {
- if (in_array('cache_'.$config['backup'], $this->valid_drivers))
- {
- $this->_backup_driver = $config['backup'];
- }
- }
- }
// ------------------------------------------------------------------------
/**
* Is the requested driver supported in this environment?
*
- * @param string The driver to test.
- * @return array
+ * @param string The driver to test.
+ * @return array
*/
public function is_supported($driver)
{
@@ -188,29 +223,7 @@ 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 Class
/* End of file Cache.php */
/* Location: ./system/libraries/Cache/Cache.php */ \ No newline at end of file
diff --git a/system/libraries/Cache/drivers/Cache_apc.php b/system/libraries/Cache/drivers/Cache_apc.php
index de75719c4..c85034f95 100644
--- a/system/libraries/Cache/drivers/Cache_apc.php
+++ b/system/libraries/Cache/drivers/Cache_apc.php
@@ -2,70 +2,80 @@
/**
* CodeIgniter
*
- * An open source application development framework for PHP 5.1.6 or newer
+ * An open source application development framework for PHP 5.2.4 or newer
+ *
+ * NOTICE OF LICENSE
+ *
+ * Licensed under the Open Software License version 3.0
+ *
+ * This source file is subject to the Open Software License (OSL 3.0) that is
+ * bundled with this package in the files license.txt / license.rst. It is
+ * also available through the world wide web at this URL:
+ * http://opensource.org/licenses/OSL-3.0
+ * If you did not receive a copy of the license and are unable to obtain it
+ * through the world wide web, please send an email to
+ * licensing@ellislab.com so we can send you a copy immediately.
*
* @package CodeIgniter
- * @author ExpressionEngine Dev Team
- * @copyright Copyright (c) 2006 - 2011 EllisLab, Inc.
- * @license http://codeigniter.com/user_guide/license.html
+ * @author EllisLab Dev Team
+ * @copyright Copyright (c) 2006 - 2012 EllisLab, Inc.
+ * @license http://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
* @link http://codeigniter.com
* @since Version 2.0
- * @filesource
+ * @filesource
*/
-// ------------------------------------------------------------------------
-
/**
- * CodeIgniter APC Caching Class
+ * CodeIgniter APC Caching Class
*
* @package CodeIgniter
* @subpackage Libraries
* @category Core
- * @author ExpressionEngine Dev Team
- * @link
+ * @author EllisLab Dev Team
+ * @link
*/
-
class CI_Cache_apc extends CI_Driver {
/**
- * Get
+ * Get
*
- * Look for a value in the cache. If it exists, return the data
+ * Look for a value in the cache. If it exists, return the data
* if not, return FALSE
*
- * @param string
- * @return mixed value that is stored/FALSE on failure
+ * @param string
+ * @return mixed value that is stored/FALSE on failure
*/
public function get($id)
{
$data = apc_fetch($id);
- return (is_array($data)) ? $data[0] : FALSE;
+ return is_array($data) ? $data[0] : FALSE;
}
- // ------------------------------------------------------------------------
-
+ // ------------------------------------------------------------------------
+
/**
* Cache Save
*
- * @param string Unique Key
- * @param mixed Data to store
- * @param int Length of time (in seconds) to cache the data
+ * @param string Unique Key
+ * @param mixed Data to store
+ * @param int Length of time (in seconds) to cache the data
*
- * @return boolean true on success/false on failure
+ * @return bool true on success/false on failure
*/
public function save($id, $data, $ttl = 60)
{
+ $ttl = (int) $ttl;
return apc_store($id, array($data, time(), $ttl), $ttl);
}
-
+
// ------------------------------------------------------------------------
/**
* Delete from Cache
*
- * @param mixed unique identifier of the item in the cache
- * @param boolean true on success/false on failure
+ * @param mixed unique identifier of the item in the cache
+ * @return bool true on success/false on failure
*/
public function delete($id)
{
@@ -77,7 +87,7 @@ class CI_Cache_apc extends CI_Driver {
/**
* Clean the cache
*
- * @return boolean false on failure/true on success
+ * @return bool false on failure/true on success
*/
public function clean()
{
@@ -89,8 +99,8 @@ class CI_Cache_apc extends CI_Driver {
/**
* Cache Info
*
- * @param string user/filehits
- * @return mixed array on success, false on failure
+ * @param string user/filehits
+ * @return mixed array on success, false on failure
*/
public function cache_info($type = NULL)
{
@@ -102,8 +112,8 @@ class CI_Cache_apc extends CI_Driver {
/**
* Get Cache Metadata
*
- * @param mixed key to get cache metadata on
- * @return mixed array on success/false on failure
+ * @param mixed key to get cache metadata on
+ * @return mixed array on success/false on failure
*/
public function get_metadata($id)
{
@@ -129,23 +139,21 @@ class CI_Cache_apc extends CI_Driver {
* is_supported()
*
* Check to see if APC is available on this system, bail if it isn't.
+ *
+ * @return bool
*/
public function is_supported()
{
- if ( ! extension_loaded('apc') OR ! function_exists('apc_store'))
+ if ( ! extension_loaded('apc') OR ! (bool) @ini_get('apc.enabled'))
{
log_message('error', 'The APC PHP extension must be loaded to use APC Cache.');
return FALSE;
}
-
+
return TRUE;
}
- // ------------------------------------------------------------------------
-
-
}
-// End Class
/* End of file Cache_apc.php */
/* Location: ./system/libraries/Cache/drivers/Cache_apc.php */ \ No newline at end of file
diff --git a/system/libraries/Cache/drivers/Cache_dummy.php b/system/libraries/Cache/drivers/Cache_dummy.php
index f96a68e27..3f2b4b956 100644
--- a/system/libraries/Cache/drivers/Cache_dummy.php
+++ b/system/libraries/Cache/drivers/Cache_dummy.php
@@ -2,29 +2,38 @@
/**
* CodeIgniter
*
- * An open source application development framework for PHP 4.3.2 or newer
+ * An open source application development framework for PHP 5.2.4 or newer
+ *
+ * NOTICE OF LICENSE
+ *
+ * Licensed under the Open Software License version 3.0
+ *
+ * This source file is subject to the Open Software License (OSL 3.0) that is
+ * bundled with this package in the files license.txt / license.rst. It is
+ * also available through the world wide web at this URL:
+ * http://opensource.org/licenses/OSL-3.0
+ * If you did not receive a copy of the license and are unable to obtain it
+ * through the world wide web, please send an email to
+ * licensing@ellislab.com so we can send you a copy immediately.
*
* @package CodeIgniter
- * @author ExpressionEngine Dev Team
- * @copyright Copyright (c) 2006 - 2011 EllisLab, Inc.
- * @license http://codeigniter.com/user_guide/license.html
+ * @author EllisLab Dev Team
+ * @copyright Copyright (c) 2006 - 2012 EllisLab, Inc.
+ * @license http://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
* @link http://codeigniter.com
* @since Version 2.0
* @filesource
*/
-// ------------------------------------------------------------------------
-
/**
* CodeIgniter Dummy Caching Class
*
* @package CodeIgniter
* @subpackage Libraries
* @category Core
- * @author ExpressionEngine Dev Team
+ * @author EllisLab Dev Team
* @link
*/
-
class CI_Cache_dummy extends CI_Driver {
/**
@@ -32,8 +41,8 @@ class CI_Cache_dummy extends CI_Driver {
*
* Since this is the dummy class, it's always going to return FALSE.
*
- * @param string
- * @return Boolean FALSE
+ * @param string
+ * @return bool FALSE
*/
public function get($id)
{
@@ -45,11 +54,10 @@ class CI_Cache_dummy extends CI_Driver {
/**
* Cache Save
*
- * @param string Unique Key
- * @param mixed Data to store
- * @param int Length of time (in seconds) to cache the data
- *
- * @return boolean TRUE, Simulating success
+ * @param string Unique Key
+ * @param mixed Data to store
+ * @param int Length of time (in seconds) to cache the data
+ * @return bool TRUE, Simulating success
*/
public function save($id, $data, $ttl = 60)
{
@@ -61,8 +69,8 @@ class CI_Cache_dummy extends CI_Driver {
/**
* Delete from Cache
*
- * @param mixed unique identifier of the item in the cache
- * @param boolean TRUE, simulating success
+ * @param mixed unique identifier of the item in the cache
+ * @return bool TRUE, simulating success
*/
public function delete($id)
{
@@ -74,7 +82,7 @@ class CI_Cache_dummy extends CI_Driver {
/**
* Clean the cache
*
- * @return boolean TRUE, simulating success
+ * @return bool TRUE, simulating success
*/
public function clean()
{
@@ -86,8 +94,8 @@ class CI_Cache_dummy extends CI_Driver {
/**
* Cache Info
*
- * @param string user/filehits
- * @return boolean FALSE
+ * @param string user/filehits
+ * @return bool FALSE
*/
public function cache_info($type = NULL)
{
@@ -99,8 +107,8 @@ class CI_Cache_dummy extends CI_Driver {
/**
* Get Cache Metadata
*
- * @param mixed key to get cache metadata on
- * @return boolean FALSE
+ * @param mixed key to get cache metadata on
+ * @return bool FALSE
*/
public function get_metadata($id)
{
@@ -113,17 +121,14 @@ class CI_Cache_dummy extends CI_Driver {
* Is this caching driver supported on the system?
* Of course this one is.
*
- * @return TRUE;
+ * @return bool TRUE
*/
public function is_supported()
{
return TRUE;
}
- // ------------------------------------------------------------------------
-
}
-// End Class
/* End of file Cache_dummy.php */
/* Location: ./system/libraries/Cache/drivers/Cache_dummy.php */ \ No newline at end of file
diff --git a/system/libraries/Cache/drivers/Cache_file.php b/system/libraries/Cache/drivers/Cache_file.php
index 6c37e7005..37d77c268 100644
--- a/system/libraries/Cache/drivers/Cache_file.php
+++ b/system/libraries/Cache/drivers/Cache_file.php
@@ -2,44 +2,58 @@
/**
* CodeIgniter
*
- * An open source application development framework for PHP 4.3.2 or newer
+ * An open source application development framework for PHP 5.2.4 or newer
+ *
+ * NOTICE OF LICENSE
+ *
+ * Licensed under the Open Software License version 3.0
+ *
+ * This source file is subject to the Open Software License (OSL 3.0) that is
+ * bundled with this package in the files license.txt / license.rst. It is
+ * also available through the world wide web at this URL:
+ * http://opensource.org/licenses/OSL-3.0
+ * If you did not receive a copy of the license and are unable to obtain it
+ * through the world wide web, please send an email to
+ * licensing@ellislab.com so we can send you a copy immediately.
*
* @package CodeIgniter
- * @author ExpressionEngine Dev Team
- * @copyright Copyright (c) 2006 - 2011 EllisLab, Inc.
- * @license http://codeigniter.com/user_guide/license.html
+ * @author EllisLab Dev Team
+ * @copyright Copyright (c) 2006 - 2012 EllisLab, Inc.
+ * @license http://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
* @link http://codeigniter.com
* @since Version 2.0
- * @filesource
+ * @filesource
*/
-// ------------------------------------------------------------------------
-
/**
- * CodeIgniter Memcached Caching Class
+ * CodeIgniter File Caching Class
*
* @package CodeIgniter
* @subpackage Libraries
* @category Core
- * @author ExpressionEngine Dev Team
- * @link
+ * @author EllisLab Dev Team
+ * @link
*/
-
class CI_Cache_file extends CI_Driver {
+ /**
+ * Directory in which to save cache files
+ *
+ * @var string
+ */
protected $_cache_path;
/**
- * Constructor
+ * 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;
}
// ------------------------------------------------------------------------
@@ -47,8 +61,8 @@ class CI_Cache_file extends CI_Driver {
/**
* Fetch from cache
*
- * @param mixed unique key id
- * @return mixed data on success/false on failure
+ * @param mixed unique key id
+ * @return mixed data on success/false on failure
*/
public function get($id)
{
@@ -56,16 +70,15 @@ class CI_Cache_file extends CI_Driver {
{
return FALSE;
}
-
- $data = read_file($this->_cache_path.$id);
- $data = unserialize($data);
-
- if (time() > $data['time'] + $data['ttl'])
+
+ $data = unserialize(file_get_contents($this->_cache_path.$id));
+
+ if ($data['ttl'] > 0 && time() > $data['time'] + $data['ttl'])
{
unlink($this->_cache_path.$id);
return FALSE;
}
-
+
return $data['data'];
}
@@ -74,24 +87,24 @@ class CI_Cache_file extends CI_Driver {
/**
* Save into cache
*
- * @param string unique key
- * @param mixed data to store
- * @param int length of time (in seconds) the cache is valid
- * - Default is 60 seconds
- * @return boolean true on success/false on failure
+ * @param string unique key
+ * @param mixed data to store
+ * @param int length of time (in seconds) the cache is valid
+ * - Default is 60 seconds
+ * @return bool true on success/false on failure
*/
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)))
{
- @chmod($this->_cache_path.$id, 0777);
- return TRUE;
+ @chmod($this->_cache_path.$id, 0660);
+ return TRUE;
}
return FALSE;
@@ -102,12 +115,12 @@ class CI_Cache_file extends CI_Driver {
/**
* Delete from Cache
*
- * @param mixed unique identifier of item in cache
- * @return boolean true on success/false on failure
+ * @param mixed unique identifier of item in cache
+ * @return bool true on success/false on failure
*/
public function delete($id)
{
- return unlink($this->_cache_path.$id);
+ return file_exists($this->_cache_path.$id) ? unlink($this->_cache_path.$id) : FALSE;
}
// ------------------------------------------------------------------------
@@ -115,8 +128,8 @@ class CI_Cache_file extends CI_Driver {
/**
* Clean the Cache
*
- * @return boolean false on failure/true on success
- */
+ * @return bool false on failure/true on success
+ */
public function clean()
{
return delete_files($this->_cache_path);
@@ -129,8 +142,8 @@ class CI_Cache_file extends CI_Driver {
*
* Not supported by file-based caching
*
- * @param string user/filehits
- * @return mixed FALSE
+ * @param string user/filehits
+ * @return mixed FALSE
*/
public function cache_info($type = NULL)
{
@@ -142,8 +155,8 @@ class CI_Cache_file extends CI_Driver {
/**
* Get Cache Metadata
*
- * @param mixed key to get cache metadata on
- * @return mixed FALSE on failure, array on success.
+ * @param mixed key to get cache metadata on
+ * @return mixed FALSE on failure, array on success.
*/
public function get_metadata($id)
{
@@ -151,25 +164,24 @@ class CI_Cache_file extends CI_Driver {
{
return FALSE;
}
-
- $data = read_file($this->_cache_path.$id);
- $data = unserialize($data);
-
+
+ $data = unserialize(file_get_contents($this->_cache_path.$id));
+
if (is_array($data))
{
$mtime = filemtime($this->_cache_path.$id);
- if ( ! isset($data['data']['ttl']))
+ if ( ! isset($data['ttl']))
{
return FALSE;
}
return array(
- 'expire' => $mtime + $data['data']['ttl'],
+ 'expire' => $mtime + $data['ttl'],
'mtime' => $mtime
);
}
-
+
return FALSE;
}
@@ -179,17 +191,15 @@ class CI_Cache_file extends CI_Driver {
* Is supported
*
* In the file driver, check to see that the cache directory is indeed writable
- *
- * @return boolean
+ *
+ * @return bool
*/
public function is_supported()
{
return is_really_writable($this->_cache_path);
}
- // ------------------------------------------------------------------------
}
-// End Class
/* End of file Cache_file.php */
/* Location: ./system/libraries/Cache/drivers/Cache_file.php */ \ No newline at end of file
diff --git a/system/libraries/Cache/drivers/Cache_memcached.php b/system/libraries/Cache/drivers/Cache_memcached.php
index 04aa81a5a..bf90f6197 100644
--- a/system/libraries/Cache/drivers/Cache_memcached.php
+++ b/system/libraries/Cache/drivers/Cache_memcached.php
@@ -2,54 +2,71 @@
/**
* CodeIgniter
*
- * An open source application development framework for PHP 4.3.2 or newer
+ * An open source application development framework for PHP 5.2.4 or newer
+ *
+ * NOTICE OF LICENSE
+ *
+ * Licensed under the Open Software License version 3.0
+ *
+ * This source file is subject to the Open Software License (OSL 3.0) that is
+ * bundled with this package in the files license.txt / license.rst. It is
+ * also available through the world wide web at this URL:
+ * http://opensource.org/licenses/OSL-3.0
+ * If you did not receive a copy of the license and are unable to obtain it
+ * through the world wide web, please send an email to
+ * licensing@ellislab.com so we can send you a copy immediately.
*
* @package CodeIgniter
- * @author ExpressionEngine Dev Team
- * @copyright Copyright (c) 2006 - 2011 EllisLab, Inc.
- * @license http://codeigniter.com/user_guide/license.html
+ * @author EllisLab Dev Team
+ * @copyright Copyright (c) 2006 - 2012 EllisLab, Inc.
+ * @license http://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
* @link http://codeigniter.com
* @since Version 2.0
* @filesource
*/
-// ------------------------------------------------------------------------
-
/**
* CodeIgniter Memcached Caching Class
*
* @package CodeIgniter
* @subpackage Libraries
* @category Core
- * @author ExpressionEngine Dev Team
+ * @author EllisLab Dev Team
* @link
*/
-
class CI_Cache_memcached extends CI_Driver {
- private $_memcached; // Holds the memcached object
-
- protected $_memcache_conf = array(
- 'default' => array(
- 'default_host' => '127.0.0.1',
- 'default_port' => 11211,
- 'default_weight' => 1
- )
- );
+ /**
+ * 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
+ )
+ );
/**
* Fetch from cache
*
- * @param mixed unique key id
- * @return mixed data on success/false on failure
+ * @param mixed unique key id
+ * @return mixed data on success/false on failure
*/
public function get($id)
{
$data = $this->_memcached->get($id);
- return (is_array($data)) ? $data[0] : FALSE;
+ return is_array($data) ? $data[0] : FALSE;
}
// ------------------------------------------------------------------------
@@ -57,14 +74,23 @@ class CI_Cache_memcached extends CI_Driver {
/**
* Save
*
- * @param string unique identifier
- * @param mixed data being cached
- * @param int time to live
- * @return boolean true on success, false on failure
+ * @param string unique identifier
+ * @param mixed data being cached
+ * @param int time to live
+ * @return bool true on success, false on failure
*/
public function save($id, $data, $ttl = 60)
{
- return $this->_memcached->set($id, array($data, time(), $ttl), $ttl);
+ if (get_class($this->_memcached) === 'Memcached')
+ {
+ return $this->_memcached->set($id, array($data, time(), $ttl), $ttl);
+ }
+ elseif (get_class($this->_memcached) === 'Memcache')
+ {
+ return $this->_memcached->set($id, array($data, time(), $ttl), 0, $ttl);
+ }
+
+ return FALSE;
}
// ------------------------------------------------------------------------
@@ -72,8 +98,8 @@ class CI_Cache_memcached extends CI_Driver {
/**
* Delete from Cache
*
- * @param mixed key to be deleted.
- * @return boolean true on success, false on failure
+ * @param mixed key to be deleted.
+ * @return bool true on success, false on failure
*/
public function delete($id)
{
@@ -85,7 +111,7 @@ class CI_Cache_memcached extends CI_Driver {
/**
* Clean the Cache
*
- * @return boolean false on failure/true on success
+ * @return bool false on failure/true on success
*/
public function clean()
{
@@ -97,10 +123,9 @@ class CI_Cache_memcached extends CI_Driver {
/**
* Cache Info
*
- * @param null type not supported in memcached
- * @return mixed array on success, false on failure
+ * @return mixed array on success, false on failure
*/
- public function cache_info($type = NULL)
+ public function cache_info()
{
return $this->_memcached->getStats();
}
@@ -110,8 +135,8 @@ class CI_Cache_memcached extends CI_Driver {
/**
* Get Cache Metadata
*
- * @param mixed key to get cache metadata on
- * @return mixed FALSE on failure, array on success.
+ * @param mixed key to get cache metadata on
+ * @return mixed FALSE on failure, array on success.
*/
public function get_metadata($id)
{
@@ -135,8 +160,10 @@ class CI_Cache_memcached extends CI_Driver {
/**
* Setup memcached.
+ *
+ * @return bool
*/
- private function _setup_memcached()
+ protected function _setup_memcached()
{
// Try to load memcached server info from the config file.
$CI =& get_instance();
@@ -158,14 +185,13 @@ class CI_Cache_memcached extends CI_Driver {
{
$this->_memcached = new Memcached();
}
- else if (class_exists('Memcache'))
+ elseif (class_exists('Memcache'))
{
$this->_memcached = new Memcache();
}
else
{
log_message('error', 'Failed to create object for Memcached Cache; extension not loaded?');
-
return FALSE;
}
@@ -173,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(
@@ -216,23 +242,21 @@ class CI_Cache_memcached extends CI_Driver {
*
* Returns FALSE if memcached is not supported on the system.
* If it is, we setup the memcached object & return TRUE
+ *
+ * @return bool
*/
public function is_supported()
{
if ( ! extension_loaded('memcached') && ! extension_loaded('memcache'))
{
log_message('error', 'The Memcached Extension must be loaded to use Memcached Cache.');
-
return FALSE;
}
return $this->_setup_memcached();
}
- // ------------------------------------------------------------------------
-
}
-// End Class
/* End of file Cache_memcached.php */
/* Location: ./system/libraries/Cache/drivers/Cache_memcached.php */ \ No newline at end of file
diff --git a/system/libraries/Cache/drivers/Cache_redis.php b/system/libraries/Cache/drivers/Cache_redis.php
new file mode 100644
index 000000000..e4a26b5f0
--- /dev/null
+++ b/system/libraries/Cache/drivers/Cache_redis.php
@@ -0,0 +1,236 @@
+<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
+/**
+ * CodeIgniter
+ *
+ * An open source application development framework for PHP 5.2.4 or newer
+ *
+ * NOTICE OF LICENSE
+ *
+ * Licensed under the Open Software License version 3.0
+ *
+ * This source file is subject to the Open Software License (OSL 3.0) that is
+ * bundled with this package in the files license.txt / license.rst. It is
+ * also available through the world wide web at this URL:
+ * http://opensource.org/licenses/OSL-3.0
+ * If you did not receive a copy of the license and are unable to obtain it
+ * through the world wide web, please send an email to
+ * licensing@ellislab.com so we can send you a copy immediately.
+ *
+ * @package CodeIgniter
+ * @author EllisLab Dev Team
+ * @copyright Copyright (c) 2006 - 2012 EllisLab, Inc.
+ * @license http://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
+ * @link http://codeigniter.com
+ * @since Version 3.0
+ * @filesource
+ */
+
+/**
+ * CodeIgniter Redis Caching Class
+ *
+ * @package CodeIgniter
+ * @subpackage Libraries
+ * @category Core
+ * @author Anton Lindqvist <anton@qvister.se>
+ * @link
+ */
+class CI_Cache_redis extends CI_Driver
+{
+ /**
+ * Default config
+ *
+ * @static
+ * @var array
+ */
+ protected static $_default_config = array(
+ 'host' => '127.0.0.1',
+ 'password' => NULL,
+ 'port' => 6379,
+ 'timeout' => 0
+ );
+
+ /**
+ * Redis connection
+ *
+ * @var Redis
+ */
+ protected $_redis;
+
+ // ------------------------------------------------------------------------
+
+ /**
+ * Get cache
+ *
+ * @param string Cache key identifier
+ * @return mixed
+ */
+ public function get($key)
+ {
+ return $this->_redis->get($key);
+ }
+
+ // ------------------------------------------------------------------------
+
+ /**
+ * Save cache
+ *
+ * @param string Cache key identifier
+ * @param mixed Data to save
+ * @param int Time to live
+ * @return bool
+ */
+ public function save($key, $value, $ttl = NULL)
+ {
+ return ($ttl)
+ ? $this->_redis->setex($key, $ttl, $value)
+ : $this->_redis->set($key, $value);
+ }
+
+ // ------------------------------------------------------------------------
+
+ /**
+ * Delete from cache
+ *
+ * @param string Cache key
+ * @return bool
+ */
+ public function delete($key)
+ {
+ return ($this->_redis->delete($key) === 1);
+ }
+
+ // ------------------------------------------------------------------------
+
+ /**
+ * Clean cache
+ *
+ * @return bool
+ * @see Redis::flushDB()
+ */
+ public function clean()
+ {
+ return $this->_redis->flushDB();
+ }
+
+ // ------------------------------------------------------------------------
+
+ /**
+ * Get cache driver info
+ *
+ * @param string Not supported in Redis.
+ * Only included in order to offer a
+ * consistent cache API.
+ * @return array
+ * @see Redis::info()
+ */
+ public function cache_info($type = NULL)
+ {
+ return $this->_redis->info();
+ }
+
+ // ------------------------------------------------------------------------
+
+ /**
+ * Get cache metadata
+ *
+ * @param string Cache key
+ * @return array
+ */
+ public function get_metadata($key)
+ {
+ $value = $this->get($key);
+
+ if ($value)
+ {
+ return array(
+ 'expire' => time() + $this->_redis->ttl($key),
+ 'data' => $value
+ );
+ }
+
+ return FALSE;
+ }
+
+ // ------------------------------------------------------------------------
+
+ /**
+ * Check if Redis driver is supported
+ *
+ * @return bool
+ */
+ public function is_supported()
+ {
+ if (extension_loaded('redis'))
+ {
+ $this->_setup_redis();
+ return TRUE;
+ }
+ else
+ {
+ log_message('error', 'The Redis extension must be loaded to use Redis cache.');
+ return FALSE;
+ }
+ }
+
+ // ------------------------------------------------------------------------
+
+ /**
+ * Setup Redis config and connection
+ *
+ * Loads Redis config file if present. Will halt execution
+ * if a Redis connection can't be established.
+ *
+ * @return bool
+ * @see Redis::connect()
+ */
+ protected function _setup_redis()
+ {
+ $config = array();
+ $CI =& get_instance();
+
+ if ($CI->config->load('redis', TRUE, TRUE))
+ {
+ $config += $CI->config->item('redis');
+ }
+
+ $config = array_merge(self::$_default_config, $config);
+
+ $this->_redis = new Redis();
+
+ try
+ {
+ $this->_redis->connect($config['host'], $config['port'], $config['timeout']);
+ }
+ catch (RedisException $e)
+ {
+ show_error('Redis connection refused. ' . $e->getMessage());
+ }
+
+ if (isset($config['password']))
+ {
+ $this->_redis->auth($config['password']);
+ }
+ }
+
+ // ------------------------------------------------------------------------
+
+ /**
+
+ * Class destructor
+ *
+ * Closes the connection to Redis if present.
+ *
+ * @return void
+ */
+ public function __destruct()
+ {
+ if ($this->_redis)
+ {
+ $this->_redis->close();
+ }
+ }
+
+}
+
+/* End of file Cache_redis.php */
+/* Location: ./system/libraries/Cache/drivers/Cache_redis.php */ \ No newline at end of file
diff --git a/system/libraries/Cache/drivers/Cache_wincache.php b/system/libraries/Cache/drivers/Cache_wincache.php
new file mode 100644
index 000000000..89e9f77c8
--- /dev/null
+++ b/system/libraries/Cache/drivers/Cache_wincache.php
@@ -0,0 +1,162 @@
+<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
+/**
+ * CodeIgniter
+ *
+ * An open source application development framework for PHP 5.2.4 or newer
+ *
+ * NOTICE OF LICENSE
+ *
+ * Licensed under the Open Software License version 3.0
+ *
+ * This source file is subject to the Open Software License (OSL 3.0) that is
+ * bundled with this package in the files license.txt / license.rst. It is
+ * also available through the world wide web at this URL:
+ * http://opensource.org/licenses/OSL-3.0
+ * If you did not receive a copy of the license and are unable to obtain it
+ * through the world wide web, please send an email to
+ * licensing@ellislab.com so we can send you a copy immediately.
+ *
+ * @package CodeIgniter
+ * @author EllisLab Dev Team
+ * @copyright Copyright (c) 2006 - 2012 EllisLab, Inc.
+ * @license http://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
+ * @link http://codeigniter.com
+ * @since Version 3.0
+ * @filesource
+ */
+
+/**
+ * CodeIgniter Wincache Caching Class
+ *
+ * Read more about Wincache functions here:
+ * http://www.php.net/manual/en/ref.wincache.php
+ *
+ * @package CodeIgniter
+ * @subpackage Libraries
+ * @category Core
+ * @author Mike Murkovic
+ * @link
+ */
+class CI_Cache_wincache extends CI_Driver {
+
+ /**
+ * Get
+ *
+ * Look for a value in the cache. If it exists, return the data,
+ * if not, return FALSE
+ *
+ * @param string
+ * @return mixed value that is stored/FALSE on failure
+ */
+ public function get($id)
+ {
+ $success = FALSE;
+ $data = wincache_ucache_get($id, $success);
+
+ // Success returned by reference from wincache_ucache_get()
+ return ($success) ? $data : FALSE;
+ }
+
+ // ------------------------------------------------------------------------
+
+ /**
+ * Cache Save
+ *
+ * @param string Unique Key
+ * @param mixed Data to store
+ * @param int Length of time (in seconds) to cache the data
+ * @return bool true on success/false on failure
+ */
+ public function save($id, $data, $ttl = 60)
+ {
+ return wincache_ucache_set($id, $data, $ttl);
+ }
+
+ // ------------------------------------------------------------------------
+
+ /**
+ * Delete from Cache
+ *
+ * @param mixed unique identifier of the item in the cache
+ * @return bool true on success/false on failure
+ */
+ public function delete($id)
+ {
+ return wincache_ucache_delete($id);
+ }
+
+ // ------------------------------------------------------------------------
+
+ /**
+ * Clean the cache
+ *
+ * @return bool false on failure/true on success
+ */
+ public function clean()
+ {
+ return wincache_ucache_clear();
+ }
+
+ // ------------------------------------------------------------------------
+
+ /**
+ * Cache Info
+ *
+ * @return mixed array on success, false on failure
+ */
+ public function cache_info()
+ {
+ return wincache_ucache_info(TRUE);
+ }
+
+ // ------------------------------------------------------------------------
+
+ /**
+ * Get Cache Metadata
+ *
+ * @param mixed key to get cache metadata on
+ * @return mixed array on success/false on failure
+ */
+ public function get_metadata($id)
+ {
+ if ($stored = wincache_ucache_info(FALSE, $id))
+ {
+ $age = $stored['ucache_entries'][1]['age_seconds'];
+ $ttl = $stored['ucache_entries'][1]['ttl_seconds'];
+ $hitcount = $stored['ucache_entries'][1]['hitcount'];
+
+ return array(
+ 'expire' => $ttl - $age,
+ 'hitcount' => $hitcount,
+ 'age' => $age,
+ 'ttl' => $ttl
+ );
+ }
+
+ return FALSE;
+ }
+
+ // ------------------------------------------------------------------------
+
+ /**
+ * is_supported()
+ *
+ * Check to see if WinCache is available on this system, bail if it isn't.
+ *
+ * @return bool
+ */
+ public function is_supported()
+ {
+ if ( ! extension_loaded('wincache'))
+ {
+ log_message('error', 'The Wincache PHP extension must be loaded to use Wincache Cache.');
+ return FALSE;
+ }
+
+ return TRUE;
+ }
+
+}
+
+/* End of file Cache_wincache.php */
+/* Location: ./system/libraries/Cache/drivers/Cache_wincache.php */ \ No newline at end of file
diff --git a/system/libraries/Calendar.php b/system/libraries/Calendar.php
index df0fd6eeb..a49f171b9 100644
--- a/system/libraries/Calendar.php
+++ b/system/libraries/Calendar.php
@@ -1,20 +1,30 @@
-<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
+<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* CodeIgniter
*
- * An open source application development framework for PHP 5.1.6 or newer
+ * An open source application development framework for PHP 5.2.4 or newer
+ *
+ * NOTICE OF LICENSE
+ *
+ * Licensed under the Open Software License version 3.0
+ *
+ * This source file is subject to the Open Software License (OSL 3.0) that is
+ * bundled with this package in the files license.txt / license.rst. It is
+ * also available through the world wide web at this URL:
+ * http://opensource.org/licenses/OSL-3.0
+ * If you did not receive a copy of the license and are unable to obtain it
+ * through the world wide web, please send an email to
+ * licensing@ellislab.com so we can send you a copy immediately.
*
* @package CodeIgniter
- * @author ExpressionEngine Dev Team
- * @copyright Copyright (c) 2008 - 2011, EllisLab, Inc.
- * @license http://codeigniter.com/user_guide/license.html
+ * @author EllisLab Dev Team
+ * @copyright Copyright (c) 2008 - 2012, EllisLab, Inc. (http://ellislab.com/)
+ * @license http://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
* @link http://codeigniter.com
* @since Version 1.0
* @filesource
*/
-// ------------------------------------------------------------------------
-
/**
* CodeIgniter Calendar Class
*
@@ -23,25 +33,74 @@
* @package CodeIgniter
* @subpackage Libraries
* @category Libraries
- * @author ExpressionEngine Dev Team
+ * @author EllisLab Dev Team
* @link http://codeigniter.com/user_guide/libraries/calendar.html
*/
class CI_Calendar {
- var $CI;
- var $lang;
- var $local_time;
- var $template = '';
- var $start_day = 'sunday';
- var $month_type = 'long';
- var $day_type = 'abr';
- var $show_next_prev = FALSE;
- var $next_prev_url = '';
+ /**
+ * Reference to CodeIgniter instance
+ *
+ * @var object
+ */
+ protected $CI;
+
+ /**
+ * 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';
+
+ /**
+ * 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
*
* Loads the calendar language file and sets the default time reference
+ *
+ * @param array
+ * @return void
*/
public function __construct($config = array())
{
@@ -59,7 +118,7 @@ class CI_Calendar {
$this->initialize($config);
}
- log_message('debug', "Calendar Class Initialized");
+ log_message('debug', 'Calendar Class Initialized');
}
// --------------------------------------------------------------------
@@ -69,11 +128,10 @@ class CI_Calendar {
*
* Accepts an associative array as input, containing display preferences
*
- * @access public
* @param array config preferences
* @return void
*/
- function initialize($config = array())
+ public function initialize($config = array())
{
foreach ($config as $key => $val)
{
@@ -89,29 +147,35 @@ class CI_Calendar {
/**
* Generate the calendar
*
- * @access public
- * @param integer the year
- * @param integer the month
+ * @param int the year
+ * @param int the month
* @param array the data to be shown in the calendar cells
* @return string
*/
- function generate($year = '', $month = '', $data = array())
+ public function generate($year = '', $month = '', $data = array())
{
// Set and validate the supplied month/year
- if ($year == '')
- $year = date("Y", $this->local_time);
-
- if ($month == '')
- $month = date("m", $this->local_time);
-
- if (strlen($year) == 1)
+ if (empty($year))
+ {
+ $year = date('Y', $this->local_time);
+ }
+ elseif (strlen($year) === 1)
+ {
$year = '200'.$year;
-
- if (strlen($year) == 2)
+ }
+ elseif (strlen($year) === 2)
+ {
$year = '20'.$year;
+ }
- if (strlen($month) == 1)
+ if (empty($month))
+ {
+ $month = date('m', $this->local_time);
+ }
+ elseif (strlen($month) === 1)
+ {
$month = '0'.$month;
+ }
$adjusted_date = $this->adjust_date($month, $year);
@@ -123,12 +187,12 @@ 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);
$date = getdate($local_date);
- $day = $start_day + 1 - $date["wday"];
+ $day = $start_day + 1 - $date['wday'];
while ($day > 1)
{
@@ -137,58 +201,46 @@ class CI_Calendar {
// Set the current month/year/day
// We use this to determine the "today" date
- $cur_year = date("Y", $this->local_time);
- $cur_month = date("m", $this->local_time);
- $cur_day = date("j", $this->local_time);
+ $cur_year = date('Y', $this->local_time);
+ $cur_month = date('m', $this->local_time);
+ $cur_day = date('j', $this->local_time);
- $is_current_month = ($cur_year == $year AND $cur_month == $month) ? TRUE : FALSE;
+ $is_current_month = ($cur_year == $year && $cur_month == $month);
// Generate the template data array
$this->parse_template();
// Begin building the calendar output
- $out = $this->temp['table_open'];
- $out .= "\n";
-
- $out .= "\n";
- $out .= $this->temp['heading_row_start'];
- $out .= "\n";
+ $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);
+ $this->next_prev_url = preg_replace('/(.+?)\/*$/', '\\1/', $this->next_prev_url);
$adjusted_date = $this->adjust_date($month - 1, $year);
- $out .= str_replace('{previous_url}', $this->next_prev_url.$adjusted_date['year'].'/'.$adjusted_date['month'], $this->temp['heading_previous_cell']);
- $out .= "\n";
+ $out .= str_replace('{previous_url}', $this->next_prev_url.$adjusted_date['year'].'/'.$adjusted_date['month'], $this->temp['heading_previous_cell'])."\n";
}
// 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, $this->temp['heading_title_cell']);
- $this->temp['heading_title_cell'] = str_replace('{heading}', $this->get_month_name($month)."&nbsp;".$year, $this->temp['heading_title_cell']);
+ $this->temp['heading_title_cell'] = str_replace('{colspan}', $colspan,
+ str_replace('{heading}', $this->get_month_name($month).'&nbsp;'.$year, $this->temp['heading_title_cell']));
- $out .= $this->temp['heading_title_cell'];
- $out .= "\n";
+ $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']);
}
- $out .= "\n";
- $out .= $this->temp['heading_row_end'];
- $out .= "\n";
-
- // Write the cells containing the days of the week
- $out .= "\n";
- $out .= $this->temp['week_row_start'];
- $out .= "\n";
+ $out .= "\n".$this->temp['heading_row_end']."\n\n"
+ // Write the cells containing the days of the week
+ .$this->temp['week_row_start']."\n";
$day_names = $this->get_day_names();
@@ -197,33 +249,31 @@ class CI_Calendar {
$out .= str_replace('{week_day}', $day_names[($start_day + $i) %7], $this->temp['week_day_cell']);
}
- $out .= "\n";
- $out .= $this->temp['week_row_end'];
- $out .= "\n";
+ $out .= "\n".$this->temp['week_row_end']."\n";
// Build the main body of the calendar
while ($day <= $total_days)
{
- $out .= "\n";
- $out .= $this->temp['cal_row_start'];
- $out .= "\n";
+ $out .= "\n".$this->temp['cal_row_start']."\n";
for ($i = 0; $i < 7; $i++)
{
- $out .= ($is_current_month == TRUE AND $day == $cur_day) ? $this->temp['cal_cell_start_today'] : $this->temp['cal_cell_start'];
+ $out .= ($is_current_month === TRUE && $day == $cur_day) ? $this->temp['cal_cell_start_today'] : $this->temp['cal_cell_start'];
- if ($day > 0 AND $day <= $total_days)
+ if ($day > 0 && $day <= $total_days)
{
if (isset($data[$day]))
{
// Cells with content
- $temp = ($is_current_month == TRUE AND $day == $cur_day) ? $this->temp['cal_cell_content_today'] : $this->temp['cal_cell_content'];
- $out .= str_replace('{day}', $day, str_replace('{content}', $data[$day], $temp));
+ $temp = ($is_current_month === TRUE && $day == $cur_day) ?
+ $this->temp['cal_cell_content_today'] : $this->temp['cal_cell_content'];
+ $out .= str_replace(array('{content}', '{day}'), array($data[$day], $day), $temp);
}
else
{
// Cells with no content
- $temp = ($is_current_month == TRUE AND $day == $cur_day) ? $this->temp['cal_cell_no_content_today'] : $this->temp['cal_cell_no_content'];
+ $temp = ($is_current_month === TRUE && $day == $cur_day) ?
+ $this->temp['cal_cell_no_content_today'] : $this->temp['cal_cell_no_content'];
$out .= str_replace('{day}', $day, $temp);
}
}
@@ -233,19 +283,14 @@ class CI_Calendar {
$out .= $this->temp['cal_cell_blank'];
}
- $out .= ($is_current_month == TRUE AND $day == $cur_day) ? $this->temp['cal_cell_end_today'] : $this->temp['cal_cell_end'];
+ $out .= ($is_current_month === TRUE && $day == $cur_day) ? $this->temp['cal_cell_end_today'] : $this->temp['cal_cell_end'];
$day++;
}
- $out .= "\n";
- $out .= $this->temp['cal_row_end'];
- $out .= "\n";
+ $out .= "\n".$this->temp['cal_row_end']."\n";
}
- $out .= "\n";
- $out .= $this->temp['table_close'];
-
- return $out;
+ return $out .= "\n".$this->temp['table_close'];
}
// --------------------------------------------------------------------
@@ -256,13 +301,12 @@ class CI_Calendar {
* Generates a textual month name based on the numeric
* month provided.
*
- * @access public
- * @param integer the month
+ * @param int the month
* @return string
*/
- function get_month_name($month)
+ 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(str_replace('cal_', '', $month));
- }
-
- 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]);
}
// --------------------------------------------------------------------
@@ -287,22 +326,23 @@ class CI_Calendar {
* Get Day Names
*
* Returns an array of day names (Sunday, Monday, etc.) based
- * on the type. Options: long, short, abrev
+ * on the type. Options: long, short, abrev
*
- * @access public
* @param string
* @return array
*/
- function get_day_names($day_type = '')
+ 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');
}
@@ -312,9 +352,9 @@ class CI_Calendar {
}
$days = array();
- foreach ($day_names as $val)
+ for ($i = 0, $c = count($day_names); $i < $c; $i++)
{
- $days[] = ($this->CI->lang->line('cal_'.$val) === FALSE) ? ucfirst($val) : $this->CI->lang->line('cal_'.$val);
+ $days[] = ($this->CI->lang->line('cal_'.$day_names[$i]) === FALSE) ? ucfirst($day_names[$i]) : $this->CI->lang->line('cal_'.$day_names[$i]);
}
return $days;
@@ -329,12 +369,11 @@ class CI_Calendar {
* For example, if you submit 13 as the month, the year will
* increment and the month will become January.
*
- * @access public
- * @param integer the month
- * @param integer the year
+ * @param int the month
+ * @param int the year
* @return array
*/
- function adjust_date($month, $year)
+ public function adjust_date($month, $year)
{
$date = array();
@@ -353,7 +392,7 @@ class CI_Calendar {
$date['year']--;
}
- if (strlen($date['month']) == 1)
+ if (strlen($date['month']) === 1)
{
$date['month'] = '0'.$date['month'];
}
@@ -366,12 +405,11 @@ class CI_Calendar {
/**
* Total days in a given month
*
- * @access public
- * @param integer the month
- * @param integer the year
- * @return integer
+ * @param int the month
+ * @param int the year
+ * @return int
*/
- function get_total_days($month, $year)
+ public function get_total_days($month, $year)
{
$days_in_month = array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
@@ -383,7 +421,7 @@ class CI_Calendar {
// Is the year a leap year?
if ($month == 2)
{
- if ($year % 400 == 0 OR ($year % 4 == 0 AND $year % 100 != 0))
+ if ($year % 400 === 0 OR ($year % 4 === 0 && $year % 100 !== 0))
{
return 29;
}
@@ -399,34 +437,33 @@ class CI_Calendar {
*
* This is used in the event that the user has not created their own template
*
- * @access public
- * @return array
+ * @return array
*/
- function default_template()
+ 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}">&lt;&lt;</a></th>',
- 'heading_title_cell' => '<th colspan="{colspan}">{heading}</th>',
- 'heading_next_cell' => '<th><a href="{next_url}">&gt;&gt;</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' => '&nbsp;',
- '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}">&lt;&lt;</a></th>',
+ 'heading_title_cell' => '<th colspan="{colspan}">{heading}</th>',
+ 'heading_next_cell' => '<th><a href="{next_url}">&gt;&gt;</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' => '&nbsp;',
+ 'cal_cell_end' => '</td>',
+ 'cal_cell_end_today' => '</td>',
+ 'cal_row_end' => '</tr>',
+ 'table_close' => '</table>'
+ );
}
// --------------------------------------------------------------------
@@ -437,14 +474,13 @@ class CI_Calendar {
* Harvests the data within the template {pseudo-variables}
* used to display the calendar
*
- * @access public
* @return void
*/
- function parse_template()
+ public function parse_template()
{
$this->temp = $this->default_template();
- if ($this->template == '')
+ if ($this->template === '')
{
return;
}
@@ -453,23 +489,18 @@ class CI_Calendar {
foreach (array('table_open', 'table_close', 'heading_row_start', 'heading_previous_cell', 'heading_title_cell', 'heading_next_cell', 'heading_row_end', 'week_row_start', 'week_day_cell', 'week_row_end', 'cal_row_start', 'cal_cell_start', 'cal_cell_content', 'cal_cell_no_content', 'cal_cell_blank', 'cal_cell_end', 'cal_row_end', 'cal_cell_start_today', 'cal_cell_content_today', 'cal_cell_no_content_today', 'cal_cell_end_today') as $val)
{
- if (preg_match("/\{".$val."\}(.*?)\{\/".$val."\}/si", $this->template, $match))
+ if (preg_match('/\{'.$val.'\}(.*?)\{\/'.$val.'\}/si', $this->template, $match))
{
- $this->temp[$val] = $match['1'];
+ $this->temp[$val] = $match[1];
}
- else
+ elseif (in_array($val, $today, TRUE))
{
- if (in_array($val, $today, TRUE))
- {
- $this->temp[$val] = $this->temp[str_replace('_today', '', $val)];
- }
+ $this->temp[$val] = $this->temp[substr($val, 0, -6)];
}
}
}
}
-// END CI_Calendar class
-
/* End of file Calendar.php */
/* Location: ./system/libraries/Calendar.php */ \ No newline at end of file
diff --git a/system/libraries/Cart.php b/system/libraries/Cart.php
index ab5a70c98..c442f88da 100644
--- a/system/libraries/Cart.php
+++ b/system/libraries/Cart.php
@@ -1,44 +1,89 @@
-<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
+<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* CodeIgniter
*
- * An open source application development framework for PHP 5.1.6 or newer
+ * An open source application development framework for PHP 5.2.4 or newer
+ *
+ * NOTICE OF LICENSE
+ *
+ * Licensed under the Open Software License version 3.0
+ *
+ * This source file is subject to the Open Software License (OSL 3.0) that is
+ * bundled with this package in the files license.txt / license.rst. It is
+ * also available through the world wide web at this URL:
+ * http://opensource.org/licenses/OSL-3.0
+ * If you did not receive a copy of the license and are unable to obtain it
+ * through the world wide web, please send an email to
+ * licensing@ellislab.com so we can send you a copy immediately.
*
* @package CodeIgniter
- * @author ExpressionEngine Dev Team
- * @copyright Copyright (c) 2006 - 2011, EllisLab, Inc.
- * @license http://codeigniter.com/user_guide/license.html
+ * @author EllisLab Dev Team
+ * @copyright Copyright (c) 2006 - 2012, EllisLab, Inc. (http://ellislab.com/)
+ * @license http://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
* @link http://codeigniter.com
* @since Version 1.0
* @filesource
*/
-// ------------------------------------------------------------------------
-
/**
* Shopping Cart Class
*
* @package CodeIgniter
* @subpackage Libraries
* @category Shopping Cart
- * @author ExpressionEngine Dev Team
+ * @author EllisLab Dev Team
* @link http://codeigniter.com/user_guide/libraries/cart.html
*/
class CI_Cart {
- // These are the regular expression rules that we use to validate the product ID and product name
- var $product_id_rules = '\.a-z0-9_-'; // alpha-numeric, dashes, underscores, or periods
- var $product_name_rules = '\.\:\-_ a-z0-9'; // alpha-numeric, dashes, underscores, colons or periods
+ /**
+ * 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!
+ // --------------------------------------------------------------------------
- // Private variables. Do not change!
- var $CI;
- var $_cart_contents = array();
+ /**
+ * 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())
{
@@ -46,31 +91,20 @@ class CI_Cart {
$this->CI =& get_instance();
// Are any config settings being passed manually? If so, set them
- $config = array();
- if (count($params) > 0)
- {
- foreach ($params as $key => $val)
- {
- $config[$key] = $val;
- }
- }
+ $config = is_array($params) ? $params : array();
// Load the Sessions class
$this->CI->load->library('session', $config);
- // Grab the shopping cart array from the session table, if it exists
- if ($this->CI->session->userdata('cart_contents') !== FALSE)
- {
- $this->_cart_contents = $this->CI->session->userdata('cart_contents');
- }
- else
+ // Grab the shopping cart array from the session table
+ $this->_cart_contents = $this->CI->session->userdata('cart_contents');
+ if ($this->_cart_contents === FALSE)
{
// No cart exists so we'll set some base values
- $this->_cart_contents['cart_total'] = 0;
- $this->_cart_contents['total_items'] = 0;
+ $this->_cart_contents = array('cart_total' => 0, 'total_items' => 0);
}
- log_message('debug', "Cart Class Initialized");
+ log_message('debug', 'Cart Class Initialized');
}
// --------------------------------------------------------------------
@@ -78,14 +112,13 @@ class CI_Cart {
/**
* Insert items into the cart and save it to the session table
*
- * @access public
* @param array
* @return bool
*/
- function insert($items = array())
+ public function insert($items = array())
{
// Was any cart data passed? No? Bah...
- if ( ! is_array($items) OR count($items) == 0)
+ if ( ! is_array($items) OR count($items) === 0)
{
log_message('error', 'The insert method must be passed an array containing data.');
return FALSE;
@@ -108,7 +141,7 @@ class CI_Cart {
{
foreach ($items as $val)
{
- if (is_array($val) AND isset($val['id']))
+ if (is_array($val) && isset($val['id']))
{
if ($this->_insert($val))
{
@@ -119,7 +152,7 @@ class CI_Cart {
}
// Save the cart data if the insert was successful
- if ($save_cart == TRUE)
+ if ($save_cart === TRUE)
{
$this->_save_cart();
return isset($rowid) ? $rowid : TRUE;
@@ -133,14 +166,13 @@ class CI_Cart {
/**
* Insert
*
- * @access private
* @param array
* @return bool
*/
- function _insert($items = array())
+ protected function _insert($items = array())
{
// Was any cart data passed? No? Bah...
- if ( ! is_array($items) OR count($items) == 0)
+ if ( ! is_array($items) OR count($items) === 0)
{
log_message('error', 'The insert method must be passed an array containing data.');
return FALSE;
@@ -149,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;
@@ -157,10 +189,8 @@ class CI_Cart {
// --------------------------------------------------------------------
- // Prep the quantity. It can only be a number. Duh...
- $items['qty'] = trim(preg_replace('/([^0-9])/i', '', $items['qty']));
- // Trim any leading zeros
- $items['qty'] = trim(preg_replace('/(^[0]+)/i', '', $items['qty']));
+ // Prep the quantity. It can only be a number. Duh... also trim any leading zeros
+ $items['qty'] = (float) $items['qty'];
// If the quantity is zero or blank there's nothing for us to do
if ( ! is_numeric($items['qty']) OR $items['qty'] == 0)
@@ -173,7 +203,7 @@ class CI_Cart {
// Validate the product ID. It can only be alpha-numeric, dashes, underscores or periods
// Not totally sure we should impose this rule, but it seems prudent to standardize IDs.
// Note: These can be user-specified by setting the $this->product_id_rules variable.
- if ( ! preg_match("/^[".$this->product_id_rules."]+$/i", $items['id']))
+ if ( ! preg_match('/^['.$this->product_id_rules.']+$/i', $items['id']))
{
log_message('error', 'Invalid product ID. The product ID can only contain alpha-numeric characters, dashes, and underscores');
return FALSE;
@@ -183,7 +213,7 @@ class CI_Cart {
// Validate the product name. It can only be alpha-numeric, dashes, underscores, colons or periods.
// Note: These can be user-specified by setting the $this->product_name_rules variable.
- if ( ! preg_match("/^[".$this->product_name_rules."]+$/i", $items['name']))
+ if ($this->product_name_safe && ! preg_match('/^['.$this->product_name_rules.']+$/i', $items['name']))
{
log_message('error', 'An invalid name was submitted as the product name: '.$items['name'].' The name can only contain alpha-numeric characters, dashes, underscores, colons, and spaces');
return FALSE;
@@ -191,10 +221,8 @@ class CI_Cart {
// --------------------------------------------------------------------
- // Prep the price. Remove anything that isn't a number or decimal point.
- $items['price'] = trim(preg_replace('/([^0-9\.])/i', '', $items['price']));
- // Trim any leading zeros
- $items['price'] = trim(preg_replace('/(^[0]+)/i', '', $items['price']));
+ // Prep the price. Remove leading zeros and anything that isn't a number or decimal point.
+ $items['price'] = (float) $items['price'];
// Is the price a valid number?
if ( ! is_numeric($items['price']))
@@ -215,9 +243,9 @@ class CI_Cart {
// Internally, we need to treat identical submissions, but with different options, as a unique product.
// Our solution is to convert the options array to a string and MD5 it along with the product ID.
// This becomes the unique "row ID"
- if (isset($items['options']) AND count($items['options']) > 0)
+ if (isset($items['options']) && count($items['options']) > 0)
{
- $rowid = md5($items['id'].implode('', $items['options']));
+ $rowid = md5($items['id'].serialize($items['options']));
}
else
{
@@ -230,20 +258,14 @@ class CI_Cart {
// --------------------------------------------------------------------
// Now that we have our unique "row ID", we'll add our cart items to the master array
+ // grab quantity if it's already there and add it on
+ $old_quantity = isset($this->_cart_contents[$rowid]['qty']) ? (int) $this->_cart_contents[$rowid]['qty'] : 0;
- // let's unset this first, just to make sure our index contains only the data from this submission
- unset($this->_cart_contents[$rowid]);
-
- // Create a new index with our new row ID
- $this->_cart_contents[$rowid]['rowid'] = $rowid;
-
- // And add the new items to the cart array
- foreach ($items as $key => $val)
- {
- $this->_cart_contents[$rowid][$key] = $val;
- }
+ // Re-create the entry, just to make sure our index contains only the data from this submission
+ $items['rowid'] = $rowid;
+ $items['qty'] += $old_quantity;
+ $this->_cart_contents[$rowid] = $items;
- // Woot!
return $rowid;
}
@@ -257,15 +279,13 @@ class CI_Cart {
* changes to the quantity before checkout. That array must contain the
* product ID and quantity for each item.
*
- * @access public
* @param array
- * @param string
* @return bool
*/
- function update($items = array())
+ public function update($items = array())
{
// Was any cart data passed?
- if ( ! is_array($items) OR count($items) == 0)
+ if ( ! is_array($items) OR count($items) === 0)
{
return FALSE;
}
@@ -275,9 +295,9 @@ class CI_Cart {
// determine the array type is by looking for a required array key named "id".
// If it's not found we assume it's a multi-dimensional array
$save_cart = FALSE;
- if (isset($items['rowid']) AND isset($items['qty']))
+ if (isset($items['rowid'], $items['qty']))
{
- if ($this->_update($items) == TRUE)
+ if ($this->_update($items) === TRUE)
{
$save_cart = TRUE;
}
@@ -286,9 +306,9 @@ class CI_Cart {
{
foreach ($items as $val)
{
- if (is_array($val) AND isset($val['rowid']) AND isset($val['qty']))
+ if (is_array($val) && isset($val['rowid'], $val['qty']))
{
- if ($this->_update($val) == TRUE)
+ if ($this->_update($val) === TRUE)
{
$save_cart = TRUE;
}
@@ -297,7 +317,7 @@ class CI_Cart {
}
// Save the cart data if the insert was successful
- if ($save_cart == TRUE)
+ if ($save_cart === TRUE)
{
$this->_save_cart();
return TRUE;
@@ -316,20 +336,19 @@ class CI_Cart {
* changes to the quantity before checkout. That array must contain the
* product ID and quantity for each item.
*
- * @access private
* @param array
* @return bool
*/
- function _update($items = array())
+ 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;
}
// Prep the quantity
- $items['qty'] = preg_replace('/([^0-9])/i', '', $items['qty']);
+ $items['qty'] = (float) $items['qty'];
// Is the quantity a number?
if ( ! is_numeric($items['qty']))
@@ -337,13 +356,6 @@ class CI_Cart {
return FALSE;
}
- // Is the new quantity different than what is already saved in the cart?
- // If it's the same there's nothing to do
- if ($this->_cart_contents[$items['rowid']]['qty'] == $items['qty'])
- {
- return FALSE;
- }
-
// Is the quantity zero? If so we will remove the item from the cart.
// If the quantity is greater than zero we are updating
if ($items['qty'] == 0)
@@ -363,38 +375,26 @@ class CI_Cart {
/**
* Save the cart array to the session DB
*
- * @access private
* @return bool
*/
- function _save_cart()
+ protected function _save_cart()
{
- // Unset these so our total can be calculated correctly below
- unset($this->_cart_contents['total_items']);
- unset($this->_cart_contents['cart_total']);
-
// Lets add up the individual prices and set the cart sub-total
- $total = 0;
- $items = 0;
+ $this->_cart_contents['total_items'] = $this->_cart_contents['cart_total'] = 0;
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;
}
- $total += ($val['price'] * $val['qty']);
- $items += $val['qty'];
-
- // Set the subtotal
+ $this->_cart_contents['cart_total'] += ($val['price'] * $val['qty']);
+ $this->_cart_contents['total_items'] += $val['qty'];
$this->_cart_contents[$key]['subtotal'] = ($this->_cart_contents[$key]['price'] * $this->_cart_contents[$key]['qty']);
}
- // Set the cart total and total items.
- $this->_cart_contents['total_items'] = $items;
- $this->_cart_contents['cart_total'] = $total;
-
- // 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');
@@ -416,10 +416,9 @@ class CI_Cart {
/**
* Cart Total
*
- * @access public
- * @return integer
+ * @return int
*/
- function total()
+ public function total()
{
return $this->_cart_contents['cart_total'];
}
@@ -427,14 +426,31 @@ class CI_Cart {
// --------------------------------------------------------------------
/**
+ * Remove Item
+ *
+ * Removes an item from the cart
+ *
+ * @param int
+ * @return bool
+ */
+ public function remove($rowid)
+ {
+ // unset & save
+ unset($this->_cart_contents[$rowid]);
+ $this->_save_cart();
+ return TRUE;
+ }
+
+ // --------------------------------------------------------------------
+
+ /**
* Total Items
*
* Returns the total item count
*
- * @access public
- * @return integer
+ * @return int
*/
- function total_items()
+ public function total_items()
{
return $this->_cart_contents['total_items'];
}
@@ -446,12 +462,13 @@ class CI_Cart {
*
* Returns the entire cart array
*
- * @access public
+ * @param bool
* @return array
*/
- function contents()
+ public function contents($newest_first = FALSE)
{
- $cart = $this->_cart_contents;
+ // do we want the newest first?
+ $cart = ($newest_first) ? array_reverse($this->_cart_contents) : $this->_cart_contents;
// Remove these so they don't create a problem when showing the cart table
unset($cart['total_items']);
@@ -468,17 +485,12 @@ class CI_Cart {
* Returns TRUE if the rowid passed to this function correlates to an item
* that has options associated with it.
*
- * @access public
- * @return array
+ * @param mixed
+ * @return bool
*/
- function has_options($rowid = '')
+ public function has_options($rowid = '')
{
- if ( ! isset($this->_cart_contents[$rowid]['options']) OR count($this->_cart_contents[$rowid]['options']) === 0)
- {
- return FALSE;
- }
-
- return TRUE;
+ return (isset($this->_cart_contents[$rowid]['options']) && count($this->_cart_contents[$rowid]['options']) !== 0);
}
// --------------------------------------------------------------------
@@ -488,17 +500,12 @@ class CI_Cart {
*
* Returns the an array of options, for a particular product row ID
*
- * @access public
+ * @param int
* @return array
*/
- function product_options($rowid = '')
+ public function product_options($rowid = '')
{
- if ( ! isset($this->_cart_contents[$rowid]['options']))
- {
- return array();
- }
-
- return $this->_cart_contents[$rowid]['options'];
+ return isset($this->_cart_contents[$rowid]['options']) ? $this->_cart_contents[$rowid]['options'] : array();
}
// --------------------------------------------------------------------
@@ -508,20 +515,12 @@ class CI_Cart {
*
* Returns the supplied number with commas and a decimal point.
*
- * @access public
- * @return integer
+ * @param float
+ * @return string
*/
- function format_number($n = '')
+ public function format_number($n = '')
{
- if ($n == '')
- {
- return '';
- }
-
- // Remove anything that isn't a number or decimal point.
- $n = trim(preg_replace('/([^0-9\.])/i', '', $n));
-
- return number_format($n, 2, '.', ',');
+ return ($n === '') ? '' : number_format( (float) $n, 2, '.', ',');
}
// --------------------------------------------------------------------
@@ -531,22 +530,15 @@ class CI_Cart {
*
* Empties the cart and kills the session
*
- * @access public
- * @return null
+ * @return void
*/
- function destroy()
+ public function destroy()
{
- unset($this->_cart_contents);
-
- $this->_cart_contents['cart_total'] = 0;
- $this->_cart_contents['total_items'] = 0;
-
+ $this->_cart_contents = array('cart_total' => 0, 'total_items' => 0);
$this->CI->session->unset_userdata('cart_contents');
}
-
}
-// END Cart Class
/* End of file Cart.php */
/* Location: ./system/libraries/Cart.php */ \ No newline at end of file
diff --git a/system/libraries/Driver.php b/system/libraries/Driver.php
index 77476e139..86b233a15 100644
--- a/system/libraries/Driver.php
+++ b/system/libraries/Driver.php
@@ -1,20 +1,30 @@
-<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
+<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* CodeIgniter
*
- * An open source application development framework for PHP 5.1.6 or newer
+ * An open source application development framework for PHP 5.2.4 or newer
+ *
+ * NOTICE OF LICENSE
+ *
+ * Licensed under the Open Software License version 3.0
+ *
+ * This source file is subject to the Open Software License (OSL 3.0) that is
+ * bundled with this package in the files license.txt / license.rst. It is
+ * also available through the world wide web at this URL:
+ * http://opensource.org/licenses/OSL-3.0
+ * If you did not receive a copy of the license and are unable to obtain it
+ * through the world wide web, please send an email to
+ * licensing@ellislab.com so we can send you a copy immediately.
*
* @package CodeIgniter
* @author EllisLab Dev Team
- * @copyright Copyright (c) 2006 - 2011, EllisLab, Inc.
- * @license http://codeigniter.com/user_guide/license.html
+ * @copyright Copyright (c) 2006 - 2012, EllisLab, Inc. (http://ellislab.com/)
+ * @license http://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
* @link http://codeigniter.com
* @since Version 1.0
* @filesource
*/
-// ------------------------------------------------------------------------
-
/**
* CodeIgniter Driver Library Class
*
@@ -29,7 +39,18 @@
*/
class CI_Driver_Library {
- protected $valid_drivers = array();
+ /**
+ * 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;
/**
@@ -42,7 +63,7 @@ class CI_Driver_Library {
* @return object Child class
*/
public function __get($child)
- {
+ {
// Try to load the driver
return load_driver($child);
}
@@ -64,11 +85,11 @@ class CI_Driver_Library {
// The class will be prefixed with the parent lib
$child_class = $this->lib_name.'_'.$child;
-
+
// Remove the CI_ prefix and lowercase
$lib_name = ucfirst(strtolower(str_replace('CI_', '', $this->lib_name)));
$driver_name = strtolower(str_replace('CI_', '', $child_class));
-
+
if (in_array($driver_name, array_map('strtolower', $this->valid_drivers)))
{
// check and see if the driver is in a separate file
@@ -93,8 +114,8 @@ class CI_Driver_Library {
// it's a valid driver, but the file simply can't be found
if ( ! class_exists($child_class))
{
- log_message('error', "Unable to load the requested driver: ".$child_class);
- show_error("Unable to load the requested driver: ".$child_class);
+ log_message('error', 'Unable to load the requested driver: '.$child_class);
+ show_error('Unable to load the requested driver: '.$child_class);
}
}
@@ -108,9 +129,10 @@ class CI_Driver_Library {
log_message('error', 'Invalid driver requested: '.$child_class);
show_error('Invalid driver requested: '.$child_class);
}
+
}
-// END CI_Driver_Library CLASS
+// --------------------------------------------------------------------------
/**
* CodeIgniter Driver Class
@@ -125,12 +147,34 @@ class CI_Driver_Library {
* @link
*/
class CI_Driver {
- protected $parent;
- private $methods = array();
- private $properties = array();
+ /**
+ * Instance of the parent class
+ *
+ * @var object
+ */
+ protected $_parent;
- private static $reflections = array();
+ /**
+ * 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();
/**
* Decorate
@@ -142,14 +186,14 @@ class CI_Driver {
*/
public function decorate($parent)
{
- $this->parent = $parent;
+ $this->_parent = $parent;
// Lock down attributes to what is defined in the class
// and speed up references in magic methods
$class_name = get_class($parent);
- if ( ! isset(self::$reflections[$class_name]))
+ if ( ! isset(self::$_reflections[$class_name]))
{
$r = new ReflectionObject($parent);
@@ -157,7 +201,7 @@ class CI_Driver {
{
if ($method->isPublic())
{
- $this->methods[] = $method->getName();
+ $this->_methods[] = $method->getName();
}
}
@@ -165,15 +209,15 @@ class CI_Driver {
{
if ($prop->isPublic())
{
- $this->properties[] = $prop->getName();
+ $this->_properties[] = $prop->getName();
}
}
- self::$reflections[$class_name] = array($this->methods, $this->properties);
+ self::$_reflections[$class_name] = array($this->_methods, $this->_properties);
}
else
{
- list($this->methods, $this->properties) = self::$reflections[$class_name];
+ list($this->_methods, $this->_properties) = self::$_reflections[$class_name];
}
}
@@ -184,16 +228,15 @@ class CI_Driver {
*
* Handles access to the parent driver library's methods
*
- * @access public
* @param string
* @param array
* @return mixed
*/
public function __call($method, $args = array())
{
- if (in_array($method, $this->methods))
+ if (in_array($method, $this->_methods))
{
- return call_user_func_array(array($this->parent, $method), $args);
+ return call_user_func_array(array($this->_parent, $method), $args);
}
$trace = debug_backtrace();
@@ -213,9 +256,9 @@ class CI_Driver {
*/
public function __get($var)
{
- if (in_array($var, $this->properties))
+ if (in_array($var, $this->_properties))
{
- return $this->parent->$var;
+ return $this->_parent->$var;
}
}
@@ -232,16 +275,13 @@ class CI_Driver {
*/
public function __set($var, $val)
{
- if (in_array($var, $this->properties))
+ if (in_array($var, $this->_properties))
{
- $this->parent->$var = $val;
+ $this->_parent->$var = $val;
}
}
- // --------------------------------------------------------------------
-
}
-// END CI_Driver CLASS
/* End of file Driver.php */
/* Location: ./system/libraries/Driver.php */
diff --git a/system/libraries/Email.php b/system/libraries/Email.php
index 28a3d17b4..fdb9be4da 100644
--- a/system/libraries/Email.php
+++ b/system/libraries/Email.php
@@ -1,20 +1,30 @@
-<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
+<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* CodeIgniter
*
- * An open source application development framework for PHP 5.1.6 or newer
+ * An open source application development framework for PHP 5.2.4 or newer
+ *
+ * NOTICE OF LICENSE
+ *
+ * Licensed under the Open Software License version 3.0
+ *
+ * This source file is subject to the Open Software License (OSL 3.0) that is
+ * bundled with this package in the files license.txt / license.rst. It is
+ * also available through the world wide web at this URL:
+ * http://opensource.org/licenses/OSL-3.0
+ * If you did not receive a copy of the license and are unable to obtain it
+ * through the world wide web, please send an email to
+ * licensing@ellislab.com so we can send you a copy immediately.
*
* @package CodeIgniter
- * @author ExpressionEngine Dev Team
- * @copyright Copyright (c) 2008 - 2011, EllisLab, Inc.
- * @license http://codeigniter.com/user_guide/license.html
+ * @author EllisLab Dev Team
+ * @copyright Copyright (c) 2008 - 2012, EllisLab, Inc. (http://ellislab.com/)
+ * @license http://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
* @link http://codeigniter.com
* @since Version 1.0
* @filesource
*/
-// ------------------------------------------------------------------------
-
/**
* CodeIgniter Email Class
*
@@ -23,64 +33,68 @@
* @package CodeIgniter
* @subpackage Libraries
* @category Libraries
- * @author ExpressionEngine Dev Team
+ * @author EllisLab Dev Team
* @link http://codeigniter.com/user_guide/libraries/email.html
*/
class CI_Email {
- var $useragent = "CodeIgniter";
- var $mailpath = "/usr/sbin/sendmail"; // Sendmail path
- var $protocol = "mail"; // mail/sendmail/smtp
- var $smtp_host = ""; // SMTP Server. Example: mail.earthlink.net
- var $smtp_user = ""; // SMTP Username
- var $smtp_pass = ""; // SMTP Password
- var $smtp_port = "25"; // SMTP Port
- var $smtp_timeout = 5; // SMTP Timeout in seconds
- var $wordwrap = TRUE; // TRUE/FALSE Turns word-wrap on/off
- var $wrapchars = "76"; // Number of characters to wrap at.
- var $mailtype = "text"; // text/html Defines email formatting
- var $charset = "utf-8"; // Default char set: iso-8859-1 or us-ascii
- var $multipart = "mixed"; // "mixed" (in the body) or "related" (separate)
- var $alt_message = ''; // Alternative message for HTML emails
- var $validate = FALSE; // TRUE/FALSE. Enables email validation
- var $priority = "3"; // Default priority (1 - 5)
- var $newline = "\n"; // Default newline. "\r\n" or "\n" (Use "\r\n" to comply with RFC 822)
- var $crlf = "\n"; // The RFC 2045 compliant CRLF for quoted-printable is "\r\n". Apparently some servers,
+ public $useragent = 'CodeIgniter';
+ public $mailpath = '/usr/sbin/sendmail'; // Sendmail path
+ public $protocol = 'mail'; // mail/sendmail/smtp
+ public $smtp_host = ''; // SMTP Server. Example: mail.earthlink.net
+ public $smtp_user = ''; // SMTP Username
+ public $smtp_pass = ''; // SMTP Password
+ public $smtp_port = 25; // SMTP Port
+ public $smtp_timeout = 5; // SMTP Timeout in seconds
+ public $smtp_crypto = ''; // SMTP Encryption. Can be null, tls or ssl.
+ public $wordwrap = TRUE; // TRUE/FALSE Turns word-wrap on/off
+ public $wrapchars = 76; // Number of characters to wrap at.
+ public $mailtype = 'text'; // text/html Defines email formatting
+ public $charset = 'utf-8'; // Default char set: iso-8859-1 or us-ascii
+ public $multipart = 'mixed'; // "mixed" (in the body) or "related" (separate)
+ public $alt_message = ''; // Alternative message for HTML emails
+ public $validate = FALSE; // TRUE/FALSE. Enables email validation
+ public $priority = 3; // Default priority (1 - 5)
+ public $newline = "\n"; // Default newline. "\r\n" or "\n" (Use "\r\n" to comply with RFC 822)
+ public $crlf = "\n"; // The RFC 2045 compliant CRLF for quoted-printable is "\r\n". Apparently some servers,
// even on the receiving end think they need to muck with CRLFs, so using "\n", while
// distasteful, is the only thing that seems to work for all environments.
- var $send_multipart = TRUE; // TRUE/FALSE - Yahoo does not like multipart alternative, so this is an override. Set to FALSE for Yahoo.
- var $bcc_batch_mode = FALSE; // TRUE/FALSE Turns on/off Bcc batch feature
- var $bcc_batch_size = 200; // If bcc_batch_mode = TRUE, sets max number of Bccs in each batch
- var $_safe_mode = FALSE;
- var $_subject = "";
- var $_body = "";
- var $_finalbody = "";
- var $_alt_boundary = "";
- var $_atc_boundary = "";
- var $_header_str = "";
- var $_smtp_connect = "";
- var $_encoding = "8bit";
- var $_IP = FALSE;
- var $_smtp_auth = FALSE;
- var $_replyto_flag = FALSE;
- var $_debug_msg = array();
- var $_recipients = array();
- var $_cc_array = array();
- var $_bcc_array = array();
- var $_headers = array();
- var $_attach_name = array();
- var $_attach_type = array();
- var $_attach_disp = array();
- var $_protocols = array('mail', 'sendmail', 'smtp');
- var $_base_charsets = array('us-ascii', 'iso-2022-'); // 7-bit charsets (excluding language suffix)
- var $_bit_depths = array('7bit', '8bit');
- var $_priorities = array('1 (Highest)', '2 (High)', '3 (Normal)', '4 (Low)', '5 (Lowest)');
-
+ public $dsn = FALSE; // Delivery Status Notification
+ public $send_multipart = TRUE; // TRUE/FALSE - Yahoo does not like multipart alternative, so this is an override. Set to FALSE for Yahoo.
+ public $bcc_batch_mode = FALSE; // TRUE/FALSE - Turns on/off Bcc batch feature
+ public $bcc_batch_size = 200; // If bcc_batch_mode = TRUE, sets max number of Bccs in each batch
+
+ protected $_safe_mode = FALSE;
+ protected $_subject = '';
+ protected $_body = '';
+ protected $_finalbody = '';
+ protected $_alt_boundary = '';
+ protected $_atc_boundary = '';
+ protected $_header_str = '';
+ protected $_smtp_connect = '';
+ protected $_encoding = '8bit';
+ protected $_IP = FALSE;
+ protected $_smtp_auth = FALSE;
+ protected $_replyto_flag = FALSE;
+ protected $_debug_msg = array();
+ protected $_recipients = array();
+ protected $_cc_array = array();
+ protected $_bcc_array = array();
+ protected $_headers = array();
+ protected $_attach_name = array();
+ protected $_attach_type = array();
+ protected $_attach_disp = array();
+ protected $_protocols = array('mail', 'sendmail', 'smtp');
+ protected $_base_charsets = array('us-ascii', 'iso-2022-'); // 7-bit charsets (excluding language suffix)
+ protected $_bit_depths = array('7bit', '8bit');
+ protected $_priorities = array('1 (Highest)', '2 (High)', '3 (Normal)', '4 (Low)', '5 (Lowest)');
/**
* Constructor - Sets Email Preferences
*
* The constructor can be passed an array of config values
+ *
+ * @return void
*/
public function __construct($config = array())
{
@@ -90,11 +104,11 @@ class CI_Email {
}
else
{
- $this->_smtp_auth = ($this->smtp_user == '' AND $this->smtp_pass == '') ? FALSE : TRUE;
- $this->_safe_mode = ((boolean)@ini_get("safe_mode") === FALSE) ? FALSE : TRUE;
+ $this->_smtp_auth = ! ($this->smtp_user === '' && $this->smtp_pass === '');
+ $this->_safe_mode = (bool) @ini_get('safe_mode');
}
- log_message('debug', "Email Class Initialized");
+ log_message('debug', 'Email Class Initialized');
}
// --------------------------------------------------------------------
@@ -102,7 +116,6 @@ class CI_Email {
/**
* Initialize preferences
*
- * @access public
* @param array
* @return void
*/
@@ -126,8 +139,8 @@ class CI_Email {
}
$this->clear();
- $this->_smtp_auth = ($this->smtp_user == '' AND $this->smtp_pass == '') ? FALSE : TRUE;
- $this->_safe_mode = ((boolean)@ini_get("safe_mode") === FALSE) ? FALSE : TRUE;
+ $this->_smtp_auth = ! ($this->smtp_user === '' && $this->smtp_pass === '');
+ $this->_safe_mode = (bool) @ini_get('safe_mode');
return $this;
}
@@ -137,24 +150,24 @@ class CI_Email {
/**
* Initialize the Email Data
*
- * @access public
- * @return void
+ * @param bool
+ * @return object
*/
public function clear($clear_attachments = FALSE)
{
- $this->_subject = "";
- $this->_body = "";
- $this->_finalbody = "";
- $this->_header_str = "";
- $this->_replyto_flag = FALSE;
+ $this->_subject = '';
+ $this->_body = '';
+ $this->_finalbody = '';
+ $this->_header_str = '';
+ $this->_replyto_flag = FALSE;
$this->_recipients = array();
$this->_cc_array = array();
$this->_bcc_array = array();
$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)
{
@@ -171,16 +184,15 @@ class CI_Email {
/**
* Set FROM
*
- * @access public
* @param string
* @param string
- * @return void
+ * @return object
*/
public function from($from, $name = '')
{
- if (preg_match( '/\<(.*)\>/', $from, $match))
+ if (preg_match('/\<(.*)\>/', $from, $match))
{
- $from = $match['1'];
+ $from = $match[1];
}
if ($this->validate)
@@ -189,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))
@@ -203,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;
}
@@ -214,16 +226,15 @@ class CI_Email {
/**
* Set Reply-to
*
- * @access public
* @param string
* @param string
- * @return void
+ * @return object
*/
public function reply_to($replyto, $name = '')
{
- if (preg_match( '/\<(.*)\>/', $replyto, $match))
+ if (preg_match('/\<(.*)\>/', $replyto, $match))
{
- $replyto = $match['1'];
+ $replyto = $match[1];
}
if ($this->validate)
@@ -231,17 +242,17 @@ class CI_Email {
$this->validate_email($this->_str_to_array($replyto));
}
- if ($name == '')
+ if ($name === '')
{
$name = $replyto;
}
- if (strncmp($name, '"', 1) != 0)
+ if (strpos($name, '"') !== 0)
{
$name = '"'.$name.'"';
}
- $this->_set_header('Reply-To', $name.' <'.$replyto.'>');
+ $this->set_header('Reply-To', $name.' <'.$replyto.'>');
$this->_replyto_flag = TRUE;
return $this;
@@ -252,9 +263,8 @@ class CI_Email {
/**
* Set Recipients
*
- * @access public
* @param string
- * @return void
+ * @return object
*/
public function to($to)
{
@@ -266,19 +276,19 @@ class CI_Email {
$this->validate_email($to);
}
- if ($this->_get_protocol() != 'mail')
+ if ($this->_get_protocol() !== 'mail')
{
- $this->_set_header('To', implode(", ", $to));
+ $this->set_header('To', implode(', ', $to));
}
switch ($this->_get_protocol())
{
- case 'smtp' :
+ case 'smtp':
$this->_recipients = $to;
break;
- case 'sendmail' :
- case 'mail' :
- $this->_recipients = implode(", ", $to);
+ case 'sendmail':
+ case 'mail':
+ $this->_recipients = implode(', ', $to);
break;
}
@@ -290,23 +300,21 @@ class CI_Email {
/**
* Set CC
*
- * @access public
* @param string
- * @return void
+ * @return object
*/
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")
+ if ($this->_get_protocol() === 'smtp')
{
$this->_cc_array = $cc;
}
@@ -319,34 +327,32 @@ class CI_Email {
/**
* Set BCC
*
- * @access public
* @param string
* @param string
- * @return void
+ * @return object
*/
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)
{
$this->validate_email($bcc);
}
- if (($this->_get_protocol() == "smtp") OR ($this->bcc_batch_mode && count($bcc) > $this->bcc_batch_size))
+ if ($this->_get_protocol() === 'smtp' OR ($this->bcc_batch_mode && count($bcc) > $this->bcc_batch_size))
{
$this->_bcc_array = $bcc;
}
else
{
- $this->_set_header('Bcc', implode(", ", $bcc));
+ $this->set_header('Bcc', implode(', ', $bcc));
}
return $this;
@@ -357,14 +363,13 @@ class CI_Email {
/**
* Set Email Subject
*
- * @access public
* @param string
- * @return void
+ * @return object
*/
public function subject($subject)
{
$subject = $this->_prep_q_encoding($subject);
- $this->_set_header('Subject', $subject);
+ $this->set_header('Subject', $subject);
return $this;
}
@@ -373,13 +378,24 @@ class CI_Email {
/**
* Set Body
*
- * @access public
* @param string
- * @return void
+ * @return object
*/
public function message($body)
{
- $this->_body = stripslashes(rtrim(str_replace("\r", "", $body)));
+ $this->_body = rtrim(str_replace("\r", '', $body));
+
+ /* strip slashes only if magic quotes is ON
+ if we do it with magic quotes OFF, it strips real, user-inputted chars.
+
+ NOTE: In PHP 5.4 get_magic_quotes_gpc() will always return 0 and
+ it will probably not exist in future versions at all.
+ */
+ if ( ! is_php('5.4') && get_magic_quotes_gpc())
+ {
+ $this->_body = stripslashes($this->_body);
+ }
+
return $this;
}
@@ -388,15 +404,14 @@ class CI_Email {
/**
* Assign file attachments
*
- * @access public
* @param string
- * @return void
+ * @return object
*/
- public function attach($filename, $disposition = 'attachment')
+ public function attach($filename, $disposition = '', $newname = NULL, $mime = '')
{
- $this->_attach_name[] = $filename;
- $this->_attach_type[] = $this->_mime_types(pathinfo($filename, PATHINFO_EXTENSION));
- $this->_attach_disp[] = $disposition; // Can also be 'inline' Not sure if it matters
+ $this->_attach_name[] = array($filename, $newname);
+ $this->_attach_disp[] = empty($disposition) ? 'attachment' : $disposition; // Can also be 'inline' Not sure if it matters
+ $this->_attach_type[] = $mime;
return $this;
}
@@ -405,12 +420,11 @@ class CI_Email {
/**
* Add a Header Item
*
- * @access protected
* @param string
* @param string
* @return void
*/
- protected function _set_header($header, $value)
+ public function set_header($header, $value)
{
$this->_headers[$header] = $value;
}
@@ -420,7 +434,6 @@ class CI_Email {
/**
* Convert a String to an Array
*
- * @access protected
* @param string
* @return array
*/
@@ -428,16 +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 = trim($email);
- settype($email, "array");
- }
+ return (strpos($email, ',') !== FALSE)
+ ? preg_split('/[\s,]/', $email, -1, PREG_SPLIT_NO_EMPTY)
+ : (array) trim($email);
}
+
return $email;
}
@@ -446,9 +454,8 @@ class CI_Email {
/**
* Set Multipart Value
*
- * @access public
* @param string
- * @return void
+ * @return object
*/
public function set_alt_message($str = '')
{
@@ -461,13 +468,12 @@ class CI_Email {
/**
* Set Mailtype
*
- * @access public
* @param string
- * @return void
+ * @return object
*/
public function set_mailtype($type = 'text')
{
- $this->mailtype = ($type == 'html') ? 'html' : 'text';
+ $this->mailtype = ($type === 'html') ? 'html' : 'text';
return $this;
}
@@ -476,9 +482,8 @@ class CI_Email {
/**
* Set Wordwrap
*
- * @access public
* @param bool
- * @return void
+ * @return object
*/
public function set_wordwrap($wordwrap = TRUE)
{
@@ -491,13 +496,12 @@ class CI_Email {
/**
* Set Protocol
*
- * @access public
* @param string
- * @return void
+ * @return object
*/
public function set_protocol($protocol = 'mail')
{
- $this->protocol = ( ! in_array($protocol, $this->_protocols, TRUE)) ? 'mail' : strtolower($protocol);
+ $this->protocol = in_array($protocol, $this->_protocols, TRUE) ? strtolower($protocol) : 'mail';
return $this;
}
@@ -506,25 +510,12 @@ class CI_Email {
/**
* Set Priority
*
- * @access public
- * @param integer
- * @return void
+ * @param int
+ * @return object
*/
public function set_priority($n = 3)
{
- if ( ! is_numeric($n))
- {
- $this->priority = 3;
- return;
- }
-
- if ($n < 1 OR $n > 5)
- {
- $this->priority = 3;
- return;
- }
-
- $this->priority = $n;
+ $this->priority = preg_match('/^[1-5]$/', $n) ? (int) $n : 3;
return $this;
}
@@ -533,20 +524,12 @@ class CI_Email {
/**
* Set Newline Character
*
- * @access public
* @param string
- * @return void
+ * @return object
*/
public function set_newline($newline = "\n")
{
- if ($newline != "\n" AND $newline != "\r\n" AND $newline != "\r")
- {
- $this->newline = "\n";
- return;
- }
-
- $this->newline = $newline;
-
+ $this->newline = in_array($newline, array("\n", "\r\n", "\r")) ? $newline : "\n";
return $this;
}
@@ -555,20 +538,12 @@ class CI_Email {
/**
* Set CRLF
*
- * @access public
* @param string
- * @return void
+ * @return object
*/
public function set_crlf($crlf = "\n")
{
- if ($crlf != "\n" AND $crlf != "\r\n" AND $crlf != "\r")
- {
- $this->crlf = "\n";
- return;
- }
-
- $this->crlf = $crlf;
-
+ $this->crlf = ($crlf !== "\n" && $crlf !== "\r\n" && $crlf !== "\r") ? "\n" : $crlf;
return $this;
}
@@ -577,13 +552,12 @@ class CI_Email {
/**
* Set Message Boundary
*
- * @access protected
* @return void
*/
protected function _set_boundaries()
{
- $this->_alt_boundary = "B_ALT_".uniqid(''); // multipart/alternative
- $this->_atc_boundary = "B_ATC_".uniqid(''); // attachment boundary
+ $this->_alt_boundary = 'B_ALT_'.uniqid(''); // multipart/alternative
+ $this->_atc_boundary = 'B_ATC_'.uniqid(''); // attachment boundary
}
// --------------------------------------------------------------------
@@ -591,16 +565,12 @@ class CI_Email {
/**
* Get the Message ID
*
- * @access protected
* @return string
*/
protected function _get_message_id()
{
- $from = $this->_headers['Return-Path'];
- $from = str_replace(">", "", $from);
- $from = str_replace("<", "", $from);
-
- return "<".uniqid('').strstr($from, '@').">";
+ $from = str_replace(array('>', '<'), '', $this->_headers['Return-Path']);
+ return '<'.uniqid('').strstr($from, '@').'>';
}
// --------------------------------------------------------------------
@@ -608,16 +578,15 @@ class CI_Email {
/**
* Get Mail Protocol
*
- * @access protected
* @param bool
- * @return string
+ * @return mixed
*/
protected function _get_protocol($return = TRUE)
{
$this->protocol = strtolower($this->protocol);
- $this->protocol = ( ! in_array($this->protocol, $this->_protocols, TRUE)) ? 'mail' : $this->protocol;
+ in_array($this->protocol, $this->_protocols, TRUE) OR $this->protocol = 'mail';
- if ($return == TRUE)
+ if ($return === TRUE)
{
return $this->protocol;
}
@@ -628,23 +597,22 @@ class CI_Email {
/**
* Get Mail Encoding
*
- * @access protected
* @param bool
* @return string
*/
protected function _get_encoding($return = TRUE)
{
- $this->_encoding = ( ! in_array($this->_encoding, $this->_bit_depths)) ? '8bit' : $this->_encoding;
+ in_array($this->_encoding, $this->_bit_depths) OR $this->_encoding = '8bit';
foreach ($this->_base_charsets as $charset)
{
- if (strncmp($charset, $this->charset, strlen($charset)) == 0)
+ if (strpos($charset, $this->charset) === 0)
{
$this->_encoding = '7bit';
}
}
- if ($return == TRUE)
+ if ($return === TRUE)
{
return $this->_encoding;
}
@@ -655,20 +623,15 @@ class CI_Email {
/**
* Get content type (text/html/attachment)
*
- * @access protected
* @return string
*/
protected function _get_content_type()
{
- if ($this->mailtype == 'html' && count($this->_attach_name) == 0)
- {
- return 'html';
- }
- elseif ($this->mailtype == 'html' && count($this->_attach_name) > 0)
+ if ($this->mailtype === 'html')
{
- return 'html-attach';
+ return (count($this->_attach_name) === 0) ? 'html' : 'html-attach';
}
- elseif ($this->mailtype == 'text' && count($this->_attach_name) > 0)
+ elseif ($this->mailtype === 'text' && count($this->_attach_name) > 0)
{
return 'plain-attach';
}
@@ -683,17 +646,16 @@ class CI_Email {
/**
* Set RFC 822 Date
*
- * @access protected
* @return string
*/
protected function _set_date()
{
- $timezone = date("Z");
- $operator = (strncmp($timezone, '-', 1) == 0) ? '-' : '+';
+ $timezone = date('Z');
+ $operator = ($timezone[0] === '-') ? '-' : '+';
$timezone = abs($timezone);
- $timezone = floor($timezone/3600) * 100 + ($timezone % 3600 ) / 60;
+ $timezone = floor($timezone/3600) * 100 + ($timezone % 3600) / 60;
- return sprintf("%s %s%04d", date("D, j M Y H:i:s"), $operator, $timezone);
+ return sprintf('%s %s%04d', date('D, j M Y H:i:s'), $operator, $timezone);
}
// --------------------------------------------------------------------
@@ -701,12 +663,11 @@ class CI_Email {
/**
* Mime message
*
- * @access protected
* @return string
*/
protected function _get_mime_message()
{
- return "This is a multi-part message in MIME format.".$this->newline."Your email application may not support this format.";
+ return 'This is a multi-part message in MIME format.'.$this->newline.'Your email application may not support this format.';
}
// --------------------------------------------------------------------
@@ -714,7 +675,6 @@ class CI_Email {
/**
* Validate Email Address
*
- * @access public
* @param string
* @return bool
*/
@@ -743,13 +703,12 @@ class CI_Email {
/**
* Email Validation
*
- * @access public
* @param string
* @return bool
*/
- public function valid_email($address)
+ public function valid_email($email)
{
- return ( ! preg_match("/^([a-z0-9\+_\-]+)(\.[a-z0-9\+_\-]+)*@([a-z0-9\-]+\.)+[a-z]{2,6}$/ix", $address)) ? FALSE : TRUE;
+ return (bool) filter_var($email, FILTER_VALIDATE_EMAIL);
}
// --------------------------------------------------------------------
@@ -757,7 +716,6 @@ class CI_Email {
/**
* Clean Extended Email Address: Joe Smith <joe@smith.com>
*
- * @access public
* @param string
* @return string
*/
@@ -765,28 +723,14 @@ class CI_Email {
{
if ( ! is_array($email))
{
- if (preg_match('/\<(.*)\>/', $email, $match))
- {
- return $match['1'];
- }
- else
- {
- return $email;
- }
+ return preg_match('/\<(.*)\>/', $email, $match) ? $match[1] : $email;
}
$clean_email = array();
foreach ($email as $addy)
{
- if (preg_match( '/\<(.*)\>/', $addy, $match))
- {
- $clean_email[] = $match['1'];
- }
- else
- {
- $clean_email[] = $addy;
- }
+ $clean_email[] = preg_match('/\<(.*)\>/', $addy, $match) ? $match[1] : $addy;
}
return $clean_email;
@@ -802,42 +746,24 @@ class CI_Email {
* If the user hasn't specified his own alternative message
* it creates one by stripping the HTML
*
- * @access protected
* @return string
*/
protected function _get_alt_message()
{
- if ($this->alt_message != "")
+ if ($this->alt_message !== '')
{
return $this->word_wrap($this->alt_message, '76');
}
- if (preg_match('/\<body.*?\>(.*)\<\/body\>/si', $this->_body, $match))
- {
- $body = $match['1'];
- }
- else
- {
- $body = $this->_body;
- }
-
- $body = trim(strip_tags($body));
- $body = preg_replace( '#<!--(.*)--\>#', "", $body);
- $body = str_replace("\t", "", $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--)
{
- $n = "";
-
- for ($x = 1; $x <= $i; $x ++)
- {
- $n .= "\n";
- }
-
- $body = str_replace($n, "\n\n", $body);
+ $body = str_replace(str_repeat("\n", $i), "\n\n", $body);
}
- return $this->word_wrap($body, '76');
+ return $this->word_wrap($body, 76);
}
// --------------------------------------------------------------------
@@ -845,21 +771,20 @@ class CI_Email {
/**
* Word Wrap
*
- * @access public
* @param string
- * @param integer
+ * @param int
* @return string
*/
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)
@@ -870,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; $i < count($matches['0']); $i++)
+ for ($i = 0, $c = count($matches[0]); $i < $c; $i++)
{
- $unwrap[] = $matches['1'][$i];
- $str = str_replace($matches['1'][$i], "{{unwrapped".$i."}}", $str);
+ $unwrap[] = $matches[1][$i];
+ $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?
@@ -897,10 +822,10 @@ class CI_Email {
}
$temp = '';
- while ((strlen($line)) > $charlim)
+ 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;
}
@@ -909,19 +834,16 @@ class CI_Email {
$temp .= substr($line, 0, $charlim-1);
$line = substr($line, $charlim-1);
}
+ while (strlen($line) > $charlim);
// 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 != '')
- {
- $output .= $temp.$this->newline.$line;
- }
- else
+ if ($temp !== '')
{
- $output .= $line;
+ $output .= $temp.$this->newline;
}
- $output .= $this->newline;
+ $output .= $line.$this->newline;
}
// Put our markers back
@@ -929,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);
}
}
@@ -941,17 +863,15 @@ class CI_Email {
/**
* Build final headers
*
- * @access protected
- * @param string
* @return string
*/
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');
}
// --------------------------------------------------------------------
@@ -959,31 +879,30 @@ class CI_Email {
/**
* Write Headers as a string
*
- * @access protected
* @return void
*/
protected function _write_headers()
{
- if ($this->protocol == 'mail')
+ if ($this->protocol === 'mail')
{
$this->_subject = $this->_headers['Subject'];
unset($this->_headers['Subject']);
}
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;
}
}
- if ($this->_get_protocol() == 'mail')
+ if ($this->_get_protocol() === 'mail')
{
$this->_header_str = rtrim($this->_header_str);
}
@@ -994,12 +913,11 @@ class CI_Email {
/**
* Build Final Body and attachments
*
- * @access protected
* @return void
*/
protected function _build_message()
{
- if ($this->wordwrap === TRUE AND $this->mailtype != 'html')
+ if ($this->wordwrap === TRUE && $this->mailtype !== 'html')
{
$this->_body = $this->word_wrap($this->_body);
}
@@ -1007,17 +925,17 @@ class CI_Email {
$this->_set_boundaries();
$this->_write_headers();
- $hdr = ($this->_get_protocol() == 'mail') ? $this->newline : '';
+ $hdr = ($this->_get_protocol() === 'mail') ? $this->newline : '';
$body = '';
switch ($this->_get_content_type())
{
case 'plain' :
- $hdr .= "Content-Type: text/plain; charset=" . $this->charset . $this->newline;
- $hdr .= "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')
+ if ($this->_get_protocol() === 'mail')
{
$this->_header_str .= $hdr;
$this->_finalbody = $this->_body;
@@ -1029,143 +947,138 @@ class CI_Email {
return;
- break;
case 'html' :
if ($this->send_multipart === FALSE)
{
- $hdr .= "Content-Type: text/html; charset=" . $this->charset . $this->newline;
- $hdr .= "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;
- $body .= "--" . $this->_alt_boundary . $this->newline;
+ $body .= $this->_get_mime_message().$this->newline.$this->newline
+ .'--'.$this->_alt_boundary.$this->newline
- $body .= "Content-Type: text/plain; charset=" . $this->charset . $this->newline;
- $body .= "Content-Transfer-Encoding: " . $this->_get_encoding() . $this->newline . $this->newline;
- $body .= $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
- $body .= "Content-Type: text/html; charset=" . $this->charset . $this->newline;
- $body .= "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')
+ if ($this->_get_protocol() === 'mail')
{
$this->_header_str .= $hdr;
}
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;
- break;
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')
+ if ($this->_get_protocol() === 'mail')
{
$this->_header_str .= $hdr;
}
- $body .= $this->_get_mime_message() . $this->newline . $this->newline;
- $body .= "--" . $this->_atc_boundary . $this->newline;
+ $body .= $this->_get_mime_message().$this->newline.$this->newline
+ .'--'.$this->_atc_boundary.$this->newline
- $body .= "Content-Type: text/plain; charset=" . $this->charset . $this->newline;
- $body .= "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
- $body .= $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')
+ if ($this->_get_protocol() === 'mail')
{
$this->_header_str .= $hdr;
}
- $body .= $this->_get_mime_message() . $this->newline . $this->newline;
- $body .= "--" . $this->_atc_boundary . $this->newline;
+ $body .= $this->_get_mime_message().$this->newline.$this->newline
+ .'--'.$this->_atc_boundary.$this->newline
- $body .= "Content-Type: multipart/alternative; boundary=\"" . $this->_alt_boundary . "\"" . $this->newline .$this->newline;
- $body .= "--" . $this->_alt_boundary . $this->newline;
+ .'Content-Type: multipart/alternative; boundary="'.$this->_alt_boundary.'"'.$this->newline.$this->newline
+ .'--'.$this->_alt_boundary.$this->newline
- $body .= "Content-Type: text/plain; charset=" . $this->charset . $this->newline;
- $body .= "Content-Transfer-Encoding: " . $this->_get_encoding() . $this->newline . $this->newline;
- $body .= $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
- $body .= "Content-Type: text/html; charset=" . $this->charset . $this->newline;
- $body .= "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
- $body .= $this->_prep_quoted_printable($this->_body) . $this->newline . $this->newline;
- $body .= "--" . $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;
}
$attachment = array();
-
- $z = 0;
-
- for ($i=0; $i < count($this->_attach_name); $i++)
+ for ($i = 0, $c = count($this->_attach_name), $z = 0; $i < $c; $i++)
{
- $filename = $this->_attach_name[$i];
- $basename = basename($filename);
+ $filename = $this->_attach_name[$i][0];
+ $basename = is_null($this->_attach_name[$i][1]) ? basename($filename) : $this->_attach_name[$i][1];
$ctype = $this->_attach_type[$i];
+ $file_content = '';
- if ( ! file_exists($filename))
+ if ($this->_attach_type[$i] === '')
{
- $this->_set_error_message('lang:email_attachment_missing', $filename);
- return FALSE;
- }
+ if ( ! file_exists($filename))
+ {
+ $this->_set_error_message('lang:email_attachment_missing', $filename);
+ return FALSE;
+ }
- $h = "--".$this->_atc_boundary.$this->newline;
- $h .= "Content-type: ".$ctype."; ";
- $h .= "name=\"".$basename."\"".$this->newline;
- $h .= "Content-Disposition: ".$this->_attach_disp[$i].";".$this->newline;
- $h .= "Content-Transfer-Encoding: base64".$this->newline;
+ $file = filesize($filename) +1;
- $attachment[$z++] = $h;
- $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);
- }
-
- $body .= implode($this->newline, $attachment).$this->newline."--".$this->_atc_boundary."--";
-
+ $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;
- if ($this->_get_protocol() == 'mail')
- {
- $this->_finalbody = $body;
- }
- else
- {
- $this->_finalbody = $hdr . $body;
+ $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;
return;
}
@@ -1177,9 +1090,8 @@ class CI_Email {
* Prepares string for Quoted-Printable Content-Transfer-Encoding
* Refer to RFC 2045 http://www.ietf.org/rfc/rfc2045.txt
*
- * @access protected
* @param string
- * @param integer
+ * @param int
* @return string
*/
protected function _prep_quoted_printable($str, $charlim = '')
@@ -1187,16 +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';
+ $charlim = 76;
}
- // Reduce multiple spaces
- $str = preg_replace("| +|", " ", $str);
-
- // kill nulls
- $str = preg_replace('/\x00+/', '', $str);
+ // Reduce multiple spaces & remove nulls
+ $str = preg_replace(array('| +|', '/\x00+/'), array(' ', ''), $str);
// Standardize newlines
if (strpos($str, "\r") !== FALSE)
@@ -1208,13 +1117,10 @@ class CI_Email {
// properly and MUAs will behave, so {unwrap} must go!
$str = str_replace(array('{unwrap}', '{/unwrap}'), '', $str);
- // Break into an array of lines
- $lines = explode("\n", $str);
-
$escape = '=';
$output = '';
- foreach ($lines as $line)
+ foreach (explode("\n", $str) as $line)
{
$length = strlen($line);
$temp = '';
@@ -1225,17 +1131,15 @@ class CI_Email {
for ($i = 0; $i < $length; $i++)
{
// Grab the next character
- $char = substr($line, $i, 1);
+ $char = $line[$i];
$ascii = ord($char);
// Convert spaces and tabs but only if it's the end of the line
- if ($i == ($length - 1))
+ if ($i === ($length - 1) && ($ascii === 32 OR $ascii === 9))
{
- $char = ($ascii == '32' OR $ascii == '9') ? $escape.sprintf('%02s', dechex($ascii)) : $char;
+ $char = $escape.sprintf('%02s', dechex($ascii));
}
-
- // encode = signs
- if ($ascii == '61')
+ elseif ($ascii === 61) // encode = signs
{
$char = $escape.strtoupper(sprintf('%02s', dechex($ascii))); // =3D
}
@@ -1257,9 +1161,7 @@ class CI_Email {
}
// get rid of extra CRLF tacked onto the end
- $output = substr($output, 0, strlen($this->crlf) * -1);
-
- return $output;
+ return substr($output, 0, strlen($this->crlf) * -1);
}
// --------------------------------------------------------------------
@@ -1270,10 +1172,9 @@ class CI_Email {
* Performs "Q Encoding" on a string for use in email headers. It's related
* but not identical to quoted-printable, so it has its own method
*
- * @access public
- * @param str
- * @param bool // set to TRUE for processing From: headers
- * @return str
+ * @param string
+ * @param bool set to TRUE for processing From: headers
+ * @return string
*/
protected function _prep_q_encoding($str, $from = FALSE)
{
@@ -1298,7 +1199,7 @@ class CI_Email {
for ($i = 0, $length = strlen($str); $i < $length; $i++)
{
// Grab the next character
- $char = substr($str, $i, 1);
+ $char = $str[$i];
$ascii = ord($char);
// convert ALL non-printable ASCII characters and our specials
@@ -1308,7 +1209,7 @@ class CI_Email {
}
// handle regular spaces a bit more compactly than =20
- if ($ascii == 32)
+ if ($ascii === 32)
{
$char = '_';
}
@@ -1325,13 +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"
- $str = trim(preg_replace('/^(.*)$/m', ' =?'.$this->charset.'?Q?$1?=', $str));
-
- return $str;
+ return trim(preg_replace('/^(.*)$/m', ' =?'.$this->charset.'?Q?$1?=', $output.$temp));
}
// --------------------------------------------------------------------
@@ -1339,19 +1236,18 @@ class CI_Email {
/**
* Send Email
*
- * @access public
* @return bool
*/
public function send()
{
- if ($this->_replyto_flag == FALSE)
+ if ($this->_replyto_flag === FALSE)
{
$this->reply_to($this->_headers['From']);
}
- if (( ! isset($this->_recipients) AND ! isset($this->_headers['To'])) AND
- ( ! isset($this->_bcc_array) AND ! isset($this->_headers['Bcc'])) AND
- ( ! isset($this->_headers['Cc'])))
+ if ( ! isset($this->_recipients) && ! isset($this->_headers['To'])
+ && ! isset($this->_bcc_array) && ! isset($this->_headers['Bcc'])
+ && ! isset($this->_headers['Cc']))
{
$this->_set_error_message('lang:email_no_recipients');
return FALSE;
@@ -1359,71 +1255,57 @@ class CI_Email {
$this->_build_headers();
- if ($this->bcc_batch_mode AND count($this->_bcc_array) > 0)
+ if ($this->bcc_batch_mode && count($this->_bcc_array) > $this->bcc_batch_size)
{
- if (count($this->_bcc_array) > $this->bcc_batch_size)
- return $this->batch_bcc_send();
+ return $this->batch_bcc_send();
}
$this->_build_message();
-
- if ( ! $this->_spool_email())
- {
- return FALSE;
- }
- else
- {
- return TRUE;
- }
+ return $this->_spool_email();
}
// --------------------------------------------------------------------
/**
- * Batch Bcc Send. Sends groups of BCCs in batches
+ * Batch Bcc Send. Sends groups of BCCs in batches
*
- * @access public
- * @return bool
+ * @return void
*/
public function batch_bcc_send()
{
- $float = $this->bcc_batch_size -1;
-
- $set = "";
-
+ $float = $this->bcc_batch_size - 1;
+ $set = '';
$chunk = array();
- for ($i = 0; $i < count($this->_bcc_array); $i++)
+ for ($i = 0, $c = count($this->_bcc_array); $i < $c; $i++)
{
if (isset($this->_bcc_array[$i]))
{
- $set .= ", ".$this->_bcc_array[$i];
+ $set .= ', '.$this->_bcc_array[$i];
}
- if ($i == $float)
+ if ($i === $float)
{
$chunk[] = substr($set, 1);
- $float = $float + $this->bcc_batch_size;
- $set = "";
+ $float += $this->bcc_batch_size;
+ $set = '';
}
- if ($i == count($this->_bcc_array)-1)
+ if ($i === $c-1)
{
$chunk[] = substr($set, 1);
}
}
- for ($i = 0; $i < count($chunk); $i++)
+ for ($i = 0, $c = count($chunk); $i < $c; $i++)
{
unset($this->_headers['Bcc']);
- unset($bcc);
- $bcc = $this->_str_to_array($chunk[$i]);
- $bcc = $this->clean_email($bcc);
+ $bcc = $this->clean_email($this->_str_to_array($chunk[$i]));
- if ($this->protocol != 'smtp')
+ if ($this->protocol !== 'smtp')
{
- $this->_set_header('Bcc', implode(", ", $bcc));
+ $this->set_header('Bcc', implode(', ', $bcc));
}
else
{
@@ -1440,12 +1322,11 @@ class CI_Email {
/**
* Unwrap special elements
*
- * @access protected
* @return void
*/
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);
}
// --------------------------------------------------------------------
@@ -1453,7 +1334,6 @@ class CI_Email {
/**
* Strip line-breaks via callback
*
- * @access protected
* @return string
*/
protected function _remove_nl_callback($matches)
@@ -1471,40 +1351,17 @@ class CI_Email {
/**
* Spool mail to the mail server
*
- * @access protected
* @return bool
*/
protected function _spool_email()
{
$this->_unwrap_specials();
- switch ($this->_get_protocol())
+ $method = '_send_with_'.$this->_get_protocol();
+ if ( ! $this->$method())
{
- case 'mail' :
-
- if ( ! $this->_send_with_mail())
- {
- $this->_set_error_message('lang:email_send_failure_phpmail');
- return FALSE;
- }
- break;
- case 'sendmail' :
-
- if ( ! $this->_send_with_sendmail())
- {
- $this->_set_error_message('lang:email_send_failure_sendmail');
- return FALSE;
- }
- break;
- case 'smtp' :
-
- if ( ! $this->_send_with_smtp())
- {
- $this->_set_error_message('lang:email_send_failure_smtp');
- return FALSE;
- }
- break;
-
+ $this->_set_error_message('lang:email_send_failure_'.($this->_get_protocol() === 'mail' ? 'phpmail' : $this->_get_protocol()));
+ return FALSE;
}
$this->_set_error_message('lang:email_sent', $this->_get_protocol());
@@ -1516,35 +1373,19 @@ class CI_Email {
/**
* Send using mail()
*
- * @access protected
* @return bool
*/
protected function _send_with_mail()
{
- if ($this->_safe_mode == TRUE)
+ if ($this->_safe_mode === TRUE)
{
- if ( ! mail($this->_recipients, $this->_subject, $this->_finalbody, $this->_header_str))
- {
- return FALSE;
- }
- else
- {
- return TRUE;
- }
+ return mail($this->_recipients, $this->_subject, $this->_finalbody, $this->_header_str);
}
else
{
// 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.
-
- if ( ! mail($this->_recipients, $this->_subject, $this->_finalbody, $this->_header_str, "-f ".$this->clean_email($this->_headers['From'])))
- {
- return FALSE;
- }
- else
- {
- return TRUE;
- }
+ return mail($this->_recipients, $this->_subject, $this->_finalbody, $this->_header_str, '-f '.$this->clean_email($this->_headers['From']));
}
}
@@ -1553,12 +1394,11 @@ class CI_Email {
/**
* Send using Sendmail
*
- * @access protected
* @return bool
*/
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)
{
@@ -1571,12 +1411,7 @@ class CI_Email {
$status = pclose($fp);
- if (version_compare(PHP_VERSION, '4.2.3') == -1)
- {
- $status = $status >> 8 & 0xFF;
- }
-
- if ($status != 0)
+ if ($status !== 0)
{
$this->_set_error_message('lang:email_exit_status', $status);
$this->_set_error_message('lang:email_no_socket');
@@ -1591,19 +1426,20 @@ class CI_Email {
/**
* Send using SMTP
*
- * @access protected
* @return bool
*/
protected function _send_with_smtp()
{
- if ($this->smtp_host == '')
+ if ($this->smtp_host === '')
{
$this->_set_error_message('lang:email_no_hostname');
return FALSE;
}
- $this->_smtp_connect();
- $this->_smtp_authenticate();
+ if ( ! $this->_smtp_connect() OR ! $this->_smtp_authenticate())
+ {
+ return FALSE;
+ }
$this->_send_command('from', $this->clean_email($this->_headers['From']));
@@ -1616,7 +1452,7 @@ class CI_Email {
{
foreach ($this->_cc_array as $val)
{
- if ($val != "")
+ if ($val !== '')
{
$this->_send_command('to', $val);
}
@@ -1627,7 +1463,7 @@ class CI_Email {
{
foreach ($this->_bcc_array as $val)
{
- if ($val != "")
+ if ($val !== '')
{
$this->_send_command('to', $val);
}
@@ -1637,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('.');
@@ -1645,7 +1481,7 @@ class CI_Email {
$this->_set_error_message($reply);
- if (strncmp($reply, '250', 3) != 0)
+ if (strpos($reply, '250') !== 0)
{
$this->_set_error_message('lang:email_smtp_error', $reply);
return FALSE;
@@ -1660,25 +1496,41 @@ class CI_Email {
/**
* SMTP Connect
*
- * @access protected
* @param string
* @return string
*/
protected function _smtp_connect()
{
- $this->_smtp_connect = fsockopen($this->smtp_host,
- $this->smtp_port,
- $errno,
- $errstr,
- $this->smtp_timeout);
+ $ssl = ($this->smtp_crypto === 'ssl') ? 'ssl://' : NULL;
+
+ $this->_smtp_connect = fsockopen($ssl.$this->smtp_host,
+ $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')
+ {
+ $this->_send_command('hello');
+ $this->_send_command('starttls');
+
+ $crypto = stream_socket_enable_crypto($this->_smtp_connect, TRUE, STREAM_CRYPTO_METHOD_TLS_CLIENT);
+
+ if ($crypto !== TRUE)
+ {
+ $this->_set_error_message('lang:email_smtp_error', $this->_get_smtp_data());
+ return FALSE;
+ }
+ }
+
return $this->_send_command('hello');
}
@@ -1687,7 +1539,6 @@ class CI_Email {
/**
* Send SMTP command
*
- * @access protected
* @param string
* @param string
* @return string
@@ -1698,50 +1549,63 @@ 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' :
- $this->_send_data('RCPT TO:<'.$data.'>');
+ if ($this->dsn)
+ {
+ $this->_send_data('RCPT TO:<'.$data.'> NOTIFY=SUCCESS,DELAY,FAILURE ORCPT=rfc822;'.$data);
+ }
+ else
+ {
+ $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 ( (int) 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);
}
@@ -1754,7 +1618,6 @@ class CI_Email {
/**
* SMTP Authenticate
*
- * @access protected
* @return bool
*/
protected function _smtp_authenticate()
@@ -1764,7 +1627,7 @@ class CI_Email {
return TRUE;
}
- if ($this->smtp_user == "" AND $this->smtp_pass == "")
+ if ($this->smtp_user === '' && $this->smtp_pass === '')
{
$this->_set_error_message('lang:email_no_smtp_unpw');
return FALSE;
@@ -1774,7 +1637,7 @@ class CI_Email {
$reply = $this->_get_smtp_data();
- if (strncmp($reply, '334', 3) != 0)
+ if (strpos($reply, '334') !== 0)
{
$this->_set_error_message('lang:email_failed_smtp_login', $reply);
return FALSE;
@@ -1784,7 +1647,7 @@ class CI_Email {
$reply = $this->_get_smtp_data();
- if (strncmp($reply, '334', 3) != 0)
+ if (strpos($reply, '334') !== 0)
{
$this->_set_error_message('lang:email_smtp_auth_un', $reply);
return FALSE;
@@ -1794,7 +1657,7 @@ class CI_Email {
$reply = $this->_get_smtp_data();
- if (strncmp($reply, '235', 3) != 0)
+ if (strpos($reply, '235') !== 0)
{
$this->_set_error_message('lang:email_smtp_auth_pw', $reply);
return FALSE;
@@ -1808,7 +1671,6 @@ class CI_Email {
/**
* Send SMTP data
*
- * @access protected
* @return bool
*/
protected function _send_data($data)
@@ -1818,10 +1680,8 @@ class CI_Email {
$this->_set_error_message('lang:email_smtp_data_failure', $data);
return FALSE;
}
- else
- {
- return TRUE;
- }
+
+ return TRUE;
}
// --------------------------------------------------------------------
@@ -1829,18 +1689,17 @@ class CI_Email {
/**
* Get SMTP data
*
- * @access protected
* @return string
*/
protected function _get_smtp_data()
{
- $data = "";
+ $data = '';
while ($str = fgets($this->_smtp_connect, 512))
{
$data .= $str;
- if (substr($str, 3, 1) == " ")
+ if ($str[3] === ' ')
{
break;
}
@@ -1854,12 +1713,11 @@ class CI_Email {
/**
* Get Hostname
*
- * @access protected
* @return string
*/
protected function _get_hostname()
{
- return (isset($_SERVER['SERVER_NAME'])) ? $_SERVER['SERVER_NAME'] : 'localhost.localdomain';
+ return isset($_SERVER['SERVER_NAME']) ? $_SERVER['SERVER_NAME'] : 'localhost.localdomain';
}
// --------------------------------------------------------------------
@@ -1867,7 +1725,6 @@ class CI_Email {
/**
* Get IP
*
- * @access protected
* @return string
*/
protected function _get_ip()
@@ -1877,14 +1734,18 @@ class CI_Email {
return $this->_IP;
}
- $cip = (isset($_SERVER['HTTP_CLIENT_IP']) AND $_SERVER['HTTP_CLIENT_IP'] != "") ? $_SERVER['HTTP_CLIENT_IP'] : FALSE;
- $rip = (isset($_SERVER['REMOTE_ADDR']) AND $_SERVER['REMOTE_ADDR'] != "") ? $_SERVER['REMOTE_ADDR'] : FALSE;
- $fip = (isset($_SERVER['HTTP_X_FORWARDED_FOR']) AND $_SERVER['HTTP_X_FORWARDED_FOR'] != "") ? $_SERVER['HTTP_X_FORWARDED_FOR'] : FALSE;
-
- if ($cip && $rip) $this->_IP = $cip;
- elseif ($rip) $this->_IP = $rip;
- elseif ($cip) $this->_IP = $cip;
- elseif ($fip) $this->_IP = $fip;
+ $cip = ( ! empty($_SERVER['HTTP_CLIENT_IP'])) ? $_SERVER['HTTP_CLIENT_IP'] : FALSE;
+ $rip = ( ! empty($_SERVER['REMOTE_ADDR'])) ? $_SERVER['REMOTE_ADDR'] : FALSE;
+ if ($cip) $this->_IP = $cip;
+ elseif ($rip) $this->_IP = $rip;
+ else
+ {
+ $fip = ( ! empty($_SERVER['HTTP_X_FORWARDED_FOR'])) ? $_SERVER['HTTP_X_FORWARDED_FOR'] : FALSE;
+ if ($fip)
+ {
+ $this->_IP = $fip;
+ }
+ }
if (strpos($this->_IP, ',') !== FALSE)
{
@@ -1892,15 +1753,11 @@ class CI_Email {
$this->_IP = end($x);
}
- if ( ! preg_match( "/^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$/", $this->_IP))
+ if ( ! preg_match('/^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$/', $this->_IP))
{
$this->_IP = '0.0.0.0';
}
- unset($cip);
- unset($rip);
- unset($fip);
-
return $this->_IP;
}
@@ -1909,7 +1766,6 @@ class CI_Email {
/**
* Get Debug Message
*
- * @access public
* @return string
*/
public function print_debugger()
@@ -1924,8 +1780,7 @@ class CI_Email {
}
}
- $msg .= "<pre>".$this->_header_str."\n".htmlspecialchars($this->_subject)."\n".htmlspecialchars($this->_finalbody).'</pre>';
- return $msg;
+ return $msg.'<pre>'.$this->_header_str."\n".htmlspecialchars($this->_subject)."\n".htmlspecialchars($this->_finalbody).'</pre>';
}
// --------------------------------------------------------------------
@@ -1933,22 +1788,21 @@ class CI_Email {
/**
* Set Message
*
- * @access protected
* @param string
- * @return string
+ * @return void
*/
protected function _set_error_message($msg, $val = '')
{
$CI =& get_instance();
$CI->lang->load('email');
- if (substr($msg, 0, 5) != 'lang:' || FALSE === ($line = $CI->lang->line(substr($msg, 5))))
+ 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 />';
}
}
@@ -1957,106 +1811,31 @@ class CI_Email {
/**
* Mime Types
*
- * @access protected
* @param string
* @return string
*/
- protected function _mime_types($ext = "")
+ 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)])) ? "application/x-unknown-content-type" : $mimes[strtolower($ext)];
+ 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 CI_Email class
/* 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 b30a8cf0b..8ffd93aea 100644
--- a/system/libraries/Encrypt.php
+++ b/system/libraries/Encrypt.php
@@ -1,20 +1,30 @@
-<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
+<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* CodeIgniter
*
- * An open source application development framework for PHP 5.1.6 or newer
+ * An open source application development framework for PHP 5.2.4 or newer
+ *
+ * NOTICE OF LICENSE
+ *
+ * Licensed under the Open Software License version 3.0
+ *
+ * This source file is subject to the Open Software License (OSL 3.0) that is
+ * bundled with this package in the files license.txt / license.rst. It is
+ * also available through the world wide web at this URL:
+ * http://opensource.org/licenses/OSL-3.0
+ * If you did not receive a copy of the license and are unable to obtain it
+ * through the world wide web, please send an email to
+ * licensing@ellislab.com so we can send you a copy immediately.
*
* @package CodeIgniter
- * @author ExpressionEngine Dev Team
- * @copyright Copyright (c) 2008 - 2011, EllisLab, Inc.
- * @license http://codeigniter.com/user_guide/license.html
+ * @author EllisLab Dev Team
+ * @copyright Copyright (c) 2008 - 2012, EllisLab, Inc. (http://ellislab.com/)
+ * @license http://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
* @link http://codeigniter.com
* @since Version 1.0
* @filesource
*/
-// ------------------------------------------------------------------------
-
/**
* CodeIgniter Encryption Class
*
@@ -23,29 +33,55 @@
* @package CodeIgniter
* @subpackage Libraries
* @category Libraries
- * @author ExpressionEngine Dev Team
+ * @author EllisLab Dev Team
* @link http://codeigniter.com/user_guide/libraries/encryption.html
*/
class CI_Encrypt {
- var $CI;
- var $encryption_key = '';
- var $_hash_type = 'sha1';
- var $_mcrypt_exists = FALSE;
- var $_mcrypt_cipher;
- var $_mcrypt_mode;
+ /**
+ * Reference to the user's encryption key
+ *
+ * @var string
+ */
+ public $encryption_key = '';
/**
- * Constructor
+ * Type of hash operation
*
- * Simply determines whether the mcrypt library exists.
+ * @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->CI =& get_instance();
- $this->_mcrypt_exists = ( ! function_exists('mcrypt_encrypt')) ? FALSE : TRUE;
- log_message('debug', "Encrypt Class Initialized");
+ $this->_mcrypt_exists = function_exists('mcrypt_encrypt');
+ log_message('debug', 'Encrypt Class Initialized');
}
// --------------------------------------------------------------------
@@ -56,23 +92,21 @@ class CI_Encrypt {
* Returns it as MD5 in order to have an exact-length 128 bit key.
* Mcrypt is sensitive to keys that are not the correct length
*
- * @access public
* @param string
* @return string
*/
- function get_key($key = '')
+ 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)
+ if ($key === FALSE)
{
show_error('In order to use the encryption class requires that you set an encryption key in your config file.');
}
@@ -86,13 +120,13 @@ class CI_Encrypt {
/**
* Set the encryption key
*
- * @access public
* @param string
- * @return void
+ * @return object
*/
- function set_key($key = '')
+ public function set_key($key = '')
{
$this->encryption_key = $key;
+ return $this;
}
// --------------------------------------------------------------------
@@ -108,25 +142,14 @@ class CI_Encrypt {
* that is randomized with each call to this function,
* even if the supplied message and key are the same.
*
- * @access public
* @param string the string to encode
* @param string the key
* @return string
*/
- function encode($string, $key = '')
+ public function encode($string, $key = '')
{
- $key = $this->get_key($key);
-
- if ($this->_mcrypt_exists === TRUE)
- {
- $enc = $this->mcrypt_encode($string, $key);
- }
- else
- {
- $enc = $this->_xor_encode($string, $key);
- }
-
- return base64_encode($enc);
+ $method = ($this->_mcrypt_exists === TRUE) ? 'mcrypt_encode' : '_xor_encode';
+ return base64_encode($this->$method($string, $this->get_key($key)));
}
// --------------------------------------------------------------------
@@ -136,35 +159,19 @@ class CI_Encrypt {
*
* Reverses the above process
*
- * @access public
* @param string
* @param string
* @return string
*/
- function decode($string, $key = '')
+ public function decode($string, $key = '')
{
- $key = $this->get_key($key);
-
if (preg_match('/[^a-zA-Z0-9\/\+=]/', $string))
{
return FALSE;
}
- $dec = base64_decode($string);
-
- if ($this->_mcrypt_exists === TRUE)
- {
- if (($dec = $this->mcrypt_decode($dec, $key)) === FALSE)
- {
- return FALSE;
- }
- }
- else
- {
- $dec = $this->_xor_decode($dec, $key);
- }
-
- return $dec;
+ $method = ($this->_mcrypt_exists === TRUE) ? 'mcrypt_decode' : '_xor_decode';
+ return $this->$method(base64_decode($string), $this->get_key($key));
}
// --------------------------------------------------------------------
@@ -179,19 +186,22 @@ class CI_Encrypt {
*
* For more details, see http://codeigniter.com/user_guide/installation/upgrade_200.html#encryption
*
- * @access public
* @param string
* @param int (mcrypt mode constant)
* @param string
* @return string
*/
- function encode_from_legacy($string, $legacy_mode = MCRYPT_MODE_ECB, $key = '')
+ public function encode_from_legacy($string, $legacy_mode = MCRYPT_MODE_ECB, $key = '')
{
if ($this->_mcrypt_exists === FALSE)
{
log_message('error', 'Encoding from legacy is available only when Mcrypt is in use.');
return FALSE;
}
+ elseif (preg_match('/[^a-zA-Z0-9\/\+=]/', $string))
+ {
+ return FALSE;
+ }
// decode it first
// set mode temporarily to what it was when string was encoded with the legacy
@@ -200,16 +210,10 @@ class CI_Encrypt {
$this->set_mode($legacy_mode);
$key = $this->get_key($key);
-
- if (preg_match('/[^a-zA-Z0-9\/\+=]/', $string))
- {
- return FALSE;
- }
-
$dec = base64_decode($string);
-
if (($dec = $this->mcrypt_decode($dec, $key)) === FALSE)
{
+ $this->set_mode($current_mode);
return FALSE;
}
@@ -230,25 +234,25 @@ class CI_Encrypt {
* Takes a plain-text string and key as input and generates an
* encoded bit-string using XOR
*
- * @access private
* @param string
* @param string
* @return string
*/
- function _xor_encode($string, $key)
+ protected function _xor_encode($string, $key)
{
$rand = '';
- while (strlen($rand) < 32)
+ do
{
$rand .= mt_rand(0, mt_getrandmax());
}
+ while (strlen($rand) < 32);
$rand = $this->hash($rand);
$enc = '';
- for ($i = 0; $i < strlen($string); $i++)
+ for ($i = 0, $ls = strlen($string), $lr = strlen($rand); $i < $ls; $i++)
{
- $enc .= substr($rand, ($i % strlen($rand)), 1).(substr($rand, ($i % strlen($rand)), 1) ^ substr($string, $i, 1));
+ $enc .= $rand[($i % $lr)].($rand[($i % $lr)] ^ $string[$i]);
}
return $this->_xor_merge($enc, $key);
@@ -262,19 +266,18 @@ class CI_Encrypt {
* Takes an encoded string and key as input and generates the
* plain-text original message
*
- * @access private
* @param string
* @param string
* @return string
*/
- function _xor_decode($string, $key)
+ protected function _xor_decode($string, $key)
{
$string = $this->_xor_merge($string, $key);
$dec = '';
- for ($i = 0; $i < strlen($string); $i++)
+ for ($i = 0, $l = strlen($string); $i < $l; $i++)
{
- $dec .= (substr($string, $i++, 1) ^ substr($string, $i, 1));
+ $dec .= ($string[$i++] ^ $string[$i]);
}
return $dec;
@@ -287,18 +290,17 @@ class CI_Encrypt {
*
* Takes a string and key as input and computes the difference using XOR
*
- * @access private
* @param string
* @param string
* @return string
*/
- function _xor_merge($string, $key)
+ protected function _xor_merge($string, $key)
{
$hash = $this->hash($key);
$str = '';
- for ($i = 0; $i < strlen($string); $i++)
+ for ($i = 0, $ls = strlen($string), $lh = strlen($hash); $i < $ls; $i++)
{
- $str .= substr($string, $i, 1) ^ substr($hash, ($i % strlen($hash)), 1);
+ $str .= $string[$i] ^ $hash[($i % $lh)];
}
return $str;
@@ -309,12 +311,11 @@ class CI_Encrypt {
/**
* Encrypt using Mcrypt
*
- * @access public
* @param string
* @param string
* @return string
*/
- function mcrypt_encode($data, $key)
+ public function mcrypt_encode($data, $key)
{
$init_size = mcrypt_get_iv_size($this->_get_cipher(), $this->_get_mode());
$init_vect = mcrypt_create_iv($init_size, MCRYPT_RAND);
@@ -326,12 +327,11 @@ class CI_Encrypt {
/**
* Decrypt using Mcrypt
*
- * @access public
* @param string
* @param string
* @return string
*/
- function mcrypt_decode($data, $key)
+ public function mcrypt_decode($data, $key)
{
$data = $this->_remove_cipher_noise($data, $key);
$init_size = mcrypt_get_iv_size($this->_get_cipher(), $this->_get_mode());
@@ -353,27 +353,23 @@ class CI_Encrypt {
* against Man-in-the-middle attacks on CBC mode ciphers
* http://www.ciphersbyritter.com/GLOSSARY.HTM#IV
*
- * Function description
- *
- * @access private
* @param string
* @param string
* @return string
*/
- function _add_cipher_noise($data, $key)
+ protected function _add_cipher_noise($data, $key)
{
- $keyhash = $this->hash($key);
- $keylen = strlen($keyhash);
+ $key = $this->hash($key);
$str = '';
- for ($i = 0, $j = 0, $len = strlen($data); $i < $len; ++$i, ++$j)
+ for ($i = 0, $j = 0, $ld = strlen($data), $lk = strlen($key); $i < $ld; ++$i, ++$j)
{
- if ($j >= $keylen)
+ if ($j >= $lk)
{
$j = 0;
}
- $str .= chr((ord($data[$i]) + ord($keyhash[$j])) % 256);
+ $str .= chr((ord($data[$i]) + ord($key[$j])) % 256);
}
return $str;
@@ -387,28 +383,27 @@ class CI_Encrypt {
*
* Function description
*
- * @access public
- * @param type
- * @return type
+ * @param string $data
+ * @param string $key
+ * @return string
*/
- function _remove_cipher_noise($data, $key)
+ protected function _remove_cipher_noise($data, $key)
{
- $keyhash = $this->hash($key);
- $keylen = strlen($keyhash);
+ $key = $this->hash($key);
$str = '';
- for ($i = 0, $j = 0, $len = strlen($data); $i < $len; ++$i, ++$j)
+ for ($i = 0, $j = 0, $ld = strlen($data), $lk = strlen($key); $i < $ld; ++$i, ++$j)
{
- if ($j >= $keylen)
+ if ($j >= $lk)
{
$j = 0;
}
- $temp = ord($data[$i]) - ord($keyhash[$j]);
+ $temp = ord($data[$i]) - ord($key[$j]);
if ($temp < 0)
{
- $temp = $temp + 256;
+ $temp += 256;
}
$str .= chr($temp);
@@ -422,13 +417,13 @@ class CI_Encrypt {
/**
* Set the Mcrypt Cipher
*
- * @access public
- * @param constant
- * @return string
+ * @param int
+ * @return object
*/
- function set_cipher($cipher)
+ public function set_cipher($cipher)
{
$this->_mcrypt_cipher = $cipher;
+ return $this;
}
// --------------------------------------------------------------------
@@ -436,13 +431,13 @@ class CI_Encrypt {
/**
* Set the Mcrypt Mode
*
- * @access public
- * @param constant
- * @return string
+ * @param int
+ * @return object
*/
- function set_mode($mode)
+ public function set_mode($mode)
{
$this->_mcrypt_mode = $mode;
+ return $this;
}
// --------------------------------------------------------------------
@@ -450,14 +445,13 @@ class CI_Encrypt {
/**
* Get Mcrypt cipher Value
*
- * @access private
- * @return string
+ * @return int
*/
- function _get_cipher()
+ protected function _get_cipher()
{
- if ($this->_mcrypt_cipher == '')
+ if ($this->_mcrypt_cipher === NULL)
{
- $this->_mcrypt_cipher = MCRYPT_RIJNDAEL_256;
+ return $this->_mcrypt_cipher = MCRYPT_RIJNDAEL_256;
}
return $this->_mcrypt_cipher;
@@ -468,14 +462,13 @@ class CI_Encrypt {
/**
* Get Mcrypt Mode Value
*
- * @access private
- * @return string
+ * @return int
*/
- function _get_mode()
+ protected function _get_mode()
{
- if ($this->_mcrypt_mode == '')
+ if ($this->_mcrypt_mode === NULL)
{
- $this->_mcrypt_mode = MCRYPT_MODE_CBC;
+ return $this->_mcrypt_mode = MCRYPT_MODE_CBC;
}
return $this->_mcrypt_mode;
@@ -486,13 +479,12 @@ class CI_Encrypt {
/**
* Set the Hash type
*
- * @access public
* @param string
- * @return string
+ * @return void
*/
- function set_hash($type = 'sha1')
+ public function set_hash($type = 'sha1')
{
- $this->_hash_type = ($type != 'sha1' AND $type != 'md5') ? 'sha1' : $type;
+ $this->_hash_type = ($type !== 'sha1' && $type !== 'md5') ? 'sha1' : $type;
}
// --------------------------------------------------------------------
@@ -500,48 +492,15 @@ class CI_Encrypt {
/**
* Hash encode a string
*
- * @access public
- * @param string
- * @return string
- */
- function hash($str)
- {
- return ($this->_hash_type == 'sha1') ? $this->sha1($str) : md5($str);
- }
-
- // --------------------------------------------------------------------
-
- /**
- * Generate an SHA1 Hash
- *
- * @access public
* @param string
* @return string
*/
- function sha1($str)
+ public function hash($str)
{
- if ( ! function_exists('sha1'))
- {
- if ( ! function_exists('mhash'))
- {
- require_once(BASEPATH.'libraries/Sha1.php');
- $SH = new CI_SHA;
- return $SH->generate($str);
- }
- else
- {
- return bin2hex(mhash(MHASH_SHA1, $str));
- }
- }
- else
- {
- return sha1($str);
- }
+ return ($this->_hash_type === 'sha1') ? sha1($str) : md5($str);
}
}
-// END CI_Encrypt class
-
/* End of file 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 a34809e05..b490a34ca 100644
--- a/system/libraries/Form_validation.php
+++ b/system/libraries/Form_validation.php
@@ -1,48 +1,133 @@
-<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
+<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* CodeIgniter
*
- * An open source application development framework for PHP 5.1.6 or newer
+ * An open source application development framework for PHP 5.2.4 or newer
+ *
+ * NOTICE OF LICENSE
+ *
+ * Licensed under the Open Software License version 3.0
+ *
+ * This source file is subject to the Open Software License (OSL 3.0) that is
+ * bundled with this package in the files license.txt / license.rst. It is
+ * also available through the world wide web at this URL:
+ * http://opensource.org/licenses/OSL-3.0
+ * If you did not receive a copy of the license and are unable to obtain it
+ * through the world wide web, please send an email to
+ * licensing@ellislab.com so we can send you a copy immediately.
*
* @package CodeIgniter
- * @author ExpressionEngine Dev Team
- * @copyright Copyright (c) 2008 - 2011, EllisLab, Inc.
- * @license http://codeigniter.com/user_guide/license.html
+ * @author EllisLab Dev Team
+ * @copyright Copyright (c) 2008 - 2012, EllisLab, Inc. (http://ellislab.com/)
+ * @license http://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
* @link http://codeigniter.com
* @since Version 1.0
* @filesource
*/
-// ------------------------------------------------------------------------
-
/**
* Form Validation Class
*
* @package CodeIgniter
* @subpackage Libraries
* @category Validation
- * @author ExpressionEngine Dev Team
+ * @author EllisLab Dev Team
* @link http://codeigniter.com/user_guide/libraries/form_validation.html
*/
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;
/**
- * Constructor
+ * 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();
+ // applies delimiters set in config file.
+ if (isset($rules['error_prefix']))
+ {
+ $this->_error_prefix = $rules['error_prefix'];
+ unset($rules['error_prefix']);
+ }
+ if (isset($rules['error_suffix']))
+ {
+ $this->_error_suffix = $rules['error_suffix'];
+ unset($rules['error_suffix']);
+ }
+
// Validation rules can be stored in a config file.
$this->_config_rules = $rules;
@@ -50,12 +135,12 @@ class CI_Form_validation {
$this->CI->load->helper('form');
// Set the character encoding in MB.
- if (function_exists('mb_internal_encoding'))
+ if (MB_ENABLED === TRUE)
{
mb_internal_encoding($this->CI->config->item('charset'));
}
- log_message('debug', "Form Validation Class Initialized");
+ log_message('debug', 'Form Validation Class Initialized');
}
// --------------------------------------------------------------------
@@ -66,64 +151,71 @@ class CI_Form_validation {
* This function takes an array of field names and validation
* rules as input, validates the info, and stores it
*
- * @access public
- * @param mixed
- * @param string
- * @return void
+ * @param mixed $field
+ * @param string $label
+ * @param mixed $rules
+ * @return object
*/
public function set_rules($field, $label = '', $rules = '')
{
// No reason to set rules if we have no POST data
- if (count($_POST) == 0)
+ // or a validation array has not been specified
+ if ($this->CI->input->method() !== 'post' && empty($this->validation_data))
{
return $this;
}
- // If an array was passed via the first parameter instead of indidual string
+ // If an array was passed via the first parameter instead of individual string
// values we cycle through it and recursively call this function.
if (is_array($field))
{
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;
}
+ // Convert an array of rules to a string
+ if (is_array($rules))
+ {
+ $rules = implode('|', $rules);
+ }
+
// 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? We test for the existence of a bracket "[" in
- // the field name to determine this. If it is an array, we break it apart
+ // 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
- if (strpos($field, '[') !== FALSE AND preg_match_all('/\[(.*?)\]/', $field, $matches))
+ if (preg_match_all('/\[(.*?)\]/', $field, $matches))
{
// Note: Due to a bug in current() that affects some versions
// of PHP we can not pass function call directly into it
$x = explode('[', $field);
$indexes[] = current($x);
- for ($i = 0; $i < count($matches['0']); $i++)
+ for ($i = 0, $c = count($matches[0]); $i < $c; $i++)
{
- if ($matches['1'][$i] != '')
+ if ($matches[1][$i] !== '')
{
- $indexes[] = $matches['1'][$i];
+ $indexes[] = $matches[1][$i];
}
}
@@ -137,13 +229,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;
@@ -152,15 +244,37 @@ class CI_Form_validation {
// --------------------------------------------------------------------
/**
+ * By default, form validation uses the $_POST array to validate
+ *
+ * If an array is set through this method, then this array will
+ * be used instead of the $_POST array
+ *
+ * Note that if you are validating multiple arrays, then the
+ * reset_validation() function should be called after validating
+ * each array due to the limitations of CI's singleton
+ *
+ * @param array $data
+ * @return void
+ */
+ public function set_data($data = '')
+ {
+ if ( ! empty($data) && is_array($data))
+ {
+ $this->validation_data = $data;
+ }
+ }
+
+ // --------------------------------------------------------------------
+
+ /**
* 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.
*
- * @access public
- * @param string
+ * @param array
* @param string
- * @return string
+ * @return object
*/
public function set_message($lang, $val = '')
{
@@ -170,7 +284,6 @@ class CI_Form_validation {
}
$this->_error_messages = array_merge($this->_error_messages, $lang);
-
return $this;
}
@@ -181,16 +294,14 @@ class CI_Form_validation {
*
* Permits a prefix/suffix to be added to each error message
*
- * @access public
* @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;
}
@@ -201,23 +312,24 @@ class CI_Form_validation {
*
* Gets the error message associated with a particular field
*
- * @access public
* @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;
}
@@ -228,14 +340,27 @@ class CI_Form_validation {
// --------------------------------------------------------------------
/**
+ * Get Array of Error Messages
+ *
+ * Returns the error messages as an array
+ *
+ * @return array
+ */
+ public function error_array()
+ {
+ return $this->_error_array;
+ }
+
+ // --------------------------------------------------------------------
+
+ /**
* Error String
*
* Returns the error messages as a string, wrapped in the error delimiters
*
- * @access public
* @param string
* @param string
- * @return str
+ * @return string
*/
public function error_string($prefix = '', $suffix = '')
{
@@ -245,12 +370,12 @@ class CI_Form_validation {
return '';
}
- if ($prefix == '')
+ if ($prefix === '')
{
$prefix = $this->_error_prefix;
}
- if ($suffix == '')
+ if ($suffix === '')
{
$suffix = $this->_error_suffix;
}
@@ -259,7 +384,7 @@ class CI_Form_validation {
$str = '';
foreach ($this->_error_array as $val)
{
- if ($val != '')
+ if ($val !== '')
{
$str .= $prefix.$val.$suffix."\n";
}
@@ -275,31 +400,32 @@ class CI_Form_validation {
*
* This function does all the work.
*
- * @access public
+ * @param string $group
* @return bool
*/
public function run($group = '')
{
// Do we even have any data to process? Mm?
- if (count($_POST) == 0)
+ $validation_array = empty($this->validation_data) ? $_POST : $this->validation_data;
+ if (count($validation_array) === 0)
{
return FALSE;
}
// Does the _field_data array containing the validation rules exist?
// If not, we look to see if they were assigned via a config file
- if (count($this->_field_data) == 0)
+ if (count($this->_field_data) === 0)
{
// No validation rules? We're done...
- if (count($this->_config_rules) == 0)
+ if (count($this->_config_rules) === 0)
{
return FALSE;
}
// 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]);
}
@@ -308,10 +434,10 @@ class CI_Form_validation {
$this->set_rules($this->_config_rules);
}
- // We're we able to set the rules correctly?
- if (count($this->_field_data) == 0)
+ // 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;
}
}
@@ -323,19 +449,21 @@ class CI_Form_validation {
// corresponding $_POST item and test for errors
foreach ($this->_field_data as $field => $row)
{
- // Fetch the data from the corresponding $_POST array and cache it in the _field_data array.
+ // 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)
+ if ($row['is_array'] === TRUE)
{
- $this->_field_data[$field]['postdata'] = $this->_reduce_array($_POST, $row['keys']);
+ $this->_field_data[$field]['postdata'] = $this->_reduce_array($validation_array, $row['keys']);
}
- else
+ elseif (isset($validation_array[$field]) && $validation_array[$field] !== '')
{
- if (isset($_POST[$field]) AND $_POST[$field] != "")
- {
- $this->_field_data[$field]['postdata'] = $_POST[$field];
- }
+ $this->_field_data[$field]['postdata'] = $validation_array[$field];
+ }
+
+ // Don't try to validate if we have no rules set
+ if (empty($row['rules']))
+ {
+ continue;
}
$this->_execute($row, explode('|', $row['rules']), $this->_field_data[$field]['postdata']);
@@ -343,7 +471,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;
@@ -352,14 +479,7 @@ class CI_Form_validation {
// Now we need to re-set the POST data with the new, processed data
$this->_reset_post_array();
- // No errors, validation passes!
- if ($total_errors == 0)
- {
- return TRUE;
- }
-
- // Validation fails
- return FALSE;
+ return ($total_errors === 0);
}
// --------------------------------------------------------------------
@@ -367,31 +487,16 @@ class CI_Form_validation {
/**
* Traverse a multidimensional $_POST array index until the data is found
*
- * @access private
* @param array
* @param array
- * @param integer
+ * @param int
* @return mixed
*/
protected function _reduce_array($array, $keys, $i = 0)
{
- if (is_array($array))
+ if (is_array($array) && isset($keys[$i]))
{
- if (isset($keys[$i]))
- {
- if (isset($array[$keys[$i]]))
- {
- $array = $this->_reduce_array($array[$keys[$i]], $keys, ($i+1));
- }
- else
- {
- return NULL;
- }
- }
- else
- {
- return $array;
- }
+ return isset($array[$keys[$i]]) ? $this->_reduce_array($array[$keys[$i]], $keys, ($i+1)) : NULL;
}
return $array;
@@ -402,8 +507,7 @@ class CI_Form_validation {
/**
* Re-populate the _POST array with our finalized and processed data
*
- * @access private
- * @return null
+ * @return void
*/
protected function _reset_post_array()
{
@@ -411,7 +515,7 @@ class CI_Form_validation {
{
if ( ! is_null($row['postdata']))
{
- if ($row['is_array'] == FALSE)
+ if ($row['is_array'] === FALSE)
{
if (isset($_POST[$row['field']]))
{
@@ -424,7 +528,7 @@ class CI_Form_validation {
$post_ref =& $_POST;
// before we assign values, make a reference to the right POST key
- if (count($row['keys']) == 1)
+ if (count($row['keys']) === 1)
{
$post_ref =& $post_ref[current($row['keys'])];
}
@@ -460,11 +564,10 @@ class CI_Form_validation {
/**
* Executes the Validation routines
*
- * @access private
* @param array
* @param array
* @param mixed
- * @param integer
+ * @param int
* @return mixed
*/
protected function _execute($row, $rules, $postdata = NULL, $cycles = 0)
@@ -474,24 +577,21 @@ class CI_Form_validation {
{
foreach ($postdata as $key => $val)
{
- $this->_execute($row, $rules, $val, $cycles);
- $cycles++;
+ $this->_execute($row, $rules, $val, $key);
}
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
{
@@ -499,26 +599,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
@@ -539,13 +634,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
@@ -559,14 +654,17 @@ class CI_Form_validation {
}
else
{
- $postdata = $this->_field_data[$row['field']]['postdata'];
+ // If we get an array field, but it's not expected - then it is most likely
+ // somebody messing with the form on the client side, so we'll just consider
+ // it an empty field
+ $postdata = is_array($this->_field_data[$row['field']]['postdata'])
+ ? NULL
+ : $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;
@@ -575,7 +673,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];
@@ -586,68 +684,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)
+ 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)
+ 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]))
@@ -663,8 +762,8 @@ 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"
- if (isset($this->_field_data[$param]) AND isset($this->_field_data[$param]['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']);
}
@@ -690,7 +789,6 @@ class CI_Form_validation {
/**
* Translate a field name
*
- * @access private
* @param string the field name
* @return string
*/
@@ -698,7 +796,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);
@@ -721,20 +819,19 @@ class CI_Form_validation {
* Permits you to repopulate a form field with the value it was submitted
* with, or, if that value doesn't exist, with the default
*
- * @access public
* @param string the field name
* @param string
- * @return void
+ * @return string
*/
public function set_value($field = '', $default = '')
{
- if ( ! isset($this->_field_data[$field]))
+ if ( ! isset($this->_field_data[$field], $this->_field_data[$field]['postdata']))
{
return $default;
}
// If the data is an array output them one at a time.
- // E.g: form_input('name[]', set_value('name[]');
+ // E.g: form_input('name[]', set_value('name[]');
if (is_array($this->_field_data[$field]['postdata']))
{
return array_shift($this->_field_data[$field]['postdata']);
@@ -751,24 +848,19 @@ class CI_Form_validation {
* Enables pull-down lists to be set to the value the user
* selected in the event of an error
*
- * @access public
* @param string
* @param string
+ * @param bool
* @return string
*/
public function set_select($field = '', $value = '', $default = FALSE)
{
- if ( ! isset($this->_field_data[$field]) OR ! isset($this->_field_data[$field]['postdata']))
+ if ( ! isset($this->_field_data[$field], $this->_field_data[$field]['postdata']))
{
- if ($default === TRUE AND count($this->_field_data) === 0)
- {
- return ' selected="selected"';
- }
- return '';
+ return ($default === TRUE && count($this->_field_data) === 0) ? ' selected="selected"' : '';
}
$field = $this->_field_data[$field]['postdata'];
-
if (is_array($field))
{
if ( ! in_array($value, $field))
@@ -776,12 +868,9 @@ class CI_Form_validation {
return '';
}
}
- else
+ elseif (($field === '' OR $value === '') OR ($field !== $value))
{
- if (($field == '' OR $value == '') OR ($field != $value))
- {
- return '';
- }
+ return '';
}
return ' selected="selected"';
@@ -795,24 +884,19 @@ class CI_Form_validation {
* Enables radio buttons to be set to the value the user
* selected in the event of an error
*
- * @access public
* @param string
* @param string
+ * @param bool
* @return string
*/
public function set_radio($field = '', $value = '', $default = FALSE)
{
- if ( ! isset($this->_field_data[$field]) OR ! isset($this->_field_data[$field]['postdata']))
+ if ( ! isset($this->_field_data[$field], $this->_field_data[$field]['postdata']))
{
- if ($default === TRUE AND count($this->_field_data) === 0)
- {
- return ' checked="checked"';
- }
- return '';
+ return ($default === TRUE && count($this->_field_data) === 0) ? ' checked="checked"' : '';
}
$field = $this->_field_data[$field]['postdata'];
-
if (is_array($field))
{
if ( ! in_array($value, $field))
@@ -820,12 +904,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"';
@@ -839,40 +920,15 @@ class CI_Form_validation {
* Enables checkboxes to be set to the value the user
* selected in the event of an error
*
- * @access public
* @param string
* @param string
+ * @param bool
* @return string
*/
public function set_checkbox($field = '', $value = '', $default = FALSE)
{
- if ( ! isset($this->_field_data[$field]) OR ! isset($this->_field_data[$field]['postdata']))
- {
- if ($default === TRUE AND count($this->_field_data) === 0)
- {
- return ' checked="checked"';
- }
- return '';
- }
-
- $field = $this->_field_data[$field]['postdata'];
-
- if (is_array($field))
- {
- if ( ! in_array($value, $field))
- {
- return '';
- }
- }
- else
- {
- if (($field == '' OR $value == '') OR ($field != $value))
- {
- return '';
- }
- }
-
- return ' checked="checked"';
+ // Logic is exactly the same as for radio fields
+ return $this->set_radio($field, $value, $default);
}
// --------------------------------------------------------------------
@@ -880,20 +936,12 @@ class CI_Form_validation {
/**
* Required
*
- * @access public
* @param string
* @return bool
*/
public function required($str)
{
- if ( ! is_array($str))
- {
- return (trim($str) == '') ? FALSE : TRUE;
- }
- else
- {
- return ( ! empty($str));
- }
+ return is_array($str) ? (bool) count($str) : (trim($str) !== '');
}
// --------------------------------------------------------------------
@@ -901,19 +949,13 @@ class CI_Form_validation {
/**
* Performs a Regular Expression match test.
*
- * @access public
* @param string
- * @param regex
+ * @param string regex
* @return bool
*/
public function regex_match($str, $regex)
{
- if ( ! preg_match($regex, $str))
- {
- return FALSE;
- }
-
- return TRUE;
+ return (bool) preg_match($regex, $str);
}
// --------------------------------------------------------------------
@@ -921,64 +963,63 @@ class CI_Form_validation {
/**
* Match one field to another
*
- * @access public
* @param string
- * @param field
+ * @param string field
* @return bool
*/
public function matches($str, $field)
{
- if ( ! isset($_POST[$field]))
- {
- return FALSE;
- }
+ $validation_array = empty($this->validation_data) ? $_POST : $this->validation_data;
- $field = $_POST[$field];
-
- return ($str !== $field) ? FALSE : TRUE;
+ return isset($validation_array[$field]) ? ($str === $validation_array[$field]) : FALSE;
}
-
+
// --------------------------------------------------------------------
/**
- * Match one field to another
+ * Is Unique
+ *
+ * Check if the input value doesn't already exist
+ * in the specified database field.
*
- * @access public
* @param string
- * @param field
+ * @param string field
* @return bool
*/
public function is_unique($str, $field)
{
- list($table, $field)=explode('.', $field);
- $query = $this->CI->db->limit(1)->get_where($table, array($field => $str));
-
- return $query->num_rows() === 0;
- }
+ list($table, $field) = explode('.', $field);
+ if (isset($this->CI->db))
+ {
+ $query = $this->CI->db->limit(1)->get_where($table, array($field => $str));
+ return $query->num_rows() === 0;
+ }
+ return FALSE;
+ }
// --------------------------------------------------------------------
/**
* Minimum Length
*
- * @access public
* @param string
- * @param value
+ * @param string
* @return bool
*/
public function min_length($str, $val)
{
- if (preg_match("/[^0-9]/", $val))
+ if ( ! is_numeric($val))
{
return FALSE;
}
-
- if (function_exists('mb_strlen'))
+ else
{
- return (mb_strlen($str) < $val) ? FALSE : TRUE;
+ $val = (int) $val;
}
- return (strlen($str) < $val) ? FALSE : TRUE;
+ return (MB_ENABLED === TRUE)
+ ? ($val <= mb_strlen($str))
+ : ($val <= strlen($str));
}
// --------------------------------------------------------------------
@@ -986,24 +1027,24 @@ class CI_Form_validation {
/**
* Max Length
*
- * @access public
* @param string
- * @param value
+ * @param string
* @return bool
*/
public function max_length($str, $val)
{
- if (preg_match("/[^0-9]/", $val))
+ if ( ! is_numeric($val))
{
return FALSE;
}
-
- if (function_exists('mb_strlen'))
+ else
{
- return (mb_strlen($str) > $val) ? FALSE : TRUE;
+ $val = (int) $val;
}
- return (strlen($str) > $val) ? FALSE : TRUE;
+ return (MB_ENABLED === TRUE)
+ ? ($val >= mb_strlen($str))
+ : ($val >= strlen($str));
}
// --------------------------------------------------------------------
@@ -1011,24 +1052,24 @@ class CI_Form_validation {
/**
* Exact Length
*
- * @access public
* @param string
- * @param value
+ * @param string
* @return bool
*/
public function exact_length($str, $val)
{
- if (preg_match("/[^0-9]/", $val))
+ if ( ! is_numeric($val))
{
return FALSE;
}
-
- if (function_exists('mb_strlen'))
+ else
{
- return (mb_strlen($str) != $val) ? FALSE : TRUE;
+ $val = (int) $val;
}
- return (strlen($str) != $val) ? FALSE : TRUE;
+ return (MB_ENABLED === TRUE)
+ ? (mb_strlen($str) === $val)
+ : (strlen($str) === $val);
}
// --------------------------------------------------------------------
@@ -1036,13 +1077,12 @@ class CI_Form_validation {
/**
* Valid Email
*
- * @access public
* @param string
* @return bool
*/
public function valid_email($str)
{
- return ( ! preg_match("/^([a-z0-9\+_\-]+)(\.[a-z0-9\+_\-]+)*@([a-z0-9\-]+\.)+[a-z]{2,6}$/ix", $str)) ? FALSE : TRUE;
+ return (bool) filter_var($str, FILTER_VALIDATE_EMAIL);
}
// --------------------------------------------------------------------
@@ -1050,7 +1090,6 @@ class CI_Form_validation {
/**
* Valid Emails
*
- * @access public
* @param string
* @return bool
*/
@@ -1063,7 +1102,7 @@ class CI_Form_validation {
foreach (explode(',', $str) as $email)
{
- if (trim($email) != '' && $this->valid_email(trim($email)) === FALSE)
+ if (trim($email) !== '' && $this->valid_email(trim($email)) === FALSE)
{
return FALSE;
}
@@ -1077,13 +1116,13 @@ class CI_Form_validation {
/**
* Validate IP Address
*
- * @access public
* @param string
- * @return string
+ * @param string 'ipv4' or 'ipv6' to validate a specific IP format
+ * @return bool
*/
- public function valid_ip($ip)
+ public function valid_ip($ip, $which = '')
{
- return $this->CI->input->valid_ip($ip);
+ return $this->CI->input->valid_ip($ip, $which);
}
// --------------------------------------------------------------------
@@ -1091,13 +1130,12 @@ class CI_Form_validation {
/**
* Alpha
*
- * @access public
* @param string
* @return bool
*/
public function alpha($str)
{
- return ( ! preg_match("/^([a-z])+$/i", $str)) ? FALSE : TRUE;
+ return ctype_alpha($str);
}
// --------------------------------------------------------------------
@@ -1105,13 +1143,12 @@ class CI_Form_validation {
/**
* Alpha-numeric
*
- * @access public
* @param string
* @return bool
*/
public function alpha_numeric($str)
{
- return ( ! preg_match("/^([a-z0-9])+$/i", $str)) ? FALSE : TRUE;
+ return ctype_alnum((string) $str);
}
// --------------------------------------------------------------------
@@ -1119,13 +1156,12 @@ class CI_Form_validation {
/**
* Alpha-numeric with underscores and dashes
*
- * @access public
* @param string
* @return bool
*/
public function alpha_dash($str)
{
- return ( ! preg_match("/^([-a-z0-9_-])+$/i", $str)) ? FALSE : TRUE;
+ return (bool) preg_match('/^[a-z0-9_-]+$/i', $str);
}
// --------------------------------------------------------------------
@@ -1133,74 +1169,67 @@ class CI_Form_validation {
/**
* Numeric
*
- * @access public
* @param string
* @return bool
*/
public function numeric($str)
{
- return (bool)preg_match( '/^[\-+]?[0-9]*\.?[0-9]+$/', $str);
+ return (bool) preg_match('/^[\-+]?[0-9]*\.?[0-9]+$/', $str);
}
// --------------------------------------------------------------------
/**
- * Is Numeric
+ * Integer
*
- * @access public
* @param string
* @return bool
*/
- public function is_numeric($str)
+ public function integer($str)
{
- return ( ! is_numeric($str)) ? FALSE : TRUE;
+ return (bool) preg_match('/^[\-+]?[0-9]+$/', $str);
}
// --------------------------------------------------------------------
/**
- * Integer
+ * Decimal number
*
- * @access public
* @param string
* @return bool
*/
- public function integer($str)
+ public function decimal($str)
{
- return (bool) preg_match('/^[\-+]?[0-9]+$/', $str);
+ return (bool) preg_match('/^[\-+]?[0-9]+\.[0-9]+$/', $str);
}
// --------------------------------------------------------------------
/**
- * Decimal number
+ * Greater than
*
- * @access public
* @param string
+ * @param int
* @return bool
*/
- public function decimal($str)
+ public function greater_than($str, $min)
{
- return (bool) preg_match('/^[\-+]?[0-9]+\.[0-9]+$/', $str);
+ return is_numeric($str) ? ($str > $min) : FALSE;
}
// --------------------------------------------------------------------
/**
- * Greather than
+ * Equal to or Greater than
*
- * @access public
* @param string
+ * @param int
* @return bool
*/
- public function greater_than($str, $min)
+ public function greater_than_equal_to($str, $min)
{
- if ( ! is_numeric($str))
- {
- return FALSE;
- }
- return $str > $min;
+ return is_numeric($str) ? ($str >= $min) : FALSE;
}
// --------------------------------------------------------------------
@@ -1208,17 +1237,27 @@ class CI_Form_validation {
/**
* Less than
*
- * @access public
* @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;
+ }
+
+ // --------------------------------------------------------------------
+
+ /**
+ * Equal to or Less than
+ *
+ * @param string
+ * @param int
+ * @return bool
+ */
+ public function less_than_equal_to($str, $max)
+ {
+ return is_numeric($str) ? ($str <= $max) : FALSE;
}
// --------------------------------------------------------------------
@@ -1226,13 +1265,12 @@ class CI_Form_validation {
/**
* Is a Natural number (0,1,2,3, etc.)
*
- * @access public
* @param string
* @return bool
*/
public function is_natural($str)
{
- return (bool) preg_match( '/^[0-9]+$/', $str);
+ return ctype_digit((string) $str);
}
// --------------------------------------------------------------------
@@ -1240,23 +1278,12 @@ class CI_Form_validation {
/**
* Is a Natural number, but not a zero (1,2,3, etc.)
*
- * @access public
* @param string
* @return bool
*/
public function is_natural_no_zero($str)
{
- if ( ! preg_match( '/^[0-9]+$/', $str))
- {
- return FALSE;
- }
-
- if ($str == 0)
- {
- return FALSE;
- }
-
- return TRUE;
+ return ($str != 0 && ctype_digit((string) $str));
}
// --------------------------------------------------------------------
@@ -1267,13 +1294,12 @@ class CI_Form_validation {
* Tests a string for characters outside of the Base64 alphabet
* as defined by RFC 2045 http://www.faqs.org/rfcs/rfc2045
*
- * @access public
* @param string
* @return bool
*/
public function valid_base64($str)
{
- return (bool) ! preg_match('/[^a-zA-Z0-9\/\+=]/', $str);
+ return ! preg_match('/[^a-zA-Z0-9\/\+=]/', $str);
}
// --------------------------------------------------------------------
@@ -1284,7 +1310,6 @@ class CI_Form_validation {
* This function allows HTML to be safely shown in a form.
* Special characters are converted.
*
- * @access public
* @param string
* @return string
*/
@@ -1300,12 +1325,12 @@ class CI_Form_validation {
return $data;
}
- if ($this->_safe_form_data == FALSE OR $data === '')
+ if ($this->_safe_form_data === FALSE OR $data === '')
{
return $data;
}
- return str_replace(array("'", '"', '<', '>'), array("&#39;", "&quot;", '&lt;', '&gt;'), stripslashes($data));
+ return str_replace(array("'", '"', '<', '>'), array('&#39;', '&quot;', '&lt;', '&gt;'), stripslashes($data));
}
// --------------------------------------------------------------------
@@ -1313,20 +1338,19 @@ class CI_Form_validation {
/**
* Prep URL
*
- * @access public
* @param string
* @return string
*/
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;
@@ -1337,13 +1361,12 @@ class CI_Form_validation {
/**
* Strip Image Tags
*
- * @access public
* @param string
* @return string
*/
public function strip_image_tags($str)
{
- return $this->CI->input->strip_image_tags($str);
+ return $this->CI->security->strip_image_tags($str);
}
// --------------------------------------------------------------------
@@ -1351,7 +1374,6 @@ class CI_Form_validation {
/**
* XSS Clean
*
- * @access public
* @param string
* @return string
*/
@@ -1365,17 +1387,34 @@ class CI_Form_validation {
/**
* Convert PHP tags to entities
*
- * @access public
* @param string
* @return string
*/
public function encode_php_tags($str)
{
- return str_replace(array('<?php', '<?PHP', '<?', '?>'), array('&lt;?php', '&lt;?PHP', '&lt;?', '?&gt;'), $str);
+ return str_replace(array('<?', '?>'), array('&lt;?', '?&gt;'), $str);
+ }
+
+ // --------------------------------------------------------------------
+
+ /**
+ * Reset validation vars
+ *
+ * Prevents subsequent validation routines from being affected by the
+ * results of any previous validation routine due to the CI singleton.
+ *
+ * @return void
+ */
+ public function reset_validation()
+ {
+ $this->_field_data = array();
+ $this->_config_rules = array();
+ $this->_error_array = array();
+ $this->_error_messages = array();
+ $this->error_string = '';
}
}
-// END Form Validation Class
/* 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 d7a8b3b02..76f5e151a 100644
--- a/system/libraries/Ftp.php
+++ b/system/libraries/Ftp.php
@@ -1,45 +1,49 @@
-<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
+<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* CodeIgniter
*
- * An open source application development framework for PHP 5.1.6 or newer
+ * An open source application development framework for PHP 5.2.4 or newer
+ *
+ * NOTICE OF LICENSE
+ *
+ * Licensed under the Open Software License version 3.0
+ *
+ * This source file is subject to the Open Software License (OSL 3.0) that is
+ * bundled with this package in the files license.txt / license.rst. It is
+ * also available through the world wide web at this URL:
+ * http://opensource.org/licenses/OSL-3.0
+ * If you did not receive a copy of the license and are unable to obtain it
+ * through the world wide web, please send an email to
+ * licensing@ellislab.com so we can send you a copy immediately.
*
* @package CodeIgniter
- * @author ExpressionEngine Dev Team
- * @copyright Copyright (c) 2008 - 2011, EllisLab, Inc.
- * @license http://codeigniter.com/user_guide/license.html
+ * @author EllisLab Dev Team
+ * @copyright Copyright (c) 2008 - 2012, EllisLab, Inc. (http://ellislab.com/)
+ * @license http://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
* @link http://codeigniter.com
* @since Version 1.0
* @filesource
*/
-// ------------------------------------------------------------------------
-
/**
* FTP Class
*
* @package CodeIgniter
* @subpackage Libraries
* @category Libraries
- * @author ExpressionEngine Dev Team
+ * @author EllisLab Dev Team
* @link http://codeigniter.com/user_guide/libraries/ftp.html
*/
class CI_FTP {
- var $hostname = '';
- var $username = '';
- var $password = '';
- var $port = 21;
- var $passive = TRUE;
- var $debug = FALSE;
- var $conn_id = FALSE;
-
+ public $hostname = '';
+ public $username = '';
+ public $password = '';
+ public $port = 21;
+ public $passive = TRUE;
+ public $debug = FALSE;
+ public $conn_id = FALSE;
- /**
- * Constructor - Sets Preferences
- *
- * The constructor can be passed an array of config values
- */
public function __construct($config = array())
{
if (count($config) > 0)
@@ -47,7 +51,7 @@ class CI_FTP {
$this->initialize($config);
}
- log_message('debug', "FTP Class Initialized");
+ log_message('debug', 'FTP Class Initialized');
}
// --------------------------------------------------------------------
@@ -55,11 +59,10 @@ class CI_FTP {
/**
* Initialize preferences
*
- * @access public
* @param array
* @return void
*/
- function initialize($config = array())
+ public function initialize($config = array())
{
foreach ($config as $key => $val)
{
@@ -78,11 +81,10 @@ class CI_FTP {
/**
* FTP Connect
*
- * @access public
* @param array the connection values
* @return bool
*/
- function connect($config = array())
+ public function connect($config = array())
{
if (count($config) > 0)
{
@@ -91,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');
}
@@ -100,7 +102,7 @@ class CI_FTP {
if ( ! $this->_login())
{
- if ($this->debug == TRUE)
+ if ($this->debug === TRUE)
{
$this->_error('ftp_unable_to_login');
}
@@ -108,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);
}
@@ -121,10 +123,9 @@ class CI_FTP {
/**
* FTP Login
*
- * @access private
* @return bool
*/
- function _login()
+ protected function _login()
{
return @ftp_login($this->conn_id, $this->username, $this->password);
}
@@ -134,14 +135,13 @@ class CI_FTP {
/**
* Validates the connection ID
*
- * @access private
* @return bool
*/
- function _is_conn()
+ protected function _is_conn()
{
if ( ! is_resource($this->conn_id))
{
- if ($this->debug == TRUE)
+ if ($this->debug === TRUE)
{
$this->_error('ftp_no_connection');
}
@@ -152,24 +152,22 @@ class CI_FTP {
// --------------------------------------------------------------------
-
/**
* Change directory
*
* The second parameter lets us momentarily turn off debugging so that
* this function can be used to test for the existence of a folder
- * without throwing an error. There's no FTP equivalent to is_dir()
+ * without throwing an error. There's no FTP equivalent to is_dir()
* so we do it by trying to change to a particular directory.
* Internally, this parameter is only used by the "mirror" function below.
*
- * @access public
* @param string
* @param bool
* @return bool
*/
- function changedir($path = '', $supress_debug = FALSE)
+ public function changedir($path = '', $supress_debug = FALSE)
{
- if ($path == '' OR ! $this->_is_conn())
+ if ($path === '' OR ! $this->_is_conn())
{
return FALSE;
}
@@ -178,7 +176,7 @@ class CI_FTP {
if ($result === FALSE)
{
- if ($this->debug == TRUE AND $supress_debug == FALSE)
+ if ($this->debug === TRUE && $supress_debug === FALSE)
{
$this->_error('ftp_unable_to_changedir');
}
@@ -193,13 +191,13 @@ class CI_FTP {
/**
* Create a directory
*
- * @access public
* @param string
+ * @param int
* @return bool
*/
- function mkdir($path = '', $permissions = NULL)
+ public function mkdir($path = '', $permissions = NULL)
{
- if ($path == '' OR ! $this->_is_conn())
+ if ($path === '' OR ! $this->_is_conn())
{
return FALSE;
}
@@ -208,7 +206,7 @@ class CI_FTP {
if ($result === FALSE)
{
- if ($this->debug == TRUE)
+ if ($this->debug === TRUE)
{
$this->_error('ftp_unable_to_makdir');
}
@@ -218,7 +216,7 @@ class CI_FTP {
// Set file permissions if needed
if ( ! is_null($permissions))
{
- $this->chmod($path, (int)$permissions);
+ $this->chmod($path, (int) $permissions);
}
return TRUE;
@@ -229,13 +227,13 @@ class CI_FTP {
/**
* Upload a file to the server
*
- * @access public
* @param string
* @param string
* @param string
+ * @param int
* @return bool
*/
- function upload($locpath, $rempath, $mode = 'auto', $permissions = NULL)
+ public function upload($locpath, $rempath, $mode = 'auto', $permissions = NULL)
{
if ( ! $this->_is_conn())
{
@@ -249,20 +247,20 @@ class CI_FTP {
}
// Set the mode if not specified
- if ($mode == 'auto')
+ if ($mode === 'auto')
{
// Get the file extension so we can set the upload type
$ext = $this->_getext($locpath);
$mode = $this->_settype($ext);
}
- $mode = ($mode == 'ascii') ? FTP_ASCII : FTP_BINARY;
+ $mode = ($mode === 'ascii') ? FTP_ASCII : FTP_BINARY;
$result = @ftp_put($this->conn_id, $rempath, $locpath, $mode);
if ($result === FALSE)
{
- if ($this->debug == TRUE)
+ if ($this->debug === TRUE)
{
$this->_error('ftp_unable_to_upload');
}
@@ -272,7 +270,7 @@ class CI_FTP {
// Set file permissions if needed
if ( ! is_null($permissions))
{
- $this->chmod($rempath, (int)$permissions);
+ $this->chmod($rempath, (int) $permissions);
}
return TRUE;
@@ -283,13 +281,12 @@ class CI_FTP {
/**
* Download a file from a remote server to the local server
*
- * @access public
* @param string
* @param string
* @param string
* @return bool
*/
- function download($rempath, $locpath, $mode = 'auto')
+ public function download($rempath, $locpath, $mode = 'auto')
{
if ( ! $this->_is_conn())
{
@@ -297,20 +294,20 @@ class CI_FTP {
}
// Set the mode if not specified
- if ($mode == 'auto')
+ if ($mode === 'auto')
{
// Get the file extension so we can set the upload type
$ext = $this->_getext($rempath);
$mode = $this->_settype($ext);
}
- $mode = ($mode == 'ascii') ? FTP_ASCII : FTP_BINARY;
+ $mode = ($mode === 'ascii') ? FTP_ASCII : FTP_BINARY;
$result = @ftp_get($this->conn_id, $locpath, $rempath, $mode);
if ($result === FALSE)
{
- if ($this->debug == TRUE)
+ if ($this->debug === TRUE)
{
$this->_error('ftp_unable_to_download');
}
@@ -325,13 +322,12 @@ class CI_FTP {
/**
* Rename (or move) a file
*
- * @access public
* @param string
* @param string
* @param bool
* @return bool
*/
- function rename($old_file, $new_file, $move = FALSE)
+ public function rename($old_file, $new_file, $move = FALSE)
{
if ( ! $this->_is_conn())
{
@@ -342,11 +338,9 @@ class CI_FTP {
if ($result === FALSE)
{
- if ($this->debug == TRUE)
+ if ($this->debug === TRUE)
{
- $msg = ($move == FALSE) ? 'ftp_unable_to_rename' : 'ftp_unable_to_move';
-
- $this->_error($msg);
+ $this->_error('ftp_unable_to_' . ($move === FALSE ? 'rename' : 'move'));
}
return FALSE;
}
@@ -359,12 +353,11 @@ class CI_FTP {
/**
* Move a file
*
- * @access public
* @param string
* @param string
* @return bool
*/
- function move($old_file, $new_file)
+ public function move($old_file, $new_file)
{
return $this->rename($old_file, $new_file, TRUE);
}
@@ -374,11 +367,10 @@ class CI_FTP {
/**
* Rename (or move) a file
*
- * @access public
* @param string
* @return bool
*/
- function delete_file($filepath)
+ public function delete_file($filepath)
{
if ( ! $this->_is_conn())
{
@@ -389,7 +381,7 @@ class CI_FTP {
if ($result === FALSE)
{
- if ($this->debug == TRUE)
+ if ($this->debug === TRUE)
{
$this->_error('ftp_unable_to_delete');
}
@@ -405,11 +397,10 @@ class CI_FTP {
* Delete a folder and recursively delete everything (including sub-folders)
* containted within it.
*
- * @access public
* @param string
* @return bool
*/
- function delete_dir($filepath)
+ public function delete_dir($filepath)
{
if ( ! $this->_is_conn())
{
@@ -417,11 +408,11 @@ class CI_FTP {
}
// Add a trailing slash to the file path if needed
- $filepath = preg_replace("/(.+?)\/*$/", "\\1/", $filepath);
+ $filepath = preg_replace('/(.+?)\/*$/', '\\1/', $filepath);
$list = $this->list_files($filepath);
- if ($list !== FALSE AND count($list) > 0)
+ if ($list !== FALSE && count($list) > 0)
{
foreach ($list as $item)
{
@@ -438,7 +429,7 @@ class CI_FTP {
if ($result === FALSE)
{
- if ($this->debug == TRUE)
+ if ($this->debug === TRUE)
{
$this->_error('ftp_unable_to_delete');
}
@@ -453,33 +444,22 @@ class CI_FTP {
/**
* Set file permissions
*
- * @access public
* @param string the file path
- * @param string the permissions
+ * @param int the permissions
* @return bool
*/
- function chmod($path, $perm)
+ public function chmod($path, $perm)
{
if ( ! $this->_is_conn())
{
return FALSE;
}
- // Permissions can only be set when running PHP 5
- if ( ! function_exists('ftp_chmod'))
- {
- if ($this->debug == TRUE)
- {
- $this->_error('ftp_unable_to_chmod');
- }
- return FALSE;
- }
-
$result = @ftp_chmod($this->conn_id, $perm, $path);
if ($result === FALSE)
{
- if ($this->debug == TRUE)
+ if ($this->debug === TRUE)
{
$this->_error('ftp_unable_to_chmod');
}
@@ -494,10 +474,9 @@ class CI_FTP {
/**
* FTP List files in the specified directory
*
- * @access public
* @return array
*/
- function list_files($path = '.')
+ public function list_files($path = '.')
{
if ( ! $this->_is_conn())
{
@@ -512,16 +491,16 @@ class CI_FTP {
/**
* Read a directory and recreate it remotely
*
- * This function recursively reads a folder and everything it contains (including
- * sub-folders) and creates a mirror via FTP based on it. Whatever the directory structure
- * of the original file path will be recreated on the server.
+ * This function recursively reads a folder and everything it contains
+ * (including sub-folders) and creates a mirror via FTP based on it.
+ * Whatever the directory structure of the original file path will be
+ * recreated on the server.
*
- * @access public
* @param string path to source with trailing slash
* @param string path to destination - include the base folder with trailing slash
* @return bool
*/
- function mirror($locpath, $rempath)
+ public function mirror($locpath, $rempath)
{
if ( ! $this->_is_conn())
{
@@ -531,24 +510,20 @@ class CI_FTP {
// Open the local file path
if ($fp = @opendir($locpath))
{
- // Attempt to open the remote file path.
- if ( ! $this->changedir($rempath, TRUE))
+ // Attempt to open the remote file path and try to create it, if it doesn't exist
+ if ( ! $this->changedir($rempath, TRUE) && ( ! $this->mkdir($rempath) OR ! $this->changedir($rempath)))
{
- // If it doesn't exist we'll attempt to create the direcotory
- if ( ! $this->mkdir($rempath) OR ! $this->changedir($rempath))
- {
- return FALSE;
- }
+ return FALSE;
}
// Recursively read the local directory
while (FALSE !== ($file = readdir($fp)))
{
- if (@is_dir($locpath.$file) && substr($file, 0, 1) != '.')
+ if (@is_dir($locpath.$file) && $file[0] !== '.')
{
- $this->mirror($locpath.$file."/", $rempath.$file."/");
+ $this->mirror($locpath.$file.'/', $rempath.$file.'/');
}
- elseif (substr($file, 0, 1) != ".")
+ elseif ($file[0] !== '.')
{
// Get the file extension so we can se the upload type
$ext = $this->_getext($file);
@@ -563,17 +538,15 @@ class CI_FTP {
return FALSE;
}
-
// --------------------------------------------------------------------
/**
* Extract the file extension
*
- * @access private
* @param string
* @return string
*/
- function _getext($filename)
+ protected function _getext($filename)
{
if (FALSE === strpos($filename, '.'))
{
@@ -584,36 +557,34 @@ class CI_FTP {
return end($x);
}
-
// --------------------------------------------------------------------
/**
* Set the upload type
*
- * @access private
* @param string
* @return string
*/
- function _settype($ext)
+ protected function _settype($ext)
{
$text_types = array(
- 'txt',
- 'text',
- 'php',
- 'phps',
- 'php4',
- 'js',
- 'css',
- 'htm',
- 'html',
- 'phtml',
- 'shtml',
- 'log',
- 'xml'
- );
-
-
- return (in_array($ext, $text_types)) ? 'ascii' : 'binary';
+ 'txt',
+ 'text',
+ 'php',
+ 'phps',
+ 'php4',
+ 'js',
+ 'css',
+ 'htm',
+ 'html',
+ 'phtml',
+ 'shtml',
+ 'log',
+ 'xml'
+ );
+
+
+ return in_array($ext, $text_types) ? 'ascii' : 'binary';
}
// ------------------------------------------------------------------------
@@ -621,19 +592,16 @@ class CI_FTP {
/**
* Close the connection
*
- * @access public
- * @param string path to source
- * @param string path to destination
* @return bool
*/
- function close()
+ public function close()
{
if ( ! $this->_is_conn())
{
return FALSE;
}
- @ftp_close($this->conn_id);
+ return @ftp_close($this->conn_id);
}
// ------------------------------------------------------------------------
@@ -641,20 +609,17 @@ class CI_FTP {
/**
* Display error message
*
- * @access private
* @param string
- * @return bool
+ * @return void
*/
- function _error($line)
+ protected function _error($line)
{
$CI =& get_instance();
$CI->lang->load('ftp');
show_error($CI->lang->line($line));
}
-
}
-// END FTP Class
/* End of file Ftp.php */
/* Location: ./system/libraries/Ftp.php */ \ No newline at end of file
diff --git a/system/libraries/Image_lib.php b/system/libraries/Image_lib.php
index a8a0387d8..899b995d4 100644
--- a/system/libraries/Image_lib.php
+++ b/system/libraries/Image_lib.php
@@ -1,85 +1,369 @@
-<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
+<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* CodeIgniter
*
- * An open source application development framework for PHP 5.1.6 or newer
+ * An open source application development framework for PHP 5.2.4 or newer
+ *
+ * NOTICE OF LICENSE
+ *
+ * Licensed under the Open Software License version 3.0
+ *
+ * This source file is subject to the Open Software License (OSL 3.0) that is
+ * bundled with this package in the files license.txt / license.rst. It is
+ * also available through the world wide web at this URL:
+ * http://opensource.org/licenses/OSL-3.0
+ * If you did not receive a copy of the license and are unable to obtain it
+ * through the world wide web, please send an email to
+ * licensing@ellislab.com so we can send you a copy immediately.
*
* @package CodeIgniter
- * @author ExpressionEngine Dev Team
- * @copyright Copyright (c) 2008 - 2011, EllisLab, Inc.
- * @license http://codeigniter.com/user_guide/license.html
+ * @author EllisLab Dev Team
+ * @copyright Copyright (c) 2008 - 2012, EllisLab, Inc. (http://ellislab.com/)
+ * @license http://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
* @link http://codeigniter.com
* @since Version 1.0
* @filesource
*/
-// ------------------------------------------------------------------------
-
/**
* Image Manipulation class
*
* @package CodeIgniter
* @subpackage Libraries
* @category Image_lib
- * @author ExpressionEngine Dev Team
+ * @author EllisLab Dev Team
* @link http://codeigniter.com/user_guide/libraries/image_lib.html
*/
class CI_Image_lib {
- var $image_library = 'gd2'; // Can be: imagemagick, netpbm, gd, gd2
- var $library_path = '';
- var $dynamic_output = FALSE; // Whether to send to browser or write to disk
- var $source_image = '';
- var $new_image = '';
- var $width = '';
- var $height = '';
- var $quality = '90';
- var $create_thumb = FALSE;
- var $thumb_marker = '_thumb';
- var $maintain_ratio = TRUE; // Whether to maintain aspect ratio when resizing or use hard values
- var $master_dim = 'auto'; // auto, height, or width. Determines what to use as the master dimension
- var $rotation_angle = '';
- var $x_axis = '';
- var $y_axis = '';
+ /**
+ * 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 = '';
+
+ /**
+ * Whether to send to browser or write to disk
+ *
+ * @var bool
+ */
+ public $dynamic_output = FALSE;
+
+ /**
+ * Path to original image
+ *
+ * @var string
+ */
+ public $source_image = '';
+
+ /**
+ * 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';
+
+ /**
+ * 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 = '';
+ /**
+ * 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
- var $wm_text = ''; // Watermark text if graphic is not used
- var $wm_type = 'text'; // Type of watermarking. Options: text/overlay
- var $wm_x_transp = 4;
- var $wm_y_transp = 4;
- var $wm_overlay_path = ''; // Watermark image path
- var $wm_font_path = ''; // TT font
- var $wm_font_size = 17; // Font size (different versions of GD will either use points or pixels)
- var $wm_vrt_alignment = 'B'; // Vertical alignment: T M B
- var $wm_hor_alignment = 'C'; // Horizontal alignment: L R C
- var $wm_padding = 0; // Padding around text
- var $wm_hor_offset = 0; // Lets you push text to the right
- var $wm_vrt_offset = 0; // Lets you push text down
- var $wm_font_color = '#ffffff'; // Text color
- var $wm_shadow_color = ''; // Dropshadow color
- var $wm_shadow_distance = 2; // Dropshadow distance
- var $wm_opacity = 50; // Image opacity: 1 - 100 Only works with image
+ // --------------------------------------------------------------------------
+
+ /**
+ * 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;
+
+ /**
+ * 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
- var $source_folder = '';
- var $dest_folder = '';
- var $mime_type = '';
- var $orig_width = '';
- var $orig_height = '';
- var $image_type = '';
- var $size_str = '';
- var $full_src_path = '';
- var $full_dst_path = '';
- var $create_fnc = 'imagecreatetruecolor';
- var $copy_fnc = 'imagecopyresampled';
- var $error_msg = array();
- var $wm_use_drop_shadow = FALSE;
- var $wm_use_truetype = FALSE;
-
- /**
- * Constructor
+ // --------------------------------------------------------------------------
+
+ /**
+ * Source image folder
*
- * @param string
+ * @var string
+ */
+ public $source_folder = '';
+
+ /**
+ * Destination image folder
+ *
+ * @var string
+ */
+ public $dest_folder = '';
+
+ /**
+ * Image mime-type
+ *
+ * @var string
+ */
+ public $mime_type = '';
+
+ /**
+ * Original image width
+ *
+ * @var int
+ */
+ public $orig_width = '';
+
+ /**
+ * Original image height
+ *
+ * @var int
+ */
+ public $orig_height = '';
+
+ /**
+ * 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 = '';
+
+ /**
+ * 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())
@@ -89,7 +373,7 @@ class CI_Image_lib {
$this->initialize($props);
}
- log_message('debug', "Image Lib Class Initialized");
+ log_message('debug', 'Image Lib Class Initialized');
}
// --------------------------------------------------------------------
@@ -99,20 +383,41 @@ class CI_Image_lib {
*
* Resets values in case this class is used in a loop
*
- * @access public
* @return void
*/
- function clear()
+ public function clear()
{
- $props = array('source_folder', 'dest_folder', 'source_image', 'full_src_path', 'full_dst_path', 'new_image', 'image_type', 'size_str', 'quality', 'orig_width', 'orig_height', 'rotation_angle', 'x_axis', 'y_axis', 'create_fnc', 'copy_fnc', 'wm_overlay_path', 'wm_use_truetype', 'dynamic_output', 'wm_font_size', 'wm_text', 'wm_vrt_alignment', 'wm_hor_alignment', 'wm_padding', 'wm_hor_offset', 'wm_vrt_offset', 'wm_font_color', 'wm_use_drop_shadow', 'wm_shadow_color', 'wm_shadow_distance', 'wm_opacity');
+ $props = array('library_path', 'source_image', 'new_image', 'width', 'height', 'rotation_angle', 'x_axis', 'y_axis', 'wm_text', 'wm_overlay_path', 'wm_font_path', 'wm_shadow_color', 'source_folder', 'dest_folder', 'mime_type', 'orig_width', 'orig_height', 'image_type', 'size_str', 'full_src_path', 'full_dst_path');
foreach ($props as $val)
{
$this->$val = '';
}
- // special consideration for master_dim
- $this->master_dim = 'auto';
+ $this->image_library = 'gd2';
+ $this->dynamic_output = FALSE;
+ $this->quality = 90;
+ $this->create_thumb = FALSE;
+ $this->thumb_marker = '_thumb';
+ $this->maintain_ratio = TRUE;
+ $this->master_dim = 'auto';
+ $this->wm_type = 'text';
+ $this->wm_x_transp = 4;
+ $this->wm_y_transp = 4;
+ $this->wm_font_size = 17;
+ $this->wm_vrt_alignment = 'B';
+ $this->wm_hor_alignment = 'C';
+ $this->wm_padding = 0;
+ $this->wm_hor_offset = 0;
+ $this->wm_vrt_offset = 0;
+ $this->wm_font_color = '#ffffff';
+ $this->wm_shadow_distance = 2;
+ $this->wm_opacity = 50;
+ $this->create_fnc = 'imagecreatetruecolor';
+ $this->copy_fnc = 'imagecopyresampled';
+ $this->error_msg = array();
+ $this->wm_use_drop_shadow = FALSE;
+ $this->wm_use_truetype = FALSE;
}
// --------------------------------------------------------------------
@@ -120,42 +425,58 @@ class CI_Image_lib {
/**
* initialize image preferences
*
- * @access public
* @param array
* @return bool
*/
- function initialize($props = array())
+ public function initialize($props = array())
{
- /*
- * Convert array elements into class variables
- */
+ // Convert array elements into class variables
if (count($props) > 0)
{
foreach ($props as $key => $val)
{
- $this->$key = $val;
+ if (property_exists($this, $key))
+ {
+ if (in_array($key, array('wm_font_color', 'wm_shadow_color')))
+ {
+ if (preg_match('/^#?([0-9a-f]{3}|[0-9a-f]{6})$/i', $val, $matches))
+ {
+ /* $matches[1] contains our hex color value, but it might be
+ * both in the full 6-length format or the shortened 3-length
+ * value.
+ * We'll later need the full version, so we keep it if it's
+ * already there and if not - we'll convert to it. We can
+ * access string characters by their index as in an array,
+ * so we'll do that and use concatenation to form the final
+ * value:
+ */
+ $val = (strlen($matches[1]) === 6)
+ ? '#'.$matches[1]
+ : '#'.$matches[1][0].$matches[1][0].$matches[1][1].$matches[1][1].$matches[1][2].$matches[1][2];
+ }
+ else
+ {
+ continue;
+ }
+ }
+
+ $this->$key = $val;
+ }
}
}
- /*
- * Is there a source image?
- *
- * If not, there's no reason to continue
- *
- */
- if ($this->source_image == '')
+ // Is there a source image? If not, there's no reason to continue
+ if ($this->source_image === '')
{
$this->set_error('imglib_source_image_required');
- return FALSE;
+ return FALSE;
}
- /*
- * Is getimagesize() Available?
+ /* Is getimagesize() available?
*
* We use it to determine the image properties (width/height).
- * Note: We need to figure out how to determine image
+ * Note: We need to figure out how to determine image
* properties using ImageMagick and NetPBM
- *
*/
if ( ! function_exists('getimagesize'))
{
@@ -165,17 +486,15 @@ class CI_Image_lib {
$this->image_library = strtolower($this->image_library);
- /*
- * Set the full server path
+ /* Set the full server path
*
* The source image may or may not contain a path.
* Either way, we'll try use realpath to generate the
* full server path in order to more reliably read it.
- *
*/
- if (function_exists('realpath') AND @realpath($this->source_image) !== FALSE)
+ if (function_exists('realpath') && @realpath($this->source_image) !== FALSE)
{
- $full_source_path = str_replace("\\", "/", realpath($this->source_image));
+ $full_source_path = str_replace('\\', '/', realpath($this->source_image));
}
else
{
@@ -189,7 +508,7 @@ class CI_Image_lib {
// Set the Image Properties
if ( ! $this->get_image_properties($this->source_folder.$this->source_image))
{
- return FALSE;
+ return FALSE;
}
/*
@@ -197,64 +516,58 @@ class CI_Image_lib {
*
* If the user has set a "new_image" name it means
* we are making a copy of the source image. If not
- * it means we are altering the original. We'll
+ * 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;
}
+ elseif (strpos($this->new_image, '/') === FALSE)
+ {
+ $this->dest_folder = $this->source_folder;
+ $this->dest_image = $this->new_image;
+ }
else
{
- if (strpos($this->new_image, '/') === FALSE)
+ if (strpos($this->new_image, '/') === FALSE && strpos($this->new_image, '\\') === FALSE)
{
- $this->dest_folder = $this->source_folder;
- $this->dest_image = $this->new_image;
+ $full_dest_path = str_replace('\\', '/', realpath($this->new_image));
}
else
{
- if (function_exists('realpath') AND @realpath($this->new_image) !== FALSE)
- {
- $full_dest_path = str_replace("\\", "/", realpath($this->new_image));
- }
- else
- {
- $full_dest_path = $this->new_image;
- }
+ $full_dest_path = $this->new_image;
+ }
- // Is there a file name?
- if ( ! preg_match("#\.(jpg|jpeg|gif|png)$#i", $full_dest_path))
- {
- $this->dest_folder = $full_dest_path.'/';
- $this->dest_image = $this->source_image;
- }
- else
- {
- $x = explode('/', $full_dest_path);
- $this->dest_image = end($x);
- $this->dest_folder = str_replace($this->dest_image, '', $full_dest_path);
- }
+ // Is there a file name?
+ if ( ! preg_match('#\.(jpg|jpeg|gif|png)$#i', $full_dest_path))
+ {
+ $this->dest_folder = $full_dest_path.'/';
+ $this->dest_image = $this->source_image;
+ }
+ else
+ {
+ $x = explode('/', $full_dest_path);
+ $this->dest_image = end($x);
+ $this->dest_folder = str_replace($this->dest_image, '', $full_dest_path);
}
}
- /*
- * Compile the finalized filenames/paths
+ /* Compile the finalized filenames/paths
*
* We'll create two master strings containing the
* full server path to the source image and the
* full server path to the destination image.
* 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 = '';
}
- $xp = $this->explode_name($this->dest_image);
+ $xp = $this->explode_name($this->dest_image);
$filename = $xp['name'];
$file_ext = $xp['ext'];
@@ -262,71 +575,60 @@ class CI_Image_lib {
$this->full_src_path = $this->source_folder.$this->source_image;
$this->full_dst_path = $this->dest_folder.$filename.$this->thumb_marker.$file_ext;
- /*
- * Should we maintain image proportions?
+ /* Should we maintain image proportions?
*
* When creating thumbs or copies, the target width/height
* might not be in correct proportion with the source
- * image's width/height. We'll recalculate it here.
- *
+ * image's width/height. We'll recalculate it here.
*/
- if ($this->maintain_ratio === TRUE && ($this->width != '' AND $this->height != ''))
+ if ($this->maintain_ratio === TRUE && ($this->width !== 0 OR $this->height !== 0))
{
$this->image_reproportion();
}
- /*
- * Was a width and height specified?
- *
- * If the destination width/height was
- * not submitted we will use the values
- * from the actual file
+ /* Was a width and height specified?
*
+ * 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;
+ }
// Set the quality
- $this->quality = trim(str_replace("%", "", $this->quality));
+ $this->quality = trim(str_replace('%', '', $this->quality));
- if ($this->quality == '' OR $this->quality == 0 OR ! is_numeric($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 ! is_numeric($this->x_axis)) ? 0 : $this->x_axis;
- $this->y_axis = ($this->y_axis == '' OR ! is_numeric($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_font_color != '')
+ if ($this->wm_overlay_path !== '')
{
- if (strlen($this->wm_font_color) == 6)
- {
- $this->wm_font_color = '#'.$this->wm_font_color;
- }
+ $this->wm_overlay_path = str_replace('\\', '/', realpath($this->wm_overlay_path));
}
- if ($this->wm_shadow_color != '')
+ if ($this->wm_shadow_color !== '')
{
- if (strlen($this->wm_shadow_color) == 6)
- {
- $this->wm_shadow_color = '#'.$this->wm_shadow_color;
- }
- }
-
- if ($this->wm_overlay_path != '')
- {
- $this->wm_overlay_path = str_replace("\\", "/", realpath($this->wm_overlay_path));
+ $this->wm_use_drop_shadow = TRUE;
}
-
- if ($this->wm_shadow_color != '')
+ elseif ($this->wm_use_drop_shadow === TRUE && $this->wm_shadow_color === '')
{
- $this->wm_use_drop_shadow = TRUE;
+ $this->wm_use_drop_shadow = FALSE;
}
- if ($this->wm_font_path != '')
+ if ($this->wm_font_path !== '')
{
$this->wm_use_truetype = TRUE;
}
@@ -342,18 +644,11 @@ class CI_Image_lib {
* This is a wrapper function that chooses the proper
* resize function based on the protocol specified
*
- * @access public
* @return bool
*/
- function resize()
+ public function resize()
{
- $protocol = 'image_process_'.$this->image_library;
-
- if (preg_match('/gd2$/i', $protocol))
- {
- $protocol = 'image_process_gd';
- }
-
+ $protocol = ($this->image_library === 'gd2') ? 'image_process_gd' : 'image_process_'.$this->image_library;
return $this->$protocol('resize');
}
@@ -365,18 +660,11 @@ class CI_Image_lib {
* This is a wrapper function that chooses the proper
* cropping function based on the protocol specified
*
- * @access public
* @return bool
*/
- function crop()
+ public function crop()
{
- $protocol = 'image_process_'.$this->image_library;
-
- if (preg_match('/gd2$/i', $protocol))
- {
- $protocol = 'image_process_gd';
- }
-
+ $protocol = ($this->image_library === 'gd2') ? 'image_process_gd' : 'image_process_'.$this->image_library;
return $this->$protocol('crop');
}
@@ -388,22 +676,21 @@ class CI_Image_lib {
* This is a wrapper function that chooses the proper
* rotation function based on the protocol specified
*
- * @access public
* @return bool
*/
- function rotate()
+ public function rotate()
{
// 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;
+ 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;
@@ -414,23 +701,16 @@ class CI_Image_lib {
$this->height = $this->orig_height;
}
-
// Choose resizing function
- if ($this->image_library == 'imagemagick' OR $this->image_library == 'netpbm')
+ if ($this->image_library === 'imagemagick' OR $this->image_library === 'netpbm')
{
$protocol = 'image_process_'.$this->image_library;
-
return $this->$protocol('rotate');
}
- if ($this->rotation_angle == 'hor' OR $this->rotation_angle == 'vrt')
- {
- return $this->image_mirror_gd();
- }
- else
- {
- return $this->image_rotate_gd();
- }
+ return ($this->rotation_angle === 'hor' OR $this->rotation_angle === 'vrt')
+ ? $this->image_mirror_gd()
+ : $this->image_rotate_gd();
}
// --------------------------------------------------------------------
@@ -440,36 +720,29 @@ class CI_Image_lib {
*
* This function will resize or crop
*
- * @access public
* @param string
* @return bool
*/
- function image_process_gd($action = 'resize')
+ public function image_process_gd($action = 'resize')
{
$v2_override = FALSE;
// 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)
+ if ($this->dynamic_output === FALSE && $this->orig_width === $this->width && $this->orig_height === $this->height)
{
- if ($this->orig_width == $this->width AND $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)
- {
- if (@copy($this->full_src_path, $this->full_dst_path))
- {
- @chmod($this->full_dst_path, FILE_WRITE_MODE);
- }
- }
-
- return TRUE;
+ @chmod($this->full_dst_path, FILE_WRITE_MODE);
}
+
+ return TRUE;
}
// Let's set up our values based on the action
- if ($action == 'crop')
+ if ($action === 'crop')
{
- // Reassign the source width/height if cropping
+ // Reassign the source width/height if cropping
$this->orig_width = $this->width;
$this->orig_height = $this->height;
@@ -477,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
@@ -493,14 +766,15 @@ class CI_Image_lib {
return FALSE;
}
- // Create The Image
- //
- // old conditional which users report cause problems with shared GD libs who report themselves as "2.0 or greater"
- // 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' AND function_exists('imagecreatetruecolor') AND $v2_override == FALSE)
- if ($this->image_library == 'gd2' AND function_exists('imagecreatetruecolor'))
+ /* Create the image
+ *
+ * Old conditional which users report cause problems with shared GD libs who report themselves as "2.0 or greater"
+ * 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'))
{
$create = 'imagecreatetruecolor';
$copy = 'imagecopyresampled';
@@ -513,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);
@@ -521,21 +795,17 @@ 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)
+ // Show the image
+ if ($this->dynamic_output === TRUE)
{
$this->image_display_gd($dst_img);
}
- else
+ elseif ( ! $this->image_save_gd($dst_img)) // Or save it
{
- // Or save it
- if ( ! $this->image_save_gd($dst_img))
- {
- return FALSE;
- }
+ return FALSE;
}
- // Kill the file handles
+ // Kill the file handles
imagedestroy($dst_img);
imagedestroy($src_img);
@@ -552,57 +822,53 @@ class CI_Image_lib {
*
* This function will resize, crop or rotate
*
- * @access public
* @param string
* @return bool
*/
- function image_process_imagemagick($action = 'resize')
+ 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;
}
- if ( ! preg_match("/convert$/i", $this->library_path))
+ if ( ! preg_match('/convert$/i', $this->library_path))
{
- $this->library_path = rtrim($this->library_path, '/').'/';
-
- $this->library_path .= 'convert';
+ $this->library_path = rtrim($this->library_path, '/').'/convert';
}
// Execute the command
- $cmd = $this->library_path." -quality ".$this->quality;
+ $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";
+ $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')
{
- switch ($this->rotation_angle)
- {
- case 'hor' : $angle = '-flop';
- break;
- case 'vrt' : $angle = '-flip';
- break;
- default : $angle = '-rotate '.$this->rotation_angle;
- break;
- }
+ $angle = ($this->rotation_angle === 'hor' OR $this->rotation_angle === 'vrt')
+ ? '-flop' : '-rotate '.$this->rotation_angle;
- $cmd .= " ".$angle." \"$this->full_src_path\" \"$this->full_dst_path\" 2>&1";
+ $cmd .= ' '.$angle.' "'.$this->full_src_path.'" "'.$this->full_dst_path.'" 2>&1';
}
- else // Resize
+ else // Resize
{
- $cmd .= " -resize ".$this->width."x".$this->height." \"$this->full_src_path\" \"$this->full_dst_path\" 2>&1";
+ if($this->maintain_ratio === TRUE)
+ {
+ $cmd .= ' -resize '.$this->width.'x'.$this->height.' "'.$this->full_src_path.'" "'.$this->full_dst_path.'" 2>&1';
+ }
+ else
+ {
+ $cmd .= ' -resize '.$this->width.'x'.$this->height.'\! "'.$this->full_src_path.'" "'.$this->full_dst_path.'" 2>&1';
+ }
}
$retval = 1;
-
@exec($cmd, $output, $retval);
- // Did it work?
+ // Did it work?
if ($retval > 0)
{
$this->set_error('imglib_image_process_failed');
@@ -622,52 +888,51 @@ class CI_Image_lib {
*
* This function will resize, crop or rotate
*
- * @access public
* @param string
* @return bool
*/
- function image_process_netpbm($action = 'resize')
+ public function image_process_netpbm($action = 'resize')
{
- if ($this->library_path == '')
+ if ($this->library_path === '')
{
$this->set_error('imglib_libpath_invalid');
return FALSE;
}
- // Build the resizing command
+ // Build the resizing command
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;
}
@@ -681,10 +946,9 @@ class CI_Image_lib {
$cmd = $this->library_path.$cmd_in.' '.$this->full_src_path.' | '.$cmd_inner.' | '.$cmd_out.' > '.$this->dest_folder.'netpbm.tmp';
$retval = 1;
-
@exec($cmd, $output, $retval);
- // Did it work?
+ // Did it work?
if ($retval > 0)
{
$this->set_error('imglib_image_process_failed');
@@ -695,7 +959,7 @@ class CI_Image_lib {
// If you try manipulating the original it fails so
// we have to rename the temp file.
copy ($this->dest_folder.'netpbm.tmp', $this->full_dst_path);
- unlink ($this->dest_folder.'netpbm.tmp');
+ unlink($this->dest_folder.'netpbm.tmp');
@chmod($this->full_dst_path, FILE_WRITE_MODE);
return TRUE;
@@ -706,12 +970,11 @@ class CI_Image_lib {
/**
* Image Rotate Using GD
*
- * @access public
* @return bool
*/
- function image_rotate_gd()
+ public function image_rotate_gd()
{
- // Create the image handle
+ // Create the image handle
if ( ! ($src_img = $this->image_create_gd()))
{
return FALSE;
@@ -724,29 +987,24 @@ class CI_Image_lib {
$white = imagecolorallocate($src_img, 255, 255, 255);
- // Rotate it!
+ // Rotate it!
$dst_img = imagerotate($src_img, $this->rotation_angle, $white);
- // Save the Image
- if ($this->dynamic_output == TRUE)
+ // Show the image
+ if ($this->dynamic_output === TRUE)
{
$this->image_display_gd($dst_img);
}
- else
+ elseif ( ! $this->image_save_gd($dst_img)) // ... or save it
{
- // Or save it
- if ( ! $this->image_save_gd($dst_img))
- {
- return FALSE;
- }
+ return FALSE;
}
- // Kill the file handles
+ // Kill the file handles
imagedestroy($dst_img);
imagedestroy($src_img);
// Set the file to 777
-
@chmod($this->full_dst_path, FILE_WRITE_MODE);
return TRUE;
@@ -759,10 +1017,9 @@ class CI_Image_lib {
*
* This function will flip horizontal or vertical
*
- * @access public
* @return bool
*/
- function image_mirror_gd()
+ public function image_mirror_gd()
{
if ( ! $src_img = $this->image_create_gd())
{
@@ -772,13 +1029,10 @@ class CI_Image_lib {
$width = $this->orig_width;
$height = $this->orig_height;
- if ($this->rotation_angle == 'hor')
+ if ($this->rotation_angle === 'hor')
{
- for ($i = 0; $i < $height; $i++)
+ for ($i = 0; $i < $height; $i++, $left = 0, $right = $width-1)
{
- $left = 0;
- $right = $width-1;
-
while ($left < $right)
{
$cl = imagecolorat($src_img, $left, $i);
@@ -794,11 +1048,8 @@ class CI_Image_lib {
}
else
{
- for ($i = 0; $i < $width; $i++)
+ for ($i = 0; $i < $width; $i++, $top = 0, $bot = $height-1)
{
- $top = 0;
- $bot = $height-1;
-
while ($top < $bot)
{
$ct = imagecolorat($src_img, $i, $top);
@@ -813,21 +1064,17 @@ class CI_Image_lib {
}
}
- // Show the image
- if ($this->dynamic_output == TRUE)
+ // Show the image
+ if ($this->dynamic_output === TRUE)
{
$this->image_display_gd($src_img);
}
- else
+ elseif ( ! $this->image_save_gd($src_img)) // ... or save it
{
- // Or save it
- if ( ! $this->image_save_gd($src_img))
- {
- return FALSE;
- }
+ return FALSE;
}
- // Kill the file handles
+ // Kill the file handles
imagedestroy($src_img);
// Set the file to 777
@@ -844,20 +1091,11 @@ class CI_Image_lib {
* This is a wrapper function that chooses the type
* of watermarking based on the specified preference.
*
- * @access public
- * @param string
* @return bool
*/
- function watermark()
+ public function watermark()
{
- if ($this->wm_type == 'overlay')
- {
- return $this->overlay_watermark();
- }
- else
- {
- return $this->text_watermark();
- }
+ return ($this->wm_type === 'overlay') ? $this->overlay_watermark() : $this->text_watermark();
}
// --------------------------------------------------------------------
@@ -865,10 +1103,9 @@ class CI_Image_lib {
/**
* Watermark - Graphic Version
*
- * @access public
* @return bool
*/
- function overlay_watermark()
+ public function overlay_watermark()
{
if ( ! function_exists('imagecolortransparent'))
{
@@ -876,63 +1113,61 @@ class CI_Image_lib {
return FALSE;
}
- // Fetch source image properties
+ // Fetch source image properties
$this->get_image_properties();
- // Fetch watermark image properties
- $props = $this->get_image_properties($this->wm_overlay_path, TRUE);
+ // Fetch watermark image properties
+ $props = $this->get_image_properties($this->wm_overlay_path, TRUE);
$wm_img_type = $props['image_type'];
- $wm_width = $props['width'];
- $wm_height = $props['height'];
+ $wm_width = $props['width'];
+ $wm_height = $props['height'];
- // Create two image resources
+ // Create two image resources
$wm_img = $this->image_create_gd($this->wm_overlay_path, $wm_img_type);
$src_img = $this->image_create_gd($this->full_src_path);
// Reverse the offset if necessary
// When the image is positioned at the bottom
// we don't want the vertical offset to push it
- // further down. We want the reverse, so we'll
- // invert the offset. Same with the horizontal
+ // further down. We want the reverse, so we'll
+ // invert the offset. Same with the horizontal
// offset when the image is at the right
- $this->wm_vrt_alignment = strtoupper(substr($this->wm_vrt_alignment, 0, 1));
- $this->wm_hor_alignment = strtoupper(substr($this->wm_hor_alignment, 0, 1));
+ $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
+ // Set the base x and y axis values
$x_axis = $this->wm_hor_offset + $this->wm_padding;
$y_axis = $this->wm_vrt_offset + $this->wm_padding;
- // Set the vertical position
- switch ($this->wm_vrt_alignment)
+ // Set the vertical position
+ if ($this->wm_vrt_alignment === 'M')
{
- case 'T':
- break;
- case 'M': $y_axis += ($this->orig_height / 2) - ($wm_height / 2);
- break;
- case 'B': $y_axis += $this->orig_height - $wm_height;
- break;
+ $y_axis += ($this->orig_height / 2) - ($wm_height / 2);
+ }
+ elseif ($this->wm_vrt_alignment === 'B')
+ {
+ $y_axis += $this->orig_height - $wm_height;
}
- // Set the horizontal position
- switch ($this->wm_hor_alignment)
+ // Set the horizontal position
+ if ($this->wm_hor_alignment === 'C')
{
- case 'L':
- break;
- case 'C': $x_axis += ($this->orig_width / 2) - ($wm_width / 2);
- break;
- case 'R': $x_axis += $this->orig_width - $wm_width;
- break;
+ $x_axis += ($this->orig_width / 2) - ($wm_width / 2);
+ }
+ elseif ($this->wm_hor_alignment === 'R')
+ {
+ $x_axis += $this->orig_width - $wm_width;
}
// Build the finalized image
- if ($wm_img_type == 3 AND function_exists('imagealphablending'))
+ if ($wm_img_type === 3 && function_exists('imagealphablending'))
{
@imagealphablending($src_img, TRUE);
}
@@ -954,17 +1189,14 @@ class CI_Image_lib {
imagecopymerge($src_img, $wm_img, $x_axis, $y_axis, 0, 0, $wm_width, $wm_height, $this->wm_opacity);
}
- // Output the image
- if ($this->dynamic_output == TRUE)
+ // Output the image
+ if ($this->dynamic_output === TRUE)
{
$this->image_display_gd($src_img);
}
- else
+ elseif ( ! $this->image_save_gd($src_img)) // ... or save it
{
- if ( ! $this->image_save_gd($src_img))
- {
- return FALSE;
- }
+ return FALSE;
}
imagedestroy($src_img);
@@ -978,60 +1210,46 @@ class CI_Image_lib {
/**
* Watermark - Text Version
*
- * @access public
* @return bool
*/
- function text_watermark()
+ public function text_watermark()
{
if ( ! ($src_img = $this->image_create_gd()))
{
return FALSE;
}
- if ($this->wm_use_truetype == TRUE AND ! 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;
}
- // Fetch source image properties
+ // Fetch source image properties
$this->get_image_properties();
- // Set RGB values for text and shadow
- $this->wm_font_color = str_replace('#', '', $this->wm_font_color);
- $this->wm_shadow_color = str_replace('#', '', $this->wm_shadow_color);
-
- $R1 = hexdec(substr($this->wm_font_color, 0, 2));
- $G1 = hexdec(substr($this->wm_font_color, 2, 2));
- $B1 = hexdec(substr($this->wm_font_color, 4, 2));
-
- $R2 = hexdec(substr($this->wm_shadow_color, 0, 2));
- $G2 = hexdec(substr($this->wm_shadow_color, 2, 2));
- $B2 = hexdec(substr($this->wm_shadow_color, 4, 2));
-
- $txt_color = imagecolorclosest($src_img, $R1, $G1, $B1);
- $drp_color = imagecolorclosest($src_img, $R2, $G2, $B2);
-
// Reverse the vertical offset
// When the image is positioned at the bottom
// we don't want the vertical offset to push it
- // further down. We want the reverse, so we'll
- // invert the offset. Note: The horizontal
+ // further down. We want the reverse, so we'll
+ // 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 == '')
- $this->wm_font_size = '17';
+ if ($this->wm_font_size === '')
+ {
+ $this->wm_font_size = 17;
+ }
$fontwidth = $this->wm_font_size-($this->wm_font_size/4);
$fontheight = $this->wm_font_size;
@@ -1047,59 +1265,65 @@ class CI_Image_lib {
$x_axis = $this->wm_hor_offset + $this->wm_padding;
$y_axis = $this->wm_vrt_offset + $this->wm_padding;
- // Set verticle alignment
- 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));
$this->wm_hor_alignment = strtoupper(substr($this->wm_hor_alignment, 0, 1));
- switch ($this->wm_vrt_alignment)
+ // Set verticle alignment
+ if ($this->wm_vrt_alignment === 'M')
{
- case "T" :
- break;
- case "M": $y_axis += ($this->orig_height/2)+($fontheight/2);
- break;
- case "B": $y_axis += ($this->orig_height - $fontheight - $this->wm_shadow_distance - ($fontheight/2));
- break;
+ $y_axis += ($this->orig_height / 2) + ($fontheight / 2);
+ }
+ elseif ($this->wm_vrt_alignment === 'B')
+ {
+ $y_axis += $this->orig_height - $fontheight - $this->wm_shadow_distance - ($fontheight / 2);
}
$x_shad = $x_axis + $this->wm_shadow_distance;
$y_shad = $y_axis + $this->wm_shadow_distance;
- // Set horizontal alignment
- switch ($this->wm_hor_alignment)
+ if ($this->wm_use_drop_shadow)
{
- case "L":
- break;
- case "R":
- if ($this->wm_use_drop_shadow)
- $x_shad += ($this->orig_width - $fontwidth*strlen($this->wm_text));
- $x_axis += ($this->orig_width - $fontwidth*strlen($this->wm_text));
- break;
- case "C":
- if ($this->wm_use_drop_shadow)
- $x_shad += floor(($this->orig_width - $fontwidth*strlen($this->wm_text))/2);
- $x_axis += floor(($this->orig_width -$fontwidth*strlen($this->wm_text))/2);
- break;
- }
+ // Set horizontal alignment
+ if ($this->wm_hor_alignment === 'R')
+ {
+ $x_shad += $this->orig_width - ($fontwidth * strlen($this->wm_text));
+ $x_axis += $this->orig_width - ($fontwidth * strlen($this->wm_text));
+ }
+ elseif ($this->wm_hor_alignment === 'C')
+ {
+ $x_shad += floor(($this->orig_width - ($fontwidth * strlen($this->wm_text))) / 2);
+ $x_axis += floor(($this->orig_width - ($fontwidth * strlen($this->wm_text))) / 2);
+ }
- // Add the text to the source image
- if ($this->wm_use_truetype)
- {
- if ($this->wm_use_drop_shadow)
+ /* Set RGB values for text and shadow
+ *
+ * First character is #, so we don't really need it.
+ * Get the rest of the string and split it into 2-length
+ * hex values:
+ */
+ $txt_color = str_split(substr($this->wm_font_color, 1, 6), 2);
+ $txt_color = imagecolorclosest($src_img, hexdec($txt_color[0]), hexdec($txt_color[1]), hexdec($txt_color[2]));
+ $drp_color = str_split(substr($this->wm_shadow_color, 1, 6), 2);
+ $drp_color = imagecolorclosest($src_img, hexdec($drp_color[0]), hexdec($drp_color[1]), hexdec($drp_color[2]));
+
+ // Add the text to the source image
+ if ($this->wm_use_truetype)
+ {
imagettftext($src_img, $this->wm_font_size, 0, $x_shad, $y_shad, $drp_color, $this->wm_font_path, $this->wm_text);
imagettftext($src_img, $this->wm_font_size, 0, $x_axis, $y_axis, $txt_color, $this->wm_font_path, $this->wm_text);
- }
- else
- {
- if ($this->wm_use_drop_shadow)
+ }
+ else
+ {
imagestring($src_img, $this->wm_font_size, $x_shad, $y_shad, $this->wm_text, $drp_color);
imagestring($src_img, $this->wm_font_size, $x_axis, $y_axis, $this->wm_text, $txt_color);
+ }
}
- // Output the final image
- if ($this->dynamic_output == TRUE)
+ // Output the final image
+ if ($this->dynamic_output === TRUE)
{
$this->image_display_gd($src_img);
}
@@ -1121,16 +1345,16 @@ class CI_Image_lib {
* This simply creates an image resource handle
* based on the type of image being processed
*
- * @access public
+ * @param string
* @param string
* @return resource
*/
- function image_create_gd($path = '', $image_type = '')
+ 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;
@@ -1178,57 +1402,56 @@ class CI_Image_lib {
* Takes an image resource as input and writes the file
* to the specified destination
*
- * @access public
* @param resource
* @return bool
*/
- function image_save_gd($resource)
+ public function image_save_gd($resource)
{
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;
@@ -1239,26 +1462,25 @@ class CI_Image_lib {
/**
* Dynamically outputs an image
*
- * @access public
* @param resource
* @return void
*/
- function image_display_gd($resource)
+ public function image_display_gd($resource)
{
- header("Content-Disposition: filename={$this->source_image};");
- header("Content-Type: {$this->mime_type}");
+ header('Content-Disposition: filename='.$this->source_image.';');
+ header('Content-Type: '.$this->mime_type);
header('Content-Transfer-Encoding: binary');
header('Last-Modified: '.gmdate('D, d M Y H:i:s', time()).' GMT');
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;
}
}
@@ -1275,38 +1497,47 @@ class CI_Image_lib {
* This function lets us re-proportion the width/height
* if users choose to maintain the aspect ratio when resizing.
*
- * @access public
* @return void
*/
- function image_reproportion()
+ public function image_reproportion()
{
- if ( ! is_numeric($this->width) OR ! is_numeric($this->height) OR $this->width == 0 OR $this->height == 0)
- return;
-
- if ( ! is_numeric($this->orig_width) OR ! is_numeric($this->orig_height) OR $this->orig_width == 0 OR $this->orig_height == 0)
- return;
-
- $new_width = ceil($this->orig_width*$this->height/$this->orig_height);
- $new_height = ceil($this->width*$this->orig_height/$this->orig_width);
-
- $ratio = (($this->orig_height/$this->orig_width) - ($this->height/$this->width));
-
- if ($this->master_dim != 'width' AND $this->master_dim != 'height')
+ 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))
{
- $this->master_dim = ($ratio < 0) ? 'width' : 'height';
+ return;
}
- if (($this->width != $new_width) AND ($this->height != $new_height))
+ // Sanitize so we don't call preg_match() anymore
+ $this->width = (int) $this->width;
+ $this->height = (int) $this->height;
+
+ if ($this->master_dim !== 'width' && $this->master_dim !== 'height')
{
- if ($this->master_dim == 'height')
+ if ($this->width > 0 && $this->height > 0)
{
- $this->width = $new_width;
+ $this->master_dim = ((($this->orig_height/$this->orig_width) - ($this->height/$this->width)) < 0)
+ ? 'width' : 'height';
}
else
{
- $this->height = $new_height;
+ $this->master_dim = ($this->height === 0) ? 'width' : 'height';
}
}
+ elseif (($this->master_dim === 'width' && $this->width === 0)
+ OR ($this->master_dim === 'height' && $this->height === 0))
+ {
+ return;
+ }
+
+ if ($this->master_dim === 'width')
+ {
+ $this->height = (int) ceil($this->width*$this->orig_height/$this->orig_width);
+ }
+ else
+ {
+ $this->width = (int) ceil($this->orig_width*$this->height/$this->orig_height);
+ }
}
// --------------------------------------------------------------------
@@ -1316,17 +1547,19 @@ class CI_Image_lib {
*
* A helper function that gets info about the file
*
- * @access public
* @param string
+ * @param bool
* @return mixed
*/
- function get_image_properties($path = '', $return = FALSE)
+ public function get_image_properties($path = '', $return = FALSE)
{
// 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;
+ }
if ( ! file_exists($path))
{
@@ -1335,26 +1568,24 @@ class CI_Image_lib {
}
$vals = getimagesize($path);
-
$types = array(1 => 'gif', 2 => 'jpeg', 3 => 'png');
+ $mime = (isset($types[$vals[2]])) ? 'image/'.$types[$vals[2]] : 'image/jpg';
- $mime = (isset($types[$vals['2']])) ? 'image/'.$types[$vals['2']] : 'image/jpg';
-
- if ($return == TRUE)
+ if ($return === TRUE)
{
- $v['width'] = $vals['0'];
- $v['height'] = $vals['1'];
- $v['image_type'] = $vals['2'];
- $v['size_str'] = $vals['3'];
- $v['mime_type'] = $mime;
-
- return $v;
+ return array(
+ 'width' => $vals[0],
+ 'height' => $vals[1],
+ 'image_type' => $vals[2],
+ 'size_str' => $vals[3],
+ 'mime_type' => $mime
+ );
}
- $this->orig_width = $vals['0'];
- $this->orig_height = $vals['1'];
- $this->image_type = $vals['2'];
- $this->size_str = $vals['3'];
+ $this->orig_width = $vals[0];
+ $this->orig_height = $vals[1];
+ $this->image_type = $vals[2];
+ $this->size_str = $vals[3];
$this->mime_type = $mime;
return TRUE;
@@ -1366,21 +1597,20 @@ class CI_Image_lib {
* Size calculator
*
* This function takes a known width x height and
- * recalculates it to a new size. Only one
+ * recalculates it to a new size. Only one
* new variable needs to be known
*
* $props = array(
- * 'width' => $width,
- * 'height' => $height,
- * 'new_width' => 40,
- * 'new_height' => ''
- * );
+ * 'width' => $width,
+ * 'height' => $height,
+ * 'new_width' => 40,
+ * 'new_height' => ''
+ * );
*
- * @access public
* @param array
* @return array
*/
- function size_calculator($vals)
+ public function size_calculator($vals)
{
if ( ! is_array($vals))
{
@@ -1391,20 +1621,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']);
}
@@ -1419,16 +1651,15 @@ class CI_Image_lib {
*
* This is a helper function that extracts the extension
* from the source_image. This function lets us deal with
- * source_images with multiple periods, like: my.cool.jpg
+ * source_images with multiple periods, like: my.cool.jpg
* It returns an associative array with two elements:
* $array['ext'] = '.jpg';
* $array['name'] = 'my.cool';
*
- * @access public
* @param array
* @return array
*/
- function explode_name($source_image)
+ public function explode_name($source_image)
{
$ext = strrchr($source_image, '.');
$name = ($ext === FALSE) ? $source_image : substr($source_image, 0, -strlen($ext));
@@ -1441,17 +1672,16 @@ class CI_Image_lib {
/**
* Is GD Installed?
*
- * @access public
* @return bool
*/
- function gd_loaded()
+ public function gd_loaded()
{
if ( ! extension_loaded('gd'))
{
- if ( ! dl('gd.so'))
- {
- return FALSE;
- }
+ /* As it is stated in the PHP manual, dl() is not always available
+ * and even if so - it could generate an E_WARNING message on failure
+ */
+ return (function_exists('dl') && @dl('gd.so'));
}
return TRUE;
@@ -1462,17 +1692,14 @@ class CI_Image_lib {
/**
* Get GD version
*
- * @access public
* @return mixed
*/
- function gd_version()
+ public function gd_version()
{
if (function_exists('gd_info'))
{
$gd_version = @gd_info();
- $gd_version = preg_replace("/\D/", "", $gd_version['GD Version']);
-
- return $gd_version;
+ return preg_replace('/\D/', '', $gd_version['GD Version']);
}
return FALSE;
@@ -1483,11 +1710,10 @@ class CI_Image_lib {
/**
* Set error message
*
- * @access public
* @param string
* @return void
*/
- function set_error($msg)
+ public function set_error($msg)
{
$CI =& get_instance();
$CI->lang->load('imglib');
@@ -1496,15 +1722,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);
}
@@ -1515,23 +1740,16 @@ class CI_Image_lib {
/**
* Show error messages
*
- * @access public
+ * @param string
* @param string
* @return string
*/
- function display_errors($open = '<p>', $close = '</p>')
+ public function display_errors($open = '<p>', $close = '</p>')
{
- $str = '';
- foreach ($this->error_msg as $val)
- {
- $str .= $open.$val.$close;
- }
-
- return $str;
+ return (count($this->error_msg) > 0) ? $open.implode($close.$open, $this->error_msg).$close : '';
}
}
-// END Image_lib Class
/* End of file 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 34e0d7001..5c8b09217 100644
--- a/system/libraries/Javascript.php
+++ b/system/libraries/Javascript.php
@@ -1,32 +1,42 @@
-<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
+<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* CodeIgniter
*
- * An open source application development framework for PHP 5.1.6 or newer
+ * An open source application development framework for PHP 5.2.4 or newer
+ *
+ * NOTICE OF LICENSE
+ *
+ * Licensed under the Open Software License version 3.0
+ *
+ * This source file is subject to the Open Software License (OSL 3.0) that is
+ * bundled with this package in the files license.txt / license.rst. It is
+ * also available through the world wide web at this URL:
+ * http://opensource.org/licenses/OSL-3.0
+ * If you did not receive a copy of the license and are unable to obtain it
+ * through the world wide web, please send an email to
+ * licensing@ellislab.com so we can send you a copy immediately.
*
* @package CodeIgniter
- * @author ExpressionEngine Dev Team
- * @copyright Copyright (c) 2008 - 2011, EllisLab, Inc.
- * @license http://codeigniter.com/user_guide/license.html
+ * @author EllisLab Dev Team
+ * @copyright Copyright (c) 2008 - 2012, EllisLab, Inc. (http://ellislab.com/)
+ * @license http://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
* @link http://codeigniter.com
* @since Version 1.0
* @filesource
*/
-// ------------------------------------------------------------------------
-
/**
* Javascript Class
*
* @package CodeIgniter
* @subpackage Libraries
* @category Javascript
- * @author ExpressionEngine Dev Team
+ * @author EllisLab Dev Team
* @link http://codeigniter.com/user_guide/libraries/javascript.html
*/
class CI_Javascript {
- var $_javascript_location = 'js';
+ protected $_javascript_location = 'js';
public function __construct($params = array())
{
@@ -34,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];
}
@@ -49,10 +59,10 @@ 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);
}
- // --------------------------------------------------------------------
+ // --------------------------------------------------------------------
// Event Code
// --------------------------------------------------------------------
@@ -61,12 +71,11 @@ class CI_Javascript {
*
* Outputs a javascript library blur event
*
- * @access public
* @param string The element to attach the event to
* @param string The code to execute
* @return string
*/
- function blur($element = 'this', $js = '')
+ public function blur($element = 'this', $js = '')
{
return $this->js->_blur($element, $js);
}
@@ -78,12 +87,11 @@ class CI_Javascript {
*
* Outputs a javascript library change event
*
- * @access public
* @param string The element to attach the event to
* @param string The code to execute
* @return string
*/
- function change($element = 'this', $js = '')
+ public function change($element = 'this', $js = '')
{
return $this->js->_change($element, $js);
}
@@ -95,13 +103,12 @@ class CI_Javascript {
*
* Outputs a javascript library click event
*
- * @access public
* @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
*/
- function click($element = 'this', $js = '', $ret_false = TRUE)
+ public function click($element = 'this', $js = '', $ret_false = TRUE)
{
return $this->js->_click($element, $js, $ret_false);
}
@@ -113,12 +120,11 @@ class CI_Javascript {
*
* Outputs a javascript library dblclick event
*
- * @access public
* @param string The element to attach the event to
* @param string The code to execute
* @return string
*/
- function dblclick($element = 'this', $js = '')
+ public function dblclick($element = 'this', $js = '')
{
return $this->js->_dblclick($element, $js);
}
@@ -130,12 +136,11 @@ class CI_Javascript {
*
* Outputs a javascript library error event
*
- * @access public
* @param string The element to attach the event to
* @param string The code to execute
* @return string
*/
- function error($element = 'this', $js = '')
+ public function error($element = 'this', $js = '')
{
return $this->js->_error($element, $js);
}
@@ -147,12 +152,11 @@ class CI_Javascript {
*
* Outputs a javascript library focus event
*
- * @access public
* @param string The element to attach the event to
* @param string The code to execute
* @return string
*/
- function focus($element = 'this', $js = '')
+ public function focus($element = 'this', $js = '')
{
return $this->js->__add_event($focus, $js);
}
@@ -164,13 +168,12 @@ class CI_Javascript {
*
* Outputs a javascript library hover event
*
- * @access public
* @param string - element
* @param string - Javascript code for mouse over
* @param string - Javascript code for mouse out
* @return string
*/
- function hover($element = 'this', $over, $out)
+ public function hover($element = 'this', $over, $out)
{
return $this->js->__hover($element, $over, $out);
}
@@ -182,12 +185,11 @@ class CI_Javascript {
*
* Outputs a javascript library keydown event
*
- * @access public
* @param string The element to attach the event to
* @param string The code to execute
* @return string
*/
- function keydown($element = 'this', $js = '')
+ public function keydown($element = 'this', $js = '')
{
return $this->js->_keydown($element, $js);
}
@@ -199,12 +201,11 @@ class CI_Javascript {
*
* Outputs a javascript library keydown event
*
- * @access public
* @param string The element to attach the event to
* @param string The code to execute
* @return string
*/
- function keyup($element = 'this', $js = '')
+ public function keyup($element = 'this', $js = '')
{
return $this->js->_keyup($element, $js);
}
@@ -216,12 +217,11 @@ class CI_Javascript {
*
* Outputs a javascript library load event
*
- * @access public
* @param string The element to attach the event to
* @param string The code to execute
* @return string
*/
- function load($element = 'this', $js = '')
+ public function load($element = 'this', $js = '')
{
return $this->js->_load($element, $js);
}
@@ -233,12 +233,11 @@ class CI_Javascript {
*
* Outputs a javascript library mousedown event
*
- * @access public
* @param string The element to attach the event to
* @param string The code to execute
* @return string
*/
- function mousedown($element = 'this', $js = '')
+ public function mousedown($element = 'this', $js = '')
{
return $this->js->_mousedown($element, $js);
}
@@ -250,12 +249,11 @@ class CI_Javascript {
*
* Outputs a javascript library mouseout event
*
- * @access public
* @param string The element to attach the event to
* @param string The code to execute
* @return string
*/
- function mouseout($element = 'this', $js = '')
+ public function mouseout($element = 'this', $js = '')
{
return $this->js->_mouseout($element, $js);
}
@@ -267,12 +265,11 @@ class CI_Javascript {
*
* Outputs a javascript library mouseover event
*
- * @access public
* @param string The element to attach the event to
* @param string The code to execute
* @return string
*/
- function mouseover($element = 'this', $js = '')
+ public function mouseover($element = 'this', $js = '')
{
return $this->js->_mouseover($element, $js);
}
@@ -284,12 +281,11 @@ class CI_Javascript {
*
* Outputs a javascript library mouseup event
*
- * @access public
* @param string The element to attach the event to
* @param string The code to execute
* @return string
*/
- function mouseup($element = 'this', $js = '')
+ public function mouseup($element = 'this', $js = '')
{
return $this->js->_mouseup($element, $js);
}
@@ -301,11 +297,10 @@ class CI_Javascript {
*
* Outputs the called javascript to the screen
*
- * @access public
* @param string The code to output
* @return string
*/
- function output($js)
+ public function output($js)
{
return $this->js->_output($js);
}
@@ -317,12 +312,11 @@ class CI_Javascript {
*
* Outputs a javascript library mouseup event
*
- * @access public
* @param string The element to attach the event to
* @param string The code to execute
* @return string
*/
- function ready($js)
+ public function ready($js)
{
return $this->js->_document_ready($js);
}
@@ -334,12 +328,11 @@ class CI_Javascript {
*
* Outputs a javascript library resize event
*
- * @access public
* @param string The element to attach the event to
* @param string The code to execute
* @return string
*/
- function resize($element = 'this', $js = '')
+ public function resize($element = 'this', $js = '')
{
return $this->js->_resize($element, $js);
}
@@ -351,12 +344,11 @@ class CI_Javascript {
*
* Outputs a javascript library scroll event
*
- * @access public
* @param string The element to attach the event to
* @param string The code to execute
* @return string
*/
- function scroll($element = 'this', $js = '')
+ public function scroll($element = 'this', $js = '')
{
return $this->js->_scroll($element, $js);
}
@@ -368,32 +360,29 @@ class CI_Javascript {
*
* Outputs a javascript library unload event
*
- * @access public
* @param string The element to attach the event to
* @param string The code to execute
* @return string
*/
- function unload($element = 'this', $js = '')
+ public function unload($element = 'this', $js = '')
{
return $this->js->_unload($element, $js);
}
- // --------------------------------------------------------------------
+ // --------------------------------------------------------------------
// Effects
// --------------------------------------------------------------------
-
/**
* Add Class
*
* Outputs a javascript library addClass event
*
- * @access public
* @param string - element
* @param string - Class to add
* @return string
*/
- function addClass($element = 'this', $class = '')
+ public function addClass($element = 'this', $class = '')
{
return $this->js->_addClass($element, $class);
}
@@ -405,13 +394,12 @@ class CI_Javascript {
*
* Outputs a javascript library animate event
*
- * @access public
* @param string - element
* @param string - One of 'slow', 'normal', 'fast', or time in milliseconds
* @param string - Javascript callback function
* @return string
*/
- function animate($element = 'this', $params = array(), $speed = '', $extra = '')
+ public function animate($element = 'this', $params = array(), $speed = '', $extra = '')
{
return $this->js->_animate($element, $params, $speed, $extra);
}
@@ -423,13 +411,12 @@ class CI_Javascript {
*
* Outputs a javascript library hide event
*
- * @access public
* @param string - element
* @param string - One of 'slow', 'normal', 'fast', or time in milliseconds
* @param string - Javascript callback function
* @return string
*/
- function fadeIn($element = 'this', $speed = '', $callback = '')
+ public function fadeIn($element = 'this', $speed = '', $callback = '')
{
return $this->js->_fadeIn($element, $speed, $callback);
}
@@ -441,13 +428,12 @@ class CI_Javascript {
*
* Outputs a javascript library hide event
*
- * @access public
* @param string - element
* @param string - One of 'slow', 'normal', 'fast', or time in milliseconds
* @param string - Javascript callback function
* @return string
*/
- function fadeOut($element = 'this', $speed = '', $callback = '')
+ public function fadeOut($element = 'this', $speed = '', $callback = '')
{
return $this->js->_fadeOut($element, $speed, $callback);
}
@@ -458,13 +444,12 @@ class CI_Javascript {
*
* Outputs a javascript library slideUp event
*
- * @access public
* @param string - element
* @param string - One of 'slow', 'normal', 'fast', or time in milliseconds
* @param string - Javascript callback function
* @return string
*/
- function slideUp($element = 'this', $speed = '', $callback = '')
+ public function slideUp($element = 'this', $speed = '', $callback = '')
{
return $this->js->_slideUp($element, $speed, $callback);
@@ -477,12 +462,11 @@ class CI_Javascript {
*
* Outputs a javascript library removeClass event
*
- * @access public
* @param string - element
* @param string - Class to add
* @return string
*/
- function removeClass($element = 'this', $class = '')
+ public function removeClass($element = 'this', $class = '')
{
return $this->js->_removeClass($element, $class);
}
@@ -494,13 +478,12 @@ class CI_Javascript {
*
* Outputs a javascript library slideDown event
*
- * @access public
* @param string - element
* @param string - One of 'slow', 'normal', 'fast', or time in milliseconds
* @param string - Javascript callback function
* @return string
*/
- function slideDown($element = 'this', $speed = '', $callback = '')
+ public function slideDown($element = 'this', $speed = '', $callback = '')
{
return $this->js->_slideDown($element, $speed, $callback);
}
@@ -512,13 +495,12 @@ class CI_Javascript {
*
* Outputs a javascript library slideToggle event
*
- * @access public
* @param string - element
* @param string - One of 'slow', 'normal', 'fast', or time in milliseconds
* @param string - Javascript callback function
* @return string
*/
- function slideToggle($element = 'this', $speed = '', $callback = '')
+ public function slideToggle($element = 'this', $speed = '', $callback = '')
{
return $this->js->_slideToggle($element, $speed, $callback);
@@ -531,13 +513,12 @@ class CI_Javascript {
*
* Outputs a javascript library hide action
*
- * @access public
* @param string - element
* @param string - One of 'slow', 'normal', 'fast', or time in milliseconds
* @param string - Javascript callback function
* @return string
*/
- function hide($element = 'this', $speed = '', $callback = '')
+ public function hide($element = 'this', $speed = '', $callback = '')
{
return $this->js->_hide($element, $speed, $callback);
}
@@ -549,11 +530,10 @@ class CI_Javascript {
*
* Outputs a javascript library toggle event
*
- * @access public
* @param string - element
* @return string
*/
- function toggle($element = 'this')
+ public function toggle($element = 'this')
{
return $this->js->_toggle($element);
@@ -566,11 +546,10 @@ class CI_Javascript {
*
* Outputs a javascript library toggle class event
*
- * @access public
* @param string - element
* @return string
*/
- function toggleClass($element = 'this', $class='')
+ public function toggleClass($element = 'this', $class='')
{
return $this->js->_toggleClass($element, $class);
}
@@ -582,13 +561,12 @@ class CI_Javascript {
*
* Outputs a javascript library show event
*
- * @access public
* @param string - element
* @param string - One of 'slow', 'normal', 'fast', or time in milliseconds
* @param string - Javascript callback function
* @return string
*/
- function show($element = 'this', $speed = '', $callback = '')
+ public function show($element = 'this', $speed = '', $callback = '')
{
return $this->js->_show($element, $speed, $callback);
}
@@ -601,11 +579,10 @@ class CI_Javascript {
*
* gather together all script needing to be output
*
- * @access public
* @param string The element to attach the event to
* @return string
*/
- function compile($view_var = 'script_foot', $script_tags = TRUE)
+ public function compile($view_var = 'script_foot', $script_tags = TRUE)
{
$this->js->_compile($view_var, $script_tags);
}
@@ -615,10 +592,9 @@ class CI_Javascript {
*
* Clears any previous javascript collected for output
*
- * @access public
* @return void
*/
- function clear_compile()
+ public function clear_compile()
{
$this->js->_clear_compile();
}
@@ -630,25 +606,21 @@ class CI_Javascript {
*
* Outputs a <script> tag with the source as an external js file
*
- * @access public
* @param string The element to attach the event to
* @return string
*/
- function external($external_file = '', $relative = FALSE)
+ public function external($external_file = '', $relative = FALSE)
{
if ($external_file !== '')
{
$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)
+ if ($relative === TRUE OR strpos($external_file, 'http://') === 0 OR strpos($external_file, 'https://') === 0)
{
$str = $this->_open_script($external_file);
}
@@ -661,8 +633,7 @@ class CI_Javascript {
$str = $this->_open_script($this->CI->config->slash_item('base_url').$this->_javascript_location.$external_file);
}
- $str .= $this->_close_script();
- return $str;
+ return $str.$this->_close_script();
}
// --------------------------------------------------------------------
@@ -672,20 +643,17 @@ class CI_Javascript {
*
* Outputs a <script> tag
*
- * @access public
* @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
*/
- function inline($script, $cdata = TRUE)
+ public function inline($script, $cdata = TRUE)
{
- $str = $this->_open_script();
- $str .= ($cdata) ? "\n// <![CDATA[\n{$script}\n// ]]>\n" : "\n{$script}\n";
- $str .= $this->_close_script();
-
- return $str;
+ return $this->_open_script()
+ . ($cdata ? "\n// <![CDATA[\n".$script."\n// ]]>\n" : "\n".$script."\n")
+ . $this->_close_script();
}
-
+
// --------------------------------------------------------------------
/**
@@ -693,15 +661,13 @@ class CI_Javascript {
*
* Outputs an opening <script>
*
- * @access private
* @param string
* @return string
*/
- function _open_script($src = '')
+ protected function _open_script($src = '')
{
- $str = '<script type="text/javascript" charset="'.strtolower($this->CI->config->item('charset')).'"';
- $str .= ($src == '') ? '>' : ' src="'.$src.'">';
- return $str;
+ return '<script type="text/javascript" charset="'.strtolower($this->CI->config->item('charset')).'"'
+ .($src === '' ? '>' : ' src="'.$src.'">');
}
// --------------------------------------------------------------------
@@ -711,34 +677,29 @@ class CI_Javascript {
*
* Outputs an closing </script>
*
- * @access private
* @param string
* @return string
*/
- function _close_script($extra = "\n")
+ protected function _close_script($extra = "\n")
{
- return "</script>$extra";
+ return '</script>'.$extra;
}
-
- // --------------------------------------------------------------------
// --------------------------------------------------------------------
// AJAX-Y STUFF - still a testbed
// --------------------------------------------------------------------
- // --------------------------------------------------------------------
/**
* Update
*
* Outputs a javascript library slideDown event
*
- * @access public
* @param string - element
* @param string - One of 'slow', 'normal', 'fast', or time in milliseconds
* @param string - Javascript callback function
* @return string
*/
- function update($element = 'this', $speed = '', $callback = '')
+ public function update($element = 'this', $speed = '', $callback = '')
{
return $this->js->_updater($element, $speed, $callback);
}
@@ -754,7 +715,7 @@ class CI_Javascript {
* @param bool match array types (defaults to objects)
* @return string a json formatted string
*/
- function generate_json($result = NULL, $match_array_type = FALSE)
+ public function generate_json($result = NULL, $match_array_type = FALSE)
{
// JSON data can optionally be passed to this function
// either as a database result object or an array, or a user supplied array
@@ -762,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))
{
@@ -781,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)
{
@@ -804,7 +765,7 @@ class CI_Javascript {
$json = implode(',', $json);
- return $_is_assoc ? "{".$json."}" : "[".$json."]";
+ return $_is_assoc ? '{'.$json.'}' : '['.$json.']';
}
@@ -815,11 +776,10 @@ class CI_Javascript {
*
* Checks for an associative array
*
- * @access public
- * @param type
- * @return type
+ * @param array
+ * @return bool
*/
- function _is_associative_array($arr)
+ protected function _is_associative_array($arr)
{
foreach (array_keys($arr) as $key => $val)
{
@@ -839,11 +799,10 @@ class CI_Javascript {
*
* Ensures a standard json value and escapes values
*
- * @access public
- * @param type
- * @return type
+ * @param mixed
+ * @return string
*/
- function _prep_args($result, $is_key = FALSE)
+ protected function _prep_args($result, $is_key = FALSE)
{
if (is_null($result))
{
@@ -855,7 +814,7 @@ class CI_Javascript {
}
elseif (is_string($result) OR $is_key)
{
- return '"'.str_replace(array('\\', "\t", "\n", "\r", '"', '/'), array('\\\\', '\\t', '\\n', "\\r", '\"', '\/'), $result).'"';
+ return '"'.str_replace(array('\\', "\t", "\n", "\r", '"', '/'), array('\\\\', '\\t', '\\n', "\\r", '\"', '\/'), $result).'"';
}
elseif (is_scalar($result))
{
@@ -863,9 +822,7 @@ class CI_Javascript {
}
}
- // --------------------------------------------------------------------
}
-// END Javascript Class
/* End of file 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 bf10d4727..baac80121 100644
--- a/system/libraries/Log.php
+++ b/system/libraries/Log.php
@@ -1,47 +1,100 @@
-<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
+<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* CodeIgniter
*
- * An open source application development framework for PHP 5.1.6 or newer
+ * An open source application development framework for PHP 5.2.4 or newer
+ *
+ * NOTICE OF LICENSE
+ *
+ * Licensed under the Open Software License version 3.0
+ *
+ * This source file is subject to the Open Software License (OSL 3.0) that is
+ * bundled with this package in the files license.txt / license.rst. It is
+ * also available through the world wide web at this URL:
+ * http://opensource.org/licenses/OSL-3.0
+ * If you did not receive a copy of the license and are unable to obtain it
+ * through the world wide web, please send an email to
+ * licensing@ellislab.com so we can send you a copy immediately.
*
* @package CodeIgniter
- * @author ExpressionEngine Dev Team
- * @copyright Copyright (c) 2008 - 2011, EllisLab, Inc.
- * @license http://codeigniter.com/user_guide/license.html
+ * @author EllisLab Dev Team
+ * @copyright Copyright (c) 2008 - 2012, EllisLab, Inc. (http://ellislab.com/)
+ * @license http://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
* @link http://codeigniter.com
* @since Version 1.0
* @filesource
*/
-// ------------------------------------------------------------------------
-
/**
* Logging Class
*
* @package CodeIgniter
* @subpackage Libraries
* @category Logging
- * @author ExpressionEngine Dev Team
+ * @author EllisLab Dev Team
* @link http://codeigniter.com/user_guide/general/errors.html
*/
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))
{
@@ -50,7 +103,7 @@ class CI_Log {
if (is_numeric($config['log_threshold']))
{
- $this->_threshold = $config['log_threshold'];
+ $this->_threshold = (int) $config['log_threshold'];
}
elseif (is_array($config['log_threshold']))
{
@@ -58,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'];
}
@@ -85,12 +138,10 @@ class CI_Log {
$level = strtoupper($level);
- if ( ! isset($this->_levels[$level]) OR ($this->_levels[$level] > $this->_threshold))
+ if (( ! isset($this->_levels[$level]) OR ($this->_levels[$level] > $this->_threshold))
+ && ! isset($this->_threshold_array[$this->_levels[$level]]))
{
- if (empty($this->_threshold_array) OR ! isset($this->_threshold_array[$this->_levels[$level]]))
- {
- return FALSE;
- }
+ return FALSE;
}
@@ -99,7 +150,8 @@ class CI_Log {
if ( ! file_exists($filepath))
{
- $message .= "<"."?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); ?".">\n\n";
+ $newfile = TRUE;
+ $message .= '<'."?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); ?".">\n\n";
}
if ( ! $fp = @fopen($filepath, FOPEN_WRITE_CREATE))
@@ -107,19 +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);
- @chmod($filepath, FILE_WRITE_MODE);
+ 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 */ \ No newline at end of file
diff --git a/system/libraries/Migration.php b/system/libraries/Migration.php
index 3734e18f5..5d637d44a 100644
--- a/system/libraries/Migration.php
+++ b/system/libraries/Migration.php
@@ -1,20 +1,30 @@
-<?php defined('BASEPATH') OR exit('No direct script access allowed');
+<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* CodeIgniter
*
- * An open source application development framework for PHP 5.1.6 or newer
+ * An open source application development framework for PHP 5.2.4 or newer
+ *
+ * NOTICE OF LICENSE
+ *
+ * Licensed under the Open Software License version 3.0
+ *
+ * This source file is subject to the Open Software License (OSL 3.0) that is
+ * bundled with this package in the files license.txt / license.rst. It is
+ * also available through the world wide web at this URL:
+ * http://opensource.org/licenses/OSL-3.0
+ * If you did not receive a copy of the license and are unable to obtain it
+ * through the world wide web, please send an email to
+ * licensing@ellislab.com so we can send you a copy immediately.
*
* @package CodeIgniter
* @author EllisLab Dev Team
- * @copyright Copyright (c) 2006 - 2011, EllisLab, Inc.
- * @license http://codeigniter.com/user_guide/license.html
+ * @copyright Copyright (c) 2006 - 2012, EllisLab, Inc. (http://ellislab.com/)
+ * @license http://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
* @link http://codeigniter.com
- * @since Version 1.0
+ * @since Version 3.0
* @filesource
*/
-// ------------------------------------------------------------------------
-
/**
* Migration Class
*
@@ -29,12 +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
@@ -45,7 +97,7 @@ class CI_Migration {
foreach ($config as $key => $val)
{
- $this->{'_' . $key} = $val;
+ $this->{'_'.$key} = $val;
}
log_message('debug', 'Migrations class initialized');
@@ -57,7 +109,7 @@ class CI_Migration {
}
// If not set, set it
- $this->_migration_path == '' AND $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, '/').'/';
@@ -68,16 +120,28 @@ class CI_Migration {
// They'll probably be using dbforge
$this->load->dbforge();
+ // Make sure the migration table name was set.
+ if (empty($this->_migration_table))
+ {
+ show_error('Migrations configuration file (migration.php) must have "migration_table" set.');
+ }
+
// If the migrations table is missing, make it
- if ( ! $this->db->table_exists('migrations'))
+ if ( ! $this->db->table_exists($this->_migration_table))
{
$this->dbforge->add_field(array(
'version' => array('type' => 'INT', 'constraint' => 3),
));
- $this->dbforge->create_table('migrations', TRUE);
+ $this->dbforge->create_table($this->_migration_table, TRUE);
+
+ $this->db->insert($this->_migration_table, array('version' => 0));
+ }
- $this->db->insert('migrations', array('version' => 0));
+ // Do we auto migrate to the latest migration?
+ if ($this->_migration_auto_latest === TRUE && ! $this->latest())
+ {
+ show_error($this->error_string());
}
}
@@ -89,8 +153,7 @@ class CI_Migration {
* Calls each migration step required to get to the schema version of
* choice
*
- * @access public
- * @param $version integer Target schema version
+ * @param int Target schema version
* @return mixed TRUE if already latest, FALSE if failed, int if upgraded
*/
public function version($target_version)
@@ -105,13 +168,12 @@ class CI_Migration {
++$stop;
$step = 1;
}
-
else
{
// Moving Down
$step = -1;
}
-
+
$method = $step === 1 ? 'up' : 'down';
$migrations = array();
@@ -119,7 +181,7 @@ class CI_Migration {
// But first let's make sure that everything is the way it should be
for ($i = $start; $i != $stop; $i += $step)
{
- $f = glob(sprintf($this->_migration_path . '%03d_*.php', $i));
+ $f = glob(sprintf($this->_migration_path.'%03d_*.php', $i));
// Only one migration per step is permitted
if (count($f) > 1)
@@ -129,11 +191,11 @@ class CI_Migration {
}
// Migration step not found
- if (count($f) == 0)
+ if (count($f) === 0)
{
// If trying to migrate up to a version greater than the last
// existing one, migrate to the last one.
- if ($step == 1)
+ if ($step === 1)
{
break;
}
@@ -160,7 +222,7 @@ class CI_Migration {
}
include $f[0];
- $class = 'Migration_' . ucfirst($match[1]);
+ $class = 'Migration_'.ucfirst($match[1]);
if ( ! class_exists($class))
{
@@ -183,9 +245,9 @@ class CI_Migration {
}
}
- log_message('debug', 'Current migration: ' . $current_version);
+ log_message('debug', 'Current migration: '.$current_version);
- $version = $i + ($step == 1 ? -1 : 0);
+ $version = $i + ($step === 1 ? -1 : 0);
// If there is nothing to do so quit
if ($migrations === array())
@@ -193,13 +255,13 @@ class CI_Migration {
return TRUE;
}
- log_message('debug', 'Migrating from ' . $method . ' to version ' . $version);
+ log_message('debug', 'Migrating from '.$method.' to version '.$version);
// Loop through the migrations
foreach ($migrations AS $migration)
{
// Run the migration class
- $class = 'Migration_' . ucfirst(strtolower($migration));
+ $class = 'Migration_'.ucfirst(strtolower($migration));
call_user_func(array(new $class, $method));
$current_version += $step;
@@ -216,22 +278,21 @@ class CI_Migration {
/**
* Set's the schema to the latest migration
*
- * @access public
* @return mixed true if already latest, false if failed, int if upgraded
*/
public function latest()
{
if ( ! $migrations = $this->find_migrations())
{
- $this->_error_string = $this->line->lang('migration_none_found');
- return false;
+ $this->_error_string = $this->lang->line('migration_none_found');
+ return FALSE;
}
$last_migration = basename(end($migrations));
-
+
// Calculate the last migration step from existing migration
// filenames and procceed to the standard version migration
- return $this->version((int) substr($last_migration, 0, 3));
+ return $this->version((int) $last_migration);
}
// --------------------------------------------------------------------
@@ -239,7 +300,6 @@ class CI_Migration {
/**
* Set's the schema to the migration version set in config
*
- * @access public
* @return mixed true if already current, false if failed, int if upgraded
*/
public function current()
@@ -252,7 +312,6 @@ class CI_Migration {
/**
* Error string
*
- * @access public
* @return string Error message returned as a string
*/
public function error_string()
@@ -263,29 +322,25 @@ class CI_Migration {
// --------------------------------------------------------------------
/**
- * Set's the schema to the latest migration
+ * Retrieves list of available migration scripts
*
- * @access protected
- * @return mixed true if already latest, false if failed, int if upgraded
+ * @return array list of migration file paths sorted by version
*/
protected function find_migrations()
{
// Load all *_*.php files in the migrations path
- $files = glob($this->_migration_path . '*_*.php');
- $file_count = count($files);
-
- for ($i = 0; $i < $file_count; $i++)
+ $files = glob($this->_migration_path.'*_*.php');
+
+ for ($i = 0, $c = count($files); $i < $c; $i++)
{
// Mark wrongly formatted files as false for later filtering
- $name = basename($files[$i], '.php');
- if ( ! preg_match('/^\d{3}_(\w+)$/', $name))
+ if ( ! preg_match('/^\d{3}_(\w+)$/', basename($files[$i], '.php')))
{
$files[$i] = FALSE;
}
}
-
- sort($files);
+ sort($files);
return $files;
}
@@ -294,12 +349,11 @@ class CI_Migration {
/**
* Retrieves current schema version
*
- * @access protected
- * @return integer Current Migration
+ * @return int Current Migration
*/
protected function _get_version()
{
- $row = $this->db->get('migrations')->row();
+ $row = $this->db->select('version')->get($this->_migration_table)->row();
return $row ? $row->version : 0;
}
@@ -308,13 +362,12 @@ class CI_Migration {
/**
* Stores the current schema version
*
- * @access protected
- * @param $migrations integer Migration reached
- * @return void Outputs a report of the migration
+ * @param int Migration reached
+ * @return void Outputs a report of the migration
*/
protected function _update_version($migrations)
{
- return $this->db->update('migrations', array(
+ return $this->db->update($this->_migration_table, array(
'version' => $migrations
));
}
@@ -324,14 +377,14 @@ class CI_Migration {
/**
* Enable the use of CI super-global
*
- * @access public
- * @param $var
+ * @param $var
* @return mixed
*/
public function __get($var)
{
return get_instance()->$var;
}
+
}
/* End of file Migration.php */
diff --git a/system/libraries/Pagination.php b/system/libraries/Pagination.php
index cc62e660b..5573f6407 100644
--- a/system/libraries/Pagination.php
+++ b/system/libraries/Pagination.php
@@ -1,83 +1,87 @@
-<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
+<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* CodeIgniter
*
- * An open source application development framework for PHP 5.1.6 or newer
+ * An open source application development framework for PHP 5.2.4 or newer
+ *
+ * NOTICE OF LICENSE
+ *
+ * Licensed under the Open Software License version 3.0
+ *
+ * This source file is subject to the Open Software License (OSL 3.0) that is
+ * bundled with this package in the files license.txt / license.rst. It is
+ * also available through the world wide web at this URL:
+ * http://opensource.org/licenses/OSL-3.0
+ * If you did not receive a copy of the license and are unable to obtain it
+ * through the world wide web, please send an email to
+ * licensing@ellislab.com so we can send you a copy immediately.
*
* @package CodeIgniter
- * @author ExpressionEngine Dev Team
- * @copyright Copyright (c) 2008 - 2011, EllisLab, Inc.
- * @license http://codeigniter.com/user_guide/license.html
+ * @author EllisLab Dev Team
+ * @copyright Copyright (c) 2008 - 2012, EllisLab, Inc. (http://ellislab.com/)
+ * @license http://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
* @link http://codeigniter.com
* @since Version 1.0
* @filesource
*/
-// ------------------------------------------------------------------------
-
/**
* Pagination Class
*
* @package CodeIgniter
* @subpackage Libraries
* @category Pagination
- * @author ExpressionEngine Dev Team
+ * @author EllisLab Dev Team
* @link http://codeigniter.com/user_guide/libraries/pagination.html
*/
class CI_Pagination {
- var $base_url = ''; // The page we are linking to
- var $prefix = ''; // A custom prefix added to the path.
- var $suffix = ''; // A custom suffix added to the path.
-
- var $total_rows = 0; // Total number of items (database results)
- var $per_page = 10; // Max number of items you want shown per page
- var $num_links = 2; // Number of "digit" links to show before/after the currently viewed page
- var $cur_page = 0; // The current page being viewed
- var $first_link = '&lsaquo; First';
- var $next_link = '&gt;';
- var $prev_link = '&lt;';
- var $last_link = 'Last &rsaquo;';
- var $uri_segment = 3;
- var $full_tag_open = '';
- var $full_tag_close = '';
- var $first_tag_open = '';
- var $first_tag_close = '&nbsp;';
- var $last_tag_open = '&nbsp;';
- var $last_tag_close = '';
- var $first_url = ''; // Alternative URL for the First Page.
- var $cur_tag_open = '&nbsp;<strong>';
- var $cur_tag_close = '</strong>';
- var $next_tag_open = '&nbsp;';
- var $next_tag_close = '&nbsp;';
- var $prev_tag_open = '&nbsp;';
- var $prev_tag_close = '';
- var $num_tag_open = '&nbsp;';
- var $num_tag_close = '';
- var $page_query_string = FALSE;
- var $query_string_segment = 'per_page';
- var $display_pages = TRUE;
- var $anchor_class = '';
+ protected $base_url = ''; // The page we are linking to
+ protected $prefix = ''; // A custom prefix added to the path.
+ protected $suffix = ''; // A custom suffix added to the path.
+ protected $total_rows = 0; // Total number of items (database results)
+ protected $per_page = 10; // Max number of items you want shown per page
+ protected $num_links = 2; // Number of "digit" links to show before/after the currently viewed page
+ protected $cur_page = 0; // The current page being viewed
+ protected $use_page_numbers = FALSE; // Use page number for segment instead of offset
+ protected $first_link = '&lsaquo; First';
+ protected $next_link = '&gt;';
+ protected $prev_link = '&lt;';
+ protected $last_link = 'Last &rsaquo;';
+ protected $uri_segment = 3;
+ protected $full_tag_open = '';
+ protected $full_tag_close = '';
+ protected $first_tag_open = '';
+ protected $first_tag_close = '&nbsp;';
+ protected $last_tag_open = '&nbsp;';
+ protected $last_tag_close = '';
+ protected $first_url = ''; // Alternative URL for the First Page.
+ protected $cur_tag_open = '&nbsp;<strong>';
+ protected $cur_tag_close = '</strong>';
+ protected $next_tag_open = '&nbsp;';
+ protected $next_tag_close = '&nbsp;';
+ protected $prev_tag_open = '&nbsp;';
+ protected $prev_tag_close = '';
+ protected $num_tag_open = '&nbsp;';
+ protected $num_tag_close = '';
+ protected $page_query_string = FALSE;
+ protected $query_string_segment = 'per_page';
+ protected $display_pages = TRUE;
+ protected $_attributes = '';
+ protected $_link_types = array();
+ protected $reuse_query_string = FALSE;
+ protected $data_page_attr = 'data-ci-pagination-page';
/**
* Constructor
*
- * @access public
* @param array initialization parameters
+ * @return void
*/
public function __construct($params = array())
{
- if (count($params) > 0)
- {
- $this->initialize($params);
- }
-
- if ($this->anchor_class != '')
- {
- $this->anchor_class = 'class="'.$this->anchor_class.'" ';
- }
-
- log_message('debug', "Pagination Class Initialized");
+ $this->initialize($params);
+ log_message('debug', 'Pagination Class Initialized');
}
// --------------------------------------------------------------------
@@ -85,12 +89,29 @@ class CI_Pagination {
/**
* Initialize Preferences
*
- * @access public
* @param array initialization parameters
* @return void
*/
- function initialize($params = array())
+ public function initialize($params = array())
{
+ $attributes = array();
+
+ if (isset($params['attributes']) && is_array($params['attributes']))
+ {
+ $attributes = $params['attributes'];
+ unset($params['attributes']);
+ }
+
+ // Deprecated legacy support for the anchor_class option
+ // Should be removed in CI 3.1+
+ if (isset($params['anchor_class']))
+ {
+ empty($params['anchor_class']) OR $attributes['class'] = $params['anchor_class'];
+ unset($params['anchor_class']);
+ }
+
+ $this->_parse_attributes($attributes);
+
if (count($params) > 0)
{
foreach ($params as $key => $val)
@@ -108,78 +129,89 @@ class CI_Pagination {
/**
* Generate the pagination links
*
- * @access public
* @return string
*/
- function create_links()
+ 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 '';
}
// Calculate the total number of pages
- $num_pages = ceil($this->total_rows / $this->per_page);
+ $num_pages = (int) ceil($this->total_rows / $this->per_page);
// Is there only one page? Hm... nothing more to do here then.
- if ($num_pages == 1)
+ if ($num_pages === 1)
{
return '';
}
+ // Set the base page index for starting page number
+ $base_page = ($this->use_page_numbers) ? 1 : 0;
+
// Determine the current page number.
$CI =& get_instance();
+ // See if we are using a prefix or suffix on links
+ 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) != 0)
+ if ($CI->input->get($this->query_string_segment) != $base_page)
{
- $this->cur_page = $CI->input->get($this->query_string_segment);
-
- // Prep the current page - no funny business!
- $this->cur_page = (int) $this->cur_page;
+ $this->cur_page = (int) $CI->input->get($this->query_string_segment);
}
}
- else
+ elseif ( ! $this->cur_page && $CI->uri->segment($this->uri_segment) !== $base_page)
{
- if ($CI->uri->segment($this->uri_segment) != 0)
- {
- $this->cur_page = $CI->uri->segment($this->uri_segment);
+ $this->cur_page = (int) $CI->uri->segment($this->uri_segment);
+ }
- // Prep the current page - no funny business!
- $this->cur_page = (int) $this->cur_page;
- }
+ // 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))
+ {
+ $this->cur_page = $base_page;
}
- $this->num_links = (int)$this->num_links;
+ $this->num_links = (int) $this->num_links;
if ($this->num_links < 1)
{
show_error('Your number of links must be a positive number.');
}
- if ( ! is_numeric($this->cur_page))
- {
- $this->cur_page = 0;
- }
-
// Is the page number beyond the result range?
// If so we show the last page
- if ($this->cur_page > $this->total_rows)
+ if ($this->use_page_numbers)
+ {
+ if ($this->cur_page > $num_pages)
+ {
+ $this->cur_page = $num_pages;
+ }
+ }
+ elseif ($this->cur_page > $this->total_rows)
{
$this->cur_page = ($num_pages - 1) * $this->per_page;
}
$uri_page_number = $this->cur_page;
- $this->cur_page = floor(($this->cur_page/$this->per_page) + 1);
+
+ if ( ! $this->use_page_numbers)
+ {
+ $this->cur_page = (int) floor(($this->cur_page/$this->per_page) + 1);
+ }
// Calculate the start and end numbers. These determine
// which number to start and end the digit links with
- $start = (($this->cur_page - $this->num_links) > 0) ? $this->cur_page - ($this->num_links - 1) : 1;
- $end = (($this->cur_page + $this->num_links) < $num_pages) ? $this->cur_page + $this->num_links : $num_pages;
+ $start = (($this->cur_page - $this->num_links) > 0) ? $this->cur_page - ($this->num_links - 1) : 1;
+ $end = (($this->cur_page + $this->num_links) < $num_pages) ? $this->cur_page + $this->num_links : $num_pages;
- // Is pagination being used over GET or POST? If get, add a per_page query
+ // Is pagination being used over GET or POST? If get, add a per_page query
// string. If post, add a trailing slash to the base URL if needed
if ($CI->config->item('enable_query_strings') === TRUE OR $this->page_query_string === TRUE)
{
@@ -192,27 +224,56 @@ class CI_Pagination {
// And here we go...
$output = '';
+ $query_string = '';
+
+ // Add anything in the query string back to the links
+ // Note: Nothing to do with query_string_segment or any other query string options
+ if ($this->reuse_query_string === TRUE)
+ {
+ $get = $CI->input->get();
+
+ // Unset the controll, method, old-school routing options
+ unset($get['c'], $get['m'], $get[$this->query_string_segment]);
+
+ if ( ! $get) $get = array();
+
+ // Put everything else onto the end
+ $query_string = (strpos($this->base_url, '&amp;') !== FALSE ? '&amp;' : '?') . http_build_query($get, '', '&amp;');
+
+ // Add this after the suffix to put it into more links easily
+ $this->suffix .= $query_string;
+ }
// Render the "First" link
- if ($this->first_link !== FALSE AND $this->cur_page > ($this->num_links + 1))
+ if ($this->first_link !== FALSE && $this->cur_page > ($this->num_links + 1))
{
- $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;
+ $first_url = ($this->first_url === '') ? $this->base_url : $this->first_url;
+
+ // Take the general parameters, and squeeze this pagination-page attr in there for JS fw's
+ $attributes = sprintf('%s %s="%d"', $this->_attributes, $this->data_page_attr, 1);
+
+ $output .= $this->first_tag_open.'<a href="'.$first_url.'"'.$attributes.$this->_attr_rel('start').'>'
+ .$this->first_link.'</a>'.$this->first_tag_close;
}
// Render the "previous" link
- if ($this->prev_link !== FALSE AND $this->cur_page != 1)
+ if ($this->prev_link !== FALSE && $this->cur_page !== 1)
{
- $i = $uri_page_number - $this->per_page;
+ $i = ($this->use_page_numbers) ? $uri_page_number - 1 : $uri_page_number - $this->per_page;
+
+ // Take the general parameters, and squeeze this pagination-page attr in there for JS fw's
+ $attributes = sprintf('%s %s="%d"', $this->_attributes, $this->data_page_attr, (int) $i);
- if ($i == 0 && $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;
+ $output .= $this->prev_tag_open.'<a href="'.$this->first_url.$query_string.'"'.$attributes.$this->_attr_rel('prev').'>'
+ .$this->prev_link.'</a>'.$this->prev_tag_close;
}
else
{
- $i = ($i == 0) ? '' : $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;
+ $append = ($i === $base_page) ? $query_string : $this->prefix.$i.$this->suffix;
+ $output .= $this->prev_tag_open.'<a href="'.$this->base_url.$append.'"'.$attributes.$this->_attr_rel('prev').'>'
+ .$this->prev_link.'</a>'.$this->prev_tag_close;
}
}
@@ -223,27 +284,30 @@ class CI_Pagination {
// Write the digit links
for ($loop = $start -1; $loop <= $end; $loop++)
{
- $i = ($loop * $this->per_page) - $this->per_page;
+ $i = ($this->use_page_numbers) ? $loop : ($loop * $this->per_page) - $this->per_page;
- if ($i >= 0)
+ // Take the general parameters, and squeeze this pagination-page attr in there for JS fw's
+ $attributes = sprintf('%s %s="%d"', $this->_attributes, $this->data_page_attr, (int) $i);
+
+ 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 == 0) ? '' : $i;
-
- if ($n == '' && $this->first_url != '')
+ $n = ($i === $base_page) ? '' : $i;
+ if ($n === '' && ! empty($this->first_url))
{
- $output .= $this->num_tag_open.'<a '.$this->anchor_class.'href="'.$this->first_url.'">'.$loop.'</a>'.$this->num_tag_close;
+ $output .= $this->num_tag_open.'<a href="'.$this->first_url.$query_string.'"'.$attributes.$this->_attr_rel('start').'>'
+ .$loop.'</a>'.$this->num_tag_close;
}
else
{
- $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;
+ $append = ($n === '') ? $query_string : $this->prefix.$n.$this->suffix;
+ $output .= $this->num_tag_open.'<a href="'.$this->base_url.$append.'"'.$attributes.$this->_attr_rel('start').'>'
+ .$loop.'</a>'.$this->num_tag_close;
}
}
}
@@ -251,29 +315,81 @@ class CI_Pagination {
}
// Render the "next" link
- if ($this->next_link !== FALSE AND $this->cur_page < $num_pages)
+ if ($this->next_link !== FALSE && $this->cur_page < $num_pages)
{
- $output .= $this->next_tag_open.'<a '.$this->anchor_class.'href="'.$this->base_url.$this->prefix.($this->cur_page * $this->per_page).$this->suffix.'">'.$this->next_link.'</a>'.$this->next_tag_close;
+ $i = ($this->use_page_numbers) ? $this->cur_page + 1 : $this->cur_page * $this->per_page;
+
+ // Take the general parameters, and squeeze this pagination-page attr in there for JS fw's
+ $attributes = sprintf('%s %s="%d"', $this->_attributes, $this->data_page_attr, (int) $i);
+
+ $output .= $this->next_tag_open.'<a href="'.$this->base_url.$this->prefix.$i.$this->suffix.'"'.$attributes
+ .$this->_attr_rel('next').'>'.$this->next_link.'</a>'.$this->next_tag_close;
}
// Render the "Last" link
- if ($this->last_link !== FALSE AND ($this->cur_page + $this->num_links) < $num_pages)
+ if ($this->last_link !== FALSE && ($this->cur_page + $this->num_links) < $num_pages)
{
- $i = (($num_pages * $this->per_page) - $this->per_page);
- $output .= $this->last_tag_open.'<a '.$this->anchor_class.'href="'.$this->base_url.$this->prefix.$i.$this->suffix.'">'.$this->last_link.'</a>'.$this->last_tag_close;
+ $i = ($this->use_page_numbers) ? $num_pages : ($num_pages * $this->per_page) - $this->per_page;
+
+ // Take the general parameters, and squeeze this pagination-page attr in there for JS fw's
+ $attributes = sprintf('%s %s="%d"', $this->_attributes, $this->data_page_attr, (int) $i);
+
+ $output .= $this->last_tag_open.'<a href="'.$this->base_url.$this->prefix.$i.$this->suffix.'"'.$attributes.'>'
+ .$this->last_link.'</a>'.$this->last_tag_close;
}
- // Kill double slashes. Note: Sometimes we can end up with a double slash
+ // Kill double slashes. Note: Sometimes we can end up with a double slash
// in the penultimate link so we'll kill all double slashes.
- $output = preg_replace("#([^:])//+#", "\\1/", $output);
+ $output = preg_replace('#([^:])//+#', '\\1/', $output);
// Add the wrapper HTML if exists
- $output = $this->full_tag_open.$output.$this->full_tag_close;
+ return $this->full_tag_open.$output.$this->full_tag_close;
+ }
+
+ // --------------------------------------------------------------------
- return $output;
+ /**
+ * Parse attributes
+ *
+ * @param array
+ * @return void
+ */
+ protected function _parse_attributes($attributes)
+ {
+ isset($attributes['rel']) OR $attributes['rel'] = TRUE;
+ $this->_link_types = ($attributes['rel'])
+ ? array('start' => 'start', 'prev' => 'prev', 'next' => 'next')
+ : array();
+ unset($attributes['rel']);
+
+ $this->_attributes = '';
+ foreach ($attributes as $key => $value)
+ {
+ $this->_attributes .= ' '.$key.'="'.$value.'"';
+ }
+ }
+
+ // --------------------------------------------------------------------
+
+ /**
+ * Add "rel" attribute
+ *
+ * @link http://www.w3.org/TR/html5/links.html#linkTypes
+ * @param string
+ * @return string
+ */
+ protected function _attr_rel($type)
+ {
+ if (isset($this->_link_types[$type]))
+ {
+ unset($this->_link_types[$type]);
+ return ' rel="'.$type.'"';
+ }
+
+ return '';
}
+
}
-// END Pagination Class
/* End of file Pagination.php */
/* Location: ./system/libraries/Pagination.php */ \ No newline at end of file
diff --git a/system/libraries/Parser.php b/system/libraries/Parser.php
index d223da020..b64c78254 100644
--- a/system/libraries/Parser.php
+++ b/system/libraries/Parser.php
@@ -1,42 +1,68 @@
-<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
+<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* CodeIgniter
*
- * An open source application development framework for PHP 5.1.6 or newer
+ * An open source application development framework for PHP 5.2.4 or newer
+ *
+ * NOTICE OF LICENSE
+ *
+ * Licensed under the Open Software License version 3.0
+ *
+ * This source file is subject to the Open Software License (OSL 3.0) that is
+ * bundled with this package in the files license.txt / license.rst. It is
+ * also available through the world wide web at this URL:
+ * http://opensource.org/licenses/OSL-3.0
+ * If you did not receive a copy of the license and are unable to obtain it
+ * through the world wide web, please send an email to
+ * licensing@ellislab.com so we can send you a copy immediately.
*
* @package CodeIgniter
- * @author ExpressionEngine Dev Team
- * @copyright Copyright (c) 2008 - 2011, EllisLab, Inc.
- * @license http://codeigniter.com/user_guide/license.html
+ * @author EllisLab Dev Team
+ * @copyright Copyright (c) 2008 - 2012, EllisLab, Inc. (http://ellislab.com/)
+ * @license http://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
* @link http://codeigniter.com
* @since Version 1.0
* @filesource
*/
-// ------------------------------------------------------------------------
-
/**
* Parser Class
*
* @package CodeIgniter
* @subpackage Libraries
* @category Parser
- * @author ExpressionEngine Dev Team
+ * @author EllisLab Dev Team
* @link http://codeigniter.com/user_guide/libraries/parser.html
*/
class CI_Parser {
- var $l_delim = '{';
- var $r_delim = '}';
- var $object;
+ /**
+ * Left delimeter character for psuedo vars
+ *
+ * @var string
+ */
+ public $l_delim = '{';
+
+ /**
+ * Right delimeter character for psuedo vars
+ *
+ * @var string
+ */
+ public $r_delim = '}';
/**
- * Parse a template
+ * Reference to CodeIgniter instance
+ *
+ * @var object
+ */
+ protected $CI;
+
+ /**
+ * Parse a template
*
* Parses pseudo-variables contained in the specified template view,
* replacing them with the data in the second param
*
- * @access public
* @param string
* @param array
* @param bool
@@ -44,8 +70,8 @@ class CI_Parser {
*/
public function parse($template, $data, $return = FALSE)
{
- $CI =& get_instance();
- $template = $CI->load->view($template, $data, TRUE);
+ $this->CI =& get_instance();
+ $template = $this->CI->load->view($template, $data, TRUE);
return $this->_parse($template, $data, $return);
}
@@ -53,18 +79,17 @@ class CI_Parser {
// --------------------------------------------------------------------
/**
- * Parse a String
+ * Parse a String
*
* Parses pseudo-variables contained in the specified string,
* replacing them with the data in the second param
*
- * @access public
* @param string
* @param array
* @param bool
* @return string
*/
- function parse_string($template, $data, $return = FALSE)
+ public function parse_string($template, $data, $return = FALSE)
{
return $this->_parse($template, $data, $return);
}
@@ -72,40 +97,33 @@ class CI_Parser {
// --------------------------------------------------------------------
/**
- * Parse a template
+ * Parse a template
*
* Parses pseudo-variables contained in the specified template,
* replacing them with the data in the second param
*
- * @access public
* @param string
* @param array
* @param bool
* @return string
*/
- function _parse($template, $data, $return = FALSE)
+ 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)
{
- $CI =& get_instance();
- $CI->output->append_output($template);
+ $this->CI->output->append_output($template);
}
return $template;
@@ -114,14 +132,13 @@ class CI_Parser {
// --------------------------------------------------------------------
/**
- * Set the left/right variable delimiters
+ * Set the left/right variable delimiters
*
- * @access public
* @param string
* @param string
* @return void
*/
- function set_delimiters($l = '{', $r = '}')
+ public function set_delimiters($l = '{', $r = '}')
{
$this->l_delim = $l;
$this->r_delim = $r;
@@ -130,33 +147,31 @@ class CI_Parser {
// --------------------------------------------------------------------
/**
- * Parse a single key/value
+ * Parse a single key/value
*
- * @access private
* @param string
* @param string
* @param string
* @return string
*/
- function _parse_single($key, $val, $string)
+ protected function _parse_single($key, $val, $string)
{
- return str_replace($this->l_delim.$key.$this->r_delim, $val, $string);
+ return str_replace($this->l_delim.$key.$this->r_delim, (string) $val, $string);
}
// --------------------------------------------------------------------
/**
- * Parse a tag pair
+ * Parse a tag pair
*
- * Parses tag pairs: {some_tag} string... {/some_tag}
+ * Parses tag pairs: {some_tag} string... {/some_tag}
*
- * @access private
* @param string
* @param array
* @param string
* @return string
*/
- function _parse_pair($variable, $data, $string)
+ protected function _parse_pair($variable, $data, $string)
{
if (FALSE === ($match = $this->_match_pair($string, $variable)))
{
@@ -166,47 +181,37 @@ class CI_Parser {
$str = '';
foreach ($data as $row)
{
- $temp = $match['1'];
+ $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;
}
- return str_replace($match['0'], $str, $string);
+ return str_replace($match[0], $str, $string);
}
// --------------------------------------------------------------------
/**
- * Matches a variable pair
+ * Matches a variable pair
*
- * @access private
* @param string
* @param string
* @return mixed
*/
- function _match_pair($string, $variable)
+ protected function _match_pair($string, $variable)
{
- if ( ! preg_match("|" . preg_quote($this->l_delim) . $variable . preg_quote($this->r_delim) . "(.+?)". preg_quote($this->l_delim) . '/' . $variable . preg_quote($this->r_delim) . "|s", $string, $match))
- {
- return FALSE;
- }
-
- return $match;
+ return preg_match('|'.preg_quote($this->l_delim).$variable.preg_quote($this->r_delim).'(.+?)'.preg_quote($this->l_delim).'/'.$variable.preg_quote($this->r_delim).'|s',
+ $string, $match)
+ ? $match : FALSE;
}
}
-// END Parser Class
/* End of file Parser.php */
-/* Location: ./system/libraries/Parser.php */
+/* Location: ./system/libraries/Parser.php */ \ No newline at end of file
diff --git a/system/libraries/Profiler.php b/system/libraries/Profiler.php
index ac58129a9..1e961f6df 100644
--- a/system/libraries/Profiler.php
+++ b/system/libraries/Profiler.php
@@ -1,20 +1,30 @@
-<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
+<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* CodeIgniter
*
- * An open source application development framework for PHP 5.1.6 or newer
+ * An open source application development framework for PHP 5.2.4 or newer
+ *
+ * NOTICE OF LICENSE
+ *
+ * Licensed under the Open Software License version 3.0
+ *
+ * This source file is subject to the Open Software License (OSL 3.0) that is
+ * bundled with this package in the files license.txt / license.rst. It is
+ * also available through the world wide web at this URL:
+ * http://opensource.org/licenses/OSL-3.0
+ * If you did not receive a copy of the license and are unable to obtain it
+ * through the world wide web, please send an email to
+ * licensing@ellislab.com so we can send you a copy immediately.
*
* @package CodeIgniter
- * @author ExpressionEngine Dev Team
- * @copyright Copyright (c) 2008 - 2011, EllisLab, Inc.
- * @license http://codeigniter.com/user_guide/license.html
+ * @author EllisLab Dev Team
+ * @copyright Copyright (c) 2008 - 2012, EllisLab, Inc. (http://ellislab.com/)
+ * @license http://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
* @link http://codeigniter.com
* @since Version 1.0
* @filesource
*/
-// ------------------------------------------------------------------------
-
/**
* CodeIgniter Profiler Class
*
@@ -27,30 +37,50 @@
* @package CodeIgniter
* @subpackage Libraries
* @category Libraries
- * @author ExpressionEngine Dev Team
+ * @author EllisLab Dev Team
* @link http://codeigniter.com/user_guide/general/profiling.html
*/
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();
@@ -86,11 +116,17 @@ class CI_Profiler {
*/
public function set_sections($config)
{
+ if (isset($config['query_toggle_count']))
+ {
+ $this->_query_toggle_count = (int) $config['query_toggle_count'];
+ unset($config['query_toggle_count']);
+ }
+
foreach ($config as $method => $enable)
{
if (in_array($method, $this->_available_sections))
{
- $this->_compile_{$method} = ($enable !== FALSE) ? TRUE : FALSE;
+ $this->_compile_{$method} = ($enable !== FALSE);
}
}
}
@@ -114,36 +150,32 @@ 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))
+ if (preg_match('/(.+?)_end/i', $key, $match)
+ && isset($this->CI->benchmark->marker[$match[1].'_end'], $this->CI->benchmark->marker[$match[1].'_start']))
{
- if (isset($this->CI->benchmark->marker[$match[1].'_end']) AND isset($this->CI->benchmark->marker[$match[1].'_start']))
- {
- $profile[$match[1]] = $this->CI->benchmark->elapsed_time($match[1].'_start', $key);
- }
+ $profile[$match[1]] = $this->CI->benchmark->elapsed_time($match[1].'_start', $key);
}
}
// 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";
- $output .= '<fieldset id="ci_profiler_benchmarks" style="border:1px solid #900;padding:6px 10px 10px 10px;margin:20px 0 20px 0;background-color:#eee">';
- $output .= "\n";
- $output .= '<legend style="color:#900;">&nbsp;&nbsp;'.$this->CI->lang->line('profiler_benchmarks').'&nbsp;&nbsp;</legend>';
- $output .= "\n";
- $output .= "\n\n<table style='width:100%'>\n";
+ $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;">&nbsp;&nbsp;'.$this->CI->lang->line('profiler_benchmarks')."&nbsp;&nbsp;</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."&nbsp;&nbsp;</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.'&nbsp;&nbsp;</td><td style="padding:5px;width:50%;color:#900;font-weight:normal;background-color:#ddd;">'
+ .$val."</td></tr>\n";
}
- $output .= "</table>\n";
- $output .= "</fieldset>";
-
- return $output;
+ return $output."</table>\n</fieldset>";
}
// --------------------------------------------------------------------
@@ -160,25 +192,22 @@ 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;
}
}
- if (count($dbs) == 0)
+ if (count($dbs) === 0)
{
- $output = "\n\n";
- $output .= '<fieldset id="ci_profiler_queries" style="border:1px solid #0000FF;padding:6px 10px 10px 10px;margin:20px 0 20px 0;background-color:#eee">';
- $output .= "\n";
- $output .= '<legend style="color:#0000FF;">&nbsp;&nbsp;'.$this->CI->lang->line('profiler_queries').'&nbsp;&nbsp;</legend>';
- $output .= "\n";
- $output .= "\n\n<table style='border:none; width:100%;'>\n";
- $output .="<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";
- $output .= "</table>\n";
- $output .= "</fieldset>";
-
- return $output;
+ 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;">&nbsp;&nbsp;'.$this->CI->lang->line('profiler_queries').'&nbsp;&nbsp;</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
@@ -188,38 +217,36 @@ class CI_Profiler {
$highlight = array('SELECT', 'DISTINCT', 'FROM', 'WHERE', 'AND', 'LEFT&nbsp;JOIN', 'ORDER&nbsp;BY', 'GROUP&nbsp;BY', 'LIMIT', 'INSERT', 'INTO', 'VALUES', 'UPDATE', 'OR&nbsp;', 'HAVING', 'OFFSET', 'NOT&nbsp;IN', 'IN', 'LIKE', 'NOT&nbsp;LIKE', 'COUNT', 'MAX', 'MIN', 'ON', 'AS', 'AVG', 'SUM', '(', ')');
$output = "\n\n";
-
$count = 0;
foreach ($dbs as $db)
{
- $count++;
-
$hide_queries = (count($db->queries) > $this->_query_toggle_count) ? ' display:none' : '';
$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">';
- $output .= "\n";
- $output .= '<legend style="color:#0000FF;">&nbsp;&nbsp;'.$this->CI->lang->line('profiler_database').':&nbsp; '.$db->database.'&nbsp;&nbsp;&nbsp;'.$this->CI->lang->line('profiler_queries').': '.count($db->queries).'&nbsp;&nbsp;'.$show_hide_js.'</legend>';
- $output .= "\n";
- $output .= "\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;">&nbsp;&nbsp;'.$this->CI->lang->line('profiler_database')
+ .':&nbsp; '.$db->database.'&nbsp;&nbsp;&nbsp;'.$this->CI->lang->line('profiler_queries')
+ .': '.count($db->queries).'&nbsp;&nbsp;'.$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)
+ 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,19 +254,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."&nbsp;&nbsp;</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.'&nbsp;&nbsp;</td><td style="padding:5px;color:#000;font-weight:normal;background-color:#ddd;">'
+ .$val."</td></tr>\n";
}
}
- $output .= "</table>\n";
- $output .= "</fieldset>";
-
+ $output .= "</table>\n</fieldset>";
}
return $output;
}
-
// --------------------------------------------------------------------
/**
@@ -249,19 +275,18 @@ class CI_Profiler {
*/
protected function _compile_get()
{
- $output = "\n\n";
- $output .= '<fieldset id="ci_profiler_get" style="border:1px solid #cd6e00;padding:6px 10px 10px 10px;margin:20px 0 20px 0;background-color:#eee">';
- $output .= "\n";
- $output .= '<legend style="color:#cd6e00;">&nbsp;&nbsp;'.$this->CI->lang->line('profiler_get_data').'&nbsp;&nbsp;</legend>';
- $output .= "\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;">&nbsp;&nbsp;'.$this->CI->lang->line('profiler_get_data')."&nbsp;&nbsp;</legend>\n";
- if (count($_GET) == 0)
+ 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)
{
@@ -270,23 +295,16 @@ class CI_Profiler {
$key = "'".$key."'";
}
- $output .= "<tr><td style='width:50%;color:#000;background-color:#ddd;padding:5px'>&#36;_GET[".$key."]&nbsp;&nbsp; </td><td style='width:50%;padding:5px;color:#cd6e00;font-weight:normal;background-color:#ddd;'>";
- if (is_array($val))
- {
- $output .= "<pre>" . htmlspecialchars(stripslashes(print_r($val, true))) . "</pre>";
- }
- else
- {
- $output .= htmlspecialchars(stripslashes($val));
- }
- $output .= "</td></tr>\n";
+ $output .= '<tr><td style="width:50%;color:#000;background-color:#ddd;padding:5px;">&#36;_GET['
+ .$key.']&nbsp;&nbsp; </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";
}
- $output .= "</fieldset>";
- return $output;
+ return $output.'</fieldset>';
}
// --------------------------------------------------------------------
@@ -298,19 +316,18 @@ class CI_Profiler {
*/
protected function _compile_post()
{
- $output = "\n\n";
- $output .= '<fieldset id="ci_profiler_post" style="border:1px solid #009900;padding:6px 10px 10px 10px;margin:20px 0 20px 0;background-color:#eee">';
- $output .= "\n";
- $output .= '<legend style="color:#009900;">&nbsp;&nbsp;'.$this->CI->lang->line('profiler_post_data').'&nbsp;&nbsp;</legend>';
- $output .= "\n";
+ $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;">&nbsp;&nbsp;'.$this->CI->lang->line('profiler_post_data')."&nbsp;&nbsp;</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)
{
@@ -319,23 +336,25 @@ class CI_Profiler {
$key = "'".$key."'";
}
- $output .= "<tr><td style='width:50%;padding:5px;color:#000;background-color:#ddd;'>&#36;_POST[".$key."]&nbsp;&nbsp; </td><td style='width:50%;padding:5px;color:#009900;font-weight:normal;background-color:#ddd;'>";
- if (is_array($val))
+ $output .= '<tr><td style="width:50%;padding:5px;color:#000;background-color:#ddd;">&#36;_POST['
+ .$key.']&nbsp;&nbsp; </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";
}
$output .= "</table>\n";
}
- $output .= "</fieldset>";
- return $output;
+ return $output.'</fieldset>';
}
// --------------------------------------------------------------------
@@ -347,24 +366,13 @@ class CI_Profiler {
*/
protected function _compile_uri_string()
{
- $output = "\n\n";
- $output .= '<fieldset id="ci_profiler_uri_string" style="border:1px solid #000;padding:6px 10px 10px 10px;margin:20px 0 20px 0;background-color:#eee">';
- $output .= "\n";
- $output .= '<legend style="color:#000;">&nbsp;&nbsp;'.$this->CI->lang->line('profiler_uri_string').'&nbsp;&nbsp;</legend>';
- $output .= "\n";
-
- if ($this->CI->uri->uri_string == '')
- {
- $output .= "<div style='color:#000;font-weight:normal;padding:4px 0 4px 0'>".$this->CI->lang->line('profiler_no_uri')."</div>";
- }
- else
- {
- $output .= "<div style='color:#000;font-weight:normal;padding:4px 0 4px 0'>".$this->CI->uri->uri_string."</div>";
- }
-
- $output .= "</fieldset>";
-
- return $output;
+ 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;">&nbsp;&nbsp;'.$this->CI->lang->line('profiler_uri_string')."&nbsp;&nbsp;</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>';
}
// --------------------------------------------------------------------
@@ -376,17 +384,12 @@ class CI_Profiler {
*/
protected function _compile_controller_info()
{
- $output = "\n\n";
- $output .= '<fieldset id="ci_profiler_controller_info" style="border:1px solid #995300;padding:6px 10px 10px 10px;margin:20px 0 20px 0;background-color:#eee">';
- $output .= "\n";
- $output .= '<legend style="color:#995300;">&nbsp;&nbsp;'.$this->CI->lang->line('profiler_controller_info').'&nbsp;&nbsp;</legend>';
- $output .= "\n";
-
- $output .= "<div style='color:#995300;font-weight:normal;padding:4px 0 4px 0'>".$this->CI->router->fetch_class()."/".$this->CI->router->fetch_method()."</div>";
-
- $output .= "</fieldset>";
-
- return $output;
+ 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;">&nbsp;&nbsp;'.$this->CI->lang->line('profiler_controller_info')."&nbsp;&nbsp;</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>';
}
// --------------------------------------------------------------------
@@ -400,24 +403,13 @@ class CI_Profiler {
*/
protected function _compile_memory_usage()
{
- $output = "\n\n";
- $output .= '<fieldset id="ci_profiler_memory_usage" style="border:1px solid #5a0099;padding:6px 10px 10px 10px;margin:20px 0 20px 0;background-color:#eee">';
- $output .= "\n";
- $output .= '<legend style="color:#5a0099;">&nbsp;&nbsp;'.$this->CI->lang->line('profiler_memory_usage').'&nbsp;&nbsp;</legend>';
- $output .= "\n";
-
- if (function_exists('memory_get_usage') && ($usage = memory_get_usage()) != '')
- {
- $output .= "<div style='color:#5a0099;font-weight:normal;padding:4px 0 4px 0'>".number_format($usage).' bytes</div>';
- }
- else
- {
- $output .= "<div style='color:#5a0099;font-weight:normal;padding:4px 0 4px 0'>".$this->CI->lang->line('profiler_no_memory')."</div>";
- }
-
- $output .= "</fieldset>";
-
- return $output;
+ 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;">&nbsp;&nbsp;'.$this->CI->lang->line('profiler_memory_usage')."&nbsp;&nbsp;</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>';
}
// --------------------------------------------------------------------
@@ -431,24 +423,21 @@ class CI_Profiler {
*/
protected function _compile_http_headers()
{
- $output = "\n\n";
- $output .= '<fieldset id="ci_profiler_http_headers" style="border:1px solid #000;padding:6px 10px 10px 10px;margin:20px 0 20px 0;background-color:#eee">';
- $output .= "\n";
- $output .= '<legend style="color:#000;">&nbsp;&nbsp;'.$this->CI->lang->line('profiler_headers').'&nbsp;&nbsp;(<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>';
- $output .= "\n";
-
- $output .= "\n\n<table style='width:100%;display:none' id='ci_profiler_httpheaders_table'>\n";
+ $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;">&nbsp;&nbsp;'.$this->CI->lang->line('profiler_headers')
+ .'&nbsp;&nbsp;(<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."&nbsp;&nbsp;</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.'&nbsp;&nbsp;</td><td style="width:50%;padding:5px;color:#000;background-color:#ddd;">'.$val."</td></tr>\n";
}
- $output .= "</table>\n";
- $output .= "</fieldset>";
-
- return $output;
+ return $output."</table>\n</fieldset>";
}
// --------------------------------------------------------------------
@@ -462,28 +451,24 @@ class CI_Profiler {
*/
protected function _compile_config()
{
- $output = "\n\n";
- $output .= '<fieldset id="ci_profiler_config" style="border:1px solid #000;padding:6px 10px 10px 10px;margin:20px 0 20px 0;background-color:#eee">';
- $output .= "\n";
- $output .= '<legend style="color:#000;">&nbsp;&nbsp;'.$this->CI->lang->line('profiler_config').'&nbsp;&nbsp;(<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>';
- $output .= "\n";
+ $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;">&nbsp;&nbsp;'.$this->CI->lang->line('profiler_config').'&nbsp;&nbsp;(<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";
- $output .= "\n\n<table style='width:100%; display:none' id='ci_profiler_config_table'>\n";
-
- foreach ($this->CI->config->config as $config=>$val)
+ foreach ($this->CI->config->config as $config => $val)
{
- if (is_array($val))
+ if (is_array($val) OR is_object($val))
{
$val = print_r($val, TRUE);
}
- $output .= "<tr><td style='padding:5px; vertical-align: top;color:#900;background-color:#ddd;'>".$config."&nbsp;&nbsp;</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.'&nbsp;&nbsp;</td><td style="padding:5px;color:#000;background-color:#ddd;">'.htmlspecialchars($val)."</td></tr>\n";
}
- $output .= "</table>\n";
- $output .= "</fieldset>";
-
- return $output;
+ return $output."</table>\n</fieldset>";
}
// --------------------------------------------------------------------
@@ -500,23 +485,22 @@ 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">';
- $output .= '<legend style="color:#000;">&nbsp;&nbsp;'.$this->CI->lang->line('profiler_session_data').'&nbsp;&nbsp;(<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>';
- $output .= "<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;">&nbsp;&nbsp;'.$this->CI->lang->line('profiler_session_data').'&nbsp;&nbsp;(<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)
{
- if (is_array($val) || is_object($val))
+ if (is_array($val) OR is_object($val))
{
$val = print_r($val, TRUE);
}
- $output .= "<tr><td style='padding:5px; vertical-align: top;color:#900;background-color:#ddd;'>".$key."&nbsp;&nbsp;</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.'&nbsp;&nbsp;</td><td style="padding:5px;color:#000;background-color:#ddd;">'.htmlspecialchars($val)."</td></tr>\n";
}
- $output .= '</table>';
- $output .= "</fieldset>";
- return $output;
+ return $output."</table>\n</fieldset>";
}
// --------------------------------------------------------------------
@@ -528,31 +512,29 @@ 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++;
}
}
- if ($fields_displayed == 0)
+ 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>';
}
- $output .= '</div>';
-
- return $output;
+ return $output.'</div>';
}
-}
-// END CI_Profiler class
+}
/* 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/Session.php b/system/libraries/Session/Session.php
index 7c340ccca..94fb4b10a 100755
--- a/system/libraries/Session/Session.php
+++ b/system/libraries/Session/Session.php
@@ -197,6 +197,27 @@ class CI_Session extends CI_Driver_Library {
}
/**
+ * Fetch all flashdata
+ *
+ * @return array Flash data 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, self::FLASHDATA_KEY.self::FLASHDATA_OLD) !== FALSE)
+ {
+ $out[$key] = $val;
+ }
+ }
+ return $out;
+ }
+
+ /**
* Add or change data in the "userdata" array
*
* @param mixed Item name or array of items
@@ -297,8 +318,8 @@ class CI_Session extends CI_Driver_Library {
*/
public function keep_flashdata($key)
{
- // 'old' flashdata gets removed. Here we mark all
- // flashdata as 'new' to preserve it from _flashdata_sweep()
+ // 'old' flashdata gets removed. Here we mark all flashdata as 'new' to preserve it from _flashdata_sweep()
+ // Note the function will return NULL if the $key provided cannot be found
$old_flashdata_key = self::FLASHDATA_KEY.self::FLASHDATA_OLD.$key;
$value = $this->userdata($old_flashdata_key);
diff --git a/system/libraries/Session/drivers/Session_cookie.php b/system/libraries/Session/drivers/Session_cookie.php
index 696105bc6..0dc109bd1 100755
--- a/system/libraries/Session/drivers/Session_cookie.php
+++ b/system/libraries/Session/drivers/Session_cookie.php
@@ -1,19 +1,30 @@
-<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
+<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* CodeIgniter
*
- * An open source application development framework for PHP 5.1.6 or newer
+ * An open source application development framework for PHP 5.2.4 or newer
+ *
+ * NOTICE OF LICENSE
+ *
+ * Licensed under the Open Software License version 3.0
+ *
+ * This source file is subject to the Open Software License (OSL 3.0) that is
+ * bundled with this package in the files license.txt / license.rst. It is
+ * also available through the world wide web at this URL:
+ * http://opensource.org/licenses/OSL-3.0
+ * If you did not receive a copy of the license and are unable to obtain it
+ * through the world wide web, please send an email to
+ * licensing@ellislab.com so we can send you a copy immediately.
*
* @package CodeIgniter
- * @author ExpressionEngine Dev Team
- * @copyright Copyright (c) 2008 - 2010, EllisLab, Inc.
- * @license http://codeigniter.com/user_guide/license.html
+ * @author EllisLab Dev Team
+ * @copyright Copyright (c) 2008 - 2012, EllisLab, Inc. (http://ellislab.com/)
+ * @license http://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
* @link http://codeigniter.com
- * @since Version 2.0
+ * @since Version 1.0
* @filesource
*/
-
/**
* Cookie-based session management driver
*
@@ -24,29 +35,144 @@
* @package CodeIgniter
* @subpackage Libraries
* @category Sessions
- * @author ExpressionEngine Dev Team
+ * @author EllisLab Dev Team
+ * @link http://codeigniter.com/user_guide/libraries/sessions.html
*/
class CI_Session_cookie extends CI_Session_driver {
- protected $sess_encrypt_cookie = FALSE;
- protected $sess_use_database = FALSE;
- protected $sess_table_name = '';
- protected $sess_expiration = 7200;
- protected $sess_expire_on_close = FALSE;
- protected $sess_match_ip = FALSE;
- protected $sess_match_useragent = TRUE;
- protected $sess_cookie_name = 'ci_session';
- protected $cookie_prefix = '';
- protected $cookie_path = '';
- protected $cookie_domain = '';
- protected $cookie_secure = FALSE;
- protected $sess_time_to_update = 300;
- protected $encryption_key = '';
- protected $time_reference = 'time';
- protected $userdata = array();
- protected $CI = null;
- protected $now = 0;
-
- const gc_probability = 5;
+
+ /**
+ * 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 = '';
+
+ /**
+ * Timezone to use for the current time
+ *
+ * @var string
+ */
+ public $time_reference = 'local';
+
+
+ /**
+ * Session data
+ *
+ * @var array
+ */
+ public $userdata = array();
+
+ /**
+ * Reference to CodeIgniter instance
+ *
+ * @var object
+ */
+ public $CI;
+
+ /**
+ * Current time
+ *
+ * @var int
+ */
+ public $now;
/**
* Initialize session driver object
@@ -63,15 +189,16 @@ class CI_Session_cookie extends CI_Session_driver {
// manually via the $params array above or via the config file
foreach (array('sess_encrypt_cookie', 'sess_use_database', 'sess_table_name', 'sess_expiration',
'sess_expire_on_close', 'sess_match_ip', 'sess_match_useragent', 'sess_cookie_name', 'cookie_path',
- 'cookie_domain', 'cookie_secure', 'sess_time_to_update', 'time_reference', 'cookie_prefix', 'encryption_key')
- as $key)
+ 'cookie_domain', 'cookie_secure', 'cookie_httponly', 'sess_time_to_update', 'time_reference', 'cookie_prefix',
+ 'encryption_key') as $key)
{
- $this->$key = (isset($this->parent->params[$key])) ? $this->parent->params[$key] : $this->CI->config->item($key);
+ $this->$key = isset($this->parent->params[$key]) ? $this->parent->params[$key] :
+ $this->CI->config->item($key);
}
- if ($this->encryption_key == '')
+ if ($this->encryption_key === '')
{
- show_error('In order to use the Cookie Session driver you are required to set an encryption key '.
+ show_error('In order to use the Session Cookie driver you are required to set an encryption key '.
'in your config file.');
}
@@ -79,13 +206,13 @@ class CI_Session_cookie extends CI_Session_driver {
$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();
}
@@ -96,7 +223,7 @@ class CI_Session_cookie extends CI_Session_driver {
// 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);
}
@@ -143,7 +270,7 @@ class CI_Session_cookie extends CI_Session_driver {
foreach (array('session_id','ip_address','user_agent','last_activity') as $val)
{
unset($custom_userdata[$val]);
- $cookie_userdata[$val] = $this->userdata($val);
+ $cookie_userdata[$val] = $this->userdata[$val];
}
// Did we find any custom data? If not, we turn the empty array into a string
@@ -159,9 +286,9 @@ class CI_Session_cookie extends CI_Session_driver {
}
// Run the update query
- $this->CI->db->where('session_id', $this->userdata('session_id'));
+ $this->CI->db->where('session_id', $this->userdata['session_id']);
$this->CI->db->update($this->sess_table_name,
- array('last_activity' => $this->userdata('last_activity'), 'user_data' => $custom_userdata));
+ array('last_activity' => $this->userdata['last_activity'], 'user_data' => $custom_userdata));
// Write the cookie. Notice that we manually pass the cookie data array to the
// _set_cookie() function. Normally that function will store $this->userdata, but
@@ -186,6 +313,9 @@ class CI_Session_cookie extends CI_Session_driver {
// Kill the cookie
setcookie($this->sess_cookie_name, addslashes(serialize(array())), ($this->now - 31500000),
$this->cookie_path, $this->cookie_domain, 0);
+
+ // Kill session data
+ $this->userdata = array();
}
/**
@@ -235,21 +365,21 @@ class CI_Session_cookie extends CI_Session_driver {
$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);
}
else
{
// encryption was not used, so we need to check the md5 hash
- $hash = substr($session, strlen($session)-32); // get last 32 chars
+ $hash = substr($session, strlen($session)-32); // get last 32 chars
$session = substr($session, 0, strlen($session)-32);
// Does the md5 hash match? This is to prevent manipulation of session data in userspace
@@ -266,30 +396,30 @@ class CI_Session_cookie extends CI_Session_driver {
$session = $this->_unserialize($session);
// Is the session data we unserialized an array with the correct format?
- if ( ! is_array($session) || ! isset($session['session_id']) || ! isset($session['ip_address']) ||
- ! isset($session['user_agent']) || ! isset($session['last_activity']))
+ if ( ! is_array($session) || ! isset($session['session_id'], $session['ip_address'], $session['user_agent'],
+ $session['last_activity']))
{
$this->sess_destroy();
return FALSE;
}
// Is the session current?
- if (($session['last_activity'] + $this->sess_expiration) < $this->now())
+ if (($session['last_activity'] + $this->sess_expiration) < $this->now)
{
$this->sess_destroy();
return FALSE;
}
- // Does the IP Match?
- if ($this->sess_match_ip == TRUE && $session['ip_address'] != $this->CI->input->ip_address())
+ // Does the IP match?
+ 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, 50)))
+ if ($this->sess_match_useragent === TRUE &&
+ trim($session['user_agent']) !== trim(substr($this->CI->input->user_agent(), 0, 120)))
{
$this->sess_destroy();
return FALSE;
@@ -300,20 +430,20 @@ class CI_Session_cookie extends CI_Session_driver {
{
$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']);
}
- $query = $this->CI->db->get($this->sess_table_name);
+ $query = $this->CI->db->limit(1)->get($this->sess_table_name);
// No result? Kill it!
- if ($query->num_rows() == 0)
+ if ($query->num_rows() === 0)
{
$this->sess_destroy();
return FALSE;
@@ -321,7 +451,7 @@ class CI_Session_cookie extends CI_Session_driver {
// 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);
@@ -351,24 +481,27 @@ class CI_Session_cookie extends CI_Session_driver {
protected function _sess_create()
{
$sessid = '';
- while (strlen($sessid) < 32)
+ do
{
$sessid .= mt_rand(0, mt_getrandmax());
}
+ while (strlen($sessid) < 32);
// To make the session ID even more secure we'll combine it with the user's IP
$sessid .= $this->CI->input->ip_address();
- $this->set_userdata('session_id', md5(uniqid($sessid, TRUE)));
- $this->set_userdata('ip_address', $this->CI->input->ip_address());
- $this->set_userdata('user_agent', substr($this->CI->input->user_agent(), 0, 50));
- $this->set_userdata('last_activity',$this->now());
-
+ $this->userdata = array(
+ 'session_id' => md5(uniqid($sessid, TRUE)),
+ 'ip_address' => $this->CI->input->ip_address(),
+ 'user_agent' => substr($this->CI->input->user_agent(), 0, 120),
+ 'last_activity' => $this->now,
+ 'user_data' => ''
+ );
// Save the data to the DB if needed
if ($this->sess_use_database === TRUE)
{
- $this->CI->db->query($this->CI->db->insert_string($this->sess_table_name, $this->all_userdata()));
+ $this->CI->db->query($this->CI->db->insert_string($this->sess_table_name, $this->userdata));
}
// Write the cookie
@@ -382,36 +515,59 @@ class CI_Session_cookie extends CI_Session_driver {
* @param boolean Force update flag (default: false)
* @return void
*/
- protected function _sess_update($force = false)
+ protected function _sess_update($force = FALSE)
{
// We only update the session every five minutes by default (unless forced)
- if (!$force && ($this->userdata['last_activity'] + $this->sess_time_to_update) >= $this->now())
+ if (!$force && ($this->userdata['last_activity'] + $this->sess_time_to_update) >= $this->now)
{
return;
}
+ // _set_cookie() will handle this for us if we aren't using database sessions
+ // by pushing all userdata to the cookie.
+ $cookie_data = NULL;
+
+ /* Changing the session ID during an AJAX call causes problems,
+ * so we'll only update our last_activity
+ */
+ if ($this->CI->input->is_ajax_request())
+ {
+ $this->userdata['last_activity'] = $this->now;
+
+ // Update the session ID and last_activity field in the DB if needed
+ if ($this->sess_use_database === TRUE)
+ {
+ // set cookie explicitly to only have our session data
+ $cookie_data = array();
+ foreach (array('session_id','ip_address','user_agent','last_activity') as $val)
+ {
+ $cookie_data[$val] = $this->userdata[$val];
+ }
+
+ $this->CI->db->query($this->CI->db->update_string($this->sess_table_name,
+ array('last_activity' => $this->userdata['last_activity']),
+ array('session_id' => $this->userdata['session_id'])));
+ }
+
+ return $this->_set_cookie($cookie_data);
+ }
+
// Save the old session id so we know which record to
// update in the database if we need it
$old_sessid = $this->userdata['session_id'];
$new_sessid = '';
- while (strlen($new_sessid) < 32)
+ do
{
$new_sessid .= mt_rand(0, mt_getrandmax());
}
+ while (strlen($new_sessid) < 32);
// To make the session ID even more secure we'll combine it with the user's IP
$new_sessid .= $this->CI->input->ip_address();
- // Turn it into a hash
- $new_sessid = md5(uniqid($new_sessid, TRUE));
-
- // Update the session data in the session data array
- $this->set_userdata('session_id', $new_sessid);
- $this->set_userdata('last_activity', $this->now());
-
- // _set_cookie() will handle this for us if we aren't using database sessions
- // by pushing all userdata to the cookie.
- $cookie_data = NULL;
+ // Turn it into a hash and update the session data array
+ $this->userdata['session_id'] = $new_sessid = md5(uniqid($new_sessid, TRUE));
+ $this->userdata['last_activity'] = $this->now;
// Update the session ID and last_activity field in the DB if needed
if ($this->sess_use_database === TRUE)
@@ -424,8 +580,7 @@ class CI_Session_cookie extends CI_Session_driver {
}
$this->CI->db->query($this->CI->db->update_string($this->sess_table_name,
- array('last_activity' => $this->now(), 'session_id' => $new_sessid),
- array('session_id' => $old_sessid)));
+ array('last_activity' => $this->now, 'session_id' => $new_sessid), array('session_id' => $old_sessid)));
}
// Write the cookie
@@ -436,22 +591,19 @@ class CI_Session_cookie extends CI_Session_driver {
* Get the "now" time
*
* @access protected
- * @return int
+ * @return int Time
*/
protected function _get_time()
{
- if (strtolower($this->time_reference) == 'gmt')
+ if ($this->time_reference === 'local' || $this->time_reference === date_default_timezone_get())
{
- $now = time();
- $time = mktime(gmdate('H', $now), gmdate('i', $now), gmdate('s', $now), gmdate('m', $now),
- gmdate('d', $now), gmdate('Y', $now));
- }
- else
- {
- $time = time();
+ return time();
}
- return $time;
+ $datetime = new DateTime('now', new DateTimeZone($this->time_reference));
+ sscanf($datetime->format('j-n-Y G:i:s'), '%d-%d-%d %d:%d:%d', $day, $month, $year, $hour, $minute, $second);
+
+ return mktime($hour, $minute, $second, $month, $day, $year);
}
/**
@@ -465,13 +617,13 @@ class CI_Session_cookie extends CI_Session_driver {
{
if (is_null($cookie_data))
{
- $cookie_data = $this->all_userdata();
+ $cookie_data = $this->userdata;
}
// 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);
}
@@ -485,7 +637,7 @@ class CI_Session_cookie extends CI_Session_driver {
// Set the cookie
setcookie($this->sess_cookie_name, $cookie_data, $expire, $this->cookie_path, $this->cookie_domain,
- $this->cookie_secure);
+ $this->cookie_secure, $this->cookie_httponly);
}
/**
@@ -496,59 +648,78 @@ class CI_Session_cookie extends CI_Session_driver {
*
* @access protected
* @param mixed Data to serialize
- * @return string
+ * @return string Serialized data
*/
protected function _serialize($data)
{
if (is_array($data))
{
- foreach ($data as $key => $val)
- {
- if (is_string($val))
- {
- $data[$key] = str_replace('\\', '{{slash}}', $val);
- }
- }
+ array_walk_recursive($data, array(&$this, '_escape_slashes'));
}
- else
+ elseif (is_string($data))
{
- if (is_string($data))
- {
- $data = str_replace('\\', '{{slash}}', $data);
- }
+ $data = str_replace('\\', '{{slash}}', $data);
}
-
return serialize($data);
}
/**
+ * Escape slashes
+ *
+ * This function converts any slashes found into a temporary marker
+ *
+ * @access protected
+ * @param string Value
+ * @param string Key
+ * @return void
+ */
+ protected function _escape_slashes(&$val, $key)
+ {
+ if (is_string($val))
+ {
+ $val = str_replace('\\', '{{slash}}', $val);
+ }
+ }
+
+ /**
* Unserialize
*
* This function unserializes a data string, then converts any
* temporary slash markers back to actual slashes
*
* @access protected
- * @param string Data to unserialize
- * @return mixed
+ * @param mixed Data to unserialize
+ * @return mixed Unserialized data
*/
protected function _unserialize($data)
{
- $data = @unserialize(strip_slashes($data));
+ $data = @unserialize(strip_slashes(trim($data)));
if (is_array($data))
{
- foreach ($data as $key => $val)
- {
- if (is_string($val))
- {
- $data[$key] = str_replace('{{slash}}', '\\', $val);
- }
- }
-
+ array_walk_recursive($data, array(&$this, '_unescape_slashes'));
return $data;
}
- return (is_string($data)) ? str_replace('{{slash}}', '\\', $data) : $data;
+ return is_string($data) ? str_replace('{{slash}}', '\\', $data) : $data;
+ }
+
+ /**
+ * Unescape slashes
+ *
+ * This function converts any slash markers back into actual slashes
+ *
+ * @access protected
+ * @param string Value
+ * @param string Key
+ * @return void
+ */
+ protected function _unescape_slashes(&$val, $key)
+ {
+ if (is_string($val))
+ {
+ $val= str_replace('{{slash}}', '\\', $val);
+ }
}
/**
@@ -562,15 +733,18 @@ class CI_Session_cookie extends CI_Session_driver {
*/
protected function _sess_gc()
{
- if ($this->sess_use_database != TRUE)
+ if ($this->sess_use_database !== TRUE)
{
return;
}
+ $probability = ini_get('session.gc_probability');
+ $divisor = ini_get('session.gc_divisor');
+
srand(time());
- if ((rand() % 100) < self::gc_probability)
+ if ((mt_rand(0, $divisor) / $divisor) < $probability)
{
- $expire = $this->now() - $this->sess_expiration;
+ $expire = $this->now - $this->sess_expiration;
$this->CI->db->where('last_activity < '.$expire);
$this->CI->db->delete($this->sess_table_name);
@@ -578,9 +752,8 @@ class CI_Session_cookie extends CI_Session_driver {
log_message('debug', 'Session garbage collection performed.');
}
}
+
}
-// END CI_Session_cookie Class
/* End of file Session_cookie.php */
/* Location: ./system/libraries/Session/drivers/Session_cookie.php */
-?>
diff --git a/system/libraries/Sha1.php b/system/libraries/Sha1.php
deleted file mode 100644
index 1a657572b..000000000
--- a/system/libraries/Sha1.php
+++ /dev/null
@@ -1,251 +0,0 @@
-<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
-/**
- * CodeIgniter
- *
- * An open source application development framework for PHP 5.1.6 or newer
- *
- * @package CodeIgniter
- * @author ExpressionEngine Dev Team
- * @copyright Copyright (c) 2008 - 2011, EllisLab, Inc.
- * @license http://codeigniter.com/user_guide/license.html
- * @link http://codeigniter.com
- * @since Version 1.0
- * @filesource
- */
-
-// ------------------------------------------------------------------------
-
-/**
- * SHA1 Encoding Class
- *
- * Purpose: Provides 160 bit hashing using The Secure Hash Algorithm
- * developed at the National Institute of Standards and Technology. The 40
- * character SHA1 message hash is computationally infeasible to crack.
- *
- * This class is a fallback for servers that are not running PHP greater than
- * 4.3, or do not have the MHASH library.
- *
- * This class is based on two scripts:
- *
- * Marcus Campbell's PHP implementation (GNU license)
- * http://www.tecknik.net/sha-1/
- *
- * ...which is based on Paul Johnston's JavaScript version
- * (BSD license). http://pajhome.org.uk/
- *
- * I encapsulated the functions and wrote one additional method to fix
- * a hex conversion bug. - Rick Ellis
- *
- * @package CodeIgniter
- * @subpackage Libraries
- * @category Encryption
- * @author ExpressionEngine Dev Team
- * @link http://codeigniter.com/user_guide/general/encryption.html
- */
-class CI_SHA1 {
-
- public function __construct()
- {
- log_message('debug', "SHA1 Class Initialized");
- }
-
- /**
- * Generate the Hash
- *
- * @access public
- * @param string
- * @return string
- */
- function generate($str)
- {
- $n = ((strlen($str) + 8) >> 6) + 1;
-
- for ($i = 0; $i < $n * 16; $i++)
- {
- $x[$i] = 0;
- }
-
- for ($i = 0; $i < strlen($str); $i++)
- {
- $x[$i >> 2] |= ord(substr($str, $i, 1)) << (24 - ($i % 4) * 8);
- }
-
- $x[$i >> 2] |= 0x80 << (24 - ($i % 4) * 8);
-
- $x[$n * 16 - 1] = strlen($str) * 8;
-
- $a = 1732584193;
- $b = -271733879;
- $c = -1732584194;
- $d = 271733878;
- $e = -1009589776;
-
- for ($i = 0; $i < count($x); $i += 16)
- {
- $olda = $a;
- $oldb = $b;
- $oldc = $c;
- $oldd = $d;
- $olde = $e;
-
- for ($j = 0; $j < 80; $j++)
- {
- if ($j < 16)
- {
- $w[$j] = $x[$i + $j];
- }
- else
- {
- $w[$j] = $this->_rol($w[$j - 3] ^ $w[$j - 8] ^ $w[$j - 14] ^ $w[$j - 16], 1);
- }
-
- $t = $this->_safe_add($this->_safe_add($this->_rol($a, 5), $this->_ft($j, $b, $c, $d)), $this->_safe_add($this->_safe_add($e, $w[$j]), $this->_kt($j)));
-
- $e = $d;
- $d = $c;
- $c = $this->_rol($b, 30);
- $b = $a;
- $a = $t;
- }
-
- $a = $this->_safe_add($a, $olda);
- $b = $this->_safe_add($b, $oldb);
- $c = $this->_safe_add($c, $oldc);
- $d = $this->_safe_add($d, $oldd);
- $e = $this->_safe_add($e, $olde);
- }
-
- return $this->_hex($a).$this->_hex($b).$this->_hex($c).$this->_hex($d).$this->_hex($e);
- }
-
- // --------------------------------------------------------------------
-
- /**
- * Convert a decimal to hex
- *
- * @access private
- * @param string
- * @return string
- */
- function _hex($str)
- {
- $str = dechex($str);
-
- if (strlen($str) == 7)
- {
- $str = '0'.$str;
- }
-
- return $str;
- }
-
- // --------------------------------------------------------------------
-
- /**
- * Return result based on iteration
- *
- * @access private
- * @return string
- */
- function _ft($t, $b, $c, $d)
- {
- if ($t < 20)
- return ($b & $c) | ((~$b) & $d);
- if ($t < 40)
- return $b ^ $c ^ $d;
- if ($t < 60)
- return ($b & $c) | ($b & $d) | ($c & $d);
-
- return $b ^ $c ^ $d;
- }
-
- // --------------------------------------------------------------------
-
- /**
- * Determine the additive constant
- *
- * @access private
- * @return string
- */
- function _kt($t)
- {
- if ($t < 20)
- {
- return 1518500249;
- }
- else if ($t < 40)
- {
- return 1859775393;
- }
- else if ($t < 60)
- {
- return -1894007588;
- }
- else
- {
- return -899497514;
- }
- }
-
- // --------------------------------------------------------------------
-
- /**
- * Add integers, wrapping at 2^32
- *
- * @access private
- * @return string
- */
- function _safe_add($x, $y)
- {
- $lsw = ($x & 0xFFFF) + ($y & 0xFFFF);
- $msw = ($x >> 16) + ($y >> 16) + ($lsw >> 16);
-
- return ($msw << 16) | ($lsw & 0xFFFF);
- }
-
- // --------------------------------------------------------------------
-
- /**
- * Bitwise rotate a 32-bit number
- *
- * @access private
- * @return integer
- */
- function _rol($num, $cnt)
- {
- return ($num << $cnt) | $this->_zero_fill($num, 32 - $cnt);
- }
-
- // --------------------------------------------------------------------
-
- /**
- * Pad string with zero
- *
- * @access private
- * @return string
- */
- function _zero_fill($a, $b)
- {
- $bin = decbin($a);
-
- if (strlen($bin) < $b)
- {
- $bin = 0;
- }
- else
- {
- $bin = substr($bin, 0, strlen($bin) - $b);
- }
-
- for ($i=0; $i < $b; $i++)
- {
- $bin = "0".$bin;
- }
-
- return bindec($bin);
- }
-}
-// END CI_SHA
-
-/* End of file Sha1.php */
-/* Location: ./system/libraries/Sha1.php */ \ No newline at end of file
diff --git a/system/libraries/Table.php b/system/libraries/Table.php
index def696776..0f8404d85 100644
--- a/system/libraries/Table.php
+++ b/system/libraries/Table.php
@@ -1,20 +1,30 @@
-<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
+<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* CodeIgniter
*
- * An open source application development framework for PHP 5.1.6 or newer
+ * An open source application development framework for PHP 5.2.4 or newer
+ *
+ * NOTICE OF LICENSE
+ *
+ * Licensed under the Open Software License version 3.0
+ *
+ * This source file is subject to the Open Software License (OSL 3.0) that is
+ * bundled with this package in the files license.txt / license.rst. It is
+ * also available through the world wide web at this URL:
+ * http://opensource.org/licenses/OSL-3.0
+ * If you did not receive a copy of the license and are unable to obtain it
+ * through the world wide web, please send an email to
+ * licensing@ellislab.com so we can send you a copy immediately.
*
* @package CodeIgniter
- * @author ExpressionEngine Dev Team
- * @copyright Copyright (c) 2008 - 2011, EllisLab, Inc.
- * @license http://codeigniter.com/user_guide/license.html
+ * @author EllisLab Dev Team
+ * @copyright Copyright (c) 2008 - 2012, EllisLab, Inc. (http://ellislab.com/)
+ * @license http://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
* @link http://codeigniter.com
* @since Version 1.3.1
* @filesource
*/
-// ------------------------------------------------------------------------
-
/**
* HTML Table Generating Class
*
@@ -23,23 +33,82 @@
* @package CodeIgniter
* @subpackage Libraries
* @category HTML Tables
- * @author ExpressionEngine Dev Team
- * @link http://codeigniter.com/user_guide/libraries/uri.html
+ * @author EllisLab Dev Team
+ * @link http://codeigniter.com/user_guide/libraries/table.html
*/
class CI_Table {
- var $rows = array();
- var $heading = array();
- var $auto_heading = TRUE;
- var $caption = NULL;
- var $template = NULL;
- var $newline = "\n";
- var $empty_cells = "";
- var $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 = '';
- public function __construct()
+ /**
+ * Callback for custom table layout
+ *
+ * @var function
+ */
+ public $function = FALSE;
+
+ /**
+ * Set the template from the table config file if it exists
+ *
+ * @param array $config (default: array())
+ * @return void
+ */
+ 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');
}
// --------------------------------------------------------------------
@@ -47,11 +116,10 @@ class CI_Table {
/**
* Set the template
*
- * @access public
* @param array
- * @return void
+ * @return bool
*/
- function set_template($template)
+ public function set_template($template)
{
if ( ! is_array($template))
{
@@ -59,6 +127,7 @@ class CI_Table {
}
$this->template = $template;
+ return TRUE;
}
// --------------------------------------------------------------------
@@ -68,11 +137,10 @@ class CI_Table {
*
* Can be passed as an array or discreet params
*
- * @access public
* @param mixed
* @return void
*/
- function set_heading()
+ public function set_heading($args = array())
{
$args = func_get_args();
$this->heading = $this->_prep_args($args);
@@ -81,19 +149,18 @@ 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.
*
- * @access public
* @param array
* @param int
* @return void
*/
- function make_columns($array = array(), $col_limit = 0)
+ public function make_columns($array = array(), $col_limit = 0)
{
- if ( ! is_array($array) OR count($array) == 0)
+ if ( ! is_array($array) OR count($array) === 0 OR ! is_int($col_limit))
{
return FALSE;
}
@@ -102,13 +169,13 @@ 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;
}
$new = array();
- while (count($array) > 0)
+ do
{
$temp = array_splice($array, 0, $col_limit);
@@ -122,6 +189,7 @@ class CI_Table {
$new[] = $temp;
}
+ while (count($array) > 0);
return $new;
}
@@ -133,11 +201,10 @@ class CI_Table {
*
* Can be passed as an array or discreet params
*
- * @access public
* @param mixed
* @return void
*/
- function set_empty($value)
+ public function set_empty($value)
{
$this->empty_cells = $value;
}
@@ -149,11 +216,10 @@ class CI_Table {
*
* Can be passed as an array or discreet params
*
- * @access public
* @param mixed
* @return void
*/
- function add_row()
+ public function add_row($args = array())
{
$args = func_get_args();
$this->rows[] = $this->_prep_args($args);
@@ -166,30 +232,22 @@ class CI_Table {
*
* Ensures a standard associative array format for all cell data
*
- * @access public
- * @param type
- * @return type
+ * @param array
+ * @return array
*/
- function _prep_args($args)
+ 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);
}
}
}
@@ -212,11 +270,10 @@ class CI_Table {
/**
* Add a table caption
*
- * @access public
* @param string
* @return void
*/
- function set_caption($caption)
+ public function set_caption($caption)
{
$this->caption = $caption;
}
@@ -226,11 +283,10 @@ class CI_Table {
/**
* Generate the table
*
- * @access public
* @param mixed
* @return string
*/
- function generate($table_data = NULL)
+ public function generate($table_data = NULL)
{
// The table data can optionally be passed to this function
// either as a database result object or an array
@@ -242,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';
}
@@ -261,24 +317,18 @@ class CI_Table {
// Build the table!
- $out = $this->template['table_open'];
- $out .= $this->newline;
+ $out = $this->template['table_open'].$this->newline;
// Add any caption here
if ($this->caption)
{
- $out .= $this->newline;
- $out .= '<caption>' . $this->caption . '</caption>';
- $out .= $this->newline;
+ $out .= $this->newline.'<caption>'.$this->caption.'</caption>'.$this->newline;
}
// Is there a table heading to display?
if (count($this->heading) > 0)
{
- $out .= $this->template['thead_open'];
- $out .= $this->newline;
- $out .= $this->template['heading_row_start'];
- $out .= $this->newline;
+ $out .= $this->template['thead_open'].$this->newline.$this->template['heading_row_start'].$this->newline;
foreach ($this->heading as $heading)
{
@@ -286,28 +336,22 @@ 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);
}
}
- $out .= $temp;
- $out .= isset($heading['data']) ? $heading['data'] : '';
- $out .= $this->template['heading_cell_end'];
+ $out .= $temp.(isset($heading['data']) ? $heading['data'] : '').$this->template['heading_cell_end'];
}
- $out .= $this->template['heading_row_end'];
- $out .= $this->newline;
- $out .= $this->template['thead_close'];
- $out .= $this->newline;
+ $out .= $this->template['heading_row_end'].$this->newline.$this->template['thead_close'].$this->newline;
}
// Build the table rows
if (count($this->rows) > 0)
{
- $out .= $this->template['tbody_open'];
- $out .= $this->newline;
+ $out .= $this->template['tbody_open'].$this->newline;
$i = 1;
foreach ($this->rows as $row)
@@ -318,10 +362,9 @@ 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'];
- $out .= $this->newline;
+ $out .= $this->template['row_'.$name.'start'].$this->newline;
foreach ($row as $cell)
{
@@ -329,40 +372,35 @@ class CI_Table {
foreach ($cell as $key => $val)
{
- if ($key != 'data')
+ 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'];
}
- $out .= $this->template['row_'.$name.'end'];
- $out .= $this->newline;
+ $out .= $this->template['row_'.$name.'end'].$this->newline;
}
- $out .= $this->template['tbody_close'];
- $out .= $this->newline;
+ $out .= $this->template['tbody_close'].$this->newline;
}
$out .= $this->template['table_close'];
@@ -378,14 +416,13 @@ class CI_Table {
/**
* Clears the table arrays. Useful if multiple tables are being generated
*
- * @access public
* @return void
*/
- function clear()
+ public function clear()
{
- $this->rows = array();
- $this->heading = array();
- $this->auto_heading = TRUE;
+ $this->rows = array();
+ $this->heading = array();
+ $this->auto_heading = TRUE;
}
// --------------------------------------------------------------------
@@ -393,30 +430,28 @@ class CI_Table {
/**
* Set table data from a database result object
*
- * @access public
* @param object
* @return void
*/
- function _set_from_object($query)
+ protected function _set_from_object($query)
{
if ( ! is_object($query))
{
- return FALSE;
+ return;
}
// First generate the headings from the table column names
- if (count($this->heading) == 0)
+ if (count($this->heading) === 0)
{
- if ( ! method_exists($query, 'list_fields'))
+ 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)
@@ -431,13 +466,13 @@ class CI_Table {
/**
* Set table data from an array
*
- * @access public
* @param array
+ * @param bool
* @return void
*/
- function _set_from_array($data, $set_heading = TRUE)
+ protected function _set_from_array($data, $set_heading = TRUE)
{
- if ( ! is_array($data) OR count($data) == 0)
+ if ( ! is_array($data) OR count($data) === 0)
{
return FALSE;
}
@@ -446,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);
}
@@ -454,8 +489,6 @@ class CI_Table {
{
$this->rows[] = $this->_prep_args($row);
}
-
- $i++;
}
}
@@ -464,12 +497,11 @@ class CI_Table {
/**
* Compile Template
*
- * @access private
* @return void
*/
- function _compile_template()
+ protected function _compile_template()
{
- if ($this->template == NULL)
+ if ($this->template === NULL)
{
$this->template = $this->_default_template();
return;
@@ -490,42 +522,39 @@ class CI_Table {
/**
* Default Template
*
- * @access private
* @return void
*/
- function _default_template()
+ 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 */ \ No newline at end of file
diff --git a/system/libraries/Trackback.php b/system/libraries/Trackback.php
index b0a767822..9a680dc2a 100644
--- a/system/libraries/Trackback.php
+++ b/system/libraries/Trackback.php
@@ -1,20 +1,30 @@
-<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
+<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* CodeIgniter
*
- * An open source application development framework for PHP 5.1.6 or newer
+ * An open source application development framework for PHP 5.2.4 or newer
+ *
+ * NOTICE OF LICENSE
+ *
+ * Licensed under the Open Software License version 3.0
+ *
+ * This source file is subject to the Open Software License (OSL 3.0) that is
+ * bundled with this package in the files license.txt / license.rst. It is
+ * also available through the world wide web at this URL:
+ * http://opensource.org/licenses/OSL-3.0
+ * If you did not receive a copy of the license and are unable to obtain it
+ * through the world wide web, please send an email to
+ * licensing@ellislab.com so we can send you a copy immediately.
*
* @package CodeIgniter
- * @author ExpressionEngine Dev Team
- * @copyright Copyright (c) 2008 - 2011, EllisLab, Inc.
- * @license http://codeigniter.com/user_guide/license.html
+ * @author EllisLab Dev Team
+ * @copyright Copyright (c) 2008 - 2012, EllisLab, Inc. (http://ellislab.com/)
+ * @license http://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
* @link http://codeigniter.com
* @since Version 1.0
* @filesource
*/
-// ------------------------------------------------------------------------
-
/**
* Trackback Class
*
@@ -23,26 +33,21 @@
* @package CodeIgniter
* @subpackage Libraries
* @category Trackbacks
- * @author ExpressionEngine Dev Team
+ * @author EllisLab Dev Team
* @link http://codeigniter.com/user_guide/libraries/trackback.html
*/
class CI_Trackback {
- var $time_format = 'local';
- var $charset = 'UTF-8';
- var $data = array('url' => '', 'title' => '', 'excerpt' => '', 'blog_name' => '', 'charset' => '');
- var $convert_ascii = TRUE;
- var $response = '';
- var $error_msg = array();
+ public $time_format = 'local';
+ public $charset = 'UTF-8';
+ public $data = array('url' => '', 'title' => '', 'excerpt' => '', 'blog_name' => '', 'charset' => '');
+ public $convert_ascii = TRUE;
+ public $response = '';
+ public $error_msg = array();
- /**
- * Constructor
- *
- * @access public
- */
public function __construct()
{
- log_message('debug', "Trackback Class Initialized");
+ log_message('debug', 'Trackback Class Initialized');
}
// --------------------------------------------------------------------
@@ -50,11 +55,10 @@ class CI_Trackback {
/**
* Send Trackback
*
- * @access public
* @param array
* @return bool
*/
- function send($tb_data)
+ public function send($tb_data)
{
if ( ! is_array($tb_data))
{
@@ -84,27 +88,17 @@ class CI_Trackback {
}
// Convert High ASCII Characters
- if ($this->convert_ascii == TRUE)
+ if ($this->convert_ascii === TRUE && in_array($item, array('excerpt', 'title', 'blog_name')))
{
- if ($item == 'excerpt')
- {
- $$item = $this->convert_ascii($$item);
- }
- elseif ($item == 'title')
- {
- $$item = $this->convert_ascii($$item);
- }
- elseif ($item == 'blog_name')
- {
- $$item = $this->convert_ascii($$item);
- }
+ $$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;
@@ -112,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;
}
@@ -132,29 +126,28 @@ class CI_Trackback {
* If the data is valid it is set to the $this->data array
* so that it can be inserted into a database.
*
- * @access public
* @return bool
*/
- function receive()
+ public function receive()
{
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' && function_exists('mb_convert_encoding'))
+ 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']);
}
@@ -170,17 +163,16 @@ 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.
*
- * @access public
* @param string
* @return void
*/
- function send_error($message = 'Incomplete Information')
+ 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;
}
@@ -192,12 +184,11 @@ class CI_Trackback {
* This should be called when a trackback has been
* successfully received and inserted.
*
- * @access public
* @return void
*/
- function send_success()
+ 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;
}
@@ -206,13 +197,12 @@ class CI_Trackback {
/**
* Fetch a particular item
*
- * @access public
* @param string
* @return string
*/
- function data($item)
+ public function data($item)
{
- return ( ! isset($this->data[$item])) ? '' : $this->data[$item];
+ return isset($this->data[$item]) ? $this->data[$item] : '';
}
// --------------------------------------------------------------------
@@ -221,14 +211,13 @@ 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
*
- * @access public
* @param string
* @param string
* @return bool
*/
- function process($url, $data)
+ public function process($url, $data)
{
$target = parse_url($url);
@@ -240,43 +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 (stristr($this->response, '<error>0</error>') === FALSE)
+ if (stripos($this->response, '<error>0</error>') === FALSE)
{
- $message = 'An unknown error was encountered';
-
- if (preg_match("/<message>(.*?)<\/message>/is", $this->response, $match))
- {
- $message = trim($match['1']);
- }
-
+ $message = preg_match('/<message>(.*?)<\/message>/is', $this->response, $match) ? trim($match[1]) : 'An unknown error was encountered';
$this->set_error($message);
return FALSE;
}
@@ -293,29 +275,22 @@ class CI_Trackback {
* It takes a string of URLs (separated by comma or
* space) and puts each URL into an array
*
- * @access public
* @param string
* @return string
*/
- function extract_urls($urls)
+ 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) == ",")
+ if (substr($urls, -1) === ',')
{
$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'));
@@ -329,17 +304,16 @@ class CI_Trackback {
*
* Simply adds "http://" if missing
*
- * @access public
* @param string
- * @return string
+ * @return void
*/
- function validate_url($url)
+ public function validate_url(&$url)
{
$url = trim($url);
- if (substr($url, 0, 4) != "http")
+ if (strpos($url, 'http') !== 0)
{
- $url = "http://".$url;
+ $url = 'http://'.$url;
}
}
@@ -348,13 +322,12 @@ class CI_Trackback {
/**
* Find the Trackback URL's ID
*
- * @access public
* @param string
* @return string
*/
- function get_id($url)
+ public function get_id($url)
{
- $tb_id = "";
+ $tb_id = '';
if (strpos($url, '?') !== FALSE)
{
@@ -378,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;
}
// --------------------------------------------------------------------
@@ -397,25 +363,20 @@ class CI_Trackback {
/**
* Convert Reserved XML characters to Entities
*
- * @access public
* @param string
* @return string
*/
- function convert_xml($str)
+ public function convert_xml($str)
{
$temp = '__TEMP_AMPERSANDS__';
- $str = preg_replace("/&#(\d+);/", "$temp\\1;", $str);
- $str = preg_replace("/&(\w+);/", "$temp\\1;", $str);
+ $str = preg_replace(array('/&#(\d+);/', '/&(\w+);/'), $temp.'\\1;', $str);
- $str = str_replace(array("&","<",">","\"", "'", "-"),
- array("&amp;", "&lt;", "&gt;", "&quot;", "&#39;", "&#45;"),
- $str);
+ $str = str_replace(array('&', '<', '>', '"', "'", '-'),
+ array('&amp;', '&lt;', '&gt;', '&quot;', '&#39;', '&#45;'),
+ $str);
- $str = preg_replace("/$temp(\d+);/","&#\\1;",$str);
- $str = preg_replace("/$temp(\w+);/","&\\1;", $str);
-
- return $str;
+ return preg_replace(array('/'.$temp.'(\d+);/', '/'.$temp.'(\w+);/'), array('&#\\1;', '&\\1;'), $str);
}
// --------------------------------------------------------------------
@@ -425,33 +386,32 @@ class CI_Trackback {
*
* Limits the string based on the character count. Will preserve complete words.
*
- * @access public
* @param string
- * @param integer
+ * @param int
* @param string
* @return string
*/
- function limit_characters($str, $n = 500, $end_char = '&#8230;')
+ public function limit_characters($str, $n = 500, $end_char = '&#8230;')
{
if (strlen($str) < $n)
{
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)
{
return $str;
}
- $out = "";
+ $out = '';
foreach (explode(' ', trim($str)) as $val)
{
$out .= $val.' ';
if (strlen($out) >= $n)
{
- return trim($out).$end_char;
+ return rtrim($out).$end_char;
}
}
}
@@ -464,11 +424,10 @@ class CI_Trackback {
* Converts Hight ascii text and MS Word special chars
* to character entities
*
- * @access public
* @param string
* @return string
*/
- function convert_ascii($str)
+ public function convert_ascii($str)
{
$count = 1;
$out = '';
@@ -484,16 +443,18 @@ class CI_Trackback {
}
else
{
- if (count($temp) == 0)
+ if (count($temp) === 0)
{
$count = ($ordinal < 224) ? 2 : 3;
}
$temp[] = $ordinal;
- if (count($temp) == $count)
+ 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;
@@ -510,11 +471,10 @@ class CI_Trackback {
/**
* Set error message
*
- * @access public
* @param string
* @return void
*/
- function set_error($msg)
+ public function set_error($msg)
{
log_message('error', $msg);
$this->error_msg[] = $msg;
@@ -525,24 +485,16 @@ class CI_Trackback {
/**
* Show error messages
*
- * @access public
* @param string
* @param string
* @return string
*/
- function display_errors($open = '<p>', $close = '</p>')
+ public function display_errors($open = '<p>', $close = '</p>')
{
- $str = '';
- foreach ($this->error_msg as $val)
- {
- $str .= $open.$val.$close;
- }
-
- return $str;
+ 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 */ \ No newline at end of file
diff --git a/system/libraries/Typography.php b/system/libraries/Typography.php
index 734cec104..a50934f2c 100644
--- a/system/libraries/Typography.php
+++ b/system/libraries/Typography.php
@@ -1,48 +1,82 @@
-<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
+<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* CodeIgniter
*
- * An open source application development framework for PHP 5.1.6 or newer
+ * An open source application development framework for PHP 5.2.4 or newer
+ *
+ * NOTICE OF LICENSE
+ *
+ * Licensed under the Open Software License version 3.0
+ *
+ * This source file is subject to the Open Software License (OSL 3.0) that is
+ * bundled with this package in the files license.txt / license.rst. It is
+ * also available through the world wide web at this URL:
+ * http://opensource.org/licenses/OSL-3.0
+ * If you did not receive a copy of the license and are unable to obtain it
+ * through the world wide web, please send an email to
+ * licensing@ellislab.com so we can send you a copy immediately.
*
* @package CodeIgniter
- * @author ExpressionEngine Dev Team
- * @copyright Copyright (c) 2008 - 2011, EllisLab, Inc.
- * @license http://codeigniter.com/user_guide/license.html
+ * @author EllisLab Dev Team
+ * @copyright Copyright (c) 2008 - 2012, EllisLab, Inc. (http://ellislab.com/)
+ * @license http://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
* @link http://codeigniter.com
* @since Version 1.0
* @filesource
*/
-// ------------------------------------------------------------------------
-
/**
* Typography Class
*
- *
- * @access private
+ * @package CodeIgniter
+ * @subpackage Libraries
* @category Helpers
- * @author ExpressionEngine Dev Team
- * @link http://codeigniter.com/user_guide/helpers/
+ * @author EllisLab Dev Team
+ * @link http://codeigniter.com/user_guide/libraries/typography.html
*/
class CI_Typography {
- // Block level elements that should not be wrapped inside <p> tags
- var $block_elements = 'address|blockquote|div|dl|fieldset|form|h\d|hr|noscript|object|ol|p|pre|script|table|ul';
+ /**
+ * 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.
- var $skip_elements = 'p|pre|ol|ul|dl|object|table|h\d';
+ /**
+ * 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.
- var $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';
+ /**
+ * 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
- var $inner_block_required = array('blockquote');
+ /**
+ * 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
- var $last_block_element = '';
+ /**
+ * the last block element parsed
+ *
+ * @var string
+ */
+ public $last_block_element = '';
- // whether or not to protect quotes within { curly braces }
- var $protect_braced_quotes = FALSE;
+ /**
+ * whether or not to protect quotes within { curly braces }
+ *
+ * @var bool
+ */
+ public $protect_braced_quotes = FALSE;
/**
* Auto Typography
@@ -55,14 +89,13 @@ class CI_Typography {
* - Converts double dashes into em-dashes.
* - Converts two spaces into entities
*
- * @access public
* @param string
* @param bool whether to reduce more then two consecutive newlines to two
* @return string
*/
- function auto_typography($str, $reduce_linebreaks = FALSE)
+ public function auto_typography($str, $reduce_linebreaks = FALSE)
{
- if ($str == '')
+ if ($str === '')
{
return '';
}
@@ -82,15 +115,12 @@ class CI_Typography {
// HTML comment tags don't conform to patterns of normal tags, so pull them out separately, only if needed
$html_comments = array();
- if (strpos($str, '<!--') !== FALSE)
+ if (strpos($str, '<!--') !== FALSE && preg_match_all('#(<!\-\-.*?\-\->)#s', $str, $matches))
{
- if (preg_match_all("#(<!\-\-.*?\-\->)#s", $str, $matches))
+ for ($i = 0, $total = count($matches[0]); $i < $total; $i++)
{
- for ($i = 0, $total = count($matches[0]); $i < $total; $i++)
- {
- $html_comments[] = $matches[0][$i];
- $str = str_replace($matches[0][$i], '{@HC'.$i.'}', $str);
- }
+ $html_comments[] = $matches[0][$i];
+ $str = str_replace($matches[0][$i], '{@HC'.$i.'}', $str);
}
}
@@ -98,83 +128,80 @@ class CI_Typography {
// not contain <pre> tags, and it keeps the PCRE patterns below simpler and faster
if (strpos($str, '<pre') !== FALSE)
{
- $str = preg_replace_callback("#<pre.*?>.*?</pre>#si", array($this, '_protect_characters'), $str);
+ $str = preg_replace_callback('#<pre.*?>.*?</pre>#si', array($this, '_protect_characters'), $str);
}
// Convert quotes within tags to temporary markers.
- $str = preg_replace_callback("#<.+?>#si", array($this, '_protect_characters'), $str);
+ $str = preg_replace_callback('#<.+?>#si', array($this, '_protect_characters'), $str);
// Do the same with braces if necessary
if ($this->protect_braced_quotes === TRUE)
{
- $str = preg_replace_callback("#\{.+?\}#si", array($this, '_protect_characters'), $str);
+ $str = preg_replace_callback('#\{.+?\}#si', array($this, '_protect_characters'), $str);
}
// Convert "ignore" tags to temporary marker. The parser splits out the string at every tag
// it encounters. Certain inline tags, like image tags, links, span tags, etc. will be
// adversely affected if they are split out so we'll convert the opening bracket < temporarily to: {@TAG}
- $str = preg_replace("#<(/*)(".$this->inline_elements.")([ >])#i", "{@TAG}\\1\\2\\3", $str);
-
- // Split the string at every tag. This expression creates an array with this prototype:
- //
- // [array]
- // {
- // [0] = <opening tag>
- // [1] = Content...
- // [2] = <closing tag>
- // Etc...
- // }
+ $str = preg_replace('#<(/*)('.$this->inline_elements.')([ >])#i', '{@TAG}\\1\\2\\3', $str);
+
+ /* Split the string at every tag. This expression creates an array with this prototype:
+ *
+ * [array]
+ * {
+ * [0] = <opening tag>
+ * [1] = Content...
+ * [2] = <closing tag>
+ * Etc...
+ * }
+ */
$chunks = preg_split('/(<(?:[^<>]+(?:"[^"]*"|\'[^\']*\')?)+>)/', $str, -1, PREG_SPLIT_DELIM_CAPTURE|PREG_SPLIT_NO_EMPTY);
// Build our finalized string. We cycle through the array, skipping tags, and processing the contained text
$str = '';
$process = TRUE;
$paragraph = FALSE;
- $current_chunk = 0;
- $total_chunks = count($chunks);
- foreach ($chunks as $chunk)
+ for ($i = 0, $c = count($chunks) - 1; $i <= $c; $i++)
{
- $current_chunk++;
-
// Are we dealing with a tag? If so, we'll skip the processing for this cycle.
// Well also set the "process" flag which allows us to skip <pre> tags and a few other things.
- if (preg_match("#<(/*)(".$this->block_elements.").*?>#", $chunk, $match))
+ if (preg_match('#<(/*)('.$this->block_elements.').*?>#', $chunks[$i], $match))
{
- if (preg_match("#".$this->skip_elements."#", $match[2]))
+ if (preg_match('#'.$this->skip_elements.'#', $match[2]))
{
- $process = ($match[1] == '/') ? TRUE : FALSE;
+ $process = ($match[1] === '/');
}
- if ($match[1] == '')
+ if ($match[1] === '')
{
$this->last_block_element = $match[2];
}
- $str .= $chunk;
+ $str .= $chunks[$i];
continue;
}
- if ($process == FALSE)
+ if ($process === FALSE)
{
- $str .= $chunk;
+ $str .= $chunks[$i];
continue;
}
// Force a newline to make sure end tags get processed by _format_newlines()
- if ($current_chunk == $total_chunks)
+ if ($i === $c)
{
- $chunk .= "\n";
+ $chunks[$i] .= "\n";
}
// Convert Newlines into <p> and <br /> tags
- $str .= $this->_format_newlines($chunk);
+ $str .= $this->_format_newlines($chunks[$i]);
}
- // No opening block level tag? Add it if needed.
- if ( ! preg_match("/^\s*<(?:".$this->block_elements.")/i", $str))
+ // No opening block level tag? Add it if needed.
+ if ( ! preg_match('/^\s*<(?:'.$this->block_elements.')/i', $str))
{
- $str = preg_replace("/^(.*?)<(".$this->block_elements.")/i", '<p>$1</p><$2', $str);
+ $str = preg_replace('/^(.*?)<('.$this->block_elements.')/i', '<p>$1</p><$2', $str);
}
// Convert quotes, elipsis, em-dashes, non-breaking spaces, and ampersands
@@ -221,7 +248,7 @@ class CI_Typography {
// Similarly, there might be cases where a closing </block> will follow
// a closing </p> tag, so we'll correct it by adding a newline in between
- "#</p></#" => "</p>\n</"
+ '#</p></#' => "</p>\n</"
);
// Do we need to reduce empty lines?
@@ -249,11 +276,10 @@ class CI_Typography {
* to curly entities, but it also converts em-dashes,
* double spaces, and ampersands
*
- * @access public
* @param string
* @return string
*/
- function format_characters($str)
+ public function format_characters($str)
{
static $table;
@@ -313,18 +339,12 @@ class CI_Typography {
*
* Converts newline characters into either <p> tags or <br />
*
- * @access public
* @param string
* @return string
*/
- function _format_newlines($str)
+ protected function _format_newlines($str)
{
- if ($str == '')
- {
- return $str;
- }
-
- if (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;
}
@@ -333,10 +353,10 @@ class CI_Typography {
$str = str_replace("\n\n", "</p>\n\n<p>", $str);
// Convert single spaces to <br /> tags
- $str = preg_replace("/([^\n])(\n)([^\n])/", "\\1<br />\\2\\3", $str);
+ $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
@@ -346,9 +366,7 @@ class CI_Typography {
// Remove empty paragraphs if they are on the first line, as this
// is a potential unintended consequence of the previous code
- $str = preg_replace("/<p><\/p>(.*)/", "\\1", $str, 1);
-
- return $str;
+ return preg_replace('/<p><\/p>(.*)/', '\\1', $str, 1);
}
// ------------------------------------------------------------------------
@@ -361,11 +379,10 @@ class CI_Typography {
* and we don't want double dashes converted to emdash entities, so they are marked with {@DD}
* likewise double spaces are converted to {@NBS} to prevent entity conversion
*
- * @access public
* @param array
* @return string
*/
- function _protect_characters($match)
+ protected function _protect_characters($match)
{
return str_replace(array("'",'"','--',' '), array('{@SQ}', '{@DQ}', '{@DD}', '{@NBS}'), $match[0]);
}
@@ -375,36 +392,25 @@ class CI_Typography {
/**
* Convert newlines to HTML line breaks except within PRE tags
*
- * @access public
* @param string
* @return string
*/
- function nl2br_except_pre($str)
+ public function nl2br_except_pre($str)
{
- $ex = explode("pre>",$str);
- $ct = count($ex);
-
- $newstr = "";
- for ($i = 0; $i < $ct; $i++)
+ $newstr = '';
+ for ($ex = explode('pre>', $str), $ct = count($ex), $i = 0; $i < $ct; $i++)
{
- if (($i % 2) == 0)
- {
- $newstr .= nl2br($ex[$i]);
- }
- else
+ $newstr .= (($i % 2) === 0) ? nl2br($ex[$i]) : $ex[$i];
+ if ($ct - 1 !== $i)
{
- $newstr .= $ex[$i];
+ $newstr .= 'pre>';
}
-
- if ($ct - 1 != $i)
- $newstr .= "pre>";
}
return $newstr;
}
}
-// END Typography Class
/* End of file Typography.php */
/* Location: ./system/libraries/Typography.php */ \ No newline at end of file
diff --git a/system/libraries/Unit_test.php b/system/libraries/Unit_test.php
index 5bd7e801a..70ad8dc41 100644
--- a/system/libraries/Unit_test.php
+++ b/system/libraries/Unit_test.php
@@ -1,20 +1,30 @@
-<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
+<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* CodeIgniter
*
- * An open source application development framework for PHP 5.1.6 or newer
+ * An open source application development framework for PHP 5.2.4 or newer
+ *
+ * NOTICE OF LICENSE
+ *
+ * Licensed under the Open Software License version 3.0
+ *
+ * This source file is subject to the Open Software License (OSL 3.0) that is
+ * bundled with this package in the files license.txt / license.rst. It is
+ * also available through the world wide web at this URL:
+ * http://opensource.org/licenses/OSL-3.0
+ * If you did not receive a copy of the license and are unable to obtain it
+ * through the world wide web, please send an email to
+ * licensing@ellislab.com so we can send you a copy immediately.
*
* @package CodeIgniter
- * @author ExpressionEngine Dev Team
- * @copyright Copyright (c) 2008 - 2011, EllisLab, Inc.
- * @license http://codeigniter.com/user_guide/license.html
+ * @author EllisLab Dev Team
+ * @copyright Copyright (c) 2008 - 2012, EllisLab, Inc. (http://ellislab.com/)
+ * @license http://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
* @link http://codeigniter.com
* @since Version 1.3.1
* @filesource
*/
-// ------------------------------------------------------------------------
-
/**
* Unit Testing Class
*
@@ -23,17 +33,17 @@
* @package CodeIgniter
* @subpackage Libraries
* @category UnitTesting
- * @author ExpressionEngine Dev Team
- * @link http://codeigniter.com/user_guide/libraries/uri.html
+ * @author EllisLab Dev Team
+ * @link http://codeigniter.com/user_guide/libraries/unit_testing.html
*/
class CI_Unit_test {
- var $active = TRUE;
- var $results = array();
- var $strict = FALSE;
- var $_template = NULL;
- var $_template_rows = NULL;
- var $_test_items_visible = array();
+ public $active = TRUE;
+ public $results = array();
+ public $strict = FALSE;
+ protected $_template = NULL;
+ protected $_template_rows = NULL;
+ protected $_test_items_visible = array();
public function __construct()
{
@@ -48,7 +58,7 @@ class CI_Unit_test {
'notes'
);
- log_message('debug', "Unit Testing Class Initialized");
+ log_message('debug', 'Unit Testing Class Initialized');
}
// --------------------------------------------------------------------
@@ -58,13 +68,12 @@ class CI_Unit_test {
*
* Runs the supplied tests
*
- * @access public
* @param array
* @return void
*/
- function set_test_items($items = array())
+ 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;
}
@@ -77,32 +86,27 @@ class CI_Unit_test {
*
* Runs the supplied tests
*
- * @access public
* @param mixed
* @param mixed
* @param string
* @return string
*/
- function run($test, $expected = TRUE, $test_name = 'undefined', $notes = '')
+ 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
{
- if ($this->strict == TRUE)
- $result = ($test === $expected) ? TRUE : FALSE;
- else
- $result = ($test == $expected) ? TRUE : FALSE;
-
+ $result = ($this->strict === TRUE) ? ($test === $expected) : ($test === $expected);
$extype = gettype($expected);
}
@@ -120,7 +124,7 @@ class CI_Unit_test {
$this->results[] = $report;
- return($this->report($this->result($report)));
+ return $this->report($this->result($report));
}
// --------------------------------------------------------------------
@@ -130,12 +134,11 @@ class CI_Unit_test {
*
* Displays a table with the test data
*
- * @access public
* @return string
*/
- function report($result = array())
+ public function report($result = array())
{
- if (count($result) == 0)
+ if (count($result) === 0)
{
$result = $this->result();
}
@@ -152,22 +155,19 @@ 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>';
}
}
- $temp = $this->_template_rows;
- $temp = str_replace('{item}', $key, $temp);
- $temp = str_replace('{result}', $val, $temp);
- $table .= $temp;
+ $table .= str_replace(array('{item}', '{result}'), array($key, $val), $this->_template_rows);
}
$r .= str_replace('{rows}', $table, $this->_template);
@@ -183,13 +183,12 @@ class CI_Unit_test {
*
* Causes the evaluation to use === rather than ==
*
- * @access public
* @param bool
- * @return null
+ * @return void
*/
- function use_strict($state = TRUE)
+ public function use_strict($state = TRUE)
{
- $this->strict = ($state == FALSE) ? FALSE : TRUE;
+ $this->strict = (bool) $state;
}
// --------------------------------------------------------------------
@@ -199,13 +198,12 @@ class CI_Unit_test {
*
* Enables/disables unit testing
*
- * @access public
* @param bool
- * @return null
+ * @return void
*/
- function active($state = TRUE)
+ public function active($state = TRUE)
{
- $this->active = ($state == FALSE) ? FALSE : TRUE;
+ $this->active = (bool) $state;
}
// --------------------------------------------------------------------
@@ -215,15 +213,14 @@ class CI_Unit_test {
*
* Returns the raw result data
*
- * @access public
* @return array
*/
- function result($results = array())
+ public function result($results = array())
{
$CI =& get_instance();
$CI->load->language('unit_test');
- if (count($results) == 0)
+ if (count($results) === 0)
{
$results = $this->results;
}
@@ -273,11 +270,10 @@ class CI_Unit_test {
*
* This lets us set the template to be used to display results
*
- * @access public
* @param string
* @return void
*/
- function set_template($template)
+ public function set_template($template)
{
$this->_template = $template;
}
@@ -289,21 +285,15 @@ class CI_Unit_test {
*
* This lets us show file names and line numbers
*
- * @access private
* @return array
*/
- function _backtrace()
+ protected function _backtrace()
{
- if (function_exists('debug_backtrace'))
- {
- $back = debug_backtrace();
-
- $file = ( ! isset($back['1']['file'])) ? '' : $back['1']['file'];
- $line = ( ! isset($back['1']['line'])) ? '' : $back['1']['line'];
-
- return array('file' => $file, 'line' => $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,19 +301,14 @@ class CI_Unit_test {
/**
* Get Default Template
*
- * @access private
* @return string
*/
- function _default_template()
+ protected function _default_template()
{
- $this->_template = "\n".'<table style="width:100%; font-size:small; margin:10px 0; border-collapse:collapse; border:1px solid #CCC;">';
- $this->_template .= '{rows}';
- $this->_template .= "\n".'</table>';
-
- $this->_template_rows = "\n\t".'<tr>';
- $this->_template_rows .= "\n\t\t".'<th style="text-align: left; border-bottom:1px solid #CCC;">{item}</th>';
- $this->_template_rows .= "\n\t\t".'<td style="border-bottom:1px solid #CCC;">{result}</td>';
- $this->_template_rows .= "\n\t".'</tr>';
+ $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>";
}
// --------------------------------------------------------------------
@@ -333,51 +318,40 @@ class CI_Unit_test {
*
* Harvests the data within the template {pseudo-variables}
*
- * @access private
* @return void
*/
- function _parse_template()
+ protected function _parse_template()
{
if ( ! is_null($this->_template_rows))
{
return;
}
- if (is_null($this->_template))
+ if (is_null($this->_template) OR ! preg_match('/\{rows\}(.*?)\{\/rows\}/si', $this->_template, $match))
{
$this->_default_template();
return;
}
- if ( ! preg_match("/\{rows\}(.*?)\{\/rows\}/si", $this->_template, $match))
- {
- $this->_default_template();
- return;
- }
-
- $this->_template_rows = $match['1'];
- $this->_template = str_replace($match['0'], '{rows}', $this->_template);
+ $this->_template_rows = $match[1];
+ $this->_template = str_replace($match[0], '{rows}', $this->_template);
}
}
-// END Unit_test Class
/**
* Helper functions to test boolean true/false
*
- *
- * @access private
* @return bool
*/
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 */ \ No newline at end of file
diff --git a/system/libraries/Upload.php b/system/libraries/Upload.php
index 8f324de79..d381440cd 100644
--- a/system/libraries/Upload.php
+++ b/system/libraries/Upload.php
@@ -1,64 +1,76 @@
-<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
+<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* CodeIgniter
*
- * An open source application development framework for PHP 5.1.6 or newer
+ * An open source application development framework for PHP 5.2.4 or newer
+ *
+ * NOTICE OF LICENSE
+ *
+ * Licensed under the Open Software License version 3.0
+ *
+ * This source file is subject to the Open Software License (OSL 3.0) that is
+ * bundled with this package in the files license.txt / license.rst. It is
+ * also available through the world wide web at this URL:
+ * http://opensource.org/licenses/OSL-3.0
+ * If you did not receive a copy of the license and are unable to obtain it
+ * through the world wide web, please send an email to
+ * licensing@ellislab.com so we can send you a copy immediately.
*
* @package CodeIgniter
- * @author ExpressionEngine Dev Team
- * @copyright Copyright (c) 2008 - 2011, EllisLab, Inc.
- * @license http://codeigniter.com/user_guide/license.html
+ * @author EllisLab Dev Team
+ * @copyright Copyright (c) 2008 - 2012, EllisLab, Inc. (http://ellislab.com/)
+ * @license http://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
* @link http://codeigniter.com
* @since Version 1.0
* @filesource
*/
-// ------------------------------------------------------------------------
-
/**
* File Uploading Class
*
* @package CodeIgniter
* @subpackage Libraries
* @category Uploads
- * @author ExpressionEngine Dev Team
+ * @author EllisLab Dev Team
* @link http://codeigniter.com/user_guide/libraries/file_uploading.html
*/
class CI_Upload {
- public $max_size = 0;
- public $max_width = 0;
- public $max_height = 0;
- public $max_filename = 0;
+ public $max_size = 0;
+ public $max_width = 0;
+ public $max_height = 0;
+ public $max_filename = 0;
public $max_filename_increment = 100;
- public $allowed_types = "";
- public $file_temp = "";
- public $file_name = "";
- public $orig_name = "";
- public $file_type = "";
- public $file_size = "";
- public $file_ext = "";
- public $upload_path = "";
- public $overwrite = FALSE;
- public $encrypt_name = FALSE;
- public $is_image = FALSE;
- public $image_width = '';
- public $image_height = '';
- public $image_type = '';
- public $image_size_str = '';
- public $error_msg = array();
- public $mimes = array();
- public $remove_spaces = TRUE;
- public $xss_clean = FALSE;
- public $temp_prefix = "temp_file_";
- public $client_name = '';
+ public $allowed_types = '';
+ public $file_temp = '';
+ public $file_name = '';
+ public $orig_name = '';
+ public $file_type = '';
+ public $file_size = '';
+ public $file_ext = '';
+ public $upload_path = '';
+ public $overwrite = FALSE;
+ public $encrypt_name = FALSE;
+ public $is_image = FALSE;
+ public $image_width = '';
+ public $image_height = '';
+ public $image_type = '';
+ public $image_size_str = '';
+ public $error_msg = array();
+ public $mimes = array();
+ public $remove_spaces = TRUE;
+ public $detect_mime = TRUE;
+ public $xss_clean = FALSE;
+ public $temp_prefix = 'temp_file_';
+ public $client_name = '';
protected $_file_name_override = '';
/**
* Constructor
*
- * @access public
+ * @param array
+ * @return void
*/
public function __construct($props = array())
{
@@ -67,7 +79,9 @@ class CI_Upload {
$this->initialize($props);
}
- log_message('debug', "Upload Class Initialized");
+ $this->mimes =& get_mimes();
+
+ log_message('debug', 'Upload Class Initialized');
}
// --------------------------------------------------------------------
@@ -81,33 +95,33 @@ class CI_Upload {
public function initialize($config = array())
{
$defaults = array(
- 'max_size' => 0,
- 'max_width' => 0,
- 'max_height' => 0,
- 'max_filename' => 0,
- 'max_filename_increment' => 100,
- 'allowed_types' => "",
- 'file_temp' => "",
- 'file_name' => "",
- 'orig_name' => "",
- 'file_type' => "",
- 'file_size' => "",
- 'file_ext' => "",
- 'upload_path' => "",
- 'overwrite' => FALSE,
- 'encrypt_name' => FALSE,
- 'is_image' => FALSE,
- 'image_width' => '',
- 'image_height' => '',
- 'image_type' => '',
- 'image_size_str' => '',
- 'error_msg' => array(),
- 'mimes' => array(),
- 'remove_spaces' => TRUE,
- 'xss_clean' => FALSE,
- 'temp_prefix' => "temp_file_",
- 'client_name' => ''
- );
+ 'max_size' => 0,
+ 'max_width' => 0,
+ 'max_height' => 0,
+ 'max_filename' => 0,
+ 'max_filename_increment' => 100,
+ 'allowed_types' => '',
+ 'file_temp' => '',
+ 'file_name' => '',
+ 'orig_name' => '',
+ 'file_type' => '',
+ 'file_size' => '',
+ 'file_ext' => '',
+ 'upload_path' => '',
+ 'overwrite' => FALSE,
+ 'encrypt_name' => FALSE,
+ 'is_image' => FALSE,
+ 'image_width' => '',
+ 'image_height' => '',
+ 'image_type' => '',
+ 'image_size_str' => '',
+ 'error_msg' => array(),
+ 'remove_spaces' => TRUE,
+ 'detect_mime' => TRUE,
+ 'xss_clean' => FALSE,
+ 'temp_prefix' => 'temp_file_',
+ 'client_name' => ''
+ );
foreach ($defaults as $key => $val)
@@ -144,8 +158,7 @@ class CI_Upload {
*/
public function do_upload($field = 'userfile')
{
-
- // Is $_FILES[$field] set? If not, no reason to continue.
+ // Is $_FILES[$field] set? If not, no reason to continue.
if ( ! isset($_FILES[$field]))
{
$this->set_error('upload_no_file_selected');
@@ -164,7 +177,7 @@ class CI_Upload {
{
$error = ( ! isset($_FILES[$field]['error'])) ? 4 : $_FILES[$field]['error'];
- switch($error)
+ switch ($error)
{
case 1: // UPLOAD_ERR_INI_SIZE
$this->set_error('upload_file_exceeds_limit');
@@ -187,18 +200,25 @@ class CI_Upload {
case 8: // UPLOAD_ERR_EXTENSION
$this->set_error('upload_stopped_by_extension');
break;
- default : $this->set_error('upload_no_file_selected');
+ default:
+ $this->set_error('upload_no_file_selected');
break;
}
return FALSE;
}
-
// Set the uploaded data as class variables
$this->file_temp = $_FILES[$field]['tmp_name'];
$this->file_size = $_FILES[$field]['size'];
- $this->file_type = preg_replace("/^(.+?);.*$/", "\\1", $_FILES[$field]['type']);
+
+ // Skip MIME type detection?
+ if ($this->detect_mime !== FALSE)
+ {
+ $this->_file_mime_type($_FILES[$field]);
+ }
+
+ $this->file_type = preg_replace('/^(.+?);.*$/', '\\1', $this->file_type);
$this->file_type = strtolower(trim(stripslashes($this->file_type), '"'));
$this->file_name = $this->_prep_filename($_FILES[$field]['name']);
$this->file_ext = $this->get_extension($this->file_name);
@@ -212,7 +232,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);
@@ -221,11 +241,10 @@ class CI_Upload {
{
$this->file_name .= $this->file_ext;
}
-
- // An extension was provided, lets have it!
else
{
- $this->file_ext = $this->get_extension($this->_file_name_override);
+ // An extension was provided, lets have it!
+ $this->file_ext = $this->get_extension($this->_file_name_override);
}
if ( ! $this->is_allowed_filetype(TRUE))
@@ -266,9 +285,9 @@ 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);
+ $this->file_name = preg_replace('/\s+/', '_', $this->file_name);
}
/*
@@ -279,7 +298,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);
@@ -292,23 +311,20 @@ class CI_Upload {
/*
* Run the file through the XSS hacking filter
* This helps prevent malicious code from being
- * embedded within a file. Scripts can easily
+ * embedded within a file. Scripts can easily
* be disguised as images or other file types.
*/
- if ($this->xss_clean)
+ if ($this->xss_clean && $this->do_xss_clean() === FALSE)
{
- if ($this->do_xss_clean() === FALSE)
- {
- $this->set_error('upload_unable_to_write_file');
- return FALSE;
- }
+ $this->set_error('upload_unable_to_write_file');
+ return FALSE;
}
/*
* Move the file to the final destination
* To deal with different server configurations
- * we'll attempt to use copy() first. If that fails
- * we'll use move_uploaded_file(). One of the two should
+ * we'll attempt to use copy() first. If that fails
+ * we'll use move_uploaded_file(). One of the two should
* reliably work in most environments
*/
if ( ! @copy($this->file_temp, $this->upload_path.$this->file_name))
@@ -323,7 +339,7 @@ class CI_Upload {
/*
* Set the finalized image dimensions
* This sets the image width/height (assuming the
- * file was an image). We use this information
+ * file was an image). We use this information
* in the "data" function.
*/
$this->set_image_properties($this->upload_path.$this->file_name);
@@ -339,26 +355,34 @@ class CI_Upload {
* Returns an associative array containing all of the information
* related to the upload, allowing the developer easy access in one array.
*
- * @return array
+ * @param string
+ * @return mixed
*/
- public function data()
+ public function data($index = NULL)
{
- return array (
- 'file_name' => $this->file_name,
- 'file_type' => $this->file_type,
- 'file_path' => $this->upload_path,
- 'full_path' => $this->upload_path.$this->file_name,
- 'raw_name' => str_replace($this->file_ext, '', $this->file_name),
- 'orig_name' => $this->orig_name,
- 'client_name' => $this->client_name,
- 'file_ext' => $this->file_ext,
- 'file_size' => $this->file_size,
- 'is_image' => $this->is_image(),
- 'image_width' => $this->image_width,
- 'image_height' => $this->image_height,
- 'image_type' => $this->image_type,
- 'image_size_str' => $this->image_size_str,
- );
+ $data = array(
+ 'file_name' => $this->file_name,
+ 'file_type' => $this->file_type,
+ 'file_path' => $this->upload_path,
+ 'full_path' => $this->upload_path.$this->file_name,
+ 'raw_name' => str_replace($this->file_ext, '', $this->file_name),
+ 'orig_name' => $this->orig_name,
+ 'client_name' => $this->client_name,
+ 'file_ext' => $this->file_ext,
+ 'file_size' => $this->file_size,
+ 'is_image' => $this->is_image(),
+ 'image_width' => $this->image_width,
+ 'image_height' => $this->image_height,
+ 'image_type' => $this->image_type,
+ 'image_size_str' => $this->image_size_str,
+ );
+
+ if ( ! empty($index))
+ {
+ return isset($data[$index]) ? $data[$index] : NULL;
+ }
+
+ return $data;
}
// --------------------------------------------------------------------
@@ -390,7 +414,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;
@@ -413,7 +437,7 @@ class CI_Upload {
}
}
- if ($new_filename == '')
+ if ($new_filename === '')
{
$this->set_error('upload_bad_filename');
return FALSE;
@@ -429,12 +453,12 @@ class CI_Upload {
/**
* Set Maximum File Size
*
- * @param integer
+ * @param int
* @return void
*/
public function set_max_filesize($n)
{
- $this->max_size = ((int) $n < 0) ? 0: (int) $n;
+ $this->max_size = ((int) $n < 0) ? 0 : (int) $n;
}
// --------------------------------------------------------------------
@@ -442,12 +466,12 @@ class CI_Upload {
/**
* Set Maximum File Name Length
*
- * @param integer
+ * @param int
* @return void
*/
public function set_max_filename($n)
{
- $this->max_filename = ((int) $n < 0) ? 0: (int) $n;
+ $this->max_filename = ((int) $n < 0) ? 0 : (int) $n;
}
// --------------------------------------------------------------------
@@ -455,12 +479,12 @@ class CI_Upload {
/**
* Set Maximum Image Width
*
- * @param integer
+ * @param int
* @return void
*/
public function set_max_width($n)
{
- $this->max_width = ((int) $n < 0) ? 0: (int) $n;
+ $this->max_width = ((int) $n < 0) ? 0 : (int) $n;
}
// --------------------------------------------------------------------
@@ -468,12 +492,12 @@ class CI_Upload {
/**
* Set Maximum Image Height
*
- * @param integer
+ * @param int
* @return void
*/
public function set_max_height($n)
{
- $this->max_height = ((int) $n < 0) ? 0: (int) $n;
+ $this->max_height = ((int) $n < 0) ? 0 : (int) $n;
}
// --------------------------------------------------------------------
@@ -486,7 +510,7 @@ class CI_Upload {
*/
public function set_allowed_types($types)
{
- if ( ! is_array($types) && $types == '*')
+ if ( ! is_array($types) && $types === '*')
{
$this->allowed_types = '*';
return;
@@ -517,10 +541,10 @@ class CI_Upload {
{
$types = array(1 => 'gif', 2 => 'jpeg', 3 => 'png');
- $this->image_width = $D['0'];
- $this->image_height = $D['1'];
- $this->image_type = ( ! isset($types[$D['2']])) ? 'unknown' : $types[$D['2']];
- $this->image_size_str = $D['3']; // string containing height and width
+ $this->image_width = $D[0];
+ $this->image_height = $D[1];
+ $this->image_type = isset($types[$D[2]]) ? $types[$D[2]] : 'unknown';
+ $this->image_size_str = $D[3]; // string containing height and width
}
}
}
@@ -538,7 +562,7 @@ class CI_Upload {
*/
public function set_xss_clean($flag = FALSE)
{
- $this->xss_clean = ($flag == TRUE) ? TRUE : FALSE;
+ $this->xss_clean = ($flag === TRUE);
}
// --------------------------------------------------------------------
@@ -560,19 +584,14 @@ class CI_Upload {
{
$this->file_type = 'image/png';
}
-
- if (in_array($this->file_type, $jpeg_mimes))
+ elseif (in_array($this->file_type, $jpeg_mimes))
{
$this->file_type = 'image/jpeg';
}
- $img_mimes = array(
- 'image/gif',
- 'image/jpeg',
- 'image/png',
- );
+ $img_mimes = array('image/gif', 'image/jpeg', 'image/png');
- return (in_array($this->file_type, $img_mimes, TRUE)) ? TRUE : FALSE;
+ return in_array($this->file_type, $img_mimes, TRUE);
}
// --------------------------------------------------------------------
@@ -580,16 +599,17 @@ class CI_Upload {
/**
* Verify that the filetype is allowed
*
+ * @param bool
* @return bool
*/
public function is_allowed_filetype($ignore_mime = FALSE)
{
- if ($this->allowed_types == '*')
+ if ($this->allowed_types === '*')
{
return TRUE;
}
- if (count($this->allowed_types) == 0 OR ! is_array($this->allowed_types))
+ if ( ! is_array($this->allowed_types) OR count($this->allowed_types) === 0)
{
$this->set_error('upload_no_file_types');
return FALSE;
@@ -605,12 +625,9 @@ class CI_Upload {
// Images get some additional checks
$image_types = array('gif', 'jpg', 'jpeg', 'png', 'jpe');
- if (in_array($ext, $image_types))
+ if (in_array($ext, $image_types) && @getimagesize($this->file_temp) === FALSE)
{
- if (getimagesize($this->file_temp) === FALSE)
- {
- return FALSE;
- }
+ return FALSE;
}
if ($ignore_mime === TRUE)
@@ -620,16 +637,13 @@ class CI_Upload {
$mime = $this->mimes_types($ext);
- if (is_array($mime))
+ if (is_array($mime) && in_array($this->file_type, $mime, TRUE))
{
- if (in_array($this->file_type, $mime, TRUE))
- {
- return TRUE;
- }
+ return TRUE;
}
- elseif ($mime == $this->file_type)
+ elseif ($mime === $this->file_type)
{
- return TRUE;
+ return TRUE;
}
return FALSE;
@@ -644,14 +658,7 @@ class CI_Upload {
*/
public function is_allowed_filesize()
{
- if ($this->max_size != 0 AND $this->file_size > $this->max_size)
- {
- return FALSE;
- }
- else
- {
- return TRUE;
- }
+ return ($this->max_size === 0 OR $this->max_size > $this->file_size);
}
// --------------------------------------------------------------------
@@ -672,17 +679,15 @@ class CI_Upload {
{
$D = @getimagesize($this->file_temp);
- if ($this->max_width > 0 AND $D['0'] > $this->max_width)
+ if ($this->max_width > 0 && $D[0] > $this->max_width)
{
return FALSE;
}
- if ($this->max_height > 0 AND $D['1'] > $this->max_height)
+ if ($this->max_height > 0 && $D[1] > $this->max_height)
{
return FALSE;
}
-
- return TRUE;
}
return TRUE;
@@ -695,20 +700,19 @@ class CI_Upload {
*
* Verifies that it is a valid upload path with proper permissions.
*
- *
* @return bool
*/
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') AND @realpath($this->upload_path) !== FALSE)
+ if (@realpath($this->upload_path) !== FALSE)
{
- $this->upload_path = str_replace("\\", "/", realpath($this->upload_path));
+ $this->upload_path = str_replace('\\', '/', realpath($this->upload_path));
}
if ( ! @is_dir($this->upload_path))
@@ -723,7 +727,7 @@ class CI_Upload {
return FALSE;
}
- $this->upload_path = preg_replace("/(.+?)\/*$/", "\\1/", $this->upload_path);
+ $this->upload_path = preg_replace('/(.+?)\/*$/', '\\1/', $this->upload_path);
return TRUE;
}
@@ -738,7 +742,7 @@ class CI_Upload {
public function get_extension($filename)
{
$x = explode('.', $filename);
- return '.'.end($x);
+ return (count($x) !== 1) ? '.'.end($x) : '';
}
// --------------------------------------------------------------------
@@ -752,37 +756,33 @@ class CI_Upload {
public function clean_file_name($filename)
{
$bad = array(
- "<!--",
- "-->",
- "'",
- "<",
- ">",
- '"',
- '&',
- '$',
- '=',
- ';',
- '?',
- '/',
- "%20",
- "%22",
- "%3c", // <
- "%253c", // <
- "%3e", // >
- "%0e", // >
- "%28", // (
- "%29", // )
- "%2528", // (
- "%26", // &
- "%24", // $
- "%3f", // ?
- "%3b", // ;
- "%3d" // =
- );
-
- $filename = str_replace($bad, '', $filename);
-
- return stripslashes($filename);
+ '<!--', '-->',
+ "'", '"',
+ '<', '>',
+ '&', '$',
+ '=',
+ ';',
+ '?',
+ '/',
+ '!',
+ '#',
+ '%20',
+ '%22',
+ '%3c', // <
+ '%253c', // <
+ '%3e', // >
+ '%0e', // >
+ '%28', // (
+ '%29', // )
+ '%2528', // (
+ '%26', // &
+ '%24', // $
+ '%3f', // ?
+ '%3b', // ;
+ '%3d' // =
+ );
+
+ return stripslashes(str_replace($bad, '', $filename));
}
// --------------------------------------------------------------------
@@ -831,23 +831,23 @@ 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
+ // 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
// IE can be fooled into mime-type detecting a malformed image as an html file, thus executing an XSS attack on anyone
- // using IE who looks at the image. It does this by inspecting the first 255 bytes of an image. To get around this
- // CI will itself look at the first 255 bytes of an image to determine its relative safety. This can save a lot of
+ // using IE who looks at the image. It does this by inspecting the first 255 bytes of an image. To get around this
+ // CI will itself look at the first 255 bytes of an image to determine its relative safety. This can save a lot of
// processor power and time if it is actually a clean image, as it will be in nearly all instances _except_ an
// attempted XSS attack.
@@ -865,10 +865,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)
@@ -897,14 +895,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);
}
@@ -921,13 +919,7 @@ class CI_Upload {
*/
public function display_errors($open = '<p>', $close = '</p>')
{
- $str = '';
- foreach ($this->error_msg as $val)
- {
- $str .= $open.$val.$close;
- }
-
- return $str;
+ return (count($this->error_msg) > 0) ? $open.implode($close.$open, $this->error_msg).$close : '';
}
// --------------------------------------------------------------------
@@ -935,7 +927,7 @@ class CI_Upload {
/**
* List of Mime Types
*
- * This is a list of mime types. We use it to validate
+ * This is a list of mime types. We use it to validate
* the "allowed types" set by the developer
*
* @param string
@@ -943,28 +935,7 @@ class CI_Upload {
*/
public function mimes_types($mime)
{
- global $mimes;
-
- if (count($this->mimes) == 0)
- {
- if (defined('ENVIRONMENT') AND 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;
- unset($mimes);
- }
-
- return ( ! isset($this->mimes[$mime])) ? FALSE : $this->mimes[$mime];
+ return isset($this->mimes[$mime]) ? $this->mimes[$mime] : FALSE;
}
// --------------------------------------------------------------------
@@ -980,7 +951,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;
}
@@ -1001,15 +972,130 @@ class CI_Upload {
}
}
- $filename .= '.'.$ext;
-
- return $filename;
+ return $filename.'.'.$ext;
}
// --------------------------------------------------------------------
+ /**
+ * File MIME type
+ *
+ * Detects the (actual) MIME type of the uploaded file, if possible.
+ * The input array is expected to be $_FILES[$field]
+ *
+ * @param array
+ * @return void
+ */
+ protected function _file_mime_type($file)
+ {
+ // We'll need this to validate the MIME info string (e.g. text/plain; charset=us-ascii)
+ $regexp = '/^([a-z\-]+\/[a-z0-9\-\.\+]+)(;\s.+)?$/';
+
+ /* Fileinfo extension - most reliable method
+ *
+ * Unfortunately, prior to PHP 5.3 - it's only available as a PECL extension and the
+ * more convenient FILEINFO_MIME_TYPE flag doesn't exist.
+ */
+ if (function_exists('finfo_file'))
+ {
+ $finfo = @finfo_open(FILEINFO_MIME);
+ if (is_resource($finfo)) // It is possible that a FALSE value is returned, if there is no magic MIME database file found on the system
+ {
+ $mime = @finfo_file($finfo, $file['tmp_name']);
+ finfo_close($finfo);
+
+ /* According to the comments section of the PHP manual page,
+ * it is possible that this function returns an empty string
+ * for some files (e.g. if they don't exist in the magic MIME database)
+ */
+ if (is_string($mime) && preg_match($regexp, $mime, $matches))
+ {
+ $this->file_type = $matches[1];
+ return;
+ }
+ }
+ }
+
+ /* This is an ugly hack, but UNIX-type systems provide a "native" way to detect the file type,
+ * which is still more secure than depending on the value of $_FILES[$field]['type'], and as it
+ * was reported in issue #750 (https://github.com/EllisLab/CodeIgniter/issues/750) - it's better
+ * than mime_content_type() as well, hence the attempts to try calling the command line with
+ * three different functions.
+ *
+ * Notes:
+ * - the DIRECTORY_SEPARATOR comparison ensures that we're not on a Windows system
+ * - many system admins would disable the exec(), shell_exec(), popen() and similar functions
+ * due to security concerns, hence the function_exists() checks
+ */
+ if (DIRECTORY_SEPARATOR !== '\\')
+ {
+ $cmd = function_exists('escapeshellarg')
+ ? 'file --brief --mime '.escapeshellarg($file['tmp_name']).' 2>&1'
+ : 'file --brief --mime '.$file['tmp_name'].' 2>&1';
+
+ if (function_exists('exec'))
+ {
+ /* This might look confusing, as $mime is being populated with all of the output when set in the second parameter.
+ * However, we only neeed the last line, which is the actual return value of exec(), and as such - it overwrites
+ * anything that could already be set for $mime previously. This effectively makes the second parameter a dummy
+ * value, which is only put to allow us to get the return status code.
+ */
+ $mime = @exec($cmd, $mime, $return_status);
+ if ($return_status === 0 && is_string($mime) && preg_match($regexp, $mime, $matches))
+ {
+ $this->file_type = $matches[1];
+ return;
+ }
+ }
+
+ if ( (bool) @ini_get('safe_mode') === FALSE && function_exists('shell_exec'))
+ {
+ $mime = @shell_exec($cmd);
+ if (strlen($mime) > 0)
+ {
+ $mime = explode("\n", trim($mime));
+ if (preg_match($regexp, $mime[(count($mime) - 1)], $matches))
+ {
+ $this->file_type = $matches[1];
+ return;
+ }
+ }
+ }
+
+ if (function_exists('popen'))
+ {
+ $proc = @popen($cmd, 'r');
+ if (is_resource($proc))
+ {
+ $mime = @fread($proc, 512);
+ @pclose($proc);
+ if ($mime !== FALSE)
+ {
+ $mime = explode("\n", trim($mime));
+ if (preg_match($regexp, $mime[(count($mime) - 1)], $matches))
+ {
+ $this->file_type = $matches[1];
+ return;
+ }
+ }
+ }
+ }
+ }
+
+ // Fall back to the deprecated mime_content_type(), if available (still better than $_FILES[$field]['type'])
+ if (function_exists('mime_content_type'))
+ {
+ $this->file_type = @mime_content_type($file['tmp_name']);
+ if (strlen($this->file_type) > 0) // It's possible that mime_content_type() returns FALSE or an empty string
+ {
+ return;
+ }
+ }
+
+ $this->file_type = $file['type'];
+ }
+
}
-// END Upload Class
/* End of file Upload.php */
/* Location: ./system/libraries/Upload.php */ \ No newline at end of file
diff --git a/system/libraries/User_agent.php b/system/libraries/User_agent.php
index 0b77a7d42..ff596f04b 100644
--- a/system/libraries/User_agent.php
+++ b/system/libraries/User_agent.php
@@ -1,59 +1,153 @@
-<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
+<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* CodeIgniter
*
- * An open source application development framework for PHP 5.1.6 or newer
+ * An open source application development framework for PHP 5.2.4 or newer
+ *
+ * NOTICE OF LICENSE
+ *
+ * Licensed under the Open Software License version 3.0
+ *
+ * This source file is subject to the Open Software License (OSL 3.0) that is
+ * bundled with this package in the files license.txt / license.rst. It is
+ * also available through the world wide web at this URL:
+ * http://opensource.org/licenses/OSL-3.0
+ * If you did not receive a copy of the license and are unable to obtain it
+ * through the world wide web, please send an email to
+ * licensing@ellislab.com so we can send you a copy immediately.
*
* @package CodeIgniter
- * @author ExpressionEngine Dev Team
- * @copyright Copyright (c) 2008 - 2011, EllisLab, Inc.
- * @license http://codeigniter.com/user_guide/license.html
+ * @author EllisLab Dev Team
+ * @copyright Copyright (c) 2008 - 2012, EllisLab, Inc. (http://ellislab.com/)
+ * @license http://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
* @link http://codeigniter.com
* @since Version 1.0
* @filesource
*/
-// ------------------------------------------------------------------------
-
/**
* User Agent Class
*
- * Identifies the platform, browser, robot, or mobile devise of the browsing agent
+ * Identifies the platform, browser, robot, or mobile device of the browsing agent
*
* @package CodeIgniter
* @subpackage Libraries
* @category User Agent
- * @author ExpressionEngine Dev Team
+ * @author EllisLab Dev Team
* @link http://codeigniter.com/user_guide/libraries/user_agent.html
*/
class CI_User_agent {
- var $agent = NULL;
+ /**
+ * Current user-agent
+ *
+ * @var string
+ */
+ public $agent = NULL;
- var $is_browser = FALSE;
- var $is_robot = FALSE;
- var $is_mobile = FALSE;
+ /**
+ * Flag for if the user-agent belongs to a browser
+ *
+ * @var bool
+ */
+ public $is_browser = FALSE;
- var $languages = array();
- var $charsets = array();
+ /**
+ * Flag for if the user-agent is a robot
+ *
+ * @var bool
+ */
+ public $is_robot = FALSE;
- var $platforms = array();
- var $browsers = array();
- var $mobiles = array();
- var $robots = array();
+ /**
+ * Flag for if the user-agent is a mobile browser
+ *
+ * @var bool
+ */
+ public $is_mobile = FALSE;
- var $platform = '';
- var $browser = '';
- var $version = '';
- var $mobile = '';
- var $robot = '';
+ /**
+ * 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 = '';
+
+ /**
+ * Current user-agent browser
+ *
+ * @var string
+ */
+ public $browser = '';
+
+ /**
+ * Current user-agent version
+ *
+ * @var string
+ */
+ public $version = '';
+
+ /**
+ * Current user-agent mobile name
+ *
+ * @var string
+ */
+ public $mobile = '';
+
+ /**
+ * Current user-agent robot name
+ *
+ * @var string
+ */
+ public $robot = '';
/**
* Constructor
*
* Sets the User Agent and runs the compilation routine
*
- * @access public
* @return void
*/
public function __construct()
@@ -63,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');
}
// --------------------------------------------------------------------
@@ -79,12 +170,11 @@ class CI_User_agent {
/**
* Compile the User Agent Data
*
- * @access private
* @return bool
*/
- private function _load_agent_file()
+ 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');
}
@@ -135,10 +225,9 @@ class CI_User_agent {
/**
* Compile the User Agent Data
*
- * @access private
* @return bool
*/
- private function _compile_data()
+ protected function _compile_data()
{
$this->_set_platform();
@@ -156,23 +245,24 @@ class CI_User_agent {
/**
* Set the Platform
*
- * @access private
- * @return mixed
+ * @return bool
*/
- private function _set_platform()
+ 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;
}
// --------------------------------------------------------------------
@@ -180,16 +270,15 @@ class CI_User_agent {
/**
* Set the Browser
*
- * @access private
* @return bool
*/
- private function _set_browser()
+ 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];
@@ -199,6 +288,7 @@ class CI_User_agent {
}
}
}
+
return FALSE;
}
@@ -207,16 +297,15 @@ class CI_User_agent {
/**
* Set the Robot
*
- * @access private
* @return bool
*/
- private function _set_robot()
+ 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;
@@ -224,6 +313,7 @@ class CI_User_agent {
}
}
}
+
return FALSE;
}
@@ -232,16 +322,15 @@ class CI_User_agent {
/**
* Set the Mobile Device
*
- * @access private
* @return bool
*/
- private function _set_mobile()
+ 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;
@@ -249,6 +338,7 @@ class CI_User_agent {
}
}
}
+
return FALSE;
}
@@ -257,19 +347,16 @@ class CI_User_agent {
/**
* Set the accepted languages
*
- * @access private
* @return void
*/
- private function _set_languages()
+ 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']))
{
- $languages = preg_replace('/(;q=[0-9\.]+)/i', '', strtolower(trim($_SERVER['HTTP_ACCEPT_LANGUAGE'])));
-
- $this->languages = explode(',', $languages);
+ $this->languages = explode(',', preg_replace('/(;q=[0-9\.]+)/i', '', strtolower(trim($_SERVER['HTTP_ACCEPT_LANGUAGE']))));
}
- if (count($this->languages) == 0)
+ if (count($this->languages) === 0)
{
$this->languages = array('Undefined');
}
@@ -280,19 +367,16 @@ class CI_User_agent {
/**
* Set the accepted character sets
*
- * @access private
* @return void
*/
- private function _set_charsets()
+ 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']))
{
- $charsets = preg_replace('/(;q=.+)/i', '', strtolower(trim($_SERVER['HTTP_ACCEPT_CHARSET'])));
-
- $this->charsets = explode(',', $charsets);
+ $this->charsets = explode(',', preg_replace('/(;q=.+)/i', '', strtolower(trim($_SERVER['HTTP_ACCEPT_CHARSET']))));
}
- if (count($this->charsets) == 0)
+ if (count($this->charsets) === 0)
{
$this->charsets = array('Undefined');
}
@@ -303,7 +387,7 @@ class CI_User_agent {
/**
* Is Browser
*
- * @access public
+ * @param string $key
* @return bool
*/
public function is_browser($key = NULL)
@@ -320,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]);
}
// --------------------------------------------------------------------
@@ -328,7 +412,7 @@ class CI_User_agent {
/**
* Is Robot
*
- * @access public
+ * @param string $key
* @return bool
*/
public function is_robot($key = NULL)
@@ -345,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]);
}
// --------------------------------------------------------------------
@@ -353,7 +437,7 @@ class CI_User_agent {
/**
* Is Mobile
*
- * @access public
+ * @param string $key
* @return bool
*/
public function is_mobile($key = NULL)
@@ -370,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,16 +462,11 @@ class CI_User_agent {
/**
* Is this a referral from another site?
*
- * @access public
* @return bool
*/
public function is_referral()
{
- if ( ! isset($_SERVER['HTTP_REFERER']) OR $_SERVER['HTTP_REFERER'] == '')
- {
- return FALSE;
- }
- return TRUE;
+ return ! empty($_SERVER['HTTP_REFERER']);
}
// --------------------------------------------------------------------
@@ -395,7 +474,6 @@ class CI_User_agent {
/**
* Agent String
*
- * @access public
* @return string
*/
public function agent_string()
@@ -408,7 +486,6 @@ class CI_User_agent {
/**
* Get Platform
*
- * @access public
* @return string
*/
public function platform()
@@ -421,7 +498,6 @@ class CI_User_agent {
/**
* Get Browser Name
*
- * @access public
* @return string
*/
public function browser()
@@ -434,7 +510,6 @@ class CI_User_agent {
/**
* Get the Browser Version
*
- * @access public
* @return string
*/
public function version()
@@ -447,7 +522,6 @@ class CI_User_agent {
/**
* Get The Robot Name
*
- * @access public
* @return string
*/
public function robot()
@@ -459,7 +533,6 @@ class CI_User_agent {
/**
* Get the Mobile Device
*
- * @access public
* @return string
*/
public function mobile()
@@ -472,12 +545,11 @@ class CI_User_agent {
/**
* Get the referrer
*
- * @access public
* @return bool
*/
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']);
}
// --------------------------------------------------------------------
@@ -485,12 +557,11 @@ class CI_User_agent {
/**
* Get the accepted languages
*
- * @access public
* @return array
*/
public function languages()
{
- if (count($this->languages) == 0)
+ if (count($this->languages) === 0)
{
$this->_set_languages();
}
@@ -503,12 +574,11 @@ class CI_User_agent {
/**
* Get the accepted Character Sets
*
- * @access public
* @return array
*/
public function charsets()
{
- if (count($this->charsets) == 0)
+ if (count($this->charsets) === 0)
{
$this->_set_charsets();
}
@@ -521,12 +591,12 @@ class CI_User_agent {
/**
* Test for a particular language
*
- * @access public
+ * @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);
}
// --------------------------------------------------------------------
@@ -534,16 +604,15 @@ class CI_User_agent {
/**
* Test for a particular character set
*
- * @access public
+ * @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 */ \ No newline at end of file
diff --git a/system/libraries/Xmlrpc.php b/system/libraries/Xmlrpc.php
index 5da6ea6ae..cbb91c40a 100644
--- a/system/libraries/Xmlrpc.php
+++ b/system/libraries/Xmlrpc.php
@@ -1,77 +1,93 @@
-<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
+<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* CodeIgniter
*
- * An open source application development framework for PHP 5.1.6 or newer
+ * An open source application development framework for PHP 5.2.4 or newer
+ *
+ * NOTICE OF LICENSE
+ *
+ * Licensed under the Open Software License version 3.0
+ *
+ * This source file is subject to the Open Software License (OSL 3.0) that is
+ * bundled with this package in the files license.txt / license.rst. It is
+ * also available through the world wide web at this URL:
+ * http://opensource.org/licenses/OSL-3.0
+ * If you did not receive a copy of the license and are unable to obtain it
+ * through the world wide web, please send an email to
+ * licensing@ellislab.com so we can send you a copy immediately.
*
* @package CodeIgniter
- * @author ExpressionEngine Dev Team
- * @copyright Copyright (c) 2008 - 2011, EllisLab, Inc.
- * @license http://codeigniter.com/user_guide/license.html
+ * @author EllisLab Dev Team
+ * @copyright Copyright (c) 2008 - 2012, EllisLab, Inc. (http://ellislab.com/)
+ * @license http://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
* @link http://codeigniter.com
* @since Version 1.0
* @filesource
*/
-if ( ! function_exists('xml_parser_create'))
-{
- show_error('Your PHP installation does not support XML');
-}
-
-
-// ------------------------------------------------------------------------
-
/**
* XML-RPC request handler class
*
* @package CodeIgniter
* @subpackage Libraries
* @category XML-RPC
- * @author ExpressionEngine Dev Team
+ * @author EllisLab Dev Team
* @link http://codeigniter.com/user_guide/libraries/xmlrpc.html
*/
-class CI_Xmlrpc {
- var $debug = FALSE; // Debugging on or off
- var $xmlrpcI4 = 'i4';
- var $xmlrpcInt = 'int';
- var $xmlrpcBoolean = 'boolean';
- var $xmlrpcDouble = 'double';
- var $xmlrpcString = 'string';
- var $xmlrpcDateTime = 'dateTime.iso8601';
- var $xmlrpcBase64 = 'base64';
- var $xmlrpcArray = 'array';
- var $xmlrpcStruct = 'struct';
-
- var $xmlrpcTypes = array();
- var $valid_parents = array();
- var $xmlrpcerr = array(); // Response numbers
- var $xmlrpcstr = array(); // Response strings
-
- var $xmlrpc_defencoding = 'UTF-8';
- var $xmlrpcName = 'XML-RPC for CodeIgniter';
- var $xmlrpcVersion = '1.1';
- var $xmlrpcerruser = 800; // Start of user errors
- var $xmlrpcerrxml = 100; // Start of XML Parse errors
- var $xmlrpc_backslash = ''; // formulate backslashes for escaping regexp
-
- var $client;
- var $method;
- var $data;
- var $message = '';
- var $error = ''; // Error string for request
- var $result;
- var $response = array(); // Response from remote server
-
- var $xss_clean = TRUE;
-
- //-------------------------------------
- // VALUES THAT MULTIPLE CLASSES NEED
- //-------------------------------------
+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
+ public $xmlrpcI4 = 'i4';
+ public $xmlrpcInt = 'int';
+ public $xmlrpcBoolean = 'boolean';
+ public $xmlrpcDouble = 'double';
+ public $xmlrpcString = 'string';
+ public $xmlrpcDateTime = 'dateTime.iso8601';
+ public $xmlrpcBase64 = 'base64';
+ public $xmlrpcArray = 'array';
+ public $xmlrpcStruct = 'struct';
+
+ public $xmlrpcTypes = array();
+ public $valid_parents = array();
+ public $xmlrpcerr = array(); // Response numbers
+ public $xmlrpcstr = array(); // Response strings
+
+ public $xmlrpc_defencoding = 'UTF-8';
+ public $xmlrpcName = 'XML-RPC for CodeIgniter';
+ public $xmlrpcVersion = '1.1';
+ public $xmlrpcerruser = 800; // Start of user errors
+ public $xmlrpcerrxml = 100; // Start of XML Parse errors
+ public $xmlrpc_backslash = ''; // formulate backslashes for escaping regexp
+
+ public $client;
+ public $method;
+ public $data;
+ public $message = '';
+ public $error = ''; // Error string for request
+ public $result;
+ public $response = array(); // Response from remote server
+
+ public $xss_clean = TRUE;
+
+
+ /**
+ * 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
@@ -88,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
@@ -116,7 +132,7 @@ class CI_Xmlrpc {
$this->xmlrpcerr['incorrect_params'] = '3';
$this->xmlrpcstr['incorrect_params'] = 'Incorrect parameters were passed to method';
$this->xmlrpcerr['introspect_unknown'] = '4';
- $this->xmlrpcstr['introspect_unknown'] = "Cannot inspect signature for request: method unknown";
+ $this->xmlrpcstr['introspect_unknown'] = 'Cannot inspect signature for request: method unknown';
$this->xmlrpcerr['http_error'] = '5';
$this->xmlrpcstr['http_error'] = "Did not receive a '200 OK' response from remote server.";
$this->xmlrpcerr['no_data'] = '6';
@@ -124,15 +140,18 @@ class CI_Xmlrpc {
$this->initialize($config);
- log_message('debug', "XML-RPC Class Initialized");
+ log_message('debug', 'XML-RPC Class Initialized');
}
+ // --------------------------------------------------------------------
- //-------------------------------------
- // Initialize Prefs
- //-------------------------------------
-
- function initialize($config = array())
+ /**
+ * Initialize
+ *
+ * @param array
+ * @return void
+ */
+ public function initialize($config = array())
{
if (count($config) > 0)
{
@@ -145,64 +164,78 @@ class CI_Xmlrpc {
}
}
}
- // END
- //-------------------------------------
- // Take URL and parse it
- //-------------------------------------
+ // --------------------------------------------------------------------
- function server($url, $port=80)
+ /**
+ * Parse server URL
+ *
+ * @param string url
+ * @param int port
+ * @return void
+ */
+ public function server($url, $port = 80, $proxy = FALSE, $proxy_port = 8080)
{
- if (substr($url, 0, 4) != "http")
+ 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);
+ $this->client = new XML_RPC_Client($path, $parts['host'], $port, $proxy, $proxy_port);
}
- // END
- //-------------------------------------
- // Set Timeout
- //-------------------------------------
+ // --------------------------------------------------------------------
- function timeout($seconds=5)
+ /**
+ * Set Timeout
+ *
+ * @param int seconds
+ * @return void
+ */
+ public function timeout($seconds = 5)
{
if ( ! is_null($this->client) && is_int($seconds))
{
$this->client->timeout = $seconds;
}
}
- // END
- //-------------------------------------
- // Set Methods
- //-------------------------------------
+ // --------------------------------------------------------------------
- function method($function)
+ /**
+ * Set Methods
+ *
+ * @param string method name
+ * @return void
+ */
+ public function method($function)
{
$this->method = $function;
}
- // END
- //-------------------------------------
- // Take Array of Data and Create Objects
- //-------------------------------------
+ // --------------------------------------------------------------------
- function request($incoming)
+ /**
+ * 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();
@@ -212,49 +245,47 @@ class CI_Xmlrpc {
$this->data[$key] = $this->values_parsing($value);
}
}
- // END
+ // --------------------------------------------------------------------
- //-------------------------------------
- // Set Debug
- //-------------------------------------
-
- function set_debug($flag = TRUE)
+ /**
+ * Set Debug
+ *
+ * @param bool
+ * @return void
+ */
+ public function set_debug($flag = TRUE)
{
- $this->debug = ($flag == TRUE) ? TRUE : FALSE;
+ $this->debug = ($flag === TRUE);
}
- //-------------------------------------
- // Values Parsing
- //-------------------------------------
+ // --------------------------------------------------------------------
- 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]]))
{
- if (is_array($value[0]))
- {
- $temp = new XML_RPC_Values($value['0'], 'array');
- }
- else
- {
- $temp = new XML_RPC_Values($value['0'], 'string');
- }
+ $temp = new XML_RPC_Values($value[0], (is_array($value[0]) ? 'array' : 'string'));
}
- elseif (is_array($value['0']) && ($value['1'] == 'struct' OR $value['1'] == 'array'))
+ else
{
- while (list($k) = each($value['0']))
+ if (is_array($value[0]) && ($value[1] === 'struct' OR $value[1] === 'array'))
{
- $value['0'][$k] = $this->values_parsing($value['0'][$k], TRUE);
+ while (list($k) = each($value[0]))
+ {
+ $value[0][$k] = $this->values_parsing($value[0][$k], TRUE);
+ }
}
- $temp = new XML_RPC_Values($value['0'], $value['1']);
- }
- else
- {
- $temp = new XML_RPC_Values($value['0'], $value['1']);
+ $temp = new XML_RPC_Values($value[0], $value[1]);
}
}
else
@@ -264,132 +295,168 @@ class CI_Xmlrpc {
return $temp;
}
- // END
-
- //-------------------------------------
- // Sends XML-RPC Request
- //-------------------------------------
+ // --------------------------------------------------------------------
- function send_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))
- {
- $this->error = $this->result->errstr;
- return FALSE;
- }
- elseif ( ! is_object($this->result->val))
+ if ( ! $this->result = $this->client->send($this->message) OR ! is_object($this->result->val))
{
$this->error = $this->result->errstr;
return FALSE;
}
$this->response = $this->result->decode();
-
return TRUE;
}
- // END
- //-------------------------------------
- // Returns Error
- //-------------------------------------
+ // --------------------------------------------------------------------
- function display_error()
+ /**
+ * Returns Error
+ *
+ * @return string
+ */
+ public function display_error()
{
return $this->error;
}
- // END
- //-------------------------------------
- // Returns Remote Server Response
- //-------------------------------------
+ // --------------------------------------------------------------------
- function display_response()
+ /**
+ * Returns Remote Server Response
+ *
+ * @return string
+ */
+ public function display_response()
{
return $this->response;
}
- // END
- //-------------------------------------
- // Sends an Error Message for Server Request
- //-------------------------------------
+ // --------------------------------------------------------------------
- function send_error_message($number, $message)
+ /**
+ * 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);
+ return new XML_RPC_Response(0, $number, $message);
}
- // END
+ // --------------------------------------------------------------------
- //-------------------------------------
- // Send Response for Server Request
- //-------------------------------------
-
- function send_response($response)
+ /**
+ * 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
-
- $response = $this->values_parsing($response);
-
- return new XML_RPC_Response($response);
+ return new XML_RPC_Response($this->values_parsing($response));
}
- // END
} // END XML_RPC Class
-
-
/**
* XML-RPC Client class
*
* @category XML-RPC
- * @author ExpressionEngine Dev Team
+ * @author EllisLab Dev Team
* @link http://codeigniter.com/user_guide/libraries/xmlrpc.html
*/
class XML_RPC_Client extends CI_Xmlrpc
{
- var $path = '';
- var $server = '';
- var $port = 80;
- var $errno = '';
- var $errstring = '';
- var $timeout = 5;
- var $no_multicall = FALSE;
-
- public function __construct($path, $server, $port=80)
+ public $path = '';
+ public $server = '';
+ public $port = 80;
+ public $proxy = FALSE;
+ public $proxy_port = 8080;
+ public $errno = '';
+ public $errstring = '';
+ public $timeout = 5;
+ public $no_multicall = FALSE;
+
+ /**
+ * Constructor
+ *
+ * @param string
+ * @param object
+ * @param int
+ * @return void
+ */
+ public function __construct($path, $server, $port = 80, $proxy = FALSE, $proxy_port = 8080)
{
parent::__construct();
$this->port = $port;
$this->server = $server;
$this->path = $path;
+ $this->proxy = $proxy;
+ $this->proxy_port = $proxy_port;
}
- function send($msg)
+ // --------------------------------------------------------------------
+
+ /**
+ * 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);
}
- function sendPayload($msg)
+ // --------------------------------------------------------------------
+
+ /**
+ * Send payload
+ *
+ * @param object
+ * @return object
+ */
+ public function sendPayload($msg)
{
- $fp = @fsockopen($this->server, $this->port,$this->errno, $this->errstr, $this->timeout);
+ if ($this->proxy === FALSE)
+ {
+ $server = $this->server;
+ $port = $this->port;
+ }
+ else
+ {
+ $server = $this->proxy;
+ $port = $this->proxy_port;
+ }
+
+ $fp = @fsockopen($server, $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))
@@ -399,55 +466,63 @@ class XML_RPC_Client extends CI_Xmlrpc
}
$r = "\r\n";
- $op = "POST {$this->path} HTTP/1.0$r";
- $op .= "Host: {$this->server}$r";
- $op .= "Content-Type: text/xml$r";
- $op .= "User-Agent: {$this->xmlrpcName}$r";
- $op .= "Content-Length: ".strlen($msg->payload). "$r$r";
- $op .= $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
*
* @category XML-RPC
- * @author ExpressionEngine Dev Team
+ * @author EllisLab Dev Team
* @link http://codeigniter.com/user_guide/libraries/xmlrpc.html
*/
class XML_RPC_Response
{
- var $val = 0;
- var $errno = 0;
- var $errstr = '';
- var $headers = array();
- var $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;
- $this->errstr = htmlentities($fstr);
+ $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
@@ -456,56 +531,84 @@ class XML_RPC_Response
}
}
- function faultCode()
+ // --------------------------------------------------------------------
+
+ /**
+ * Fault code
+ *
+ * @return int
+ */
+ public function faultCode()
{
return $this->errno;
}
- function faultString()
+ // --------------------------------------------------------------------
+
+ /**
+ * Fault string
+ *
+ * @return string
+ */
+ public function faultString()
{
return $this->errstr;
}
- function value()
+ // --------------------------------------------------------------------
+
+ /**
+ * Value
+ *
+ * @return mixed
+ */
+ public function value()
{
return $this->val;
}
- function prepare_response()
+ // --------------------------------------------------------------------
+
+ /**
+ * Prepare response
+ *
+ * @return string xml
+ */
+ public function prepare_response()
{
- $result = "<methodResponse>\n";
- if ($this->errno)
- {
- $result .= '<fault>
+ return "<methodResponse>\n"
+ .($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>';
- }
- else
- {
- $result .= "<params>\n<param>\n" .
- $this->val->serialize_class() .
- "</param>\n</params>";
- }
- $result .= "\n</methodResponse>";
- return $result;
+</fault>'
+ : "<params>\n<param>\n".$this->val->serialize_class()."</param>\n</params>")
+ ."\n</methodResponse>";
}
- function decode($array=FALSE)
+ // --------------------------------------------------------------------
+
+ /**
+ * Decode
+ *
+ * @param mixed
+ * @return array
+ */
+ public function decode($array = FALSE)
{
$CI =& get_instance();
-
- if ($array !== FALSE && is_array($array))
+
+ if (is_array($array))
{
while (list($key) = each($array))
{
@@ -519,54 +622,52 @@ 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
- //-------------------------------------
-
- function xmlrpc_decoder($xmlrpc_val)
+ /**
+ * 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);
- list($a,$b) = each($xmlrpc_val->me);
- $size = count($b);
-
+ $b = current($xmlrpc_val->me);
$arr = array();
- for ($i = 0; $i < $size; $i++)
+ for ($i = 0, $size = count($b); $i < $size; $i++)
{
$arr[] = $this->xmlrpc_decoder($xmlrpc_val->me['array'][$i]);
}
return $arr;
}
- elseif ($kind == 'struct')
+ elseif ($kind === 'struct')
{
reset($xmlrpc_val->me['struct']);
$arr = array();
@@ -579,49 +680,58 @@ class XML_RPC_Response
}
}
+ // --------------------------------------------------------------------
- //-------------------------------------
- // ISO-8601 time to server or UTC time
- //-------------------------------------
-
- 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
*
* @category XML-RPC
- * @author ExpressionEngine Dev Team
+ * @author EllisLab Dev Team
* @link http://codeigniter.com/user_guide/libraries/xmlrpc.html
*/
class XML_RPC_Message extends CI_Xmlrpc
{
- var $payload;
- var $method_name;
- var $params = array();
- var $xh = array();
-
- public function __construct($method, $pars=0)
+ public $payload;
+ public $method_name;
+ public $params = array();
+ public $xh = array();
+
+ /**
+ * Constructor
+ *
+ * @param string method name
+ * @param array
+ * @return void
+ */
+ public function __construct($method, $pars = FALSE)
{
parent::__construct();
$this->method_name = $method;
if (is_array($pars) && count($pars) > 0)
{
- for ($i=0; $i<count($pars); $i++)
+ for ($i = 0, $c = count($pars); $i < $c; $i++)
{
// $pars[$i] = XML_RPC_Values
$this->params[] = $pars[$i];
@@ -629,17 +739,20 @@ class XML_RPC_Message extends CI_Xmlrpc
}
}
- //-------------------------------------
- // Create Payload to Send
- //-------------------------------------
+ // --------------------------------------------------------------------
- function createPayload()
+ /**
+ * Create Payload to Send
+ *
+ * @return void
+ */
+ public function createPayload()
{
- $this->payload = "<?xml version=\"1.0\"?".">\r\n<methodCall>\r\n";
- $this->payload .= '<methodName>' . $this->method_name . "</methodName>\r\n";
- $this->payload .= "<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; $i<count($this->params); $i++)
+ for ($i = 0, $c = count($this->params); $i < $c; $i++)
{
// $p = XML_RPC_Values
$p = $this->params[$i];
@@ -649,11 +762,15 @@ class XML_RPC_Message extends CI_Xmlrpc
$this->payload .= "</params>\r\n</methodCall>\r\n";
}
- //-------------------------------------
- // Parse External XML-RPC Server's Response
- //-------------------------------------
+ // --------------------------------------------------------------------
- function parseResponse($fp)
+ /**
+ * Parse External XML-RPC Server's Response
+ *
+ * @param resource
+ * @return object
+ */
+ public function parseResponse($fp)
{
$data = '';
@@ -662,38 +779,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>";
- echo "---DATA---\n" . htmlspecialchars($data) . "\n---END DATA---\n\n";
- echo "</pre>";
+ echo "<pre>---DATA---\n".htmlspecialchars($data)."\n---END DATA---\n\n</pre>";
}
- //-------------------------------------
- // Check for data
- //-------------------------------------
-
- if ($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
- //-------------------------------------
-
- if (strncmp($data, 'HTTP', 4) == 0 && ! preg_match('/^HTTP\/[0-9\.]+ 200 /', $data))
+ // Check for HTTP 200 Response
+ if (strpos($data, 'HTTP') === 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.')');
}
//-------------------------------------
@@ -702,25 +805,22 @@ class XML_RPC_Message extends CI_Xmlrpc
$parser = xml_parser_create($this->xmlrpc_defencoding);
- $this->xh[$parser] = array();
- $this->xh[$parser]['isf'] = 0;
- $this->xh[$parser]['ac'] = '';
- $this->xh[$parser]['headers'] = array();
- $this->xh[$parser]['stack'] = array();
- $this->xh[$parser]['valuestack'] = array();
- $this->xh[$parser]['isf_reason'] = 0;
+ $this->xh[$parser] = array(
+ '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)))
{
@@ -732,16 +832,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);
@@ -749,66 +845,50 @@ 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)
{
- echo "---Invalid Return---\n";
- echo $this->xh[$parser]['isf_reason'];
- echo "---Invalid Return---\n\n";
+ 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";
}
- echo "---DATA---\n" . htmlspecialchars($data) . "\n---END DATA---\n\n";
-
- echo "---PARSED---\n" ;
+ echo "---DATA---\n".htmlspecialchars($data)."\n---END DATA---\n\n---PARSED---\n";
var_dump($this->xh[$parser]['value']);
echo "\n---END PARSED---</pre>";
}
- //-------------------------------------
- // SEND RESPONSE
- //-------------------------------------
-
+ // Send response
$v = $this->xh[$parser]['value'];
-
if ($this->xh[$parser]['isf'])
{
$errno_v = $v->me['struct']['faultCode'];
$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;
@@ -825,6 +905,8 @@ class XML_RPC_Message extends CI_Xmlrpc
return $r;
}
+ // --------------------------------------------------------------------
+
// ------------------------------------
// Begin Return Message Parsing section
// ------------------------------------
@@ -839,63 +921,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
- //-------------------------------------
+ // --------------------------------------------------------------------
- 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':
@@ -903,70 +983,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
- //-------------------------------------
-
- function closing_tag($the_parser, $name)
+ /**
+ * 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':
@@ -976,60 +1060,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')
@@ -1041,7 +1108,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;
@@ -1051,57 +1118,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
- //-------------------------------------
+ // --------------------------------------------------------------------
- function character_data($the_parser, $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'] = '';
}
@@ -1110,14 +1182,32 @@ class XML_RPC_Message extends CI_Xmlrpc
}
}
+ // --------------------------------------------------------------------
+
+ /**
+ * Add parameter
+ *
+ * @param mixed
+ * @return void
+ */
+ public function addParam($par)
+ {
+ $this->params[] = $par;
+ }
- function addParam($par) { $this->params[]=$par; }
+ // --------------------------------------------------------------------
- function output_parameters($array=FALSE)
+ /**
+ * Output parameters
+ *
+ * @param array
+ * @return array
+ */
+ public function output_parameters($array = FALSE)
{
$CI =& get_instance();
-
- if ($array !== FALSE && is_array($array))
+
+ if (is_array($array))
{
while (list($key) = each($array))
{
@@ -1129,61 +1219,64 @@ 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; $i < count($this->params); $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;
}
+ // --------------------------------------------------------------------
- function decode_message($param)
+ /**
+ * 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);
- list($a,$b) = each($param->me);
-
+ $b = current($param->me);
$arr = array();
- for($i = 0; $i < count($b); $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();
while (list($key,$value) = each($param->me['struct']))
@@ -1195,74 +1288,81 @@ class XML_RPC_Message extends CI_Xmlrpc
}
}
-} // End XML_RPC_Messages class
-
-
+} // END XML_RPC_Message Class
/**
* XML-RPC Values class
*
* @category XML-RPC
- * @author ExpressionEngine Dev Team
+ * @author EllisLab Dev Team
* @link http://codeigniter.com/user_guide/libraries/xmlrpc.html
*/
class XML_RPC_Values extends CI_Xmlrpc
{
- var $me = array();
- var $mytype = 0;
-
- public function __construct($val=-1, $type='')
+ 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);
}
}
}
- function addScalar($val, $type='string')
+ // --------------------------------------------------------------------
+
+ /**
+ * 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)
{
- if (strcasecmp($val,'true')==0 OR $val==1 OR ($val==true && strcasecmp($val,'false')))
- {
- $val = 1;
- }
- else
- {
- $val=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'];
@@ -1275,12 +1375,21 @@ class XML_RPC_Values extends CI_Xmlrpc
$this->me[$type] = $val;
$this->mytype = $typeof;
}
+
return 1;
}
- function addArray($vals)
+ // --------------------------------------------------------------------
+
+ /**
+ * 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;
@@ -1291,9 +1400,17 @@ class XML_RPC_Values extends CI_Xmlrpc
return 1;
}
- function addStruct($vals)
+ // --------------------------------------------------------------------
+
+ /**
+ * 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;
@@ -1303,29 +1420,37 @@ class XML_RPC_Values extends CI_Xmlrpc
return 1;
}
- function kindOf()
+ // --------------------------------------------------------------------
+
+ /**
+ * 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';
}
}
- function serializedata($typ, $val)
+ // --------------------------------------------------------------------
+
+ /**
+ * Serialize data
+ *
+ * @param string
+ * @param mixed
+ */
+ public function serializedata($typ, $val)
{
$rs = '';
- switch($this->xmlrpcTypes[$typ])
+ switch ($this->xmlrpcTypes[$typ])
{
case 3:
// struct
@@ -1333,91 +1458,101 @@ class XML_RPC_Values extends CI_Xmlrpc
reset($val);
while (list($key2, $val2) = each($val))
{
- $rs .= "<member>\n<name>{$key2}</name>\n";
- $rs .= $this->serializeval($val2);
- $rs .= "</member>\n";
+ $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; $i < count($val); $i++)
+ for ($i = 0, $c = count($val); $i < $c; $i++)
{
$rs .= $this->serializeval($val[$i]);
}
- $rs.="</data>\n</array>\n";
+ $rs .= "</data>\n</array>\n";
break;
case 1:
// others
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;
}
- function serialize_class()
+ // --------------------------------------------------------------------
+
+ /**
+ * Serialize class
+ *
+ * @return string
+ */
+ public function serialize_class()
{
return $this->serializeval($this);
}
- function serializeval($o)
+ // --------------------------------------------------------------------
+
+ /**
+ * Serialize value
+ *
+ * @param object
+ * @return string
+ */
+ public function serializeval($o)
{
$ar = $o->me;
reset($ar);
list($typ, $val) = each($ar);
- $rs = "<value>\n".$this->serializedata($typ, $val)."</value>\n";
- return $rs;
+ return "<value>\n".$this->serializedata($typ, $val)."</value>\n";
}
- function scalarval()
+ // --------------------------------------------------------------------
+
+ /**
+ * Scalar value
+ *
+ * @return mixed
+ */
+ public function scalarval()
{
reset($this->me);
- list($a,$b) = each($this->me);
- return $b;
+ return current($this->me);
}
-
- //-------------------------------------
- // Encode time in ISO-8601 form.
- //-------------------------------------
-
- // Useful for sending time in XML-RPC
-
- 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)
{
- if ($utc == 1)
- {
- $t = strftime("%Y%m%dT%H:%M:%S", $time);
- }
- else
- {
- if (function_exists('gmstrftime'))
- $t = gmstrftime("%Y%m%dT%H:%M:%S", $time);
- else
- $t = strftime("%Y%m%dT%H:%M:%S", $time - date('Z'));
- }
- return $t;
+ 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 */ \ No newline at end of file
diff --git a/system/libraries/Xmlrpcs.php b/system/libraries/Xmlrpcs.php
index 9cd332147..5d01d374d 100644
--- a/system/libraries/Xmlrpcs.php
+++ b/system/libraries/Xmlrpcs.php
@@ -1,13 +1,25 @@
-<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
+<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* CodeIgniter
*
- * An open source application development framework for PHP 5.1.6 or newer
+ * An open source application development framework for PHP 5.2.4 or newer
+ *
+ * NOTICE OF LICENSE
+ *
+ * Licensed under the Open Software License version 3.0
+ *
+ * This source file is subject to the Open Software License (OSL 3.0) that is
+ * bundled with this package in the files license.txt / license.rst. It is
+ * also available through the world wide web at this URL:
+ * http://opensource.org/licenses/OSL-3.0
+ * If you did not receive a copy of the license and are unable to obtain it
+ * through the world wide web, please send an email to
+ * licensing@ellislab.com so we can send you a copy immediately.
*
* @package CodeIgniter
- * @author ExpressionEngine Dev Team
- * @copyright Copyright (c) 2008 - 2011, EllisLab, Inc.
- * @license http://codeigniter.com/user_guide/license.html
+ * @author EllisLab Dev Team
+ * @copyright Copyright (c) 2008 - 2012, EllisLab, Inc. (http://ellislab.com/)
+ * @license http://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
* @link http://codeigniter.com
* @since Version 1.0
* @filesource
@@ -31,22 +43,46 @@ if ( ! class_exists('CI_Xmlrpc'))
* @package CodeIgniter
* @subpackage Libraries
* @category XML-RPC
- * @author ExpressionEngine Dev Team
+ * @author EllisLab Dev Team
* @link http://codeigniter.com/user_guide/libraries/xmlrpc.html
*/
class CI_Xmlrpcs extends CI_Xmlrpc
{
- var $methods = array(); //array of methods mapped to function names and signatures
- var $debug_msg = ''; // Debug Message
- var $system_methods = array(); // XML RPC Server methods
- var $controller_obj;
+ /**
+ * 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();
- var $object = FALSE;
+ /**
+ * Configuration object
+ *
+ * @var object
+ */
+ public $object = FALSE;
/**
- * Constructor
+ * Initialize XMLRPC class
+ *
+ * @param array $config
+ * @return void
*/
- public function __construct($config=array())
+ public function __construct($config = array())
{
parent::__construct();
$this->set_system_methods();
@@ -56,7 +92,7 @@ class CI_Xmlrpcs extends CI_Xmlrpc
$this->methods = array_merge($this->methods, $config['functions']);
}
- log_message('debug', "XML-RPC Server Class Initialized");
+ log_message('debug', 'XML-RPC Server Class Initialized');
}
// --------------------------------------------------------------------
@@ -64,11 +100,10 @@ class CI_Xmlrpcs extends CI_Xmlrpc
/**
* Initialize Prefs and Serve
*
- * @access public
* @param mixed
* @return void
*/
- function initialize($config=array())
+ public function initialize($config = array())
{
if (isset($config['functions']) && is_array($config['functions']))
{
@@ -96,29 +131,28 @@ class CI_Xmlrpcs extends CI_Xmlrpc
/**
* Setting of System Methods
*
- * @access public
* @return void
*/
- function set_system_methods()
+ public function set_system_methods()
{
$this->methods = array(
'system.listMethods' => array(
- 'function' => 'this.listMethods',
- 'signature' => array(array($this->xmlrpcArray, $this->xmlrpcString), array($this->xmlrpcArray)),
- 'docstring' => 'Returns an array of available methods on this server'),
- 'system.methodHelp' => array(
- 'function' => 'this.methodHelp',
- 'signature' => array(array($this->xmlrpcString, $this->xmlrpcString)),
- 'docstring' => 'Returns a documentation string for the specified method'),
+ 'function' => 'this.listMethods',
+ 'signature' => array(array($this->xmlrpcArray, $this->xmlrpcString), array($this->xmlrpcArray)),
+ 'docstring' => 'Returns an array of available methods on this server'),
+ 'system.methodHelp' => array(
+ 'function' => 'this.methodHelp',
+ 'signature' => array(array($this->xmlrpcString, $this->xmlrpcString)),
+ 'docstring' => 'Returns a documentation string for the specified method'),
'system.methodSignature' => array(
- 'function' => 'this.methodSignature',
- 'signature' => array(array($this->xmlrpcArray, $this->xmlrpcString)),
- 'docstring' => 'Returns an array describing the return type and required parameters of a method'),
- 'system.multicall' => array(
- 'function' => 'this.multicall',
- 'signature' => array(array($this->xmlrpcArray, $this->xmlrpcArray)),
- 'docstring' => 'Combine multiple RPC calls in one request. See http://www.xmlrpc.com/discuss/msgReader$1208 for details')
- );
+ 'function' => 'this.methodSignature',
+ 'signature' => array(array($this->xmlrpcArray, $this->xmlrpcString)),
+ 'docstring' => 'Returns an array describing the return type and required parameters of a method'),
+ 'system.multicall' => array(
+ 'function' => 'this.multicall',
+ 'signature' => array(array($this->xmlrpcArray, $this->xmlrpcArray)),
+ 'docstring' => 'Combine multiple RPC calls in one request. See http://www.xmlrpc.com/discuss/msgReader$1208 for details')
+ );
}
// --------------------------------------------------------------------
@@ -126,18 +160,15 @@ class CI_Xmlrpcs extends CI_Xmlrpc
/**
* Main Server Function
*
- * @access public
* @return void
*/
- function serve()
+ public function serve()
{
$r = $this->parseRequest();
- $payload = '<?xml version="1.0" encoding="'.$this->xmlrpc_defencoding.'"?'.'>'."\n";
- $payload .= $this->debug_msg;
- $payload .= $r->prepare_response();
+ $payload = '<?xml version="1.0" encoding="'.$this->xmlrpc_defencoding.'"?'.'>'."\n".$this->debug_msg.$r->prepare_response();
- header("Content-Type: text/xml");
- header("Content-Length: ".strlen($payload));
+ header('Content-Type: text/xml');
+ header('Content-Length: '.strlen($payload));
exit($payload);
}
@@ -146,14 +177,13 @@ class CI_Xmlrpcs extends CI_Xmlrpc
/**
* Add Method to Class
*
- * @access public
* @param string method name
* @param string function
* @param string signature
* @param string docstring
* @return void
*/
- function add_to_map($methodname, $function, $sig, $doc)
+ public function add_to_map($methodname, $function, $sig, $doc)
{
$this->methods[$methodname] = array(
'function' => $function,
@@ -167,11 +197,10 @@ class CI_Xmlrpcs extends CI_Xmlrpc
/**
* Parse Server Request
*
- * @access public
* @param string data
* @return object xmlrpc response
*/
- function parseRequest($data='')
+ public function parseRequest($data = '')
{
global $HTTP_RAW_POST_DATA;
@@ -179,7 +208,7 @@ class CI_Xmlrpcs extends CI_Xmlrpc
// Get Data
//-------------------------------------
- if ($data == '')
+ if ($data === '')
{
$data = $HTTP_RAW_POST_DATA;
}
@@ -189,23 +218,23 @@ class CI_Xmlrpcs extends CI_Xmlrpc
//-------------------------------------
$parser = xml_parser_create($this->xmlrpc_defencoding);
- $parser_object = new XML_RPC_Message("filler");
+ $parser_object = new XML_RPC_Message('filler');
- $parser_object->xh[$parser] = array();
- $parser_object->xh[$parser]['isf'] = 0;
- $parser_object->xh[$parser]['isf_reason'] = '';
- $parser_object->xh[$parser]['params'] = array();
- $parser_object->xh[$parser]['stack'] = array();
- $parser_object->xh[$parser]['valuestack'] = array();
- $parser_object->xh[$parser]['method'] = '';
+ $parser_object->xh[$parser] = array(
+ 'isf' => 0,
+ 'isf_reason' => '',
+ 'params' => array(),
+ 'stack' => array(),
+ 'valuestack' => array(),
+ 'method' => ''
+ );
xml_set_object($parser, $parser_object);
- 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');
-
//-------------------------------------
// PARSE + PROCESS XML DATA
//-------------------------------------
@@ -231,11 +260,11 @@ class CI_Xmlrpcs extends CI_Xmlrpc
$m = new XML_RPC_Message($parser_object->xh[$parser]['method']);
$plist='';
- for ($i=0; $i < count($parser_object->xh[$parser]['params']); $i++)
+ for ($i = 0, $c = count($parser_object->xh[$parser]['params']); $i < $c; $i++)
{
if ($this->debug === TRUE)
{
- $plist .= "$i - " . print_r(get_object_vars($parser_object->xh[$parser]['params'][$i]), TRUE). ";\n";
+ $plist .= $i.' - '.print_r(get_object_vars($parser_object->xh[$parser]['params'][$i]), TRUE).";\n";
}
$m->addParam($parser_object->xh[$parser]['params'][$i]);
@@ -243,9 +272,7 @@ class CI_Xmlrpcs extends CI_Xmlrpc
if ($this->debug === TRUE)
{
- echo "<pre>";
- echo "---PLIST---\n" . $plist . "\n---PLIST END---\n\n";
- echo "</pre>";
+ echo "<pre>---PLIST---\n".$plist."\n---PLIST END---\n\n</pre>";
}
$r = $this->_execute($m);
@@ -268,18 +295,17 @@ class CI_Xmlrpcs extends CI_Xmlrpc
/**
* Executes the Method
*
- * @access protected
* @param object
* @return mixed
*/
- function _execute($m)
+ protected function _execute($m)
{
$methName = $m->method_name;
// Check to see if it is a system call
- $system_call = (strncmp($methName, 'system', 5) == 0) ? TRUE : FALSE;
+ $system_call = (strpos($methName, 'system') === 0);
- if ($this->xss_clean == FALSE)
+ if ($this->xss_clean === FALSE)
{
$m->xss_clean = FALSE;
}
@@ -297,26 +323,21 @@ class CI_Xmlrpcs extends CI_Xmlrpc
// Check for Method (and Object)
//-------------------------------------
- $method_parts = explode(".", $this->methods[$methName]['function']);
- $objectCall = (isset($method_parts['1']) && $method_parts['1'] != "") ? TRUE : FALSE;
+ $method_parts = explode('.', $this->methods[$methName]['function']);
+ $objectCall = (isset($method_parts[1]) && $method_parts[1] !== '');
if ($system_call === TRUE)
{
- if ( ! is_callable(array($this,$method_parts['1'])))
+ if ( ! is_callable(array($this,$method_parts[1])))
{
return new XML_RPC_Response(0, $this->xmlrpcerr['unknown_method'], $this->xmlrpcstr['unknown_method']);
}
}
- else
+ elseif (($objectCall && ! is_callable(array($method_parts[0], $method_parts[1])))
+ OR ( ! $objectCall && ! is_callable($this->methods[$methName]['function']))
+ )
{
- if ($objectCall && ! is_callable(array($method_parts['0'],$method_parts['1'])))
- {
- return new XML_RPC_Response(0, $this->xmlrpcerr['unknown_method'], $this->xmlrpcstr['unknown_method']);
- }
- elseif ( ! $objectCall && ! is_callable($this->methods[$methName]['function']))
- {
- return new XML_RPC_Response(0, $this->xmlrpcerr['unknown_method'], $this->xmlrpcstr['unknown_method']);
- }
+ return new XML_RPC_Response(0, $this->xmlrpcerr['unknown_method'], $this->xmlrpcstr['unknown_method']);
}
//-------------------------------------
@@ -326,18 +347,18 @@ class CI_Xmlrpcs extends CI_Xmlrpc
if (isset($this->methods[$methName]['signature']))
{
$sig = $this->methods[$methName]['signature'];
- for ($i=0; $i<count($sig); $i++)
+ for ($i = 0, $c = count($sig); $i < $c; $i++)
{
$current_sig = $sig[$i];
- if (count($current_sig) == count($m->params)+1)
+ if (count($current_sig) === count($m->params)+1)
{
- for ($n=0; $n < count($m->params); $n++)
+ 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];
@@ -345,7 +366,7 @@ class CI_Xmlrpcs extends CI_Xmlrpc
return new XML_RPC_Response(0,
$this->xmlrpcerr['incorrect_params'],
$this->xmlrpcstr['incorrect_params'] .
- ": Wanted {$wanted}, got {$pt} at param {$pno})");
+ ': Wanted '.$wanted.', got '.$pt.' at param '.$pno.')');
}
}
}
@@ -358,7 +379,7 @@ class CI_Xmlrpcs extends CI_Xmlrpc
if ($objectCall === TRUE)
{
- if ($method_parts[0] == "this" && $system_call == TRUE)
+ if ($method_parts[0] === 'this' && $system_call === TRUE)
{
return call_user_func(array($this, $method_parts[1]), $m);
}
@@ -367,11 +388,11 @@ class CI_Xmlrpcs extends CI_Xmlrpc
if ($this->object === FALSE)
{
$CI =& get_instance();
- return $CI->$method_parts['1']($m);
+ return $CI->$method_parts[1]($m);
}
else
{
- return $this->object->$method_parts['1']($m);
+ return $this->object->$method_parts[1]($m);
//return call_user_func(array(&$method_parts['0'],$method_parts['1']), $m);
}
}
@@ -381,17 +402,16 @@ class CI_Xmlrpcs extends CI_Xmlrpc
return call_user_func($this->methods[$methName]['function'], $m);
}
}
-
+
// --------------------------------------------------------------------
/**
* Server Function: List Methods
*
- * @access public
* @param mixed
* @return object
*/
- function listMethods($m)
+ public function listMethods($m)
{
$v = new XML_RPC_Values();
$output = array();
@@ -403,23 +423,22 @@ class CI_Xmlrpcs extends CI_Xmlrpc
foreach ($this->system_methods as $key => $value)
{
- $output[]= new XML_RPC_Values($key, 'string');
+ $output[] = new XML_RPC_Values($key, 'string');
}
$v->addArray($output);
return new XML_RPC_Response($v);
}
-
+
// --------------------------------------------------------------------
/**
* Server Function: Return Signature for Method
*
- * @access public
* @param mixed
* @return object
*/
- function methodSignature($m)
+ public function methodSignature($m)
{
$parameters = $m->output_parameters();
$method_name = $parameters[0];
@@ -431,28 +450,24 @@ class CI_Xmlrpcs extends CI_Xmlrpc
$sigs = array();
$signature = $this->methods[$method_name]['signature'];
- for ($i=0; $i < count($signature); $i++)
+ for ($i = 0, $c = count($signature); $i < $c; $i++)
{
$cursig = array();
$inSig = $signature[$i];
- for ($j=0; $j<count($inSig); $j++)
+ for ($j = 0, $jc = count($inSig); $j < $jc; $j++)
{
$cursig[]= new XML_RPC_Values($inSig[$j], 'string');
}
- $sigs[]= new XML_RPC_Values($cursig, 'array');
+ $sigs[] = new XML_RPC_Values($cursig, 'array');
}
- $r = new XML_RPC_Response(new XML_RPC_Values($sigs, 'array'));
- }
- else
- {
- $r = new XML_RPC_Response(new XML_RPC_Values('undef', 'string'));
+
+ return new XML_RPC_Response(new XML_RPC_Values($sigs, 'array'));
}
+
+ return new XML_RPC_Response(new XML_RPC_Values('undef', 'string'));
}
- else
- {
- $r = new XML_RPC_Response(0,$this->xmlrpcerr['introspect_unknown'], $this->xmlrpcstr['introspect_unknown']);
- }
- return $r;
+
+ return new XML_RPC_Response(0,$this->xmlrpcerr['introspect_unknown'], $this->xmlrpcstr['introspect_unknown']);
}
// --------------------------------------------------------------------
@@ -460,11 +475,10 @@ class CI_Xmlrpcs extends CI_Xmlrpc
/**
* Server Function: Doc String for Method
*
- * @access public
* @param mixed
* @return object
*/
- function methodHelp($m)
+ public function methodHelp($m)
{
$parameters = $m->output_parameters();
$method_name = $parameters[0];
@@ -480,17 +494,16 @@ class CI_Xmlrpcs extends CI_Xmlrpc
return new XML_RPC_Response(0, $this->xmlrpcerr['introspect_unknown'], $this->xmlrpcstr['introspect_unknown']);
}
}
-
+
// --------------------------------------------------------------------
/**
* Server Function: Multi-call
*
- * @access public
* @param mixed
* @return object
*/
- function multicall($m)
+ public function multicall($m)
{
// Disabled
return new XML_RPC_Response(0, $this->xmlrpcerr['unknown_method'], $this->xmlrpcstr['unknown_method']);
@@ -507,14 +520,14 @@ class CI_Xmlrpcs extends CI_Xmlrpc
$m = new XML_RPC_Message($value[0]);
$plist='';
- for ($i=0; $i < count($value[1]); $i++)
+ for ($i = 0, $c = count($value[1]); $i < $c; $i++)
{
$m->addParam(new XML_RPC_Values($value[1][$i], 'string'));
}
$attempt = $this->_execute($m);
- if ($attempt->faultCode() != 0)
+ if ($attempt->faultCode() !== 0)
{
return $attempt;
}
@@ -530,11 +543,10 @@ class CI_Xmlrpcs extends CI_Xmlrpc
/**
* Multi-call Function: Error Handling
*
- * @access public
* @param mixed
* @return object
*/
- function multicall_error($err)
+ public function multicall_error($err)
{
$str = is_string($err) ? $this->xmlrpcstr["multicall_${err}"] : $err->faultString();
$code = is_string($err) ? $this->xmlrpcerr["multicall_${err}"] : $err->faultCode();
@@ -550,13 +562,12 @@ class CI_Xmlrpcs extends CI_Xmlrpc
/**
* Multi-call Function: Processes method
*
- * @access public
* @param mixed
* @return object
*/
- function do_multicall($call)
+ public function do_multicall($call)
{
- if ($call->kindOf() != 'struct')
+ if ($call->kindOf() !== 'struct')
{
return $this->multicall_error('notstruct');
}
@@ -566,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');
}
@@ -580,23 +591,22 @@ class CI_Xmlrpcs extends CI_Xmlrpc
{
return $this->multicall_error('noparams');
}
- elseif ($params->kindOf() != 'array')
+ elseif ($params->kindOf() !== 'array')
{
return $this->multicall_error('notarray');
}
- list($a,$b)=each($params->me);
- $numParams = count($b);
+ list($a,$b) = each($params->me);
$msg = new XML_RPC_Message($scalar_value);
- for ($i = 0; $i < $numParams; $i++)
+ for ($i = 0, $numParams = count($b); $i < $numParams; $i++)
{
$msg->params[] = $params->me['array'][$i];
}
$result = $this->_execute($msg);
- if ($result->faultCode() != 0)
+ if ($result->faultCode() !== 0)
{
return $this->multicall_error($result);
}
@@ -605,8 +615,6 @@ class CI_Xmlrpcs extends CI_Xmlrpc
}
}
-// END XML_RPC_Server class
-
/* End of file Xmlrpcs.php */
/* Location: ./system/libraries/Xmlrpcs.php */ \ No newline at end of file
diff --git a/system/libraries/Zip.php b/system/libraries/Zip.php
index 666327d5c..5c4c257f8 100644
--- a/system/libraries/Zip.php
+++ b/system/libraries/Zip.php
@@ -1,20 +1,30 @@
-<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
+<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* CodeIgniter
*
- * An open source application development framework for PHP 5.1.6 or newer
+ * An open source application development framework for PHP 5.2.4 or newer
+ *
+ * NOTICE OF LICENSE
+ *
+ * Licensed under the Open Software License version 3.0
+ *
+ * This source file is subject to the Open Software License (OSL 3.0) that is
+ * bundled with this package in the files license.txt / license.rst. It is
+ * also available through the world wide web at this URL:
+ * http://opensource.org/licenses/OSL-3.0
+ * If you did not receive a copy of the license and are unable to obtain it
+ * through the world wide web, please send an email to
+ * licensing@ellislab.com so we can send you a copy immediately.
*
* @package CodeIgniter
- * @author ExpressionEngine Dev Team
- * @copyright Copyright (c) 2008 - 2011, EllisLab, Inc.
- * @license http://codeigniter.com/user_guide/license.html
+ * @author EllisLab Dev Team
+ * @copyright Copyright (c) 2008 - 2012, EllisLab, Inc. (http://ellislab.com/)
+ * @license http://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
* @link http://codeigniter.com
* @since Version 1.0
* @filesource
*/
-// ------------------------------------------------------------------------
-
/**
* Zip Compression Class
*
@@ -27,26 +37,62 @@
* @package CodeIgniter
* @subpackage Libraries
* @category Encryption
- * @author ExpressionEngine Dev Team
+ * @author EllisLab Dev Team
* @link http://codeigniter.com/user_guide/libraries/zip.html
*/
-class CI_Zip {
+class CI_Zip {
+
+ /**
+ * Zip data in string form
+ *
+ * @var string
+ */
+ public $zipdata = '';
+
+ /**
+ * Zip data for a directory in string form
+ *
+ * @var string
+ */
+ public $directory = '';
- var $zipdata = '';
- var $directory = '';
- var $entries = 0;
- var $file_num = 0;
- var $offset = 0;
- var $now;
+ /**
+ * 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;
/**
- * Constructor
+ * Reference to time at init
+ *
+ * @var int
+ */
+ public $now;
+
+ /**
+ * Initialize zip compression class
+ *
+ * @return void
*/
public function __construct()
{
- log_message('debug', "Zip Compression Class Initialized");
-
$this->now = time();
+ log_message('debug', 'Zip Compression Class Initialized');
}
// --------------------------------------------------------------------
@@ -56,21 +102,19 @@ class CI_Zip {
*
* Lets you add a virtual directory into which you can place files.
*
- * @access public
* @param mixed the directory name. Can be string or array
* @return void
*/
- function add_dir($directory)
+ public function add_dir($directory)
{
- foreach ((array)$directory as $dir)
+ foreach ( (array) $directory as $dir)
{
- if ( ! preg_match("|.+/$|", $dir))
+ if ( ! preg_match('|.+/$|', $dir))
{
$dir .= '/';
}
$dir_time = $this->_get_mod_time($dir);
-
$this->_add_dir($dir, $dir_time['file_mtime'], $dir_time['file_mdate']);
}
}
@@ -78,22 +122,22 @@ class CI_Zip {
// --------------------------------------------------------------------
/**
- * Get file/directory modification time
+ * Get file/directory modification time
*
- * If this is a newly created file/dir, we will set the time to 'now'
+ * If this is a newly created file/dir, we will set the time to 'now'
*
- * @param string path to file
- * @return array filemtime/filemdate
+ * @param string path to file
+ * @return array filemtime/filemdate
*/
- function _get_mod_time($dir)
+ protected function _get_mod_time($dir)
{
- // filemtime() will return false, but it does raise an error.
- $date = (@filemtime($dir)) ? filemtime($dir) : getdate($this->now);
-
- $time['file_mtime'] = ($date['hours'] << 11) + ($date['minutes'] << 5) + $date['seconds'] / 2;
- $time['file_mdate'] = (($date['year'] - 1980) << 9) + ($date['mon'] << 5) + $date['mday'];
+ // filemtime() may return false, but raises an error for non-existing files
+ $date = file_exists($dir) ? filemtime($dir) : getdate($this->now);
- return $time;
+ return array(
+ 'file_mtime' => ($date['hours'] << 11) + ($date['minutes'] << 5) + $date['seconds'] / 2,
+ 'file_mdate' => (($date['year'] - 1980) << 9) + ($date['mon'] << 5) + $date['mday']
+ );
}
// --------------------------------------------------------------------
@@ -101,13 +145,14 @@ class CI_Zip {
/**
* Add Directory
*
- * @access private
* @param string the directory name
+ * @param int
+ * @param int
* @return void
*/
- function _add_dir($dir, $file_mtime, $file_mdate)
+ protected function _add_dir($dir, $file_mtime, $file_mdate)
{
- $dir = str_replace("\\", "/", $dir);
+ $dir = str_replace('\\', '/', $dir);
$this->zipdata .=
"\x50\x4b\x03\x04\x0a\x00\x00\x00\x00\x00"
@@ -150,29 +195,26 @@ class CI_Zip {
* Add Data to Zip
*
* Lets you add files to the archive. If the path is included
- * in the filename it will be placed within a directory. Make
+ * in the filename it will be placed within a directory. Make
* sure you use add_dir() first to create the folder.
*
- * @access public
* @param mixed
* @param string
* @return void
*/
- function add_data($filepath, $data = NULL)
+ public function add_data($filepath, $data = NULL)
{
if (is_array($filepath))
{
foreach ($filepath as $path => $data)
{
$file_data = $this->_get_mod_time($path);
-
$this->_add_data($path, $data, $file_data['file_mtime'], $file_data['file_mdate']);
}
}
else
{
$file_data = $this->_get_mod_time($filepath);
-
$this->_add_data($filepath, $data, $file_data['file_mtime'], $file_data['file_mdate']);
}
}
@@ -182,20 +224,19 @@ class CI_Zip {
/**
* Add Data to Zip
*
- * @access private
* @param string the file name/path
* @param string the data to be encoded
+ * @param int
+ * @param int
* @return void
*/
- function _add_data($filepath, $data, $file_mtime, $file_mdate)
+ protected function _add_data($filepath, $data, $file_mtime, $file_mdate)
{
- $filepath = str_replace("\\", "/", $filepath);
+ $filepath = str_replace('\\', '/', $filepath);
$uncompressed_size = strlen($data);
$crc32 = crc32($data);
-
- $gzdata = gzcompress($data);
- $gzdata = substr($gzdata, 2, -4);
+ $gzdata = substr(gzcompress($data), 2, -4);
$compressed_size = strlen($gzdata);
$this->zipdata .=
@@ -236,10 +277,11 @@ class CI_Zip {
/**
* Read the contents of a file and add it to the zip
*
- * @access public
+ * @param string
+ * @param bool
* @return bool
*/
- function read_file($path, $preserve_filepath = FALSE)
+ public function read_file($path, $preserve_filepath = FALSE)
{
if ( ! file_exists($path))
{
@@ -248,16 +290,16 @@ class CI_Zip {
if (FALSE !== ($data = file_get_contents($path)))
{
- $name = str_replace("\\", "/", $path);
-
+ $name = str_replace('\\', '/', $path);
if ($preserve_filepath === FALSE)
{
- $name = preg_replace("|.*/(.+)|", "\\1", $name);
+ $name = preg_replace('|.*/(.+)|', '\\1', $name);
}
$this->add_data($name, $data);
return TRUE;
}
+
return FALSE;
}
@@ -267,15 +309,17 @@ class CI_Zip {
* Read a directory and add it to the zip.
*
* This function recursively reads a folder and everything it contains (including
- * sub-folders) and creates a zip based on it. Whatever directory structure
+ * sub-folders) and creates a zip based on it. Whatever directory structure
* is in the original file path will be recreated in the zip file.
*
- * @access public
* @param string path to source
+ * @param bool
+ * @param bool
* @return bool
*/
- function read_dir($path, $preserve_filepath = TRUE, $root_path = NULL)
+ public function read_dir($path, $preserve_filepath = TRUE, $root_path = NULL)
{
+ $path = rtrim($path, '/\\').DIRECTORY_SEPARATOR;
if ( ! $fp = @opendir($path))
{
return FALSE;
@@ -284,36 +328,32 @@ 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)))
{
- if (substr($file, 0, 1) == '.')
+ if ($file[0] === '.')
{
continue;
}
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);
}
- else
+ elseif (FALSE !== ($data = file_get_contents($path.$file)))
{
- if (FALSE !== ($data = file_get_contents($path.$file)))
+ $name = str_replace(array('\\', '/'), DIRECTORY_SEPARATOR, $path);
+ if ($preserve_filepath === FALSE)
{
- $name = str_replace("\\", "/", $path);
-
- if ($preserve_filepath === FALSE)
- {
- $name = str_replace($root_path, '', $name);
- }
-
- $this->add_data($name.$file, $data);
+ $name = str_replace($root_path, '', $name);
}
+ $this->add_data($name.$file, $data);
}
}
+ closedir($fp);
return TRUE;
}
@@ -322,26 +362,23 @@ class CI_Zip {
/**
* Get the Zip file
*
- * @access public
- * @return binary string
+ * @return string (binary encoded)
*/
- function get_zip()
+ public function get_zip()
{
// Is there any data to return?
- if ($this->entries == 0)
+ if ($this->entries === 0)
{
return FALSE;
}
- $zip_data = $this->zipdata;
- $zip_data .= $this->directory."\x50\x4b\x05\x06\x00\x00\x00\x00";
- $zip_data .= pack('v', $this->entries); // total # of entries "on this disk"
- $zip_data .= pack('v', $this->entries); // total # of entries overall
- $zip_data .= pack('V', strlen($this->directory)); // size of central dir
- $zip_data .= pack('V', strlen($this->zipdata)); // offset to start of central dir
- $zip_data .= "\x00\x00"; // .zip file comment length
-
- return $zip_data;
+ return $this->zipdata
+ .$this->directory."\x50\x4b\x05\x06\x00\x00\x00\x00"
+ .pack('v', $this->entries) // total # of entries "on this disk"
+ .pack('v', $this->entries) // total # of entries overall
+ .pack('V', strlen($this->directory)) // size of central dir
+ .pack('V', strlen($this->zipdata)) // offset to start of central dir
+ ."\x00\x00"; // .zip file comment length
}
// --------------------------------------------------------------------
@@ -351,11 +388,10 @@ class CI_Zip {
*
* Lets you write a file
*
- * @access public
* @param string the file name
* @return bool
*/
- function archive($filepath)
+ public function archive($filepath)
{
if ( ! ($fp = @fopen($filepath, FOPEN_WRITE_CREATE_DESTRUCTIVE)))
{
@@ -375,23 +411,19 @@ class CI_Zip {
/**
* Download
*
- * @access public
* @param string the file name
- * @param string the data to be encoded
- * @return bool
+ * @return void
*/
- function download($filename = 'backup.zip')
+ public function download($filename = 'backup.zip')
{
- if ( ! preg_match("|.+?\.zip$|", $filename))
+ if ( ! preg_match('|.+?\.zip$|', $filename))
{
$filename .= '.zip';
}
$CI =& get_instance();
$CI->load->helper('download');
-
$get_zip = $this->get_zip();
-
$zip_content =& $get_zip;
force_download($filename, $zip_content);
@@ -402,19 +434,19 @@ class CI_Zip {
/**
* Initialize Data
*
- * Lets you clear current zip data. Useful if you need to create
+ * Lets you clear current zip data. Useful if you need to create
* multiple zips with different data.
*
- * @access public
- * @return void
+ * @return object
*/
- function clear_data()
+ public function clear_data()
{
$this->zipdata = '';
$this->directory = '';
$this->entries = 0;
$this->file_num = 0;
$this->offset = 0;
+ return $this;
}
}
diff --git a/system/libraries/javascript/Jquery.php b/system/libraries/javascript/Jquery.php
index baab83d25..44c16b578 100644
--- a/system/libraries/javascript/Jquery.php
+++ b/system/libraries/javascript/Jquery.php
@@ -1,15 +1,26 @@
-<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
-
+<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* CodeIgniter
*
- * An open source application development framework for PHP 4.3.2 or newer
+ * An open source application development framework for PHP 5.2.4 or newer
+ *
+ * NOTICE OF LICENSE
+ *
+ * Licensed under the Open Software License version 3.0
+ *
+ * This source file is subject to the Open Software License (OSL 3.0) that is
+ * bundled with this package in the files license.txt / license.rst. It is
+ * also available through the world wide web at this URL:
+ * http://opensource.org/licenses/OSL-3.0
+ * If you did not receive a copy of the license and are unable to obtain it
+ * through the world wide web, please send an email to
+ * licensing@ellislab.com so we can send you a copy immediately.
*
* @package CodeIgniter
- * @author ExpressionEngine Dev Team
- * @copyright Copyright (c) 2008 - 2011, EllisLab, Inc.
- * @license http://www.codeigniter.com/user_guide/license.html
- * @link http://www.codeigniter.com
+ * @author EllisLab Dev Team
+ * @copyright Copyright (c) 2008 - 2012, EllisLab, Inc. (http://ellislab.com/)
+ * @license http://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
+ * @link http://codeigniter.com
* @since Version 1.0
* @filesource
*/
@@ -19,84 +30,81 @@
*
* @package CodeIgniter
* @subpackage Libraries
- * @author ExpressionEngine Dev Team
* @category Loader
- * @link http://www.codeigniter.com/user_guide/libraries/javascript.html
+ * @author EllisLab Dev Team
+ * @link http://codeigniter.com/user_guide/libraries/javascript.html
*/
-
+
class CI_Jquery extends CI_Javascript {
- var $_javascript_folder = 'js';
- var $jquery_code_for_load = array();
- var $jquery_code_for_compile = array();
- var $jquery_corner_active = FALSE;
- var $jquery_table_sorter_active = FALSE;
- var $jquery_table_sorter_pager_active = FALSE;
- var $jquery_ajax_img = '';
+ protected $_javascript_folder = 'js';
+ public $jquery_code_for_load = array();
+ public $jquery_code_for_compile = array();
+ public $jquery_corner_active = FALSE;
+ public $jquery_table_sorter_active = FALSE;
+ public $jquery_table_sorter_pager_active = FALSE;
+ public $jquery_ajax_img = '';
public function __construct($params)
{
- $this->CI =& get_instance();
+ $this->CI =& get_instance();
extract($params);
if ($autoload === TRUE)
{
- $this->script();
+ $this->script();
}
-
- log_message('debug', "Jquery Class Initialized");
+
+ log_message('debug', 'Jquery Class Initialized');
}
-
- // --------------------------------------------------------------------
+
+ // --------------------------------------------------------------------
// Event Code
- // --------------------------------------------------------------------
+ // --------------------------------------------------------------------
/**
* Blur
*
* Outputs a jQuery blur event
*
- * @access private
* @param string The element to attach the event to
* @param string The code to execute
* @return string
*/
- function _blur($element = 'this', $js = '')
+ protected function _blur($element = 'this', $js = '')
{
return $this->_add_event($element, $js, 'blur');
}
-
+
// --------------------------------------------------------------------
-
+
/**
* Change
*
* Outputs a jQuery change event
*
- * @access private
* @param string The element to attach the event to
* @param string The code to execute
* @return string
*/
- function _change($element = 'this', $js = '')
+ protected function _change($element = 'this', $js = '')
{
return $this->_add_event($element, $js, 'change');
}
-
+
// --------------------------------------------------------------------
-
+
/**
* Click
*
* Outputs a jQuery click event
*
- * @access private
* @param string The element to attach the event to
* @param string The code to execute
* @param boolean whether or not to return false
* @return string
*/
- function _click($element = 'this', $js = '', $ret_false = TRUE)
+ protected function _click($element = 'this', $js = '', $ret_false = TRUE)
{
if ( ! is_array($js))
{
@@ -105,79 +113,75 @@ class CI_Jquery extends CI_Javascript {
if ($ret_false)
{
- $js[] = "return false;";
+ $js[] = 'return false;';
}
return $this->_add_event($element, $js, 'click');
}
// --------------------------------------------------------------------
-
+
/**
* Double Click
*
* Outputs a jQuery dblclick event
*
- * @access private
* @param string The element to attach the event to
* @param string The code to execute
* @return string
*/
- function _dblclick($element = 'this', $js = '')
+ protected function _dblclick($element = 'this', $js = '')
{
return $this->_add_event($element, $js, 'dblclick');
}
// --------------------------------------------------------------------
-
+
/**
* Error
*
* Outputs a jQuery error event
*
- * @access private
* @param string The element to attach the event to
* @param string The code to execute
* @return string
*/
- function _error($element = 'this', $js = '')
+ protected function _error($element = 'this', $js = '')
{
return $this->_add_event($element, $js, 'error');
}
// --------------------------------------------------------------------
-
+
/**
* Focus
*
* Outputs a jQuery focus event
*
- * @access private
* @param string The element to attach the event to
* @param string The code to execute
* @return string
*/
- function _focus($element = 'this', $js = '')
+ protected function _focus($element = 'this', $js = '')
{
return $this->_add_event($element, $js, 'focus');
}
// --------------------------------------------------------------------
-
+
/**
* Hover
*
* Outputs a jQuery hover event
*
- * @access private
* @param string - element
* @param string - Javascript code for mouse over
* @param string - Javascript code for mouse out
* @return string
*/
- function _hover($element = 'this', $over, $out)
+ 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;
@@ -185,103 +189,97 @@ class CI_Jquery extends CI_Javascript {
}
// --------------------------------------------------------------------
-
+
/**
* Keydown
*
* Outputs a jQuery keydown event
*
- * @access private
* @param string The element to attach the event to
* @param string The code to execute
* @return string
*/
- function _keydown($element = 'this', $js = '')
+ protected function _keydown($element = 'this', $js = '')
{
return $this->_add_event($element, $js, 'keydown');
}
// --------------------------------------------------------------------
-
+
/**
* Keyup
*
* Outputs a jQuery keydown event
*
- * @access private
* @param string The element to attach the event to
* @param string The code to execute
* @return string
*/
- function _keyup($element = 'this', $js = '')
+ protected function _keyup($element = 'this', $js = '')
{
return $this->_add_event($element, $js, 'keyup');
- }
+ }
// --------------------------------------------------------------------
-
+
/**
* Load
*
* Outputs a jQuery load event
*
- * @access private
* @param string The element to attach the event to
* @param string The code to execute
* @return string
*/
- function _load($element = 'this', $js = '')
+ protected function _load($element = 'this', $js = '')
{
return $this->_add_event($element, $js, 'load');
- }
-
+ }
+
// --------------------------------------------------------------------
-
+
/**
* Mousedown
*
* Outputs a jQuery mousedown event
*
- * @access private
* @param string The element to attach the event to
* @param string The code to execute
* @return string
*/
- function _mousedown($element = 'this', $js = '')
+ protected function _mousedown($element = 'this', $js = '')
{
return $this->_add_event($element, $js, 'mousedown');
}
// --------------------------------------------------------------------
-
+
/**
* Mouse Out
*
* Outputs a jQuery mouseout event
*
- * @access private
* @param string The element to attach the event to
* @param string The code to execute
* @return string
*/
- function _mouseout($element = 'this', $js = '')
+ protected function _mouseout($element = 'this', $js = '')
{
return $this->_add_event($element, $js, 'mouseout');
}
// --------------------------------------------------------------------
-
+
/**
* Mouse Over
*
* Outputs a jQuery mouseover event
*
- * @access private
* @param string The element to attach the event to
* @param string The code to execute
* @return string
*/
- function _mouseover($element = 'this', $js = '')
+ protected function _mouseover($element = 'this', $js = '')
{
return $this->_add_event($element, $js, 'mouseover');
}
@@ -293,12 +291,11 @@ class CI_Jquery extends CI_Javascript {
*
* Outputs a jQuery mouseup event
*
- * @access private
* @param string The element to attach the event to
* @param string The code to execute
* @return string
*/
- function _mouseup($element = 'this', $js = '')
+ protected function _mouseup($element = 'this', $js = '')
{
return $this->_add_event($element, $js, 'mouseup');
}
@@ -310,21 +307,20 @@ class CI_Jquery extends CI_Javascript {
*
* Outputs script directly
*
- * @access private
* @param string The element to attach the event to
* @param string The code to execute
* @return string
*/
- function _output($array_js = '')
+ protected function _output($array_js = '')
{
if ( ! is_array($array_js))
{
$array_js = array($array_js);
}
-
+
foreach ($array_js as $js)
{
- $this->jquery_code_for_compile[] = "\t$js\n";
+ $this->jquery_code_for_compile[] = "\t".$js."\n";
}
}
@@ -335,12 +331,11 @@ class CI_Jquery extends CI_Javascript {
*
* Outputs a jQuery resize event
*
- * @access private
* @param string The element to attach the event to
* @param string The code to execute
* @return string
*/
- function _resize($element = 'this', $js = '')
+ protected function _resize($element = 'this', $js = '')
{
return $this->_add_event($element, $js, 'resize');
}
@@ -352,16 +347,15 @@ class CI_Jquery extends CI_Javascript {
*
* Outputs a jQuery scroll event
*
- * @access private
* @param string The element to attach the event to
* @param string The code to execute
* @return string
*/
- function _scroll($element = 'this', $js = '')
+ protected function _scroll($element = 'this', $js = '')
{
return $this->_add_event($element, $js, 'scroll');
}
-
+
// --------------------------------------------------------------------
/**
@@ -369,34 +363,31 @@ class CI_Jquery extends CI_Javascript {
*
* Outputs a jQuery unload event
*
- * @access private
* @param string The element to attach the event to
* @param string The code to execute
* @return string
*/
- function _unload($element = 'this', $js = '')
+ protected function _unload($element = 'this', $js = '')
{
return $this->_add_event($element, $js, 'unload');
}
- // --------------------------------------------------------------------
+ // --------------------------------------------------------------------
// Effects
- // --------------------------------------------------------------------
-
+ // --------------------------------------------------------------------
+
/**
* Add Class
*
* Outputs a jQuery addClass event
*
- * @access private
* @param string - element
* @return string
*/
- function _addClass($element = 'this', $class='')
+ protected function _addClass($element = 'this', $class='')
{
$element = $this->_prep_element($element);
- $str = "$({$element}).addClass(\"$class\");";
- return $str;
+ return '$('.$element.').addClass("'.$class.'");';
}
// --------------------------------------------------------------------
@@ -406,95 +397,86 @@ class CI_Jquery extends CI_Javascript {
*
* Outputs a jQuery animate event
*
- * @access private
* @param string - element
* @param string - One of 'slow', 'normal', 'fast', or time in milliseconds
* @param string - Javascript callback function
* @return string
*/
- function _animate($element = 'this', $params = array(), $speed = '', $extra = '')
+ protected function _animate($element = 'this', $params = array(), $speed = '', $extra = '')
{
$element = $this->_prep_element($element);
$speed = $this->_validate_speed($speed);
-
+
$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;
}
-
- $str = "$({$element}).animate({\n$animations\n\t\t}".$speed.$extra.");";
-
- return $str;
+
+ return "$({$element}).animate({\n$animations\n\t\t}".$speed.$extra.');';
}
// --------------------------------------------------------------------
-
+
/**
* Fade In
*
* Outputs a jQuery hide event
*
- * @access private
* @param string - element
* @param string - One of 'slow', 'normal', 'fast', or time in milliseconds
* @param string - Javascript callback function
* @return string
*/
- function _fadeIn($element = 'this', $speed = '', $callback = '')
+ protected function _fadeIn($element = 'this', $speed = '', $callback = '')
{
- $element = $this->_prep_element($element);
+ $element = $this->_prep_element($element);
$speed = $this->_validate_speed($speed);
-
- if ($callback != '')
+
+ if ($callback !== '')
{
$callback = ", function(){\n{$callback}\n}";
}
-
- $str = "$({$element}).fadeIn({$speed}{$callback});";
-
- return $str;
+
+ return "$({$element}).fadeIn({$speed}{$callback});";
}
-
+
// --------------------------------------------------------------------
-
+
/**
* Fade Out
*
* Outputs a jQuery hide event
*
- * @access private
* @param string - element
* @param string - One of 'slow', 'normal', 'fast', or time in milliseconds
* @param string - Javascript callback function
* @return string
*/
- function _fadeOut($element = 'this', $speed = '', $callback = '')
+ protected function _fadeOut($element = 'this', $speed = '', $callback = '')
{
$element = $this->_prep_element($element);
$speed = $this->_validate_speed($speed);
-
- if ($callback != '')
+
+ if ($callback !== '')
{
$callback = ", function(){\n{$callback}\n}";
}
-
- $str = "$({$element}).fadeOut({$speed}{$callback});";
-
- return $str;
+
+ return '$('.$element.').fadeOut('.$speed.$callback.');';
}
// --------------------------------------------------------------------
@@ -504,27 +486,24 @@ class CI_Jquery extends CI_Javascript {
*
* Outputs a jQuery hide action
*
- * @access private
* @param string - element
* @param string - One of 'slow', 'normal', 'fast', or time in milliseconds
* @param string - Javascript callback function
* @return string
*/
- function _hide($element = 'this', $speed = '', $callback = '')
+ protected function _hide($element = 'this', $speed = '', $callback = '')
{
- $element = $this->_prep_element($element);
+ $element = $this->_prep_element($element);
$speed = $this->_validate_speed($speed);
-
- if ($callback != '')
+
+ if ($callback !== '')
{
$callback = ", function(){\n{$callback}\n}";
}
-
- $str = "$({$element}).hide({$speed}{$callback});";
- return $str;
+ return "$({$element}).hide({$speed}{$callback});";
}
-
+
// --------------------------------------------------------------------
/**
@@ -532,163 +511,145 @@ class CI_Jquery extends CI_Javascript {
*
* Outputs a jQuery remove class event
*
- * @access private
* @param string - element
* @return string
*/
- function _removeClass($element = 'this', $class='')
+ protected function _removeClass($element = 'this', $class='')
{
$element = $this->_prep_element($element);
- $str = "$({$element}).removeClass(\"$class\");";
- return $str;
+ return '$('.$element.').removeClass("'.$class.'");';
}
// --------------------------------------------------------------------
-
+
/**
* Slide Up
*
* Outputs a jQuery slideUp event
*
- * @access private
* @param string - element
* @param string - One of 'slow', 'normal', 'fast', or time in milliseconds
* @param string - Javascript callback function
* @return string
*/
- function _slideUp($element = 'this', $speed = '', $callback = '')
+ protected function _slideUp($element = 'this', $speed = '', $callback = '')
{
- $element = $this->_prep_element($element);
+ $element = $this->_prep_element($element);
$speed = $this->_validate_speed($speed);
-
- if ($callback != '')
+
+ if ($callback !== '')
{
$callback = ", function(){\n{$callback}\n}";
}
-
- $str = "$({$element}).slideUp({$speed}{$callback});";
-
- return $str;
+
+ return '$('.$element.').slideUp('.$speed.$callback.');';
}
-
+
// --------------------------------------------------------------------
-
+
/**
* Slide Down
*
* Outputs a jQuery slideDown event
*
- * @access private
* @param string - element
* @param string - One of 'slow', 'normal', 'fast', or time in milliseconds
* @param string - Javascript callback function
* @return string
*/
- function _slideDown($element = 'this', $speed = '', $callback = '')
+ protected function _slideDown($element = 'this', $speed = '', $callback = '')
{
$element = $this->_prep_element($element);
$speed = $this->_validate_speed($speed);
-
- if ($callback != '')
+
+ if ($callback !== '')
{
$callback = ", function(){\n{$callback}\n}";
}
-
- $str = "$({$element}).slideDown({$speed}{$callback});";
-
- return $str;
+
+ return '$('.$element.').slideDown('.$speed.$callback.');';
}
// --------------------------------------------------------------------
-
+
/**
* Slide Toggle
*
* Outputs a jQuery slideToggle event
*
- * @access public
* @param string - element
* @param string - One of 'slow', 'normal', 'fast', or time in milliseconds
* @param string - Javascript callback function
* @return string
*/
- function _slideToggle($element = 'this', $speed = '', $callback = '')
+ protected function _slideToggle($element = 'this', $speed = '', $callback = '')
{
$element = $this->_prep_element($element);
$speed = $this->_validate_speed($speed);
-
- if ($callback != '')
+
+ if ($callback !== '')
{
$callback = ", function(){\n{$callback}\n}";
}
-
- $str = "$({$element}).slideToggle({$speed}{$callback});";
-
- return $str;
+
+ return '$('.$element.').slideToggle('.$speed.$callback.');';
}
-
+
// --------------------------------------------------------------------
-
+
/**
* Toggle
*
* Outputs a jQuery toggle event
*
- * @access private
* @param string - element
* @return string
*/
- function _toggle($element = 'this')
+ protected function _toggle($element = 'this')
{
$element = $this->_prep_element($element);
- $str = "$({$element}).toggle();";
- return $str;
+ return '$('.$element.').toggle();';
}
-
+
// --------------------------------------------------------------------
-
+
/**
* Toggle Class
*
* Outputs a jQuery toggle class event
*
- * @access private
* @param string - element
* @return string
*/
- function _toggleClass($element = 'this', $class='')
+ protected function _toggleClass($element = 'this', $class='')
{
$element = $this->_prep_element($element);
- $str = "$({$element}).toggleClass(\"$class\");";
- return $str;
+ return '$('.$element.').toggleClass("'.$class.'");';
}
-
+
// --------------------------------------------------------------------
-
+
/**
* Show
*
* Outputs a jQuery show event
*
- * @access private
* @param string - element
* @param string - One of 'slow', 'normal', 'fast', or time in milliseconds
* @param string - Javascript callback function
* @return string
*/
- function _show($element = 'this', $speed = '', $callback = '')
+ protected function _show($element = 'this', $speed = '', $callback = '')
{
- $element = $this->_prep_element($element);
+ $element = $this->_prep_element($element);
$speed = $this->_validate_speed($speed);
-
- if ($callback != '')
+
+ if ($callback !== '')
{
$callback = ", function(){\n{$callback}\n}";
}
-
- $str = "$({$element}).show({$speed}{$callback});";
-
- return $str;
+
+ return '$('.$element.').show('.$speed.$callback.');';
}
// --------------------------------------------------------------------
@@ -696,69 +657,64 @@ class CI_Jquery extends CI_Javascript {
/**
* Updater
*
- * An Ajax call that populates the designated DOM node with
+ * An Ajax call that populates the designated DOM node with
* returned content
*
- * @access private
* @param string The element to attach the event to
* @param string the controller to run the call against
* @param string optional parameters
* @return string
*/
-
- function _updater($container = 'this', $controller, $options = '')
- {
+
+ protected function _updater($container = 'this', $controller, $options = '')
+ {
$container = $this->_prep_element($container);
-
$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
- $updater .= "\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 .= ", {";
- $request_options .= (is_array($options)) ? "'".implode("', '", $options)."'" : "'".str_replace(":", "':'", $options)."'";
- $request_options .= "}";
+ $request_options .= ', {'
+ .(is_array($options) ? "'".implode("', '", $options)."'" : "'".str_replace(':', "':'", $options)."'")
+ .'}';
}
- $updater .= "\t\t$($container).load('$controller'$request_options);";
- return $updater;
+ return $updater."\t\t$($container).load('$controller'$request_options);";
}
// --------------------------------------------------------------------
// Pre-written handy stuff
// --------------------------------------------------------------------
-
+
/**
* Zebra tables
*
- * @access private
* @param string table name
* @param string plugin location
* @return string
*/
- function _zebraTables($class = '', $odd = 'odd', $hover = '')
+ 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');");
}
@@ -766,34 +722,31 @@ class CI_Jquery extends CI_Javascript {
return $zebra;
}
-
-
// --------------------------------------------------------------------
// Plugins
// --------------------------------------------------------------------
-
+
/**
* Corner Plugin
*
* http://www.malsup.com/jquery/corner/
*
- * @access public
* @param string target
* @return string
*/
- function corner($element = '', $corner_style = '')
+ public function corner($element = '', $corner_style = '')
{
// 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.');';
}
-
+
// --------------------------------------------------------------------
/**
@@ -801,11 +754,10 @@ class CI_Jquery extends CI_Javascript {
*
* Load a thickbox modal window
*
- * @access public
* @return void
*/
- function modal($src, $relative = FALSE)
- {
+ public function modal($src, $relative = FALSE)
+ {
$this->jquery_code_for_load[] = $this->external($src, $relative);
}
@@ -816,10 +768,9 @@ class CI_Jquery extends CI_Javascript {
*
* Load an Effect library
*
- * @access public
* @return void
*/
- function effect($src, $relative = FALSE)
+ public function effect($src, $relative = FALSE)
{
$this->jquery_code_for_load[] = $this->external($src, $relative);
}
@@ -831,10 +782,9 @@ class CI_Jquery extends CI_Javascript {
*
* Load a plugin library
*
- * @access public
* @return void
*/
- function plugin($src, $relative = FALSE)
+ public function plugin($src, $relative = FALSE)
{
$this->jquery_code_for_load[] = $this->external($src, $relative);
}
@@ -846,10 +796,9 @@ class CI_Jquery extends CI_Javascript {
*
* Load a user interface library
*
- * @access public
* @return void
*/
- function ui($src, $relative = FALSE)
+ public function ui($src, $relative = FALSE)
{
$this->jquery_code_for_load[] = $this->external($src, $relative);
}
@@ -860,10 +809,9 @@ class CI_Jquery extends CI_Javascript {
*
* Creates a jQuery sortable
*
- * @access public
* @return void
*/
- function sortable($element, $options = array())
+ public function sortable($element, $options = array())
{
if (count($options) > 0)
@@ -871,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});";
}
// --------------------------------------------------------------------
@@ -888,16 +836,15 @@ class CI_Jquery extends CI_Javascript {
/**
* Table Sorter Plugin
*
- * @access public
* @param string table name
* @param string plugin location
* @return string
*/
- function tablesorter($table = '', $options = '')
+ 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";
}
-
+
// --------------------------------------------------------------------
// Class functions
// --------------------------------------------------------------------
@@ -907,13 +854,12 @@ class CI_Jquery extends CI_Javascript {
*
* Constructs the syntax for an event, and adds to into the array for compilation
*
- * @access private
* @param string The element to attach the event to
* @param string The code to execute
* @param string The event to pass
* @return string
- */
- function _add_event($element, $js, $event)
+ */
+ protected function _add_event($element, $js, $event)
{
if (is_array($js))
{
@@ -921,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;
}
@@ -934,65 +880,61 @@ class CI_Jquery extends CI_Javascript {
* As events are specified, they are stored in an array
* This funciton compiles them all for output on a page
*
- * @access private
* @return string
*/
- function _compile($view_var = 'script_foot', $script_tags = TRUE)
+ protected function _compile($view_var = 'script_foot', $script_tags = TRUE)
{
// External references
$external_scripts = implode('', $this->jquery_code_for_load);
$this->CI->load->vars(array('library_src' => $external_scripts));
- if (count($this->jquery_code_for_compile) == 0 )
+ if (count($this->jquery_code_for_compile) === 0)
{
// no inline references, let's just return
return;
}
// Inline references
- $script = '$(document).ready(function() {' . "\n";
- $script .= implode('', $this->jquery_code_for_compile);
- $script .= '});';
-
+ $script = '$(document).ready(function() {'."\n"
+ .implode('', $this->jquery_code_for_compile)
+ .'});';
+
$output = ($script_tags === FALSE) ? $script : $this->inline($script);
$this->CI->load->vars(array($view_var => $output));
}
-
+
// --------------------------------------------------------------------
-
+
/**
* Clear Compile
*
* Clears the array of script events collected for output
*
- * @access public
* @return void
*/
- function _clear_compile()
+ protected function _clear_compile()
{
$this->jquery_code_for_compile = array();
}
// --------------------------------------------------------------------
-
+
/**
* Document Ready
*
* A wrapper for writing document.ready()
*
- * @access private
* @return string
*/
- function _document_ready($js)
+ protected function _document_ready($js)
{
if ( ! is_array($js))
{
- $js = array ($js);
-
+ $js = array($js);
}
-
+
foreach ($js as $script)
{
$this->jquery_code_for_compile[] = $script;
@@ -1006,17 +948,16 @@ class CI_Jquery extends CI_Javascript {
*
* Outputs the script tag that loads the jquery.js file into an HTML document
*
- * @access public
* @param string
* @return string
*/
- function script($library_src = '', $relative = FALSE)
+ public function script($library_src = '', $relative = FALSE)
{
$library_src = $this->external($library_src, $relative);
$this->jquery_code_for_load[] = $library_src;
return $library_src;
}
-
+
// --------------------------------------------------------------------
/**
@@ -1026,20 +967,19 @@ class CI_Jquery extends CI_Javascript {
* unless the supplied element is the Javascript 'this'
* object, in which case no quotes are added
*
- * @access public
* @param string
* @return string
*/
- function _prep_element($element)
+ protected function _prep_element($element)
{
- if ($element != 'this')
+ if ($element !== 'this')
{
$element = '"'.$element.'"';
}
-
+
return $element;
}
-
+
// --------------------------------------------------------------------
/**
@@ -1047,21 +987,20 @@ class CI_Jquery extends CI_Javascript {
*
* Ensures the speed parameter is valid for jQuery
*
- * @access private
* @param string
* @return string
- */
- function _validate_speed($speed)
+ */
+ protected function _validate_speed($speed)
{
if (in_array($speed, array('slow', 'normal', 'fast')))
{
- $speed = '"'.$speed.'"';
+ return '"'.$speed.'"';
}
- elseif (preg_match("/[^0-9]/", $speed))
+ elseif (preg_match('/[^0-9]/', $speed))
{
- $speed = '';
+ return '';
}
-
+
return $speed;
}