summaryrefslogtreecommitdiffstats
path: root/system/libraries/Session
diff options
context:
space:
mode:
authorFlorian Pritz <bluewind@xinu.at>2017-09-26 13:46:14 +0200
committerFlorian Pritz <bluewind@xinu.at>2017-09-26 13:46:14 +0200
commit3ff6ffa3341c876b741feb66552cdd110b67872e (patch)
tree69e11cd0009ddd1346f2dc4cd8c47244368db28e /system/libraries/Session
parentbc2f7f596f727e204e8b8c5b849545745b3cbfaa (diff)
parent81a4c8c630ef59cffea0c24e64fb6fa7f09bfcf6 (diff)
Merge CodeIgniter 3 support
Diffstat (limited to 'system/libraries/Session')
-rw-r--r--system/libraries/Session/Session.php985
-rw-r--r--system/libraries/Session/SessionHandlerInterface.php59
-rw-r--r--system/libraries/Session/Session_driver.php191
-rw-r--r--system/libraries/Session/drivers/Session_database_driver.php420
-rw-r--r--system/libraries/Session/drivers/Session_files_driver.php406
-rw-r--r--system/libraries/Session/drivers/Session_memcached_driver.php375
-rw-r--r--system/libraries/Session/drivers/Session_redis_driver.php395
-rw-r--r--system/libraries/Session/drivers/index.html11
-rw-r--r--system/libraries/Session/index.html11
9 files changed, 2853 insertions, 0 deletions
diff --git a/system/libraries/Session/Session.php b/system/libraries/Session/Session.php
new file mode 100644
index 000000000..eb433de64
--- /dev/null
+++ b/system/libraries/Session/Session.php
@@ -0,0 +1,985 @@
+<?php
+/**
+ * CodeIgniter
+ *
+ * An open source application development framework for PHP
+ *
+ * This content is released under the MIT License (MIT)
+ *
+ * Copyright (c) 2014 - 2017, British Columbia Institute of Technology
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ *
+ * @package CodeIgniter
+ * @author EllisLab Dev Team
+ * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (https://ellislab.com/)
+ * @copyright Copyright (c) 2014 - 2017, British Columbia Institute of Technology (http://bcit.ca/)
+ * @license http://opensource.org/licenses/MIT MIT License
+ * @link https://codeigniter.com
+ * @since Version 2.0.0
+ * @filesource
+ */
+defined('BASEPATH') OR exit('No direct script access allowed');
+
+/**
+ * CodeIgniter Session Class
+ *
+ * @package CodeIgniter
+ * @subpackage Libraries
+ * @category Sessions
+ * @author Andrey Andreev
+ * @link https://codeigniter.com/user_guide/libraries/sessions.html
+ */
+class CI_Session {
+
+ /**
+ * Userdata array
+ *
+ * Just a reference to $_SESSION, for BC purposes.
+ */
+ public $userdata;
+
+ protected $_driver = 'files';
+ protected $_config;
+ protected $_sid_regexp;
+
+ // ------------------------------------------------------------------------
+
+ /**
+ * Class constructor
+ *
+ * @param array $params Configuration parameters
+ * @return void
+ */
+ public function __construct(array $params = array())
+ {
+ // No sessions under CLI
+ if (is_cli())
+ {
+ log_message('debug', 'Session: Initialization under CLI aborted.');
+ return;
+ }
+ 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']))
+ {
+ $this->_driver = $params['driver'];
+ unset($params['driver']);
+ }
+ elseif ($driver = config_item('sess_driver'))
+ {
+ $this->_driver = $driver;
+ }
+ // Note: BC workaround
+ elseif (config_item('sess_use_database'))
+ {
+ log_message('debug', 'Session: "sess_driver" is empty; using BC fallback to "sess_use_database".');
+ $this->_driver = 'database';
+ }
+
+ $class = $this->_ci_load_classes($this->_driver);
+
+ // Configuration ...
+ $this->_configure($params);
+ $this->_config['_sid_regexp'] = $this->_sid_regexp;
+
+ $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;
+ }
+
+ // 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('#\A'.$this->_sid_regexp.'\z#', $_COOKIE[$this->_config['cookie_name']])
+ )
+ )
+ {
+ unset($_COOKIE[$this->_config['cookie_name']]);
+ }
+
+ session_start();
+
+ // Is session ID auto-regeneration configured? (ignoring ajax requests)
+ if ((empty($_SERVER['HTTP_X_REQUESTED_WITH']) OR 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((bool) config_item('sess_regenerate_destroy'));
+ }
+ }
+ // 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
+ );
+ }
+
+ $this->_ci_init_vars();
+
+ log_message('info', "Session: Class initialized using '".$this->_driver."' driver.");
+ }
+
+ // ------------------------------------------------------------------------
+
+ /**
+ * CI Load Classes
+ *
+ * An internal method to load all possible dependency and extension
+ * classes. It kind of emulates the CI_Driver library, but is
+ * self-sufficient.
+ *
+ * @param string $driver Driver name
+ * @return string Driver class name
+ */
+ protected function _ci_load_classes($driver)
+ {
+ // PHP 5.4 compatibility
+ interface_exists('SessionHandlerInterface', FALSE) OR require_once(BASEPATH.'libraries/Session/SessionHandlerInterface.php');
+
+ $prefix = config_item('subclass_prefix');
+
+ if ( ! class_exists('CI_Session_driver', FALSE))
+ {
+ 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'))
+ {
+ 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))
+ {
+ throw new UnexpectedValueException("Session: Configured driver '".$driver."' was not found. Aborting.");
+ }
+ }
+
+ if ( ! class_exists($prefix.$class, FALSE) && 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
+ {
+ log_message('debug', 'Session: '.$prefix.$class.".php found but it doesn't declare class ".$prefix.$class.'.');
+ }
+ }
+
+ return 'CI_'.$class;
+ }
+
+ // ------------------------------------------------------------------------
+
+ /**
+ * Configuration
+ *
+ * Handle input parameters and configuration defaults
+ *
+ * @param array &$params Input parameters
+ * @return void
+ */
+ protected function _configure(&$params)
+ {
+ $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;
+ }
+
+ 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');
+
+ 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
+ {
+ $params['expiration'] = (int) $expiration;
+ ini_set('session.gc_maxlifetime', $expiration);
+ }
+
+ $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');
+
+ $this->_config = $params;
+
+ // Security is king
+ ini_set('session.use_trans_sid', 0);
+ ini_set('session.use_strict_mode', 1);
+ ini_set('session.use_cookies', 1);
+ ini_set('session.use_only_cookies', 1);
+
+ $this->_configure_sid_length();
+ }
+
+ // ------------------------------------------------------------------------
+
+ /**
+ * Configure session ID length
+ *
+ * To make life easier, we used to force SHA-1 and 4 bits per
+ * character on everyone. And of course, someone was unhappy.
+ *
+ * Then PHP 7.1 broke backwards-compatibility because ext/session
+ * is such a mess that nobody wants to touch it with a pole stick,
+ * and the one guy who does, nobody has the energy to argue with.
+ *
+ * So we were forced to make changes, and OF COURSE something was
+ * going to break and now we have this pile of shit. -- Narf
+ *
+ * @return void
+ */
+ protected function _configure_sid_length()
+ {
+ if (PHP_VERSION_ID < 70100)
+ {
+ $hash_function = ini_get('session.hash_function');
+ if (ctype_digit($hash_function))
+ {
+ if ($hash_function !== '1')
+ {
+ ini_set('session.hash_function', 1);
+ }
+
+ $bits = 160;
+ }
+ elseif ( ! in_array($hash_function, hash_algos(), TRUE))
+ {
+ ini_set('session.hash_function', 1);
+ $bits = 160;
+ }
+ elseif (($bits = strlen(hash($hash_function, 'dummy', false)) * 4) < 160)
+ {
+ ini_set('session.hash_function', 1);
+ $bits = 160;
+ }
+
+ $bits_per_character = (int) ini_get('session.hash_bits_per_character');
+ $sid_length = (int) ceil($bits / $bits_per_character);
+ }
+ else
+ {
+ $bits_per_character = (int) ini_get('session.sid_bits_per_character');
+ $sid_length = (int) ini_get('session.sid_length');
+ if (($bits = $sid_length * $bits_per_character) < 160)
+ {
+ // Add as many more characters as necessary to reach at least 160 bits
+ $sid_length += (int) ceil((160 % $bits) / $bits_per_character);
+ ini_set('session.sid_length', $sid_length);
+ }
+ }
+
+ // Yes, 4,5,6 are the only known possible values as of 2016-10-27
+ switch ($bits_per_character)
+ {
+ case 4:
+ $this->_sid_regexp = '[0-9a-f]';
+ break;
+ case 5:
+ $this->_sid_regexp = '[0-9a-v]';
+ break;
+ case 6:
+ $this->_sid_regexp = '[0-9a-zA-Z,-]';
+ break;
+ }
+
+ $this->_sid_regexp .= '{'.$sid_length.'}';
+ }
+
+ // ------------------------------------------------------------------------
+
+ /**
+ * Handle temporary variables
+ *
+ * Clears old "flash" data, marks the new one for deletion and handles
+ * "temp" data deletion.
+ *
+ * @return void
+ */
+ protected function _ci_init_vars()
+ {
+ if ( ! empty($_SESSION['__ci_vars']))
+ {
+ $current_time = time();
+
+ foreach ($_SESSION['__ci_vars'] as $key => &$value)
+ {
+ 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]);
+ }
+ }
+
+ if (empty($_SESSION['__ci_vars']))
+ {
+ unset($_SESSION['__ci_vars']);
+ }
+ }
+
+ $this->userdata =& $_SESSION;
+ }
+
+ // ------------------------------------------------------------------------
+
+ /**
+ * Mark as flash
+ *
+ * @param mixed $key Session data key(s)
+ * @return bool
+ */
+ public function mark_as_flash($key)
+ {
+ if (is_array($key))
+ {
+ 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;
+ }
+
+ if ( ! isset($_SESSION[$key]))
+ {
+ return FALSE;
+ }
+
+ $_SESSION['__ci_vars'][$key] = 'new';
+ return TRUE;
+ }
+
+ // ------------------------------------------------------------------------
+
+ /**
+ * Get flash keys
+ *
+ * @return array
+ */
+ public function get_flash_keys()
+ {
+ 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;
+ }
+
+ // ------------------------------------------------------------------------
+
+ /**
+ * Unmark flash
+ *
+ * @param mixed $key Session data key(s)
+ * @return void
+ */
+ public function unmark_flash($key)
+ {
+ if (empty($_SESSION['__ci_vars']))
+ {
+ return;
+ }
+
+ is_array($key) OR $key = array($key);
+
+ foreach ($key as $k)
+ {
+ if (isset($_SESSION['__ci_vars'][$k]) && ! is_int($_SESSION['__ci_vars'][$k]))
+ {
+ unset($_SESSION['__ci_vars'][$k]);
+ }
+ }
+
+ if (empty($_SESSION['__ci_vars']))
+ {
+ unset($_SESSION['__ci_vars']);
+ }
+ }
+
+ // ------------------------------------------------------------------------
+
+ /**
+ * Mark as temp
+ *
+ * @param mixed $key Session data key(s)
+ * @param int $ttl Time-to-live in seconds
+ * @return bool
+ */
+ public function mark_as_temp($key, $ttl = 300)
+ {
+ $ttl += time();
+
+ if (is_array($key))
+ {
+ $temp = array();
+
+ foreach ($key as $k => $v)
+ {
+ // 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] = $v;
+ }
+
+ $_SESSION['__ci_vars'] = isset($_SESSION['__ci_vars'])
+ ? array_merge($_SESSION['__ci_vars'], $temp)
+ : $temp;
+
+ return TRUE;
+ }
+
+ if ( ! isset($_SESSION[$key]))
+ {
+ return FALSE;
+ }
+
+ $_SESSION['__ci_vars'][$key] = $ttl;
+ return TRUE;
+ }
+
+ // ------------------------------------------------------------------------
+
+ /**
+ * Get temp keys
+ *
+ * @return array
+ */
+ public function get_temp_keys()
+ {
+ if ( ! isset($_SESSION['__ci_vars']))
+ {
+ return array();
+ }
+
+ $keys = array();
+ foreach (array_keys($_SESSION['__ci_vars']) as $key)
+ {
+ is_int($_SESSION['__ci_vars'][$key]) && $keys[] = $key;
+ }
+
+ return $keys;
+ }
+
+ // ------------------------------------------------------------------------
+
+ /**
+ * Unmark flash
+ *
+ * @param mixed $key Session data key(s)
+ * @return void
+ */
+ public function unmark_temp($key)
+ {
+ if (empty($_SESSION['__ci_vars']))
+ {
+ return;
+ }
+
+ is_array($key) OR $key = array($key);
+
+ foreach ($key as $k)
+ {
+ if (isset($_SESSION['__ci_vars'][$k]) && is_int($_SESSION['__ci_vars'][$k]))
+ {
+ unset($_SESSION['__ci_vars'][$k]);
+ }
+ }
+
+ if (empty($_SESSION['__ci_vars']))
+ {
+ unset($_SESSION['__ci_vars']);
+ }
+ }
+
+ // ------------------------------------------------------------------------
+
+ /**
+ * __get()
+ *
+ * @param string $key 'session_id' or a session data key
+ * @return mixed
+ */
+ public function __get($key)
+ {
+ // 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]))
+ {
+ return $_SESSION[$key];
+ }
+ elseif ($key === 'session_id')
+ {
+ return session_id();
+ }
+
+ return NULL;
+ }
+
+ // ------------------------------------------------------------------------
+
+ /**
+ * __isset()
+ *
+ * @param string $key 'session_id' or a session data key
+ * @return bool
+ */
+ public function __isset($key)
+ {
+ if ($key === 'session_id')
+ {
+ return (session_status() === PHP_SESSION_ACTIVE);
+ }
+
+ return isset($_SESSION[$key]);
+ }
+
+ // ------------------------------------------------------------------------
+
+ /**
+ * __set()
+ *
+ * @param string $key Session data key
+ * @param mixed $value Session data value
+ * @return void
+ */
+ public function __set($key, $value)
+ {
+ $_SESSION[$key] = $value;
+ }
+
+ // ------------------------------------------------------------------------
+
+ /**
+ * Session destroy
+ *
+ * Legacy CI_Session compatibility method
+ *
+ * @return void
+ */
+ public function sess_destroy()
+ {
+ session_destroy();
+ }
+
+ // ------------------------------------------------------------------------
+
+ /**
+ * Session regenerate
+ *
+ * Legacy CI_Session compatibility method
+ *
+ * @param bool $destroy Destroy old session data flag
+ * @return void
+ */
+ public function sess_regenerate($destroy = FALSE)
+ {
+ $_SESSION['__ci_last_regenerate'] = time();
+ session_regenerate_id($destroy);
+ }
+
+ // ------------------------------------------------------------------------
+
+ /**
+ * Get userdata reference
+ *
+ * Legacy CI_Session compatibility method
+ *
+ * @returns array
+ */
+ public function &get_userdata()
+ {
+ return $_SESSION;
+ }
+
+ // ------------------------------------------------------------------------
+
+ /**
+ * Userdata (fetch)
+ *
+ * Legacy CI_Session compatibility method
+ *
+ * @param string $key Session data key
+ * @return mixed Session data value or NULL if not found
+ */
+ public function userdata($key = NULL)
+ {
+ if (isset($key))
+ {
+ 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()
+ );
+
+ foreach (array_keys($_SESSION) as $key)
+ {
+ if ( ! in_array($key, $_exclude, TRUE))
+ {
+ $userdata[$key] = $_SESSION[$key];
+ }
+ }
+
+ return $userdata;
+ }
+
+ // ------------------------------------------------------------------------
+
+ /**
+ * Set userdata
+ *
+ * Legacy CI_Session compatibility method
+ *
+ * @param mixed $data Session data key or an associative array
+ * @param mixed $value Value to store
+ * @return void
+ */
+ public function set_userdata($data, $value = NULL)
+ {
+ if (is_array($data))
+ {
+ foreach ($data as $key => &$value)
+ {
+ $_SESSION[$key] = $value;
+ }
+
+ return;
+ }
+
+ $_SESSION[$data] = $value;
+ }
+
+ // ------------------------------------------------------------------------
+
+ /**
+ * Unset userdata
+ *
+ * Legacy CI_Session compatibility method
+ *
+ * @param mixed $key Session data key(s)
+ * @return void
+ */
+ public function unset_userdata($key)
+ {
+ if (is_array($key))
+ {
+ foreach ($key as $k)
+ {
+ unset($_SESSION[$k]);
+ }
+
+ return;
+ }
+
+ unset($_SESSION[$key]);
+ }
+
+ // ------------------------------------------------------------------------
+
+ /**
+ * All userdata (fetch)
+ *
+ * Legacy CI_Session compatibility method
+ *
+ * @return array $_SESSION, excluding flash data items
+ */
+ public function all_userdata()
+ {
+ return $this->userdata();
+ }
+
+ // ------------------------------------------------------------------------
+
+ /**
+ * Has userdata
+ *
+ * Legacy CI_Session compatibility method
+ *
+ * @param string $key Session data key
+ * @return bool
+ */
+ public function has_userdata($key)
+ {
+ return isset($_SESSION[$key]);
+ }
+
+ // ------------------------------------------------------------------------
+
+ /**
+ * Flashdata (fetch)
+ *
+ * Legacy CI_Session compatibility method
+ *
+ * @param string $key Session data key
+ * @return mixed Session data value or NULL if not found
+ */
+ public function flashdata($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;
+ }
+
+ $flashdata = array();
+
+ if ( ! empty($_SESSION['__ci_vars']))
+ {
+ foreach ($_SESSION['__ci_vars'] as $key => &$value)
+ {
+ is_int($value) OR $flashdata[$key] = $_SESSION[$key];
+ }
+ }
+
+ return $flashdata;
+ }
+
+ // ------------------------------------------------------------------------
+
+ /**
+ * Set flashdata
+ *
+ * Legacy CI_Session compatibility method
+ *
+ * @param mixed $data Session data key or an associative array
+ * @param mixed $value Value to store
+ * @return void
+ */
+ public function set_flashdata($data, $value = NULL)
+ {
+ $this->set_userdata($data, $value);
+ $this->mark_as_flash(is_array($data) ? array_keys($data) : $data);
+ }
+
+ // ------------------------------------------------------------------------
+
+ /**
+ * Keep flashdata
+ *
+ * Legacy CI_Session compatibility method
+ *
+ * @param mixed $key Session data key(s)
+ * @return void
+ */
+ public function keep_flashdata($key)
+ {
+ $this->mark_as_flash($key);
+ }
+
+ // ------------------------------------------------------------------------
+
+ /**
+ * Temp data (fetch)
+ *
+ * Legacy CI_Session compatibility method
+ *
+ * @param string $key Session data key
+ * @return mixed Session data value or NULL if not found
+ */
+ 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;
+ }
+
+ // ------------------------------------------------------------------------
+
+ /**
+ * Set tempdata
+ *
+ * Legacy CI_Session compatibility method
+ *
+ * @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
+ */
+ public function set_tempdata($data, $value = NULL, $ttl = 300)
+ {
+ $this->set_userdata($data, $value);
+ $this->mark_as_temp(is_array($data) ? array_keys($data) : $data, $ttl);
+ }
+
+ // ------------------------------------------------------------------------
+
+ /**
+ * Unset tempdata
+ *
+ * Legacy CI_Session compatibility method
+ *
+ * @param mixed $data Session data key(s)
+ * @return void
+ */
+ public function unset_tempdata($key)
+ {
+ $this->unmark_temp($key);
+ }
+
+}
diff --git a/system/libraries/Session/SessionHandlerInterface.php b/system/libraries/Session/SessionHandlerInterface.php
new file mode 100644
index 000000000..2eef61db8
--- /dev/null
+++ b/system/libraries/Session/SessionHandlerInterface.php
@@ -0,0 +1,59 @@
+<?php
+/**
+ * CodeIgniter
+ *
+ * An open source application development framework for PHP
+ *
+ * This content is released under the MIT License (MIT)
+ *
+ * Copyright (c) 2014 - 2017, British Columbia Institute of Technology
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ *
+ * @package CodeIgniter
+ * @author EllisLab Dev Team
+ * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (https://ellislab.com/)
+ * @copyright Copyright (c) 2014 - 2017, British Columbia Institute of Technology (http://bcit.ca/)
+ * @license http://opensource.org/licenses/MIT MIT License
+ * @link https://codeigniter.com
+ * @since Version 3.0.0
+ * @filesource
+ */
+defined('BASEPATH') OR exit('No direct script access allowed');
+
+/**
+ * SessionHandlerInterface
+ *
+ * PHP 5.4 compatibility interface
+ *
+ * @package CodeIgniter
+ * @subpackage Libraries
+ * @category Sessions
+ * @author Andrey Andreev
+ * @link https://codeigniter.com/user_guide/libraries/sessions.html
+ */
+interface SessionHandlerInterface {
+
+ public function open($save_path, $name);
+ public function close();
+ public function read($session_id);
+ public function write($session_id, $session_data);
+ public function destroy($session_id);
+ public function gc($maxlifetime);
+}
diff --git a/system/libraries/Session/Session_driver.php b/system/libraries/Session/Session_driver.php
new file mode 100644
index 000000000..f32f14ae0
--- /dev/null
+++ b/system/libraries/Session/Session_driver.php
@@ -0,0 +1,191 @@
+<?php
+/**
+ * CodeIgniter
+ *
+ * An open source application development framework for PHP
+ *
+ * This content is released under the MIT License (MIT)
+ *
+ * Copyright (c) 2014 - 2017, British Columbia Institute of Technology
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ *
+ * @package CodeIgniter
+ * @author EllisLab Dev Team
+ * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (https://ellislab.com/)
+ * @copyright Copyright (c) 2014 - 2017, British Columbia Institute of Technology (http://bcit.ca/)
+ * @license http://opensource.org/licenses/MIT MIT License
+ * @link https://codeigniter.com
+ * @since Version 3.0.0
+ * @filesource
+ */
+defined('BASEPATH') OR exit('No direct script access allowed');
+
+/**
+ * CodeIgniter Session Driver Class
+ *
+ * @package CodeIgniter
+ * @subpackage Libraries
+ * @category Sessions
+ * @author Andrey Andreev
+ * @link https://codeigniter.com/user_guide/libraries/sessions.html
+ */
+abstract class CI_Session_driver implements SessionHandlerInterface {
+
+ protected $_config;
+
+ /**
+ * Data fingerprint
+ *
+ * @var bool
+ */
+ protected $_fingerprint;
+
+ /**
+ * Lock placeholder
+ *
+ * @var mixed
+ */
+ protected $_lock = FALSE;
+
+ /**
+ * Read session ID
+ *
+ * Used to detect session_regenerate_id() calls because PHP only calls
+ * write() after regenerating the ID.
+ *
+ * @var string
+ */
+ protected $_session_id;
+
+ /**
+ * Success and failure return values
+ *
+ * Necessary due to a bug in all PHP 5 versions where return values
+ * from userspace handlers are not handled properly. PHP 7 fixes the
+ * bug, so we need to return different values depending on the version.
+ *
+ * @see https://wiki.php.net/rfc/session.user.return-value
+ * @var mixed
+ */
+ protected $_success, $_failure;
+
+ // ------------------------------------------------------------------------
+
+ /**
+ * Class constructor
+ *
+ * @param array $params Configuration parameters
+ * @return void
+ */
+ public function __construct(&$params)
+ {
+ $this->_config =& $params;
+
+ if (is_php('7'))
+ {
+ $this->_success = TRUE;
+ $this->_failure = FALSE;
+ }
+ else
+ {
+ $this->_success = 0;
+ $this->_failure = -1;
+ }
+ }
+
+ // ------------------------------------------------------------------------
+
+ /**
+ * Cookie destroy
+ *
+ * Internal method to force removal of a cookie by the client
+ * when session_destroy() is called.
+ *
+ * @return bool
+ */
+ protected function _cookie_destroy()
+ {
+ return setcookie(
+ $this->_config['cookie_name'],
+ NULL,
+ 1,
+ $this->_config['cookie_path'],
+ $this->_config['cookie_domain'],
+ $this->_config['cookie_secure'],
+ TRUE
+ );
+ }
+
+ // ------------------------------------------------------------------------
+
+ /**
+ * Get lock
+ *
+ * A dummy method allowing drivers with no locking functionality
+ * (databases other than PostgreSQL and MySQL) to act as if they
+ * do acquire a lock.
+ *
+ * @param string $session_id
+ * @return bool
+ */
+ protected function _get_lock($session_id)
+ {
+ $this->_lock = TRUE;
+ return TRUE;
+ }
+
+ // ------------------------------------------------------------------------
+
+ /**
+ * Release lock
+ *
+ * @return bool
+ */
+ protected function _release_lock()
+ {
+ if ($this->_lock)
+ {
+ $this->_lock = FALSE;
+ }
+
+ return TRUE;
+ }
+
+ // ------------------------------------------------------------------------
+
+ /**
+ * Fail
+ *
+ * Drivers other than the 'files' one don't (need to) use the
+ * session.save_path INI setting, but that leads to confusing
+ * error messages emitted by PHP when open() or write() fail,
+ * as the message contains session.save_path ...
+ * To work around the problem, the drivers will call this method
+ * so that the INI is set just in time for the error message to
+ * be properly generated.
+ *
+ * @return mixed
+ */
+ protected function _fail()
+ {
+ ini_set('session.save_path', config_item('sess_save_path'));
+ return $this->_failure;
+ }
+}
diff --git a/system/libraries/Session/drivers/Session_database_driver.php b/system/libraries/Session/drivers/Session_database_driver.php
new file mode 100644
index 000000000..b519b782f
--- /dev/null
+++ b/system/libraries/Session/drivers/Session_database_driver.php
@@ -0,0 +1,420 @@
+<?php
+/**
+ * CodeIgniter
+ *
+ * An open source application development framework for PHP
+ *
+ * This content is released under the MIT License (MIT)
+ *
+ * Copyright (c) 2014 - 2017, British Columbia Institute of Technology
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ *
+ * @package CodeIgniter
+ * @author EllisLab Dev Team
+ * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (https://ellislab.com/)
+ * @copyright Copyright (c) 2014 - 2017, British Columbia Institute of Technology (http://bcit.ca/)
+ * @license http://opensource.org/licenses/MIT MIT License
+ * @link https://codeigniter.com
+ * @since Version 3.0.0
+ * @filesource
+ */
+defined('BASEPATH') OR exit('No direct script access allowed');
+
+/**
+ * CodeIgniter Session Database Driver
+ *
+ * @package CodeIgniter
+ * @subpackage Libraries
+ * @category Sessions
+ * @author Andrey Andreev
+ * @link https://codeigniter.com/user_guide/libraries/sessions.html
+ */
+class CI_Session_database_driver extends CI_Session_driver implements SessionHandlerInterface {
+
+ /**
+ * DB object
+ *
+ * @var object
+ */
+ protected $_db;
+
+ /**
+ * Row exists flag
+ *
+ * @var bool
+ */
+ protected $_row_exists = FALSE;
+
+ /**
+ * Lock "driver" flag
+ *
+ * @var string
+ */
+ protected $_platform;
+
+ // ------------------------------------------------------------------------
+
+ /**
+ * Class constructor
+ *
+ * @param array $params Configuration parameters
+ * @return void
+ */
+ public function __construct(&$params)
+ {
+ parent::__construct($params);
+
+ $CI =& get_instance();
+ isset($CI->db) OR $CI->load->database();
+ $this->_db = $CI->db;
+
+ if ( ! $this->_db instanceof CI_DB_query_builder)
+ {
+ throw new Exception('Query Builder not enabled for the configured database. Aborting.');
+ }
+ elseif ($this->_db->pconnect)
+ {
+ throw new Exception('Configured database connection is persistent. Aborting.');
+ }
+ elseif ($this->_db->cache_on)
+ {
+ throw new Exception('Configured database connection has cache enabled. Aborting.');
+ }
+
+ $db_driver = $this->_db->dbdriver.(empty($this->_db->subdriver) ? '' : '_'.$this->_db->subdriver);
+ if (strpos($db_driver, 'mysql') !== FALSE)
+ {
+ $this->_platform = 'mysql';
+ }
+ elseif (in_array($db_driver, array('postgre', 'pdo_pgsql'), TRUE))
+ {
+ $this->_platform = 'postgre';
+ }
+
+ // Note: BC work-around for the old 'sess_table_name' setting, should be removed in the future.
+ if ( ! isset($this->_config['save_path']) && ($this->_config['save_path'] = config_item('sess_table_name')))
+ {
+ log_message('debug', 'Session: "sess_save_path" is empty; using BC fallback to "sess_table_name".');
+ }
+ }
+
+ // ------------------------------------------------------------------------
+
+ /**
+ * Open
+ *
+ * Initializes the database connection
+ *
+ * @param string $save_path Table name
+ * @param string $name Session cookie name, unused
+ * @return bool
+ */
+ public function open($save_path, $name)
+ {
+ if (empty($this->_db->conn_id) && ! $this->_db->db_connect())
+ {
+ return $this->_fail();
+ }
+
+ return $this->_success;
+ }
+
+ // ------------------------------------------------------------------------
+
+ /**
+ * Read
+ *
+ * Reads session data and acquires a lock
+ *
+ * @param string $session_id Session ID
+ * @return string Serialized session data
+ */
+ public function read($session_id)
+ {
+ if ($this->_get_lock($session_id) !== FALSE)
+ {
+ // Prevent previous QB calls from messing with our queries
+ $this->_db->reset_query();
+
+ // Needed by write() to detect session_regenerate_id() calls
+ $this->_session_id = $session_id;
+
+ $this->_db
+ ->select('data')
+ ->from($this->_config['save_path'])
+ ->where('id', $session_id);
+
+ if ($this->_config['match_ip'])
+ {
+ $this->_db->where('ip_address', $_SERVER['REMOTE_ADDR']);
+ }
+
+ if ( ! ($result = $this->_db->get()) OR ($result = $result->row()) === NULL)
+ {
+ // PHP7 will reuse the same SessionHandler object after
+ // ID regeneration, so we need to explicitly set this to
+ // FALSE instead of relying on the default ...
+ $this->_row_exists = FALSE;
+ $this->_fingerprint = md5('');
+ return '';
+ }
+
+ // PostgreSQL's variant of a BLOB datatype is Bytea, which is a
+ // PITA to work with, so we use base64-encoded data in a TEXT
+ // field instead.
+ $result = ($this->_platform === 'postgre')
+ ? base64_decode(rtrim($result->data))
+ : $result->data;
+
+ $this->_fingerprint = md5($result);
+ $this->_row_exists = TRUE;
+ return $result;
+ }
+
+ $this->_fingerprint = md5('');
+ return '';
+ }
+
+ // ------------------------------------------------------------------------
+
+ /**
+ * Write
+ *
+ * Writes (create / update) session data
+ *
+ * @param string $session_id Session ID
+ * @param string $session_data Serialized session data
+ * @return bool
+ */
+ public function write($session_id, $session_data)
+ {
+ // Prevent previous QB calls from messing with our queries
+ $this->_db->reset_query();
+
+ // Was the ID regenerated?
+ if (isset($this->_session_id) && $session_id !== $this->_session_id)
+ {
+ if ( ! $this->_release_lock() OR ! $this->_get_lock($session_id))
+ {
+ return $this->_fail();
+ }
+
+ $this->_row_exists = FALSE;
+ $this->_session_id = $session_id;
+ }
+ elseif ($this->_lock === FALSE)
+ {
+ return $this->_fail();
+ }
+
+ if ($this->_row_exists === FALSE)
+ {
+ $insert_data = array(
+ 'id' => $session_id,
+ 'ip_address' => $_SERVER['REMOTE_ADDR'],
+ 'timestamp' => time(),
+ 'data' => ($this->_platform === 'postgre' ? base64_encode($session_data) : $session_data)
+ );
+
+ if ($this->_db->insert($this->_config['save_path'], $insert_data))
+ {
+ $this->_fingerprint = md5($session_data);
+ $this->_row_exists = TRUE;
+ return $this->_success;
+ }
+
+ return $this->_fail();
+ }
+
+ $this->_db->where('id', $session_id);
+ if ($this->_config['match_ip'])
+ {
+ $this->_db->where('ip_address', $_SERVER['REMOTE_ADDR']);
+ }
+
+ $update_data = array('timestamp' => time());
+ if ($this->_fingerprint !== md5($session_data))
+ {
+ $update_data['data'] = ($this->_platform === 'postgre')
+ ? base64_encode($session_data)
+ : $session_data;
+ }
+
+ if ($this->_db->update($this->_config['save_path'], $update_data))
+ {
+ $this->_fingerprint = md5($session_data);
+ return $this->_success;
+ }
+
+ return $this->_fail();
+ }
+
+ // ------------------------------------------------------------------------
+
+ /**
+ * Close
+ *
+ * Releases locks
+ *
+ * @return bool
+ */
+ public function close()
+ {
+ return ($this->_lock && ! $this->_release_lock())
+ ? $this->_fail()
+ : $this->_success;
+ }
+
+ // ------------------------------------------------------------------------
+
+ /**
+ * Destroy
+ *
+ * Destroys the current session.
+ *
+ * @param string $session_id Session ID
+ * @return bool
+ */
+ public function destroy($session_id)
+ {
+ if ($this->_lock)
+ {
+ // Prevent previous QB calls from messing with our queries
+ $this->_db->reset_query();
+
+ $this->_db->where('id', $session_id);
+ if ($this->_config['match_ip'])
+ {
+ $this->_db->where('ip_address', $_SERVER['REMOTE_ADDR']);
+ }
+
+ if ( ! $this->_db->delete($this->_config['save_path']))
+ {
+ return $this->_fail();
+ }
+ }
+
+ if ($this->close() === $this->_success)
+ {
+ $this->_cookie_destroy();
+ return $this->_success;
+ }
+
+ return $this->_fail();
+ }
+
+ // ------------------------------------------------------------------------
+
+ /**
+ * Garbage Collector
+ *
+ * Deletes expired sessions
+ *
+ * @param int $maxlifetime Maximum lifetime of sessions
+ * @return bool
+ */
+ public function gc($maxlifetime)
+ {
+ // Prevent previous QB calls from messing with our queries
+ $this->_db->reset_query();
+
+ return ($this->_db->delete($this->_config['save_path'], 'timestamp < '.(time() - $maxlifetime)))
+ ? $this->_success
+ : $this->_fail();
+ }
+
+ // ------------------------------------------------------------------------
+
+ /**
+ * Get lock
+ *
+ * Acquires a lock, depending on the underlying platform.
+ *
+ * @param string $session_id Session ID
+ * @return bool
+ */
+ protected function _get_lock($session_id)
+ {
+ if ($this->_platform === 'mysql')
+ {
+ $arg = md5($session_id.($this->_config['match_ip'] ? '_'.$_SERVER['REMOTE_ADDR'] : ''));
+ if ($this->_db->query("SELECT GET_LOCK('".$arg."', 300) AS ci_session_lock")->row()->ci_session_lock)
+ {
+ $this->_lock = $arg;
+ return TRUE;
+ }
+
+ return FALSE;
+ }
+ elseif ($this->_platform === 'postgre')
+ {
+ $arg = "hashtext('".$session_id."')".($this->_config['match_ip'] ? ", hashtext('".$_SERVER['REMOTE_ADDR']."')" : '');
+ if ($this->_db->simple_query('SELECT pg_advisory_lock('.$arg.')'))
+ {
+ $this->_lock = $arg;
+ return TRUE;
+ }
+
+ return FALSE;
+ }
+
+ return parent::_get_lock($session_id);
+ }
+
+ // ------------------------------------------------------------------------
+
+ /**
+ * Release lock
+ *
+ * Releases a previously acquired lock
+ *
+ * @return bool
+ */
+ protected function _release_lock()
+ {
+ if ( ! $this->_lock)
+ {
+ return TRUE;
+ }
+
+ if ($this->_platform === 'mysql')
+ {
+ if ($this->_db->query("SELECT RELEASE_LOCK('".$this->_lock."') AS ci_session_lock")->row()->ci_session_lock)
+ {
+ $this->_lock = FALSE;
+ return TRUE;
+ }
+
+ return FALSE;
+ }
+ elseif ($this->_platform === 'postgre')
+ {
+ if ($this->_db->simple_query('SELECT pg_advisory_unlock('.$this->_lock.')'))
+ {
+ $this->_lock = FALSE;
+ return TRUE;
+ }
+
+ return FALSE;
+ }
+
+ return parent::_release_lock();
+ }
+}
diff --git a/system/libraries/Session/drivers/Session_files_driver.php b/system/libraries/Session/drivers/Session_files_driver.php
new file mode 100644
index 000000000..8860ef667
--- /dev/null
+++ b/system/libraries/Session/drivers/Session_files_driver.php
@@ -0,0 +1,406 @@
+<?php
+/**
+ * CodeIgniter
+ *
+ * An open source application development framework for PHP
+ *
+ * This content is released under the MIT License (MIT)
+ *
+ * Copyright (c) 2014 - 2017, British Columbia Institute of Technology
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ *
+ * @package CodeIgniter
+ * @author EllisLab Dev Team
+ * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (https://ellislab.com/)
+ * @copyright Copyright (c) 2014 - 2017, British Columbia Institute of Technology (http://bcit.ca/)
+ * @license http://opensource.org/licenses/MIT MIT License
+ * @link https://codeigniter.com
+ * @since Version 3.0.0
+ * @filesource
+*/
+defined('BASEPATH') OR exit('No direct script access allowed');
+
+/**
+ * CodeIgniter Session Files Driver
+ *
+ * @package CodeIgniter
+ * @subpackage Libraries
+ * @category Sessions
+ * @author Andrey Andreev
+ * @link https://codeigniter.com/user_guide/libraries/sessions.html
+ */
+class CI_Session_files_driver extends CI_Session_driver implements SessionHandlerInterface {
+
+ /**
+ * Save path
+ *
+ * @var string
+ */
+ protected $_save_path;
+
+ /**
+ * File handle
+ *
+ * @var resource
+ */
+ protected $_file_handle;
+
+ /**
+ * File name
+ *
+ * @var resource
+ */
+ protected $_file_path;
+
+ /**
+ * File new flag
+ *
+ * @var bool
+ */
+ protected $_file_new;
+
+ /**
+ * Validate SID regular expression
+ *
+ * @var string
+ */
+ protected $_sid_regexp;
+
+ /**
+ * mbstring.func_overload flag
+ *
+ * @var bool
+ */
+ protected static $func_overload;
+
+ // ------------------------------------------------------------------------
+
+ /**
+ * Class constructor
+ *
+ * @param array $params Configuration parameters
+ * @return void
+ */
+ public function __construct(&$params)
+ {
+ parent::__construct($params);
+
+ if (isset($this->_config['save_path']))
+ {
+ $this->_config['save_path'] = rtrim($this->_config['save_path'], '/\\');
+ ini_set('session.save_path', $this->_config['save_path']);
+ }
+ else
+ {
+ log_message('debug', 'Session: "sess_save_path" is empty; using "session.save_path" value from php.ini.');
+ $this->_config['save_path'] = rtrim(ini_get('session.save_path'), '/\\');
+ }
+
+ $this->_sid_regexp = $this->_config['_sid_regexp'];
+
+ isset(self::$func_overload) OR self::$func_overload = (extension_loaded('mbstring') && ini_get('mbstring.func_overload'));
+ }
+
+ // ------------------------------------------------------------------------
+
+ /**
+ * Open
+ *
+ * Sanitizes the save_path directory.
+ *
+ * @param string $save_path Path to session files' directory
+ * @param string $name Session cookie name
+ * @return bool
+ */
+ public function open($save_path, $name)
+ {
+ if ( ! is_dir($save_path))
+ {
+ if ( ! mkdir($save_path, 0700, TRUE))
+ {
+ throw new Exception("Session: Configured save path '".$this->_config['save_path']."' is not a directory, doesn't exist or cannot be created.");
+ }
+ }
+ elseif ( ! is_writable($save_path))
+ {
+ throw new Exception("Session: Configured save path '".$this->_config['save_path']."' is not writable by the PHP process.");
+ }
+
+ $this->_config['save_path'] = $save_path;
+ $this->_file_path = $this->_config['save_path'].DIRECTORY_SEPARATOR
+ .$name // we'll use the session cookie name as a prefix to avoid collisions
+ .($this->_config['match_ip'] ? md5($_SERVER['REMOTE_ADDR']) : '');
+
+ return $this->_success;
+ }
+
+ // ------------------------------------------------------------------------
+
+ /**
+ * Read
+ *
+ * Reads session data and acquires a lock
+ *
+ * @param string $session_id Session ID
+ * @return string Serialized session data
+ */
+ public function read($session_id)
+ {
+ // This might seem weird, but PHP 5.6 introduces session_reset(),
+ // which re-reads session data
+ if ($this->_file_handle === NULL)
+ {
+ $this->_file_new = ! file_exists($this->_file_path.$session_id);
+
+ if (($this->_file_handle = fopen($this->_file_path.$session_id, 'c+b')) === FALSE)
+ {
+ log_message('error', "Session: Unable to open file '".$this->_file_path.$session_id."'.");
+ return $this->_failure;
+ }
+
+ if (flock($this->_file_handle, LOCK_EX) === FALSE)
+ {
+ log_message('error', "Session: Unable to obtain lock for file '".$this->_file_path.$session_id."'.");
+ fclose($this->_file_handle);
+ $this->_file_handle = NULL;
+ return $this->_failure;
+ }
+
+ // Needed by write() to detect session_regenerate_id() calls
+ $this->_session_id = $session_id;
+
+ if ($this->_file_new)
+ {
+ chmod($this->_file_path.$session_id, 0600);
+ $this->_fingerprint = md5('');
+ return '';
+ }
+ }
+ // We shouldn't need this, but apparently we do ...
+ // See https://github.com/bcit-ci/CodeIgniter/issues/4039
+ elseif ($this->_file_handle === FALSE)
+ {
+ return $this->_failure;
+ }
+ else
+ {
+ rewind($this->_file_handle);
+ }
+
+ $session_data = '';
+ for ($read = 0, $length = filesize($this->_file_path.$session_id); $read < $length; $read += self::strlen($buffer))
+ {
+ if (($buffer = fread($this->_file_handle, $length - $read)) === FALSE)
+ {
+ break;
+ }
+
+ $session_data .= $buffer;
+ }
+
+ $this->_fingerprint = md5($session_data);
+ return $session_data;
+ }
+
+ // ------------------------------------------------------------------------
+
+ /**
+ * Write
+ *
+ * Writes (create / update) session data
+ *
+ * @param string $session_id Session ID
+ * @param string $session_data Serialized session data
+ * @return bool
+ */
+ public function write($session_id, $session_data)
+ {
+ // If the two IDs don't match, we have a session_regenerate_id() call
+ // and we need to close the old handle and open a new one
+ if ($session_id !== $this->_session_id && ($this->close() === $this->_failure OR $this->read($session_id) === $this->_failure))
+ {
+ return $this->_failure;
+ }
+
+ if ( ! is_resource($this->_file_handle))
+ {
+ return $this->_failure;
+ }
+ elseif ($this->_fingerprint === md5($session_data))
+ {
+ return ( ! $this->_file_new && ! touch($this->_file_path.$session_id))
+ ? $this->_failure
+ : $this->_success;
+ }
+
+ if ( ! $this->_file_new)
+ {
+ ftruncate($this->_file_handle, 0);
+ rewind($this->_file_handle);
+ }
+
+ if (($length = strlen($session_data)) > 0)
+ {
+ for ($written = 0; $written < $length; $written += $result)
+ {
+ if (($result = fwrite($this->_file_handle, substr($session_data, $written))) === FALSE)
+ {
+ break;
+ }
+ }
+
+ if ( ! is_int($result))
+ {
+ $this->_fingerprint = md5(substr($session_data, 0, $written));
+ log_message('error', 'Session: Unable to write data.');
+ return $this->_failure;
+ }
+ }
+
+ $this->_fingerprint = md5($session_data);
+ return $this->_success;
+ }
+
+ // ------------------------------------------------------------------------
+
+ /**
+ * Close
+ *
+ * Releases locks and closes file descriptor.
+ *
+ * @return bool
+ */
+ public function close()
+ {
+ if (is_resource($this->_file_handle))
+ {
+ flock($this->_file_handle, LOCK_UN);
+ fclose($this->_file_handle);
+
+ $this->_file_handle = $this->_file_new = $this->_session_id = NULL;
+ }
+
+ return $this->_success;
+ }
+
+ // ------------------------------------------------------------------------
+
+ /**
+ * Destroy
+ *
+ * Destroys the current session.
+ *
+ * @param string $session_id Session ID
+ * @return bool
+ */
+ public function destroy($session_id)
+ {
+ if ($this->close() === $this->_success)
+ {
+ if (file_exists($this->_file_path.$session_id))
+ {
+ $this->_cookie_destroy();
+ return unlink($this->_file_path.$session_id)
+ ? $this->_success
+ : $this->_failure;
+ }
+
+ return $this->_success;
+ }
+ elseif ($this->_file_path !== NULL)
+ {
+ clearstatcache();
+ if (file_exists($this->_file_path.$session_id))
+ {
+ $this->_cookie_destroy();
+ return unlink($this->_file_path.$session_id)
+ ? $this->_success
+ : $this->_failure;
+ }
+
+ return $this->_success;
+ }
+
+ return $this->_failure;
+ }
+
+ // ------------------------------------------------------------------------
+
+ /**
+ * Garbage Collector
+ *
+ * Deletes expired sessions
+ *
+ * @param int $maxlifetime Maximum lifetime of sessions
+ * @return bool
+ */
+ public function gc($maxlifetime)
+ {
+ if ( ! is_dir($this->_config['save_path']) OR ($directory = opendir($this->_config['save_path'])) === FALSE)
+ {
+ log_message('debug', "Session: Garbage collector couldn't list files under directory '".$this->_config['save_path']."'.");
+ return $this->_failure;
+ }
+
+ $ts = time() - $maxlifetime;
+
+ $pattern = ($this->_config['match_ip'] === TRUE)
+ ? '[0-9a-f]{32}'
+ : '';
+
+ $pattern = sprintf(
+ '#\A%s'.$pattern.$this->_sid_regexp.'\z#',
+ preg_quote($this->_config['cookie_name'])
+ );
+
+ while (($file = readdir($directory)) !== FALSE)
+ {
+ // If the filename doesn't match this pattern, it's either not a session file or is not ours
+ if ( ! preg_match($pattern, $file)
+ OR ! is_file($this->_config['save_path'].DIRECTORY_SEPARATOR.$file)
+ OR ($mtime = filemtime($this->_config['save_path'].DIRECTORY_SEPARATOR.$file)) === FALSE
+ OR $mtime > $ts)
+ {
+ continue;
+ }
+
+ unlink($this->_config['save_path'].DIRECTORY_SEPARATOR.$file);
+ }
+
+ closedir($directory);
+
+ return $this->_success;
+ }
+
+ // --------------------------------------------------------------------
+
+ /**
+ * Byte-safe strlen()
+ *
+ * @param string $str
+ * @return int
+ */
+ protected static function strlen($str)
+ {
+ return (self::$func_overload)
+ ? mb_strlen($str, '8bit')
+ : strlen($str);
+ }
+}
diff --git a/system/libraries/Session/drivers/Session_memcached_driver.php b/system/libraries/Session/drivers/Session_memcached_driver.php
new file mode 100644
index 000000000..2556bf0f7
--- /dev/null
+++ b/system/libraries/Session/drivers/Session_memcached_driver.php
@@ -0,0 +1,375 @@
+<?php
+/**
+ * CodeIgniter
+ *
+ * An open source application development framework for PHP
+ *
+ * This content is released under the MIT License (MIT)
+ *
+ * Copyright (c) 2014 - 2017, British Columbia Institute of Technology
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ *
+ * @package CodeIgniter
+ * @author EllisLab Dev Team
+ * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (https://ellislab.com/)
+ * @copyright Copyright (c) 2014 - 2017, British Columbia Institute of Technology (http://bcit.ca/)
+ * @license http://opensource.org/licenses/MIT MIT License
+ * @link https://codeigniter.com
+ * @since Version 3.0.0
+ * @filesource
+ */
+defined('BASEPATH') OR exit('No direct script access allowed');
+
+/**
+ * CodeIgniter Session Memcached Driver
+ *
+ * @package CodeIgniter
+ * @subpackage Libraries
+ * @category Sessions
+ * @author Andrey Andreev
+ * @link https://codeigniter.com/user_guide/libraries/sessions.html
+ */
+class CI_Session_memcached_driver extends CI_Session_driver implements SessionHandlerInterface {
+
+ /**
+ * Memcached instance
+ *
+ * @var Memcached
+ */
+ protected $_memcached;
+
+ /**
+ * Key prefix
+ *
+ * @var string
+ */
+ protected $_key_prefix = 'ci_session:';
+
+ /**
+ * Lock key
+ *
+ * @var string
+ */
+ protected $_lock_key;
+
+ // ------------------------------------------------------------------------
+
+ /**
+ * Class constructor
+ *
+ * @param array $params Configuration parameters
+ * @return void
+ */
+ public function __construct(&$params)
+ {
+ parent::__construct($params);
+
+ if (empty($this->_config['save_path']))
+ {
+ log_message('error', 'Session: No Memcached save path configured.');
+ }
+
+ if ($this->_config['match_ip'] === TRUE)
+ {
+ $this->_key_prefix .= $_SERVER['REMOTE_ADDR'].':';
+ }
+ }
+
+ // ------------------------------------------------------------------------
+
+ /**
+ * Open
+ *
+ * Sanitizes save_path and initializes connections.
+ *
+ * @param string $save_path Server path(s)
+ * @param string $name Session cookie name, unused
+ * @return bool
+ */
+ public function open($save_path, $name)
+ {
+ $this->_memcached = new Memcached();
+ $this->_memcached->setOption(Memcached::OPT_BINARY_PROTOCOL, TRUE); // required for touch() usage
+ $server_list = array();
+ foreach ($this->_memcached->getServerList() as $server)
+ {
+ $server_list[] = $server['host'].':'.$server['port'];
+ }
+
+ if ( ! preg_match_all('#,?([^,:]+)\:(\d{1,5})(?:\:(\d+))?#', $this->_config['save_path'], $matches, PREG_SET_ORDER))
+ {
+ $this->_memcached = NULL;
+ log_message('error', 'Session: Invalid Memcached save path format: '.$this->_config['save_path']);
+ return $this->_fail();
+ }
+
+ foreach ($matches as $match)
+ {
+ // If Memcached already has this server (or if the port is invalid), skip it
+ if (in_array($match[1].':'.$match[2], $server_list, TRUE))
+ {
+ log_message('debug', 'Session: Memcached server pool already has '.$match[1].':'.$match[2]);
+ continue;
+ }
+
+ if ( ! $this->_memcached->addServer($match[1], $match[2], isset($match[3]) ? $match[3] : 0))
+ {
+ log_message('error', 'Could not add '.$match[1].':'.$match[2].' to Memcached server pool.');
+ }
+ else
+ {
+ $server_list[] = $match[1].':'.$match[2];
+ }
+ }
+
+ if (empty($server_list))
+ {
+ log_message('error', 'Session: Memcached server pool is empty.');
+ return $this->_fail();
+ }
+
+ return $this->_success;
+ }
+
+ // ------------------------------------------------------------------------
+
+ /**
+ * Read
+ *
+ * Reads session data and acquires a lock
+ *
+ * @param string $session_id Session ID
+ * @return string Serialized session data
+ */
+ public function read($session_id)
+ {
+ if (isset($this->_memcached) && $this->_get_lock($session_id))
+ {
+ // Needed by write() to detect session_regenerate_id() calls
+ $this->_session_id = $session_id;
+
+ $session_data = (string) $this->_memcached->get($this->_key_prefix.$session_id);
+ $this->_fingerprint = md5($session_data);
+ return $session_data;
+ }
+
+ return $this->_fail();
+ }
+
+ // ------------------------------------------------------------------------
+
+ /**
+ * Write
+ *
+ * Writes (create / update) session data
+ *
+ * @param string $session_id Session ID
+ * @param string $session_data Serialized session data
+ * @return bool
+ */
+ public function write($session_id, $session_data)
+ {
+ if ( ! isset($this->_memcached, $this->_lock_key))
+ {
+ return $this->_fail();
+ }
+ // Was the ID regenerated?
+ elseif ($session_id !== $this->_session_id)
+ {
+ if ( ! $this->_release_lock() OR ! $this->_get_lock($session_id))
+ {
+ return $this->_fail();
+ }
+
+ $this->_fingerprint = md5('');
+ $this->_session_id = $session_id;
+ }
+
+ $key = $this->_key_prefix.$session_id;
+
+ $this->_memcached->replace($this->_lock_key, time(), 300);
+ if ($this->_fingerprint !== ($fingerprint = md5($session_data)))
+ {
+ if ($this->_memcached->set($key, $session_data, $this->_config['expiration']))
+ {
+ $this->_fingerprint = $fingerprint;
+ return $this->_success;
+ }
+
+ return $this->_fail();
+ }
+ elseif (
+ $this->_memcached->touch($key, $this->_config['expiration'])
+ OR ($this->_memcached->getResultCode() === Memcached::RES_NOTFOUND && $this->_memcached->set($key, $session_data, $this->_config['expiration']))
+ )
+ {
+ return $this->_success;
+ }
+
+ return $this->_fail();
+ }
+
+ // ------------------------------------------------------------------------
+
+ /**
+ * Close
+ *
+ * Releases locks and closes connection.
+ *
+ * @return bool
+ */
+ public function close()
+ {
+ if (isset($this->_memcached))
+ {
+ $this->_release_lock();
+ if ( ! $this->_memcached->quit())
+ {
+ return $this->_fail();
+ }
+
+ $this->_memcached = NULL;
+ return $this->_success;
+ }
+
+ return $this->_fail();
+ }
+
+ // ------------------------------------------------------------------------
+
+ /**
+ * Destroy
+ *
+ * Destroys the current session.
+ *
+ * @param string $session_id Session ID
+ * @return bool
+ */
+ public function destroy($session_id)
+ {
+ if (isset($this->_memcached, $this->_lock_key))
+ {
+ $this->_memcached->delete($this->_key_prefix.$session_id);
+ $this->_cookie_destroy();
+ return $this->_success;
+ }
+
+ return $this->_fail();
+ }
+
+ // ------------------------------------------------------------------------
+
+ /**
+ * Garbage Collector
+ *
+ * Deletes expired sessions
+ *
+ * @param int $maxlifetime Maximum lifetime of sessions
+ * @return bool
+ */
+ public function gc($maxlifetime)
+ {
+ // Not necessary, Memcached takes care of that.
+ return $this->_success;
+ }
+
+ // ------------------------------------------------------------------------
+
+ /**
+ * Get lock
+ *
+ * Acquires an (emulated) lock.
+ *
+ * @param string $session_id Session ID
+ * @return bool
+ */
+ protected function _get_lock($session_id)
+ {
+ // PHP 7 reuses the SessionHandler object on regeneration,
+ // so we need to check here if the lock key is for the
+ // correct session ID.
+ if ($this->_lock_key === $this->_key_prefix.$session_id.':lock')
+ {
+ if ( ! $this->_memcached->replace($this->_lock_key, time(), 300))
+ {
+ return ($this->_memcached->getResultCode() === Memcached::RES_NOTFOUND)
+ ? $this->_memcached->set($this->_lock_key, time(), 300)
+ : FALSE;
+ }
+ }
+
+ // 30 attempts to obtain a lock, in case another request already has it
+ $lock_key = $this->_key_prefix.$session_id.':lock';
+ $attempt = 0;
+ do
+ {
+ if ($this->_memcached->get($lock_key))
+ {
+ sleep(1);
+ continue;
+ }
+
+ if ( ! $this->_memcached->set($lock_key, time(), 300))
+ {
+ log_message('error', 'Session: Error while trying to obtain lock for '.$this->_key_prefix.$session_id);
+ return FALSE;
+ }
+
+ $this->_lock_key = $lock_key;
+ break;
+ }
+ while (++$attempt < 30);
+
+ if ($attempt === 30)
+ {
+ log_message('error', 'Session: Unable to obtain lock for '.$this->_key_prefix.$session_id.' after 30 attempts, aborting.');
+ return FALSE;
+ }
+
+ $this->_lock = TRUE;
+ return TRUE;
+ }
+
+ // ------------------------------------------------------------------------
+
+ /**
+ * Release lock
+ *
+ * Releases a previously acquired lock
+ *
+ * @return bool
+ */
+ protected function _release_lock()
+ {
+ if (isset($this->_memcached, $this->_lock_key) && $this->_lock)
+ {
+ if ( ! $this->_memcached->delete($this->_lock_key) && $this->_memcached->getResultCode() !== Memcached::RES_NOTFOUND)
+ {
+ log_message('error', 'Session: Error while trying to free lock for '.$this->_lock_key);
+ return FALSE;
+ }
+
+ $this->_lock_key = NULL;
+ $this->_lock = FALSE;
+ }
+
+ return TRUE;
+ }
+}
diff --git a/system/libraries/Session/drivers/Session_redis_driver.php b/system/libraries/Session/drivers/Session_redis_driver.php
new file mode 100644
index 000000000..e220a2951
--- /dev/null
+++ b/system/libraries/Session/drivers/Session_redis_driver.php
@@ -0,0 +1,395 @@
+<?php
+/**
+ * CodeIgniter
+ *
+ * An open source application development framework for PHP
+ *
+ * This content is released under the MIT License (MIT)
+ *
+ * Copyright (c) 2014 - 2017, British Columbia Institute of Technology
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ *
+ * @package CodeIgniter
+ * @author EllisLab Dev Team
+ * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (https://ellislab.com/)
+ * @copyright Copyright (c) 2014 - 2017, British Columbia Institute of Technology (http://bcit.ca/)
+ * @license http://opensource.org/licenses/MIT MIT License
+ * @link https://codeigniter.com
+ * @since Version 3.0.0
+ * @filesource
+ */
+defined('BASEPATH') OR exit('No direct script access allowed');
+
+/**
+ * CodeIgniter Session Redis Driver
+ *
+ * @package CodeIgniter
+ * @subpackage Libraries
+ * @category Sessions
+ * @author Andrey Andreev
+ * @link https://codeigniter.com/user_guide/libraries/sessions.html
+ */
+class CI_Session_redis_driver extends CI_Session_driver implements SessionHandlerInterface {
+
+ /**
+ * phpRedis instance
+ *
+ * @var Redis
+ */
+ protected $_redis;
+
+ /**
+ * Key prefix
+ *
+ * @var string
+ */
+ protected $_key_prefix = 'ci_session:';
+
+ /**
+ * Lock key
+ *
+ * @var string
+ */
+ protected $_lock_key;
+
+ /**
+ * Key exists flag
+ *
+ * @var bool
+ */
+ protected $_key_exists = FALSE;
+
+ // ------------------------------------------------------------------------
+
+ /**
+ * Class constructor
+ *
+ * @param array $params Configuration parameters
+ * @return void
+ */
+ public function __construct(&$params)
+ {
+ parent::__construct($params);
+
+ if (empty($this->_config['save_path']))
+ {
+ log_message('error', 'Session: No Redis save path configured.');
+ }
+ elseif (preg_match('#(?:tcp://)?([^:?]+)(?:\:(\d+))?(\?.+)?#', $this->_config['save_path'], $matches))
+ {
+ isset($matches[3]) OR $matches[3] = ''; // Just to avoid undefined index notices below
+ $this->_config['save_path'] = array(
+ 'host' => $matches[1],
+ 'port' => empty($matches[2]) ? NULL : $matches[2],
+ 'password' => preg_match('#auth=([^\s&]+)#', $matches[3], $match) ? $match[1] : NULL,
+ 'database' => preg_match('#database=(\d+)#', $matches[3], $match) ? (int) $match[1] : NULL,
+ 'timeout' => preg_match('#timeout=(\d+\.\d+)#', $matches[3], $match) ? (float) $match[1] : NULL
+ );
+
+ preg_match('#prefix=([^\s&]+)#', $matches[3], $match) && $this->_key_prefix = $match[1];
+ }
+ else
+ {
+ log_message('error', 'Session: Invalid Redis save path format: '.$this->_config['save_path']);
+ }
+
+ if ($this->_config['match_ip'] === TRUE)
+ {
+ $this->_key_prefix .= $_SERVER['REMOTE_ADDR'].':';
+ }
+ }
+
+ // ------------------------------------------------------------------------
+
+ /**
+ * Open
+ *
+ * Sanitizes save_path and initializes connection.
+ *
+ * @param string $save_path Server path
+ * @param string $name Session cookie name, unused
+ * @return bool
+ */
+ public function open($save_path, $name)
+ {
+ if (empty($this->_config['save_path']))
+ {
+ return $this->_fail();
+ }
+
+ $redis = new Redis();
+ if ( ! $redis->connect($this->_config['save_path']['host'], $this->_config['save_path']['port'], $this->_config['save_path']['timeout']))
+ {
+ log_message('error', 'Session: Unable to connect to Redis with the configured settings.');
+ }
+ elseif (isset($this->_config['save_path']['password']) && ! $redis->auth($this->_config['save_path']['password']))
+ {
+ log_message('error', 'Session: Unable to authenticate to Redis instance.');
+ }
+ elseif (isset($this->_config['save_path']['database']) && ! $redis->select($this->_config['save_path']['database']))
+ {
+ log_message('error', 'Session: Unable to select Redis database with index '.$this->_config['save_path']['database']);
+ }
+ else
+ {
+ $this->_redis = $redis;
+ return $this->_success;
+ }
+
+ return $this->_fail();
+ }
+
+ // ------------------------------------------------------------------------
+
+ /**
+ * Read
+ *
+ * Reads session data and acquires a lock
+ *
+ * @param string $session_id Session ID
+ * @return string Serialized session data
+ */
+ public function read($session_id)
+ {
+ if (isset($this->_redis) && $this->_get_lock($session_id))
+ {
+ // Needed by write() to detect session_regenerate_id() calls
+ $this->_session_id = $session_id;
+
+ $session_data = $this->_redis->get($this->_key_prefix.$session_id);
+
+ is_string($session_data)
+ ? $this->_key_exists = TRUE
+ : $session_data = '';
+
+ $this->_fingerprint = md5($session_data);
+ return $session_data;
+ }
+
+ return $this->_fail();
+ }
+
+ // ------------------------------------------------------------------------
+
+ /**
+ * Write
+ *
+ * Writes (create / update) session data
+ *
+ * @param string $session_id Session ID
+ * @param string $session_data Serialized session data
+ * @return bool
+ */
+ public function write($session_id, $session_data)
+ {
+ if ( ! isset($this->_redis, $this->_lock_key))
+ {
+ return $this->_fail();
+ }
+ // Was the ID regenerated?
+ elseif ($session_id !== $this->_session_id)
+ {
+ if ( ! $this->_release_lock() OR ! $this->_get_lock($session_id))
+ {
+ return $this->_fail();
+ }
+
+ $this->_key_exists = FALSE;
+ $this->_session_id = $session_id;
+ }
+
+ $this->_redis->setTimeout($this->_lock_key, 300);
+ if ($this->_fingerprint !== ($fingerprint = md5($session_data)) OR $this->_key_exists === FALSE)
+ {
+ if ($this->_redis->set($this->_key_prefix.$session_id, $session_data, $this->_config['expiration']))
+ {
+ $this->_fingerprint = $fingerprint;
+ $this->_key_exists = TRUE;
+ return $this->_success;
+ }
+
+ return $this->_fail();
+ }
+
+ return ($this->_redis->setTimeout($this->_key_prefix.$session_id, $this->_config['expiration']))
+ ? $this->_success
+ : $this->_fail();
+ }
+
+ // ------------------------------------------------------------------------
+
+ /**
+ * Close
+ *
+ * Releases locks and closes connection.
+ *
+ * @return bool
+ */
+ public function close()
+ {
+ if (isset($this->_redis))
+ {
+ try {
+ if ($this->_redis->ping() === '+PONG')
+ {
+ $this->_release_lock();
+ if ($this->_redis->close() === FALSE)
+ {
+ return $this->_fail();
+ }
+ }
+ }
+ catch (RedisException $e)
+ {
+ log_message('error', 'Session: Got RedisException on close(): '.$e->getMessage());
+ }
+
+ $this->_redis = NULL;
+ return $this->_success;
+ }
+
+ return $this->_success;
+ }
+
+ // ------------------------------------------------------------------------
+
+ /**
+ * Destroy
+ *
+ * Destroys the current session.
+ *
+ * @param string $session_id Session ID
+ * @return bool
+ */
+ public function destroy($session_id)
+ {
+ if (isset($this->_redis, $this->_lock_key))
+ {
+ if (($result = $this->_redis->delete($this->_key_prefix.$session_id)) !== 1)
+ {
+ log_message('debug', 'Session: Redis::delete() expected to return 1, got '.var_export($result, TRUE).' instead.');
+ }
+
+ $this->_cookie_destroy();
+ return $this->_success;
+ }
+
+ return $this->_fail();
+ }
+
+ // ------------------------------------------------------------------------
+
+ /**
+ * Garbage Collector
+ *
+ * Deletes expired sessions
+ *
+ * @param int $maxlifetime Maximum lifetime of sessions
+ * @return bool
+ */
+ public function gc($maxlifetime)
+ {
+ // Not necessary, Redis takes care of that.
+ return $this->_success;
+ }
+
+ // ------------------------------------------------------------------------
+
+ /**
+ * Get lock
+ *
+ * Acquires an (emulated) lock.
+ *
+ * @param string $session_id Session ID
+ * @return bool
+ */
+ protected function _get_lock($session_id)
+ {
+ // PHP 7 reuses the SessionHandler object on regeneration,
+ // so we need to check here if the lock key is for the
+ // correct session ID.
+ if ($this->_lock_key === $this->_key_prefix.$session_id.':lock')
+ {
+ return $this->_redis->setTimeout($this->_lock_key, 300);
+ }
+
+ // 30 attempts to obtain a lock, in case another request already has it
+ $lock_key = $this->_key_prefix.$session_id.':lock';
+ $attempt = 0;
+ do
+ {
+ if (($ttl = $this->_redis->ttl($lock_key)) > 0)
+ {
+ sleep(1);
+ continue;
+ }
+
+ if ( ! $this->_redis->setex($lock_key, 300, time()))
+ {
+ log_message('error', 'Session: Error while trying to obtain lock for '.$this->_key_prefix.$session_id);
+ return FALSE;
+ }
+
+ $this->_lock_key = $lock_key;
+ break;
+ }
+ while (++$attempt < 30);
+
+ if ($attempt === 30)
+ {
+ log_message('error', 'Session: Unable to obtain lock for '.$this->_key_prefix.$session_id.' after 30 attempts, aborting.');
+ return FALSE;
+ }
+ elseif ($ttl === -1)
+ {
+ log_message('debug', 'Session: Lock for '.$this->_key_prefix.$session_id.' had no TTL, overriding.');
+ }
+
+ $this->_lock = TRUE;
+ return TRUE;
+ }
+
+ // ------------------------------------------------------------------------
+
+ /**
+ * Release lock
+ *
+ * Releases a previously acquired lock
+ *
+ * @return bool
+ */
+ protected function _release_lock()
+ {
+ if (isset($this->_redis, $this->_lock_key) && $this->_lock)
+ {
+ if ( ! $this->_redis->delete($this->_lock_key))
+ {
+ log_message('error', 'Session: Error while trying to free lock for '.$this->_lock_key);
+ return FALSE;
+ }
+
+ $this->_lock_key = NULL;
+ $this->_lock = FALSE;
+ }
+
+ return TRUE;
+ }
+
+}
diff --git a/system/libraries/Session/drivers/index.html b/system/libraries/Session/drivers/index.html
new file mode 100644
index 000000000..b702fbc39
--- /dev/null
+++ b/system/libraries/Session/drivers/index.html
@@ -0,0 +1,11 @@
+<!DOCTYPE html>
+<html>
+<head>
+ <title>403 Forbidden</title>
+</head>
+<body>
+
+<p>Directory access is forbidden.</p>
+
+</body>
+</html>
diff --git a/system/libraries/Session/index.html b/system/libraries/Session/index.html
new file mode 100644
index 000000000..b702fbc39
--- /dev/null
+++ b/system/libraries/Session/index.html
@@ -0,0 +1,11 @@
+<!DOCTYPE html>
+<html>
+<head>
+ <title>403 Forbidden</title>
+</head>
+<body>
+
+<p>Directory access is forbidden.</p>
+
+</body>
+</html>