summaryrefslogtreecommitdiffstats
path: root/system/libraries/Session/Session.php
diff options
context:
space:
mode:
Diffstat (limited to 'system/libraries/Session/Session.php')
-rw-r--r--system/libraries/Session/Session.php961
1 files changed, 535 insertions, 426 deletions
diff --git a/system/libraries/Session/Session.php b/system/libraries/Session/Session.php
index 452afd5e5..9c3b2b06c 100644
--- a/system/libraries/Session/Session.php
+++ b/system/libraries/Session/Session.php
@@ -40,729 +40,838 @@ defined('BASEPATH') OR exit('No direct script access allowed');
/**
* CodeIgniter Session Class
*
- * The user interface defined by EllisLab, now with puggable drivers to manage different storage mechanisms.
- * By default, the cookie session driver will load, but the 'sess_driver' config/param item (see above) can be
- * used to specify the 'native' driver, or any other you might create.
- * Once loaded, this driver setup is a drop-in replacement for the former CI_Session library, taking its place as the
- * 'session' member of the global controller framework (e.g.: $CI->session or $this->session).
- * In keeping with the CI_Driver methodology, multiple drivers may be loaded, although this might be a bit confusing.
- * The CI_Session library class keeps track of the most recently loaded driver as "current" to call for driver methods.
- * Ideally, one driver is loaded and all calls go directly through the main library interface. However, any methods
- * called through the specific driver will switch the "current" driver to itself before invoking the library method
- * (which will then call back into the driver for low-level operations). So, alternation between two drivers can be
- * achieved by specifying which driver to use for each call (e.g.: $this->session->native->set_userdata('foo', 'bar');
- * $this->session->cookie->userdata('foo'); $this->session->native->unset_userdata('foo');). Notice in the previous
- * example that the _native_ userdata value 'foo' would be set to 'bar', which would NOT be returned by the call for
- * the _cookie_ userdata 'foo', nor would the _cookie_ value be unset by the call to unset the _native_ 'foo' value.
- *
* @package CodeIgniter
* @subpackage Libraries
* @category Sessions
- * @author EllisLab Dev Team
+ * @author Andrey Andreev
* @link http://codeigniter.com/user_guide/libraries/sessions.html
*/
-class CI_Session extends CI_Driver_Library {
-
- /**
- * Initialization parameters
- *
- * @var array
- */
- public $params = array();
-
- /**
- * Valid drivers list
- *
- * @var array
- */
- public $valid_drivers = array('native', 'cookie');
-
- /**
- * Current driver in use
- *
- * @var string
- */
- public $current = NULL;
-
- /**
- * User data
- *
- * @var array
- */
- protected $userdata = array();
-
- // ------------------------------------------------------------------------
+class CI_Session {
- const FLASHDATA_KEY = 'flash';
- const FLASHDATA_NEW = ':new:';
- const FLASHDATA_OLD = ':old:';
- const FLASHDATA_EXP = ':exp:';
- const EXPIRATION_KEY = '__expirations';
- const TEMP_EXP_DEF = 300;
+ protected $_driver = 'files';
+ protected $_config;
// ------------------------------------------------------------------------
/**
- * CI_Session constructor
+ * Class constructor
*
- * The constructor loads the configured driver ('sess_driver' in config.php or as a parameter), running
- * routines in its constructor, and manages flashdata aging.
- *
- * @param array Configuration parameters
+ * @param array $params Configuration parameters
* @return void
*/
public function __construct(array $params = array())
{
- $_config =& get_instance()->config;
-
// No sessions under CLI
if (is_cli())
{
+ log_message('debug', 'Session: Initialization under CLI aborted.');
return;
}
-
- log_message('debug', 'CI_Session Class Initialized');
-
- // Add possible extra entries to our valid drivers list
- $drivers = isset($params['sess_valid_drivers']) ? $params['sess_valid_drivers'] : $_config->item('sess_valid_drivers');
- if ( ! empty($drivers))
+ elseif ((bool) ini_get('session.auto_start'))
+ {
+ log_message('error', 'Session: session.auto_start is enabled in php.ini. Aborting.');
+ return;
+ }
+ elseif ( ! empty($params['driver']))
{
- $drivers = array_map('strtolower', (array) $drivers);
- $this->valid_drivers = array_merge($this->valid_drivers, array_diff($drivers, $this->valid_drivers));
+ $this->_driver = $params['driver'];
+ unset($params['driver']);
}
-
- // Get driver to load
- $driver = isset($params['sess_driver']) ? $params['sess_driver'] : $_config->item('sess_driver');
- if ( ! $driver)
+ elseif ($driver = config_item('sess_driver'))
+ {
+ $this->_driver = $driver;
+ }
+ // Note: BC workaround
+ elseif (config_item('sess_use_database'))
{
- log_message('debug', "Session: No driver name is configured, defaulting to 'cookie'.");
- $driver = 'cookie';
+ $this->_driver = 'database';
}
- if ( ! in_array($driver, $this->valid_drivers))
+ if (($class = $this->_ci_load_classes($this->_driver)) === FALSE)
{
- log_message('error', 'Session: Configured driver name is not valid, aborting.');
return;
}
- // Save a copy of parameters in case drivers need access
- $this->params = $params;
+ // Configuration ...
+ $this->_configure($params);
+
+ $class = new $class($this->_config);
+ if ($class instanceof SessionHandlerInterface)
+ {
+ if (is_php('5.4'))
+ {
+ session_set_save_handler($class, TRUE);
+ }
+ else
+ {
+ session_set_save_handler(
+ array($class, 'open'),
+ array($class, 'close'),
+ array($class, 'read'),
+ array($class, 'write'),
+ array($class, 'destroy'),
+ array($class, 'gc')
+ );
+
+ register_shutdown_function('session_write_close');
+ }
+ }
+ else
+ {
+ log_message('error', "Session: Driver '".$this->_driver."' doesn't implement SessionHandlerInterface. Aborting.");
+ return;
+ }
- // Load driver and get array reference
- $this->load_driver($driver);
+ // Sanitize the cookie, because apparently PHP doesn't do that for userspace handlers
+ if (isset($_COOKIE[$this->_config['cookie_name']])
+ && (
+ ! is_string($_COOKIE[$this->_config['cookie_name']])
+ OR ! preg_match('/^[0-9a-f]{40}$/', $_COOKIE[$this->_config['cookie_name']])
+ )
+ )
+ {
+ unset($_COOKIE[$this->_config['cookie_name']]);
+ }
- // Delete 'old' flashdata (from last request)
- $this->_flashdata_sweep();
+ session_start();
- // Mark all new flashdata as old (data will be deleted before next request)
- $this->_flashdata_mark();
+ // Is session ID auto-regeneration configured? (ignoring ajax requests)
+ if ( ! empty($_SERVER['HTTP_X_REQUESTED_WITH'])
+ && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest'
+ && ($regenerate_time = config_item('sess_time_to_update')) > 0
+ )
+ {
+ if ( ! isset($_SESSION['__ci_last_regenerate']))
+ {
+ $_SESSION['__ci_last_regenerate'] = time();
+ }
+ elseif ($_SESSION['__ci_last_regenerate'] < (time() - $regenerate_time))
+ {
+ $this->sess_regenerate(FALSE);
+ }
+ }
+ // Another work-around ... PHP doesn't seem to send the session cookie
+ // unless it is being currently created or regenerated
+ elseif (isset($_COOKIE[$this->_config['cookie_name']]) && $_COOKIE[$this->_config['cookie_name']] === session_id())
+ {
+ setcookie(
+ $this->_config['cookie_name'],
+ session_id(),
+ (empty($this->_config['cookie_lifetime']) ? 0 : time() + $this->_config['cookie_lifetime']),
+ $this->_config['cookie_path'],
+ $this->_config['cookie_domain'],
+ $this->_config['cookie_secure'],
+ TRUE
+ );
+ }
- // Delete expired tempdata
- $this->_tempdata_sweep();
+ $this->_ci_init_vars();
- log_message('debug', 'CI_Session routines successfully run');
+ log_message('debug', "Session: Class initialized using '".$this->_driver."' driver.");
}
// ------------------------------------------------------------------------
- /**
- * Loads session storage driver
- *
- * @param string Driver classname
- * @return object Loaded driver object
- */
- public function load_driver($driver)
+ protected function _ci_load_classes($driver)
{
- // Save reference to most recently loaded driver as library default and sync userdata
- $this->current = parent::load_driver($driver);
- $this->userdata =& $this->current->get_userdata();
- return $this->current;
- }
+ // PHP 5.4 compatibility
+ interface_exists('SessionHandlerInterface', FALSE) OR require_once(BASEPATH.'libraries/Session/SessionHandlerInterface.php');
- // ------------------------------------------------------------------------
+ $prefix = config_item('subclass_prefix');
- /**
- * Select default session storage driver
- *
- * @param string Driver name
- * @return void
- */
- public function select_driver($driver)
- {
- // Validate driver name
- $prefix = (string) get_instance()->config->item('subclass_prefix');
- $child = strtolower(str_replace(array('CI_', $prefix, $this->lib_name.'_'), '', $driver));
- if (in_array($child, array_map('strtolower', $this->valid_drivers)))
+ if ( ! class_exists('CI_Session_driver', FALSE))
{
- // See if driver is loaded
- if (isset($this->$child))
+ require_once(
+ file_exists(APPPATH.'libraries/Session/Session_driver.php')
+ ? APPPATH.'libraries/Session/Session_driver.php'
+ : BASEPATH.'libraries/Session/Session_driver.php'
+ );
+
+ if (file_exists($file_path = APPPATH.'libraries/Session/'.$prefix.'Session_driver.php'))
{
- // See if driver is already current
- if ($this->$child !== $this->current)
- {
- // Make driver current and sync userdata
- $this->current = $this->$child;
- $this->userdata =& $this->current->get_userdata();
- }
+ require_once($file_path);
+ }
+ }
+
+ $class = 'Session_'.$driver.'_driver';
+
+ // Allow custom drivers without the CI_ or MY_ prefix
+ if ( ! class_exists($class, FALSE) && file_exists($file_path = APPPATH.'libraries/Session/drivers/'.$class.'.php'))
+ {
+ require_once($file_path);
+ if (class_exists($class, FALSE))
+ {
+ return $class;
+ }
+ }
+
+ if ( ! class_exists('CI_'.$class, FALSE))
+ {
+ if (file_exists($file_path = APPPATH.'libraries/Session/drivers/'.$class.'.php') OR file_exists($file_path = BASEPATH.'libraries/Session/drivers/'.$class.'.php'))
+ {
+ require_once($file_path);
+ }
+
+ if ( ! class_exists('CI_'.$class, FALSE) && ! class_exists($class, FALSE))
+ {
+ log_message('error', "Session: Configured driver '".$driver."' was not found. Aborting.");
+ return FALSE;
+ }
+ }
+
+ if ( ! class_exists($prefix.$class) && file_exists($file_path = APPPATH.'libraries/Session/drivers/'.$prefix.$class.'.php'))
+ {
+ require_once($file_path);
+ if (class_exists($prefix.$class, FALSE))
+ {
+ return $prefix.$class;
}
else
{
- // Load new driver
- $this->load_driver($child);
+ log_message('debug', 'Session: '.$prefix.$class.".php found but it doesn't declare class ".$prefix.$class.'.');
}
}
+
+ return 'CI_'.$class;
}
// ------------------------------------------------------------------------
/**
- * Destroy the current session
+ * Configuration
+ *
+ * Handle input parameters and configuration defaults
*
+ * @param array &$params Input parameters
* @return void
*/
- public function sess_destroy()
+ protected function _configure(&$params)
{
- // Just call destroy on driver
- $this->current->sess_destroy();
- }
+ $expiration = config_item('sess_expiration');
- // ------------------------------------------------------------------------
+ if (isset($params['cookie_lifetime']))
+ {
+ $params['cookie_lifetime'] = (int) $params['cookie_lifetime'];
+ }
+ else
+ {
+ $params['cookie_lifetime'] = ( ! isset($expiration) && config_item('sess_expire_on_close'))
+ ? 0 : (int) $expiration;
+ }
- /**
- * Regenerate the current session
- *
- * @param bool Destroy session data flag (default: false)
- * @return void
- */
- public function sess_regenerate($destroy = FALSE)
- {
- // Call regenerate on driver and resync userdata
- $this->current->sess_regenerate($destroy);
- $this->userdata =& $this->current->get_userdata();
- }
+ isset($params['cookie_name']) OR $params['cookie_name'] = config_item('sess_cookie_name');
+ if (empty($params['cookie_name']))
+ {
+ $params['cookie_name'] = ini_get('session.name');
+ }
+ else
+ {
+ ini_set('session.name', $params['cookie_name']);
+ }
- // ------------------------------------------------------------------------
+ isset($params['cookie_path']) OR $params['cookie_path'] = config_item('cookie_path');
+ isset($params['cookie_domain']) OR $params['cookie_domain'] = config_item('cookie_domain');
+ isset($params['cookie_secure']) OR $params['cookie_secure'] = (bool) config_item('cookie_secure');
- /**
- * Fetch a specific item from the session array
- *
- * @param string Item key
- * @return string Item value or NULL if not found
- */
- public function userdata($item = NULL)
- {
- if (isset($item))
+ session_set_cookie_params(
+ $params['cookie_lifetime'],
+ $params['cookie_path'],
+ $params['cookie_domain'],
+ $params['cookie_secure'],
+ TRUE // HttpOnly; Yes, this is intentional and not configurable for security reasons
+ );
+
+ if (empty($expiration))
+ {
+ $params['expiration'] = (int) ini_get('session.gc_maxlifetime');
+ }
+ else
{
- return isset($this->userdata[$item]) ? $this->userdata[$item] : NULL;
+ $params['expiration'] = (int) $expiration;
+ ini_set('session.gc_maxlifetime', $expiration);
}
- return isset($this->userdata) ? $this->userdata : array();
- }
+ $params['match_ip'] = (bool) (isset($params['match_ip']) ? $params['match_ip'] : config_item('sess_match_ip'));
- // ------------------------------------------------------------------------
+ isset($params['save_path']) OR $params['save_path'] = config_item('sess_save_path');
- /**
- * Fetch all session data
- *
- * @deprecated 3.0.0 Use userdata() with no parameters instead
- * @return array User data array
- */
- public function all_userdata()
- {
- return isset($this->userdata) ? $this->userdata : array();
+ $this->_config = $params;
+
+ // Security is king
+ ini_set('session.use_trans_id', 0);
+ ini_set('session.use_strict_mode', 1);
+ ini_set('session.use_cookies', 1);
+ ini_set('session.use_only_cookies', 1);
+ ini_set('session.hash_function', 1);
+ ini_set('session.hash_bits_per_character', 4);
}
// ------------------------------------------------------------------------
/**
- * Add or change data in the "userdata" array
+ * Handle temporary variables
+ *
+ * Clears old "flash" data, marks the new one for deletion and handles
+ * "temp" data deletion.
*
- * @param mixed Item name or array of items
- * @param string Item value or empty string
* @return void
*/
- public function set_userdata($newdata, $newval = '')
+ protected function _ci_init_vars()
{
- // Wrap params as array if singular
- if (is_string($newdata))
+ if ( ! empty($_SESSION['__ci_vars']))
{
- $newdata = array($newdata => $newval);
- }
+ $current_time = time();
- // Set each name/value pair
- if (count($newdata) > 0)
- {
- foreach ($newdata as $key => $val)
+ foreach ($_SESSION['__ci_vars'] as $key => &$value)
{
- $this->userdata[$key] = $val;
+ if ($value === 'new')
+ {
+ $_SESSION['__ci_vars'][$key] = 'old';
+ }
+ // Hacky, but 'old' will (implicitly) always be less than time() ;)
+ // DO NOT move this above the 'new' check!
+ elseif ($value < $current_time)
+ {
+ unset($_SESSION[$key], $_SESSION['__ci_vars'][$key]);
+ }
}
- }
- // Tell driver data changed
- $this->current->sess_save();
+ if (empty($_SESSION['__ci_vars']))
+ {
+ unset($_SESSION['__ci_vars']);
+ }
+ }
}
// ------------------------------------------------------------------------
/**
- * Delete a session variable from the "userdata" array
+ * Mark as flash
*
- * @param mixed Item name or array of item names
- * @return void
+ * @param mixed $key Session data key(s)
+ * @return bool
*/
- public function unset_userdata($newdata)
+ public function mark_as_flash($key)
{
- // Wrap single name as array
- if (is_string($newdata))
+ if (is_array($key))
{
- $newdata = array($newdata => '');
+ for ($i = 0, $c = count($key); $i < $c; $i++)
+ {
+ if ( ! isset($_SESSION[$key[$i]]))
+ {
+ return FALSE;
+ }
+ }
+
+ $new = array_fill_keys($key, 'new');
+
+ $_SESSION['__ci_vars'] = isset($_SESSION['__ci_vars'])
+ ? array_merge($_SESSION['__ci_vars'], $new)
+ : $new;
+
+ return TRUE;
}
- // Unset each item name
- if (count($newdata) > 0)
+ if ( ! isset($_SESSION[$key]))
{
- foreach (array_keys($newdata) as $key)
- {
- unset($this->userdata[$key]);
- }
+ return FALSE;
}
- // Tell driver data changed
- $this->current->sess_save();
+ $_SESSION['__ci_vars'][$key] = 'new';
+ return TRUE;
}
// ------------------------------------------------------------------------
/**
- * Determine if an item exists
+ * Get flash keys
*
- * @param string Item name
- * @return bool
+ * @return array
*/
- public function has_userdata($item)
+ public function get_flash_keys()
{
- return isset($this->userdata[$item]);
+ if ( ! isset($_SESSION['__ci_vars']))
+ {
+ return array();
+ }
+
+ $keys = array();
+ foreach (array_keys($_SESSION['__ci_vars']) as $key)
+ {
+ is_int($_SESSION['__ci_vars'][$key]) OR $keys[] = $key;
+ }
+
+ return $keys;
}
// ------------------------------------------------------------------------
/**
- * Add or change flashdata, only available until the next request
+ * Unmark flash
*
- * @param mixed Item name or array of items
- * @param string Item value or empty string
+ * @param mixed $key Session data key(s)
* @return void
*/
- public function set_flashdata($newdata, $newval = '')
+ public function unmark_flash($key)
{
- // Wrap item as array if singular
- if (is_string($newdata))
+ if (empty($_SESSION['__ci_vars']))
{
- $newdata = array($newdata => $newval);
+ return;
}
- // Prepend each key name and set value
- if (count($newdata) > 0)
+ is_array($key) OR $key = array($key);
+
+ foreach ($key as $k)
{
- foreach ($newdata as $key => $val)
+ if (isset($_SESSION['__ci_vars'][$k]) && ! is_int($_SESSION['__ci_vars'][$k]))
{
- $flashdata_key = self::FLASHDATA_KEY.self::FLASHDATA_NEW.$key;
- $this->set_userdata($flashdata_key, $val);
+ unset($_SESSION['__ci_vars'][$k]);
}
}
+
+ if (empty($_SESSION['__ci_vars']))
+ {
+ unset($_SESSION['__ci_vars']);
+ }
}
// ------------------------------------------------------------------------
/**
- * Keeps existing flashdata available to next request.
+ * Mark as temp
*
- * @param mixed Item key(s)
- * @return void
+ * @param mixed $key Session data key(s)
+ * @param int $ttl Time-to-live in seconds
+ * @return bool
*/
- public function keep_flashdata($key)
+ public function mark_as_temp($key, $ttl = 300)
{
+ $ttl += time();
if (is_array($key))
{
- foreach ($key as $k)
+ $temp = array();
+
+ foreach ($key as $k => $v)
{
- $this->keep_flashdata($k);
+ // Do we have a key => ttl pair, or just a key?
+ if (is_int($k))
+ {
+ $k = $v;
+ $v = $ttl;
+ }
+ else
+ {
+ $v += time();
+ }
+
+ if ( ! isset($_SESSION[$k]))
+ {
+ return FALSE;
+ }
+
+ $temp[$k] = $ts;
}
- return;
+ $_SESSION['__ci_vars'] = isset($_SESSION['__ci_vars'])
+ ? array_merge($_SESSION['__ci_vars'], $temp)
+ : $temp;
+
+ return TRUE;
}
- // '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);
+ if ( ! isset($_SESSION[$key]))
+ {
+ return FALSE;
+ }
- $new_flashdata_key = self::FLASHDATA_KEY.self::FLASHDATA_NEW.$key;
- $this->set_userdata($new_flashdata_key, $value);
+ $_SESSION['__ci_vars'][$key] = $ttl;
+ return TRUE;
}
// ------------------------------------------------------------------------
/**
- * Fetch a specific flashdata item from the session array
+ * Get temp keys
*
- * @param string Item key
- * @return string
+ * @return array
*/
- public function flashdata($key = NULL)
+ public function get_temp_keys()
{
- if (isset($key))
+ if ( ! isset($_SESSION['__ci_vars']))
{
- return $this->userdata(self::FLASHDATA_KEY.self::FLASHDATA_OLD.$key);
+ return array();
}
- // Get our flashdata items from userdata
- $out = array();
- foreach ($this->userdata() as $key => $val)
+ $keys = array();
+ foreach (array_keys($_SESSION['__ci_vars']) as $key)
{
- if (strpos($key, self::FLASHDATA_KEY.self::FLASHDATA_OLD) !== FALSE)
- {
- $key = str_replace(self::FLASHDATA_KEY.self::FLASHDATA_OLD, '', $key);
- $out[$key] = $val;
- }
+ is_int($_SESSION['__ci_vars'][$key]) && $keys[] = $key;
}
- return $out;
+ return $keys;
}
// ------------------------------------------------------------------------
/**
- * Add or change tempdata, only available until expiration
+ * Unmark flash
*
- * @param mixed Item name or array of items
- * @param string Item value or empty string
- * @param int Item lifetime in seconds or 0 for default
+ * @param mixed $key Session data key(s)
* @return void
*/
- public function set_tempdata($newdata, $newval = '', $expire = 0)
+ public function unmark_temp($key)
{
- // Set expiration time
- $expire = time() + ($expire ? $expire : self::TEMP_EXP_DEF);
-
- // Wrap item as array if singular
- if (is_string($newdata))
+ if (empty($_SESSION['__ci_vars']))
{
- $newdata = array($newdata => $newval);
+ return;
}
- // Get or create expiration list
- $expirations = $this->userdata(self::EXPIRATION_KEY);
- if ( ! $expirations)
- {
- $expirations = array();
- }
+ is_array($key) OR $key = array($key);
- // Prepend each key name and set value
- if (count($newdata) > 0)
+ foreach ($key as $k)
{
- foreach ($newdata as $key => $val)
+ if (isset($_SESSION['__ci_vars'][$k]) && is_int($_SESSION['__ci_vars'][$k]))
{
- $tempdata_key = self::FLASHDATA_KEY.self::FLASHDATA_EXP.$key;
- $expirations[$tempdata_key] = $expire;
- $this->set_userdata($tempdata_key, $val);
+ unset($_SESSION['__ci_vars'][$k]);
}
}
- // Update expiration list
- $this->set_userdata(self::EXPIRATION_KEY, $expirations);
+ if (empty($_SESSION['__ci_vars']))
+ {
+ unset($_SESSION['__ci_vars']);
+ }
}
// ------------------------------------------------------------------------
/**
- * Delete a temporary session variable from the "userdata" array
+ * __get()
*
- * @param mixed Item name or array of item names
- * @return void
+ * @param string $key 'session_id' or a session data key
+ * @return mixed
*/
- public function unset_tempdata($newdata)
+ public function __get($key)
{
- // Get expirations list
- $expirations = $this->userdata(self::EXPIRATION_KEY);
- if (empty($expirations))
+ // Note: Keep this order the same, just in case somebody wants to
+ // use 'session_id' as a session data key, for whatever reason
+ if (isset($_SESSION[$key]))
{
- // Nothing to do
- return;
+ return $_SESSION[$key];
}
-
- // Wrap single name as array
- if (is_string($newdata))
+ elseif ($key === 'session_id')
{
- $newdata = array($newdata => '');
+ return session_id();
}
- // Prepend each item name and unset
- if (count($newdata) > 0)
- {
- foreach (array_keys($newdata) as $key)
- {
- $tempdata_key = self::FLASHDATA_KEY.self::FLASHDATA_EXP.$key;
- unset($expirations[$tempdata_key]);
- $this->unset_userdata($tempdata_key);
- }
- }
-
- // Update expiration list
- $this->set_userdata(self::EXPIRATION_KEY, $expirations);
+ return NULL;
}
// ------------------------------------------------------------------------
/**
- * Fetch a specific tempdata item from the session array
+ * __set()
*
- * @param string Item key
- * @return string
+ * @param string $key Session data key
+ * @param mixed $value Session data value
+ * @return void
*/
- public function tempdata($key = NULL)
+ public function __set($key, $value)
{
- if (isset($key))
- {
- return $this->userdata(self::FLASHDATA_KEY.self::FLASHDATA_EXP.$key);
- }
+ $_SESSION[$key] = $value;
+ }
- // Get our tempdata items from userdata
- $out = array();
- foreach ($this->userdata() as $key => $val)
- {
- if (strpos($key, self::FLASHDATA_KEY.self::FLASHDATA_EXP) !== FALSE)
- {
- $key = str_replace(self::FLASHDATA_KEY.self::FLASHDATA_EXP, '', $key);
- $out[$key] = $val;
- }
- }
+ // ------------------------------------------------------------------------
- return $out;
+ /**
+ * Session destroy
+ *
+ * Legacy CI_Session compatibility method
+ *
+ * @return void
+ */
+ public function sess_destroy()
+ {
+ session_destroy();
}
// ------------------------------------------------------------------------
/**
- * Identifies flashdata as 'old' for removal
- * when _flashdata_sweep() runs.
+ * Session regenerate
*
+ * Legacy CI_Session compatibility method
+ *
+ * @param bool $destroy Destroy old session data flag
* @return void
*/
- protected function _flashdata_mark()
+ public function sess_regenerate($destroy = FALSE)
{
- foreach ($this->userdata() as $name => $value)
- {
- $parts = explode(self::FLASHDATA_NEW, $name);
- if (count($parts) === 2)
- {
- $this->set_userdata(self::FLASHDATA_KEY.self::FLASHDATA_OLD.$parts[1], $value);
- $this->unset_userdata($name);
- }
- }
+ $_SESSION['__ci_last_regenerate'] = time();
+ session_regenerate_id($destroy);
}
// ------------------------------------------------------------------------
/**
- * Removes all flashdata marked as 'old'
+ * Get userdata reference
*
- * @return void
+ * Legacy CI_Session compatibility method
+ *
+ * @returns array
*/
- protected function _flashdata_sweep()
+ public function &get_userdata()
{
- $userdata = $this->userdata();
- foreach (array_keys($userdata) as $key)
- {
- if (strpos($key, self::FLASHDATA_OLD))
- {
- $this->unset_userdata($key);
- }
- }
+ return $_SESSION;
}
// ------------------------------------------------------------------------
/**
- * Removes all expired tempdata
+ * Userdata (fetch)
*
- * @return void
+ * Legacy CI_Session compatibility method
+ *
+ * @param string $key Session data key
+ * @return mixed Session data value or NULL if not found
*/
- protected function _tempdata_sweep()
+ public function userdata($key = NULL)
{
- // Get expirations list
- $expirations = $this->userdata(self::EXPIRATION_KEY);
- if (empty($expirations))
+ if (isset($key))
{
- // Nothing to do
- return;
+ return isset($_SESSION[$key]) ? $_SESSION[$key] : NULL;
}
+ elseif (empty($_SESSION))
+ {
+ return array();
+ }
+
+ $userdata = array();
+ $_exclude = array_merge(
+ array('__ci_vars'),
+ $this->get_flash_keys(),
+ $this->get_temp_keys()
+ );
- // Unset expired elements
- $now = time();
- $userdata = $this->userdata();
- foreach (array_keys($userdata) as $key)
+ foreach (array_keys($_SESSION) as $key)
{
- if (strpos($key, self::FLASHDATA_EXP) && $expirations[$key] < $now)
+ if ( ! in_array($key, $_exclude, TRUE))
{
- unset($expirations[$key]);
- $this->unset_userdata($key);
+ $userdata[$key] = $_SESSION[$key];
}
}
- // Update expiration list
- $this->set_userdata(self::EXPIRATION_KEY, $expirations);
+ return $userdata;
}
-}
-
-// ------------------------------------------------------------------------
-
-/**
- * CI_Session_driver Class
- *
- * Extend this class to make a new CI_Session driver.
- * A CI_Session driver basically manages an array of name/value pairs with some sort of storage mechanism.
- * To make a new driver, derive from (extend) CI_Session_driver. Overload the initialize method and read or create
- * session data. Then implement a save handler to write changed data to storage (sess_save), a destroy handler
- * to remove deleted data (sess_destroy), and an access handler to expose the data (get_userdata).
- * Put your driver in the libraries/Session/drivers folder anywhere in the loader paths. This includes the
- * application directory, the system directory, or any path you add with $CI->load->add_package_path().
- * Your driver must be named CI_Session_<name>, and your filename must be Session_<name>.php,
- * preferably also capitalized. (e.g.: CI_Session_foo in libraries/Session/drivers/Session_foo.php)
- * Then specify the driver by setting 'sess_driver' in your config file or as a parameter when loading the CI_Session
- * object. (e.g.: $config['sess_driver'] = 'foo'; OR $CI->load->driver('session', array('sess_driver' => 'foo')); )
- * Already provided are the Native driver, which manages the native PHP $_SESSION array, and
- * the Cookie driver, which manages the data in a browser cookie, with optional extra storage in a database table.
- *
- * @package CodeIgniter
- * @subpackage Libraries
- * @category Sessions
- * @author EllisLab Dev Team
- */
-abstract class CI_Session_driver extends CI_Driver {
+ // ------------------------------------------------------------------------
/**
- * CI Singleton
+ * Set userdata
+ *
+ * Legacy CI_Session compatibility method
*
- * @see get_instance()
- * @var object
+ * @param mixed $data Session data key or an associative array
+ * @param mixed $value Value to store
+ * @return void
*/
- protected $CI;
+ public function set_userdata($data, $value = NULL)
+ {
+ if (is_array($data))
+ {
+ foreach ($data as $key => &$value)
+ {
+ $_SESSION[$key] = $value;
+ }
+
+ return;
+ }
+
+ $_SESSION[$data] = $value;
+ }
// ------------------------------------------------------------------------
/**
- * Constructor
+ * Unset userdata
*
- * Gets the CI singleton, so that individual drivers
- * don't have to do it separately.
+ * Legacy CI_Session compatibility method
*
+ * @param mixed $data Session data key(s)
* @return void
*/
- public function __construct()
+ public function unset_userdata($key)
{
- $this->CI =& get_instance();
+ if (is_array($key))
+ {
+ foreach ($key as $k)
+ {
+ unset($_SESSION[$k]);
+ }
+
+ return;
+ }
+
+ unset($_SESSION[$key]);
}
// ------------------------------------------------------------------------
/**
- * Decorate
+ * All userdata (fetch)
*
- * Decorates the child with the parent driver lib's methods and properties
+ * Legacy CI_Session compatibility method
*
- * @param object Parent library object
- * @return void
+ * @return array $_SESSION, excluding flash data items
*/
- public function decorate($parent)
+ public function all_userdata()
{
- // Call base class decorate first
- parent::decorate($parent);
+ return $this->userdata();
+ }
+
+ // ------------------------------------------------------------------------
- // Call initialize method now that driver has access to $this->_parent
- $this->initialize();
+ /**
+ * Has userdata
+ *
+ * Legacy CI_Session compatibility method
+ *
+ * @param string $key Session data key
+ * @return bool
+ */
+ public function has_userdata($key)
+ {
+ return isset($_SESSION[$key]);
}
// ------------------------------------------------------------------------
/**
- * __call magic method
+ * Flashdata (fetch)
*
- * Handles access to the parent driver library's methods
+ * Legacy CI_Session compatibility method
*
- * @param string Library method name
- * @param array Method arguments (default: none)
- * @return mixed
+ * @param string $key Session data key
+ * @return mixed Session data value or NULL if not found
*/
- public function __call($method, $args = array())
+ public function flashdata($key = NULL)
{
- // Make sure the parent library uses this driver
- $this->_parent->select_driver(get_class($this));
- return parent::__call($method, $args);
+ if (isset($key))
+ {
+ return (isset($_SESSION['__ci_vars'], $_SESSION['__ci_vars'][$key], $_SESSION[$key]) && ! is_int($_SESSION['__ci_vars'][$key]))
+ ? $_SESSION[$key]
+ : NULL;
+ }
+
+ $flashdata = array();
+
+ if ( ! empty($_SESSION['__ci_vars']))
+ {
+ foreach ($_SESSION['__ci_vars'] as $key => &$value)
+ {
+ is_int($value) OR $flashdata[$key] = $_SESSION[$key];
+ }
+ }
+
+ return $flashdata;
}
// ------------------------------------------------------------------------
/**
- * Initialize driver
+ * Set flashdata
+ *
+ * Legacy CI_Session compatibiliy method
*
+ * @param mixed $data Session data key or an associative array
+ * @param mixed $value Value to store
* @return void
*/
- protected function initialize()
+ public function set_flashdata($data, $value = NULL)
{
- // Overload this method to implement initialization
+ $this->set_userdata($data, $value);
+ $this->mark_as_flash(is_array($data) ? array_keys($data) : $data);
}
// ------------------------------------------------------------------------
/**
- * Save the session data
+ * Keep flashdata
*
- * Data in the array has changed - perform any storage synchronization
- * necessary. The child class MUST implement this abstract method!
+ * Legacy CI_Session compatibility method
*
+ * @param mixed $key Session data key(s)
* @return void
*/
- abstract public function sess_save();
+ public function keep_flashdata($key)
+ {
+ $this->mark_as_flash($key);
+ }
// ------------------------------------------------------------------------
/**
- * Destroy the current session
+ * Temp data (fetch)
*
- * Clean up storage for this session - it has been terminated.
- * The child class MUST implement this abstract method!
+ * Legacy CI_Session compatibility method
*
- * @return void
+ * @param string $key Session data key
+ * @return mixed Session data value or NULL if not found
*/
- abstract public function sess_destroy();
+ public function tempdata($key = NULL)
+ {
+ if (isset($key))
+ {
+ return (isset($_SESSION['__ci_vars'], $_SESSION['__ci_vars'][$key], $_SESSION[$key]) && is_int($_SESSION['__ci_vars'][$key]))
+ ? $_SESSION[$key]
+ : NULL;
+ }
+
+ $tempdata = array();
+
+ if ( ! empty($_SESSION['__ci_vars']))
+ {
+ foreach ($_SESSION['__ci_vars'] as $key => &$value)
+ {
+ is_int($value) && $tempdata[$key] = $_SESSION[$key];
+ }
+ }
+
+ return $tempdata;
+ }
// ------------------------------------------------------------------------
/**
- * Regenerate the current session
+ * Set tempdata
*
- * Regenerate the session ID.
- * The child class MUST implement this abstract method!
+ * Legacy CI_Session compatibility method
*
- * @param bool Destroy session data flag (default: false)
+ * @param mixed $data Session data key or an associative array of items
+ * @param mixed $value Value to store
+ * @param int $ttl Time-to-live in seconds
* @return void
*/
- abstract public function sess_regenerate($destroy = FALSE);
+ public function set_tempdata($data, $value = NULL, $ttl = 300)
+ {
+ $this->set_userdata($data, $value);
+ $this->mark_as_temp($data, $ttl);
+ }
// ------------------------------------------------------------------------
/**
- * Get a reference to user data array
+ * Unset tempdata
*
- * Give array access to the main CI_Session object.
- * The child class MUST implement this abstract method!
+ * Legacy CI_Session compatibility method
*
- * @return array Reference to userdata
+ * @param mixed $data Session data key(s)
+ * @return void
*/
- abstract public function &get_userdata();
+ public function unset_tempdata($key)
+ {
+ $this->unmark_temp($key);
+ }
}