Initial
This commit is contained in:
52
system/Session/Exceptions/SessionException.php
Normal file
52
system/Session/Exceptions/SessionException.php
Normal file
@@ -0,0 +1,52 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* This file is part of CodeIgniter 4 framework.
|
||||
*
|
||||
* (c) CodeIgniter Foundation <admin@codeigniter.com>
|
||||
*
|
||||
* For the full copyright and license information, please view
|
||||
* the LICENSE file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace CodeIgniter\Session\Exceptions;
|
||||
|
||||
use CodeIgniter\Exceptions\FrameworkException;
|
||||
|
||||
class SessionException extends FrameworkException
|
||||
{
|
||||
public static function forMissingDatabaseTable()
|
||||
{
|
||||
return new static(lang('Session.missingDatabaseTable'));
|
||||
}
|
||||
|
||||
public static function forInvalidSavePath(?string $path = null)
|
||||
{
|
||||
return new static(lang('Session.invalidSavePath', [$path]));
|
||||
}
|
||||
|
||||
public static function forWriteProtectedSavePath(?string $path = null)
|
||||
{
|
||||
return new static(lang('Session.writeProtectedSavePath', [$path]));
|
||||
}
|
||||
|
||||
public static function forEmptySavepath()
|
||||
{
|
||||
return new static(lang('Session.emptySavePath'));
|
||||
}
|
||||
|
||||
public static function forInvalidSavePathFormat(string $path)
|
||||
{
|
||||
return new static(lang('Session.invalidSavePathFormat', [$path]));
|
||||
}
|
||||
|
||||
/**
|
||||
* @deprecated
|
||||
*
|
||||
* @codeCoverageIgnore
|
||||
*/
|
||||
public static function forInvalidSameSiteSetting(string $samesite)
|
||||
{
|
||||
return new static(lang('Session.invalidSameSiteSetting', [$samesite]));
|
||||
}
|
||||
}
|
||||
91
system/Session/Handlers/ArrayHandler.php
Normal file
91
system/Session/Handlers/ArrayHandler.php
Normal file
@@ -0,0 +1,91 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* This file is part of CodeIgniter 4 framework.
|
||||
*
|
||||
* (c) CodeIgniter Foundation <admin@codeigniter.com>
|
||||
*
|
||||
* For the full copyright and license information, please view
|
||||
* the LICENSE file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace CodeIgniter\Session\Handlers;
|
||||
|
||||
use ReturnTypeWillChange;
|
||||
|
||||
/**
|
||||
* Session handler using static array for storage.
|
||||
* Intended only for use during testing.
|
||||
*/
|
||||
class ArrayHandler extends BaseHandler
|
||||
{
|
||||
protected static $cache = [];
|
||||
|
||||
/**
|
||||
* Re-initialize existing session, or creates a new one.
|
||||
*
|
||||
* @param string $path The path where to store/retrieve the session
|
||||
* @param string $name The session name
|
||||
*/
|
||||
public function open($path, $name): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads the session data from the session storage, and returns the results.
|
||||
*
|
||||
* @param string $id The session ID
|
||||
*
|
||||
* @return false|string Returns an encoded string of the read data.
|
||||
* If nothing was read, it must return false.
|
||||
*/
|
||||
#[ReturnTypeWillChange]
|
||||
public function read($id)
|
||||
{
|
||||
return '';
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes the session data to the session storage.
|
||||
*
|
||||
* @param string $id The session ID
|
||||
* @param string $data The encoded session data
|
||||
*/
|
||||
public function write($id, $data): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Closes the current session.
|
||||
*/
|
||||
public function close(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Destroys a session
|
||||
*
|
||||
* @param string $id The session ID being destroyed
|
||||
*/
|
||||
public function destroy($id): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Cleans up expired sessions.
|
||||
*
|
||||
* @param int $max_lifetime Sessions that have not updated
|
||||
* for the last max_lifetime seconds will be removed.
|
||||
*
|
||||
* @return false|int Returns the number of deleted sessions on success, or false on failure.
|
||||
*/
|
||||
#[ReturnTypeWillChange]
|
||||
public function gc($max_lifetime)
|
||||
{
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
166
system/Session/Handlers/BaseHandler.php
Normal file
166
system/Session/Handlers/BaseHandler.php
Normal file
@@ -0,0 +1,166 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* This file is part of CodeIgniter 4 framework.
|
||||
*
|
||||
* (c) CodeIgniter Foundation <admin@codeigniter.com>
|
||||
*
|
||||
* For the full copyright and license information, please view
|
||||
* the LICENSE file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace CodeIgniter\Session\Handlers;
|
||||
|
||||
use Config\App as AppConfig;
|
||||
use Psr\Log\LoggerAwareTrait;
|
||||
use SessionHandlerInterface;
|
||||
|
||||
/**
|
||||
* Base class for session handling
|
||||
*/
|
||||
abstract class BaseHandler implements SessionHandlerInterface
|
||||
{
|
||||
use LoggerAwareTrait;
|
||||
|
||||
/**
|
||||
* The Data fingerprint.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $fingerprint;
|
||||
|
||||
/**
|
||||
* Lock placeholder.
|
||||
*
|
||||
* @var mixed
|
||||
*/
|
||||
protected $lock = false;
|
||||
|
||||
/**
|
||||
* Cookie prefix
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $cookiePrefix = '';
|
||||
|
||||
/**
|
||||
* Cookie domain
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $cookieDomain = '';
|
||||
|
||||
/**
|
||||
* Cookie path
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $cookiePath = '/';
|
||||
|
||||
/**
|
||||
* Cookie secure?
|
||||
*
|
||||
* @var bool
|
||||
*/
|
||||
protected $cookieSecure = false;
|
||||
|
||||
/**
|
||||
* Cookie name to use
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $cookieName;
|
||||
|
||||
/**
|
||||
* Match IP addresses for cookies?
|
||||
*
|
||||
* @var bool
|
||||
*/
|
||||
protected $matchIP = false;
|
||||
|
||||
/**
|
||||
* Current session ID
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $sessionID;
|
||||
|
||||
/**
|
||||
* The 'save path' for the session
|
||||
* varies between
|
||||
*
|
||||
* @var array|string
|
||||
*/
|
||||
protected $savePath;
|
||||
|
||||
/**
|
||||
* User's IP address.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $ipAddress;
|
||||
|
||||
public function __construct(AppConfig $config, string $ipAddress)
|
||||
{
|
||||
$this->cookiePrefix = $config->cookiePrefix;
|
||||
$this->cookieDomain = $config->cookieDomain;
|
||||
$this->cookiePath = $config->cookiePath;
|
||||
$this->cookieSecure = $config->cookieSecure;
|
||||
$this->cookieName = $config->sessionCookieName;
|
||||
$this->matchIP = $config->sessionMatchIP;
|
||||
$this->savePath = $config->sessionSavePath;
|
||||
$this->ipAddress = $ipAddress;
|
||||
}
|
||||
|
||||
/**
|
||||
* Internal method to force removal of a cookie by the client
|
||||
* when session_destroy() is called.
|
||||
*/
|
||||
protected function destroyCookie(): bool
|
||||
{
|
||||
return setcookie(
|
||||
$this->cookieName,
|
||||
'',
|
||||
['expires' => 1, 'path' => $this->cookiePath, 'domain' => $this->cookieDomain, 'secure' => $this->cookieSecure, 'httponly' => true]
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* A dummy method allowing drivers with no locking functionality
|
||||
* (databases other than PostgreSQL and MySQL) to act as if they
|
||||
* do acquire a lock.
|
||||
*/
|
||||
protected function lockSession(string $sessionID): bool
|
||||
{
|
||||
$this->lock = true;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Releases the lock, if any.
|
||||
*/
|
||||
protected function releaseLock(): bool
|
||||
{
|
||||
$this->lock = false;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
protected function fail(): bool
|
||||
{
|
||||
ini_set('session.save_path', $this->savePath);
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
324
system/Session/Handlers/DatabaseHandler.php
Normal file
324
system/Session/Handlers/DatabaseHandler.php
Normal file
@@ -0,0 +1,324 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* This file is part of CodeIgniter 4 framework.
|
||||
*
|
||||
* (c) CodeIgniter Foundation <admin@codeigniter.com>
|
||||
*
|
||||
* For the full copyright and license information, please view
|
||||
* the LICENSE file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace CodeIgniter\Session\Handlers;
|
||||
|
||||
use CodeIgniter\Database\BaseConnection;
|
||||
use CodeIgniter\Session\Exceptions\SessionException;
|
||||
use Config\App as AppConfig;
|
||||
use Config\Database;
|
||||
use ReturnTypeWillChange;
|
||||
|
||||
/**
|
||||
* Session handler using current Database for storage
|
||||
*/
|
||||
class DatabaseHandler extends BaseHandler
|
||||
{
|
||||
/**
|
||||
* The database group to use for storage.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $DBGroup;
|
||||
|
||||
/**
|
||||
* The name of the table to store session info.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $table;
|
||||
|
||||
/**
|
||||
* The DB Connection instance.
|
||||
*
|
||||
* @var BaseConnection
|
||||
*/
|
||||
protected $db;
|
||||
|
||||
/**
|
||||
* The database type, for locking purposes.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $platform;
|
||||
|
||||
/**
|
||||
* Row exists flag
|
||||
*
|
||||
* @var bool
|
||||
*/
|
||||
protected $rowExists = false;
|
||||
|
||||
/**
|
||||
* @throws SessionException
|
||||
*/
|
||||
public function __construct(AppConfig $config, string $ipAddress)
|
||||
{
|
||||
parent::__construct($config, $ipAddress);
|
||||
$this->table = $config->sessionSavePath;
|
||||
|
||||
if (empty($this->table)) {
|
||||
throw SessionException::forMissingDatabaseTable();
|
||||
}
|
||||
|
||||
$this->DBGroup = $config->sessionDBGroup ?? config(Database::class)->defaultGroup;
|
||||
|
||||
$this->db = Database::connect($this->DBGroup);
|
||||
|
||||
$driver = strtolower(get_class($this->db));
|
||||
|
||||
if (strpos($driver, 'mysql') !== false) {
|
||||
$this->platform = 'mysql';
|
||||
} elseif (strpos($driver, 'postgre') !== false) {
|
||||
$this->platform = 'postgre';
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Re-initialize existing session, or creates a new one.
|
||||
*
|
||||
* @param string $path The path where to store/retrieve the session
|
||||
* @param string $name The session name
|
||||
*/
|
||||
public function open($path, $name): bool
|
||||
{
|
||||
if (empty($this->db->connID)) {
|
||||
$this->db->initialize();
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads the session data from the session storage, and returns the results.
|
||||
*
|
||||
* @param string $id The session ID
|
||||
*
|
||||
* @return false|string Returns an encoded string of the read data.
|
||||
* If nothing was read, it must return false.
|
||||
*/
|
||||
#[ReturnTypeWillChange]
|
||||
public function read($id)
|
||||
{
|
||||
if ($this->lockSession($id) === false) {
|
||||
$this->fingerprint = md5('');
|
||||
|
||||
return '';
|
||||
}
|
||||
|
||||
if (! isset($this->sessionID)) {
|
||||
$this->sessionID = $id;
|
||||
}
|
||||
|
||||
$builder = $this->db->table($this->table)
|
||||
->select($this->platform === 'postgre' ? "encode(data, 'base64') AS data" : 'data')
|
||||
->where('id', $id);
|
||||
|
||||
if ($this->matchIP) {
|
||||
$builder = $builder->where('ip_address', $this->ipAddress);
|
||||
}
|
||||
|
||||
$result = $builder->get()->getRow();
|
||||
|
||||
if ($result === 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->rowExists = false;
|
||||
$this->fingerprint = md5('');
|
||||
|
||||
return '';
|
||||
}
|
||||
|
||||
if (is_bool($result)) {
|
||||
$result = '';
|
||||
} else {
|
||||
$result = ($this->platform === 'postgre') ? base64_decode(rtrim($result->data), true) : $result->data;
|
||||
}
|
||||
|
||||
$this->fingerprint = md5($result);
|
||||
$this->rowExists = true;
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes the session data to the session storage.
|
||||
*
|
||||
* @param string $id The session ID
|
||||
* @param string $data The encoded session data
|
||||
*/
|
||||
public function write($id, $data): bool
|
||||
{
|
||||
if ($this->lock === false) {
|
||||
return $this->fail();
|
||||
}
|
||||
|
||||
if ($this->sessionID !== $id) {
|
||||
$this->rowExists = false;
|
||||
$this->sessionID = $id;
|
||||
}
|
||||
|
||||
if ($this->rowExists === false) {
|
||||
$insertData = [
|
||||
'id' => $id,
|
||||
'ip_address' => $this->ipAddress,
|
||||
'data' => $this->platform === 'postgre' ? '\x' . bin2hex($data) : $data,
|
||||
];
|
||||
|
||||
if (! $this->db->table($this->table)->set('timestamp', 'now()', false)->insert($insertData)) {
|
||||
return $this->fail();
|
||||
}
|
||||
|
||||
$this->fingerprint = md5($data);
|
||||
$this->rowExists = true;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
$builder = $this->db->table($this->table)->where('id', $id);
|
||||
|
||||
if ($this->matchIP) {
|
||||
$builder = $builder->where('ip_address', $this->ipAddress);
|
||||
}
|
||||
|
||||
$updateData = [];
|
||||
|
||||
if ($this->fingerprint !== md5($data)) {
|
||||
$updateData['data'] = ($this->platform === 'postgre') ? '\x' . bin2hex($data) : $data;
|
||||
}
|
||||
|
||||
if (! $builder->set('timestamp', 'now()', false)->update($updateData)) {
|
||||
return $this->fail();
|
||||
}
|
||||
|
||||
$this->fingerprint = md5($data);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Closes the current session.
|
||||
*/
|
||||
public function close(): bool
|
||||
{
|
||||
return ($this->lock && ! $this->releaseLock()) ? $this->fail() : true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Destroys a session
|
||||
*
|
||||
* @param string $id The session ID being destroyed
|
||||
*/
|
||||
public function destroy($id): bool
|
||||
{
|
||||
if ($this->lock) {
|
||||
$builder = $this->db->table($this->table)->where('id', $id);
|
||||
|
||||
if ($this->matchIP) {
|
||||
$builder = $builder->where('ip_address', $this->ipAddress);
|
||||
}
|
||||
|
||||
if (! $builder->delete()) {
|
||||
return $this->fail();
|
||||
}
|
||||
}
|
||||
|
||||
if ($this->close()) {
|
||||
$this->destroyCookie();
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
return $this->fail();
|
||||
}
|
||||
|
||||
/**
|
||||
* Cleans up expired sessions.
|
||||
*
|
||||
* @param int $max_lifetime Sessions that have not updated
|
||||
* for the last max_lifetime seconds will be removed.
|
||||
*
|
||||
* @return false|int Returns the number of deleted sessions on success, or false on failure.
|
||||
*/
|
||||
#[ReturnTypeWillChange]
|
||||
public function gc($max_lifetime)
|
||||
{
|
||||
$separator = $this->platform === 'postgre' ? '\'' : ' ';
|
||||
$interval = implode($separator, ['', "{$max_lifetime} second", '']);
|
||||
|
||||
return $this->db->table($this->table)->where('timestamp <', "now() - INTERVAL {$interval}", false)->delete() ? 1 : $this->fail();
|
||||
}
|
||||
|
||||
/**
|
||||
* Lock the session.
|
||||
*/
|
||||
protected function lockSession(string $sessionID): bool
|
||||
{
|
||||
if ($this->platform === 'mysql') {
|
||||
$arg = md5($sessionID . ($this->matchIP ? '_' . $this->ipAddress : ''));
|
||||
if ($this->db->query("SELECT GET_LOCK('{$arg}', 300) AS ci_session_lock")->getRow()->ci_session_lock) {
|
||||
$this->lock = $arg;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
return $this->fail();
|
||||
}
|
||||
|
||||
if ($this->platform === 'postgre') {
|
||||
$arg = "hashtext('{$sessionID}')" . ($this->matchIP ? ", hashtext('{$this->ipAddress}')" : '');
|
||||
if ($this->db->simpleQuery("SELECT pg_advisory_lock({$arg})")) {
|
||||
$this->lock = $arg;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
return $this->fail();
|
||||
}
|
||||
|
||||
// Unsupported DB? Let the parent handle the simplified version.
|
||||
return parent::lockSession($sessionID);
|
||||
}
|
||||
|
||||
/**
|
||||
* Releases the lock, if any.
|
||||
*/
|
||||
protected function releaseLock(): bool
|
||||
{
|
||||
if (! $this->lock) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if ($this->platform === 'mysql') {
|
||||
if ($this->db->query("SELECT RELEASE_LOCK('{$this->lock}') AS ci_session_lock")->getRow()->ci_session_lock) {
|
||||
$this->lock = false;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
return $this->fail();
|
||||
}
|
||||
|
||||
if ($this->platform === 'postgre') {
|
||||
if ($this->db->simpleQuery("SELECT pg_advisory_unlock({$this->lock})")) {
|
||||
$this->lock = false;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
return $this->fail();
|
||||
}
|
||||
|
||||
// Unsupported DB? Let the parent handle the simple version.
|
||||
return parent::releaseLock();
|
||||
}
|
||||
}
|
||||
339
system/Session/Handlers/FileHandler.php
Normal file
339
system/Session/Handlers/FileHandler.php
Normal file
@@ -0,0 +1,339 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* This file is part of CodeIgniter 4 framework.
|
||||
*
|
||||
* (c) CodeIgniter Foundation <admin@codeigniter.com>
|
||||
*
|
||||
* For the full copyright and license information, please view
|
||||
* the LICENSE file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace CodeIgniter\Session\Handlers;
|
||||
|
||||
use CodeIgniter\Session\Exceptions\SessionException;
|
||||
use Config\App as AppConfig;
|
||||
use ReturnTypeWillChange;
|
||||
|
||||
/**
|
||||
* Session handler using file system for storage
|
||||
*/
|
||||
class FileHandler extends BaseHandler
|
||||
{
|
||||
/**
|
||||
* Where to save the session files to.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $savePath;
|
||||
|
||||
/**
|
||||
* The file handle
|
||||
*
|
||||
* @var resource|null
|
||||
*/
|
||||
protected $fileHandle;
|
||||
|
||||
/**
|
||||
* File Name
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $filePath;
|
||||
|
||||
/**
|
||||
* Whether this is a new file.
|
||||
*
|
||||
* @var bool
|
||||
*/
|
||||
protected $fileNew;
|
||||
|
||||
/**
|
||||
* Whether IP addresses should be matched.
|
||||
*
|
||||
* @var bool
|
||||
*/
|
||||
protected $matchIP = false;
|
||||
|
||||
/**
|
||||
* Regex of session ID
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $sessionIDRegex = '';
|
||||
|
||||
public function __construct(AppConfig $config, string $ipAddress)
|
||||
{
|
||||
parent::__construct($config, $ipAddress);
|
||||
|
||||
if (! empty($config->sessionSavePath)) {
|
||||
$this->savePath = rtrim($config->sessionSavePath, '/\\');
|
||||
ini_set('session.save_path', $config->sessionSavePath);
|
||||
} else {
|
||||
$sessionPath = rtrim(ini_get('session.save_path'), '/\\');
|
||||
|
||||
if (! $sessionPath) {
|
||||
$sessionPath = WRITEPATH . 'session';
|
||||
}
|
||||
|
||||
$this->savePath = $sessionPath;
|
||||
}
|
||||
|
||||
$this->matchIP = $config->sessionMatchIP;
|
||||
|
||||
$this->configureSessionIDRegex();
|
||||
}
|
||||
|
||||
/**
|
||||
* Re-initialize existing session, or creates a new one.
|
||||
*
|
||||
* @param string $path The path where to store/retrieve the session
|
||||
* @param string $name The session name
|
||||
*
|
||||
* @throws SessionException
|
||||
*/
|
||||
public function open($path, $name): bool
|
||||
{
|
||||
if (! is_dir($path) && ! mkdir($path, 0700, true)) {
|
||||
throw SessionException::forInvalidSavePath($this->savePath);
|
||||
}
|
||||
|
||||
if (! is_writable($path)) {
|
||||
throw SessionException::forWriteProtectedSavePath($this->savePath);
|
||||
}
|
||||
|
||||
$this->savePath = $path;
|
||||
|
||||
// we'll use the session name as prefix to avoid collisions
|
||||
$this->filePath = $this->savePath . '/' . $name . ($this->matchIP ? md5($this->ipAddress) : '');
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads the session data from the session storage, and returns the results.
|
||||
*
|
||||
* @param string $id The session ID
|
||||
*
|
||||
* @return false|string Returns an encoded string of the read data.
|
||||
* If nothing was read, it must return false.
|
||||
*/
|
||||
#[ReturnTypeWillChange]
|
||||
public function read($id)
|
||||
{
|
||||
// This might seem weird, but PHP 5.6 introduced session_reset(),
|
||||
// which re-reads session data
|
||||
if ($this->fileHandle === null) {
|
||||
$this->fileNew = ! is_file($this->filePath . $id);
|
||||
|
||||
if (($this->fileHandle = fopen($this->filePath . $id, 'c+b')) === false) {
|
||||
$this->logger->error("Session: Unable to open file '" . $this->filePath . $id . "'.");
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
if (flock($this->fileHandle, LOCK_EX) === false) {
|
||||
$this->logger->error("Session: Unable to obtain lock for file '" . $this->filePath . $id . "'.");
|
||||
fclose($this->fileHandle);
|
||||
$this->fileHandle = null;
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
if (! isset($this->sessionID)) {
|
||||
$this->sessionID = $id;
|
||||
}
|
||||
|
||||
if ($this->fileNew) {
|
||||
chmod($this->filePath . $id, 0600);
|
||||
$this->fingerprint = md5('');
|
||||
|
||||
return '';
|
||||
}
|
||||
} else {
|
||||
rewind($this->fileHandle);
|
||||
}
|
||||
|
||||
$data = '';
|
||||
$buffer = 0;
|
||||
clearstatcache(); // Address https://github.com/codeigniter4/CodeIgniter4/issues/2056
|
||||
|
||||
for ($read = 0, $length = filesize($this->filePath . $id); $read < $length; $read += strlen($buffer)) {
|
||||
if (($buffer = fread($this->fileHandle, $length - $read)) === false) {
|
||||
break;
|
||||
}
|
||||
|
||||
$data .= $buffer;
|
||||
}
|
||||
|
||||
$this->fingerprint = md5($data);
|
||||
|
||||
return $data;
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes the session data to the session storage.
|
||||
*
|
||||
* @param string $id The session ID
|
||||
* @param string $data The encoded session data
|
||||
*/
|
||||
public function write($id, $data): bool
|
||||
{
|
||||
// If the two IDs don't match, we have a session_regenerate_id() call
|
||||
if ($id !== $this->sessionID) {
|
||||
$this->sessionID = $id;
|
||||
}
|
||||
|
||||
if (! is_resource($this->fileHandle)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if ($this->fingerprint === md5($data)) {
|
||||
return ($this->fileNew) ? true : touch($this->filePath . $id);
|
||||
}
|
||||
|
||||
if (! $this->fileNew) {
|
||||
ftruncate($this->fileHandle, 0);
|
||||
rewind($this->fileHandle);
|
||||
}
|
||||
|
||||
if (($length = strlen($data)) > 0) {
|
||||
$result = null;
|
||||
|
||||
for ($written = 0; $written < $length; $written += $result) {
|
||||
if (($result = fwrite($this->fileHandle, substr($data, $written))) === false) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (! is_int($result)) {
|
||||
$this->fingerprint = md5(substr($data, 0, $written));
|
||||
$this->logger->error('Session: Unable to write data.');
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
$this->fingerprint = md5($data);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Closes the current session.
|
||||
*/
|
||||
public function close(): bool
|
||||
{
|
||||
if (is_resource($this->fileHandle)) {
|
||||
flock($this->fileHandle, LOCK_UN);
|
||||
fclose($this->fileHandle);
|
||||
|
||||
$this->fileHandle = null;
|
||||
$this->fileNew = false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Destroys a session
|
||||
*
|
||||
* @param string $id The session ID being destroyed
|
||||
*/
|
||||
public function destroy($id): bool
|
||||
{
|
||||
if ($this->close()) {
|
||||
return is_file($this->filePath . $id)
|
||||
? (unlink($this->filePath . $id) && $this->destroyCookie())
|
||||
: true;
|
||||
}
|
||||
|
||||
if ($this->filePath !== null) {
|
||||
clearstatcache();
|
||||
|
||||
return is_file($this->filePath . $id)
|
||||
? (unlink($this->filePath . $id) && $this->destroyCookie())
|
||||
: true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Cleans up expired sessions.
|
||||
*
|
||||
* @param int $max_lifetime Sessions that have not updated
|
||||
* for the last max_lifetime seconds will be removed.
|
||||
*
|
||||
* @return false|int Returns the number of deleted sessions on success, or false on failure.
|
||||
*/
|
||||
#[ReturnTypeWillChange]
|
||||
public function gc($max_lifetime)
|
||||
{
|
||||
if (! is_dir($this->savePath) || ($directory = opendir($this->savePath)) === false) {
|
||||
$this->logger->debug("Session: Garbage collector couldn't list files under directory '" . $this->savePath . "'.");
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
$ts = time() - $max_lifetime;
|
||||
|
||||
$pattern = $this->matchIP === true ? '[0-9a-f]{32}' : '';
|
||||
|
||||
$pattern = sprintf(
|
||||
'#\A%s' . $pattern . $this->sessionIDRegex . '\z#',
|
||||
preg_quote($this->cookieName, '#')
|
||||
);
|
||||
|
||||
$collected = 0;
|
||||
|
||||
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)
|
||||
|| ! is_file($this->savePath . DIRECTORY_SEPARATOR . $file)
|
||||
|| ($mtime = filemtime($this->savePath . DIRECTORY_SEPARATOR . $file)) === false
|
||||
|| $mtime > $ts
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
|
||||
unlink($this->savePath . DIRECTORY_SEPARATOR . $file);
|
||||
$collected++;
|
||||
}
|
||||
|
||||
closedir($directory);
|
||||
|
||||
return $collected;
|
||||
}
|
||||
|
||||
/**
|
||||
* Configure Session ID regular expression
|
||||
*/
|
||||
protected function configureSessionIDRegex()
|
||||
{
|
||||
$bitsPerCharacter = (int) ini_get('session.sid_bits_per_character');
|
||||
$SIDLength = (int) ini_get('session.sid_length');
|
||||
|
||||
if (($bits = $SIDLength * $bitsPerCharacter) < 160) {
|
||||
// Add as many more characters as necessary to reach at least 160 bits
|
||||
$SIDLength += (int) ceil((160 % $bits) / $bitsPerCharacter);
|
||||
ini_set('session.sid_length', (string) $SIDLength);
|
||||
}
|
||||
|
||||
switch ($bitsPerCharacter) {
|
||||
case 4:
|
||||
$this->sessionIDRegex = '[0-9a-f]';
|
||||
break;
|
||||
|
||||
case 5:
|
||||
$this->sessionIDRegex = '[0-9a-v]';
|
||||
break;
|
||||
|
||||
case 6:
|
||||
$this->sessionIDRegex = '[0-9a-zA-Z,-]';
|
||||
break;
|
||||
}
|
||||
|
||||
$this->sessionIDRegex .= '{' . $SIDLength . '}';
|
||||
}
|
||||
}
|
||||
303
system/Session/Handlers/MemcachedHandler.php
Normal file
303
system/Session/Handlers/MemcachedHandler.php
Normal file
@@ -0,0 +1,303 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* This file is part of CodeIgniter 4 framework.
|
||||
*
|
||||
* (c) CodeIgniter Foundation <admin@codeigniter.com>
|
||||
*
|
||||
* For the full copyright and license information, please view
|
||||
* the LICENSE file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace CodeIgniter\Session\Handlers;
|
||||
|
||||
use CodeIgniter\Session\Exceptions\SessionException;
|
||||
use Config\App as AppConfig;
|
||||
use Memcached;
|
||||
use ReturnTypeWillChange;
|
||||
|
||||
/**
|
||||
* Session handler using Memcache for persistence
|
||||
*/
|
||||
class MemcachedHandler extends BaseHandler
|
||||
{
|
||||
/**
|
||||
* Memcached instance
|
||||
*
|
||||
* @var Memcached|null
|
||||
*/
|
||||
protected $memcached;
|
||||
|
||||
/**
|
||||
* Key prefix
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $keyPrefix = 'ci_session:';
|
||||
|
||||
/**
|
||||
* Lock key
|
||||
*
|
||||
* @var string|null
|
||||
*/
|
||||
protected $lockKey;
|
||||
|
||||
/**
|
||||
* Number of seconds until the session ends.
|
||||
*
|
||||
* @var int
|
||||
*/
|
||||
protected $sessionExpiration = 7200;
|
||||
|
||||
/**
|
||||
* @throws SessionException
|
||||
*/
|
||||
public function __construct(AppConfig $config, string $ipAddress)
|
||||
{
|
||||
parent::__construct($config, $ipAddress);
|
||||
|
||||
if (empty($this->savePath)) {
|
||||
throw SessionException::forEmptySavepath();
|
||||
}
|
||||
|
||||
if ($this->matchIP === true) {
|
||||
$this->keyPrefix .= $this->ipAddress . ':';
|
||||
}
|
||||
|
||||
if (! empty($this->keyPrefix)) {
|
||||
ini_set('memcached.sess_prefix', $this->keyPrefix);
|
||||
}
|
||||
|
||||
$this->sessionExpiration = $config->sessionExpiration;
|
||||
}
|
||||
|
||||
/**
|
||||
* Re-initialize existing session, or creates a new one.
|
||||
*
|
||||
* @param string $path The path where to store/retrieve the session
|
||||
* @param string $name The session name
|
||||
*/
|
||||
public function open($path, $name): bool
|
||||
{
|
||||
$this->memcached = new Memcached();
|
||||
$this->memcached->setOption(Memcached::OPT_BINARY_PROTOCOL, true); // required for touch() usage
|
||||
|
||||
$serverList = [];
|
||||
|
||||
foreach ($this->memcached->getServerList() as $server) {
|
||||
$serverList[] = $server['host'] . ':' . $server['port'];
|
||||
}
|
||||
|
||||
if (! preg_match_all('#,?([^,:]+)\:(\d{1,5})(?:\:(\d+))?#', $this->savePath, $matches, PREG_SET_ORDER)) {
|
||||
$this->memcached = null;
|
||||
$this->logger->error('Session: Invalid Memcached save path format: ' . $this->savePath);
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
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], $serverList, true)) {
|
||||
$this->logger->debug('Session: Memcached server pool already has ' . $match[1] . ':' . $match[2]);
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if (! $this->memcached->addServer($match[1], $match[2], $match[3] ?? 0)) {
|
||||
$this->logger->error('Could not add ' . $match[1] . ':' . $match[2] . ' to Memcached server pool.');
|
||||
} else {
|
||||
$serverList[] = $match[1] . ':' . $match[2];
|
||||
}
|
||||
}
|
||||
|
||||
if (empty($serverList)) {
|
||||
$this->logger->error('Session: Memcached server pool is empty.');
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads the session data from the session storage, and returns the results.
|
||||
*
|
||||
* @param string $id The session ID
|
||||
*
|
||||
* @return false|string Returns an encoded string of the read data.
|
||||
* If nothing was read, it must return false.
|
||||
*/
|
||||
#[ReturnTypeWillChange]
|
||||
public function read($id)
|
||||
{
|
||||
if (isset($this->memcached) && $this->lockSession($id)) {
|
||||
if (! isset($this->sessionID)) {
|
||||
$this->sessionID = $id;
|
||||
}
|
||||
|
||||
$data = (string) $this->memcached->get($this->keyPrefix . $id);
|
||||
|
||||
$this->fingerprint = md5($data);
|
||||
|
||||
return $data;
|
||||
}
|
||||
|
||||
return '';
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes the session data to the session storage.
|
||||
*
|
||||
* @param string $id The session ID
|
||||
* @param string $data The encoded session data
|
||||
*/
|
||||
public function write($id, $data): bool
|
||||
{
|
||||
if (! isset($this->memcached)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if ($this->sessionID !== $id) {
|
||||
if (! $this->releaseLock() || ! $this->lockSession($id)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$this->fingerprint = md5('');
|
||||
$this->sessionID = $id;
|
||||
}
|
||||
|
||||
if (isset($this->lockKey)) {
|
||||
$this->memcached->replace($this->lockKey, time(), 300);
|
||||
|
||||
if ($this->fingerprint !== ($fingerprint = md5($data))) {
|
||||
if ($this->memcached->set($this->keyPrefix . $id, $data, $this->sessionExpiration)) {
|
||||
$this->fingerprint = $fingerprint;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
return $this->memcached->touch($this->keyPrefix . $id, $this->sessionExpiration);
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Closes the current session.
|
||||
*/
|
||||
public function close(): bool
|
||||
{
|
||||
if (isset($this->memcached)) {
|
||||
if (isset($this->lockKey)) {
|
||||
$this->memcached->delete($this->lockKey);
|
||||
}
|
||||
|
||||
if (! $this->memcached->quit()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$this->memcached = null;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Destroys a session
|
||||
*
|
||||
* @param string $id The session ID being destroyed
|
||||
*/
|
||||
public function destroy($id): bool
|
||||
{
|
||||
if (isset($this->memcached, $this->lockKey)) {
|
||||
$this->memcached->delete($this->keyPrefix . $id);
|
||||
|
||||
return $this->destroyCookie();
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Cleans up expired sessions.
|
||||
*
|
||||
* @param int $max_lifetime Sessions that have not updated
|
||||
* for the last max_lifetime seconds will be removed.
|
||||
*
|
||||
* @return false|int Returns the number of deleted sessions on success, or false on failure.
|
||||
*/
|
||||
#[ReturnTypeWillChange]
|
||||
public function gc($max_lifetime)
|
||||
{
|
||||
return 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Acquires an emulated lock.
|
||||
*
|
||||
* @param string $sessionID Session ID
|
||||
*/
|
||||
protected function lockSession(string $sessionID): bool
|
||||
{
|
||||
if (isset($this->lockKey)) {
|
||||
return $this->memcached->replace($this->lockKey, time(), 300);
|
||||
}
|
||||
|
||||
$lockKey = $this->keyPrefix . $sessionID . ':lock';
|
||||
$attempt = 0;
|
||||
|
||||
do {
|
||||
if ($this->memcached->get($lockKey)) {
|
||||
sleep(1);
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if (! $this->memcached->set($lockKey, time(), 300)) {
|
||||
$this->logger->error('Session: Error while trying to obtain lock for ' . $this->keyPrefix . $sessionID);
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
$this->lockKey = $lockKey;
|
||||
break;
|
||||
} while (++$attempt < 30);
|
||||
|
||||
if ($attempt === 30) {
|
||||
$this->logger->error('Session: Unable to obtain lock for ' . $this->keyPrefix . $sessionID . ' after 30 attempts, aborting.');
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
$this->lock = true;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Releases a previously acquired lock
|
||||
*/
|
||||
protected function releaseLock(): bool
|
||||
{
|
||||
if (isset($this->memcached, $this->lockKey) && $this->lock) {
|
||||
if (
|
||||
! $this->memcached->delete($this->lockKey)
|
||||
&& $this->memcached->getResultCode() !== Memcached::RES_NOTFOUND
|
||||
) {
|
||||
$this->logger->error('Session: Error while trying to free lock for ' . $this->lockKey);
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
$this->lockKey = null;
|
||||
$this->lock = false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
329
system/Session/Handlers/RedisHandler.php
Normal file
329
system/Session/Handlers/RedisHandler.php
Normal file
@@ -0,0 +1,329 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* This file is part of CodeIgniter 4 framework.
|
||||
*
|
||||
* (c) CodeIgniter Foundation <admin@codeigniter.com>
|
||||
*
|
||||
* For the full copyright and license information, please view
|
||||
* the LICENSE file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace CodeIgniter\Session\Handlers;
|
||||
|
||||
use CodeIgniter\Session\Exceptions\SessionException;
|
||||
use Config\App as AppConfig;
|
||||
use Redis;
|
||||
use RedisException;
|
||||
use ReturnTypeWillChange;
|
||||
|
||||
/**
|
||||
* Session handler using Redis for persistence
|
||||
*/
|
||||
class RedisHandler extends BaseHandler
|
||||
{
|
||||
/**
|
||||
* phpRedis instance
|
||||
*
|
||||
* @var Redis|null
|
||||
*/
|
||||
protected $redis;
|
||||
|
||||
/**
|
||||
* Key prefix
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $keyPrefix = 'ci_session:';
|
||||
|
||||
/**
|
||||
* Lock key
|
||||
*
|
||||
* @var string|null
|
||||
*/
|
||||
protected $lockKey;
|
||||
|
||||
/**
|
||||
* Key exists flag
|
||||
*
|
||||
* @var bool
|
||||
*/
|
||||
protected $keyExists = false;
|
||||
|
||||
/**
|
||||
* Number of seconds until the session ends.
|
||||
*
|
||||
* @var int
|
||||
*/
|
||||
protected $sessionExpiration = 7200;
|
||||
|
||||
/**
|
||||
* @throws SessionException
|
||||
*/
|
||||
public function __construct(AppConfig $config, string $ipAddress)
|
||||
{
|
||||
parent::__construct($config, $ipAddress);
|
||||
|
||||
if (empty($this->savePath)) {
|
||||
throw SessionException::forEmptySavepath();
|
||||
}
|
||||
|
||||
if (preg_match('#(?:tcp://)?([^:?]+)(?:\:(\d+))?(\?.+)?#', $this->savePath, $matches)) {
|
||||
if (! isset($matches[3])) {
|
||||
$matches[3] = ''; // Just to avoid undefined index notices below
|
||||
}
|
||||
|
||||
$this->savePath = [
|
||||
'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->keyPrefix = $match[1];
|
||||
} else {
|
||||
throw SessionException::forInvalidSavePathFormat($this->savePath);
|
||||
}
|
||||
|
||||
if ($this->matchIP === true) {
|
||||
$this->keyPrefix .= $this->ipAddress . ':';
|
||||
}
|
||||
|
||||
$this->sessionExpiration = empty($config->sessionExpiration)
|
||||
? (int) ini_get('session.gc_maxlifetime')
|
||||
: (int) $config->sessionExpiration;
|
||||
}
|
||||
|
||||
/**
|
||||
* Re-initialize existing session, or creates a new one.
|
||||
*
|
||||
* @param string $path The path where to store/retrieve the session
|
||||
* @param string $name The session name
|
||||
*/
|
||||
public function open($path, $name): bool
|
||||
{
|
||||
if (empty($this->savePath)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$redis = new Redis();
|
||||
|
||||
if (! $redis->connect($this->savePath['host'], $this->savePath['port'], $this->savePath['timeout'])) {
|
||||
$this->logger->error('Session: Unable to connect to Redis with the configured settings.');
|
||||
} elseif (isset($this->savePath['password']) && ! $redis->auth($this->savePath['password'])) {
|
||||
$this->logger->error('Session: Unable to authenticate to Redis instance.');
|
||||
} elseif (isset($this->savePath['database']) && ! $redis->select($this->savePath['database'])) {
|
||||
$this->logger->error('Session: Unable to select Redis database with index ' . $this->savePath['database']);
|
||||
} else {
|
||||
$this->redis = $redis;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads the session data from the session storage, and returns the results.
|
||||
*
|
||||
* @param string $id The session ID
|
||||
*
|
||||
* @return false|string Returns an encoded string of the read data.
|
||||
* If nothing was read, it must return false.
|
||||
*/
|
||||
#[ReturnTypeWillChange]
|
||||
public function read($id)
|
||||
{
|
||||
if (isset($this->redis) && $this->lockSession($id)) {
|
||||
if (! isset($this->sessionID)) {
|
||||
$this->sessionID = $id;
|
||||
}
|
||||
|
||||
$data = $this->redis->get($this->keyPrefix . $id);
|
||||
|
||||
if (is_string($data)) {
|
||||
$this->keyExists = true;
|
||||
} else {
|
||||
$data = '';
|
||||
}
|
||||
|
||||
$this->fingerprint = md5($data);
|
||||
|
||||
return $data;
|
||||
}
|
||||
|
||||
return '';
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes the session data to the session storage.
|
||||
*
|
||||
* @param string $id The session ID
|
||||
* @param string $data The encoded session data
|
||||
*/
|
||||
public function write($id, $data): bool
|
||||
{
|
||||
if (! isset($this->redis)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if ($this->sessionID !== $id) {
|
||||
if (! $this->releaseLock() || ! $this->lockSession($id)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$this->keyExists = false;
|
||||
$this->sessionID = $id;
|
||||
}
|
||||
|
||||
if (isset($this->lockKey)) {
|
||||
$this->redis->expire($this->lockKey, 300);
|
||||
|
||||
if ($this->fingerprint !== ($fingerprint = md5($data)) || $this->keyExists === false) {
|
||||
if ($this->redis->set($this->keyPrefix . $id, $data, $this->sessionExpiration)) {
|
||||
$this->fingerprint = $fingerprint;
|
||||
$this->keyExists = true;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
return $this->redis->expire($this->keyPrefix . $id, $this->sessionExpiration);
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Closes the current session.
|
||||
*/
|
||||
public function close(): bool
|
||||
{
|
||||
if (isset($this->redis)) {
|
||||
try {
|
||||
$pingReply = $this->redis->ping();
|
||||
|
||||
if (($pingReply === true) || ($pingReply === '+PONG')) {
|
||||
if (isset($this->lockKey)) {
|
||||
$this->redis->del($this->lockKey);
|
||||
}
|
||||
|
||||
if (! $this->redis->close()) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
} catch (RedisException $e) {
|
||||
$this->logger->error('Session: Got RedisException on close(): ' . $e->getMessage());
|
||||
}
|
||||
|
||||
$this->redis = null;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Destroys a session
|
||||
*
|
||||
* @param string $id The session ID being destroyed
|
||||
*/
|
||||
public function destroy($id): bool
|
||||
{
|
||||
if (isset($this->redis, $this->lockKey)) {
|
||||
if (($result = $this->redis->del($this->keyPrefix . $id)) !== 1) {
|
||||
$this->logger->debug('Session: Redis::del() expected to return 1, got ' . var_export($result, true) . ' instead.');
|
||||
}
|
||||
|
||||
return $this->destroyCookie();
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Cleans up expired sessions.
|
||||
*
|
||||
* @param int $max_lifetime Sessions that have not updated
|
||||
* for the last max_lifetime seconds will be removed.
|
||||
*
|
||||
* @return false|int Returns the number of deleted sessions on success, or false on failure.
|
||||
*/
|
||||
#[ReturnTypeWillChange]
|
||||
public function gc($max_lifetime)
|
||||
{
|
||||
return 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Acquires an emulated lock.
|
||||
*
|
||||
* @param string $sessionID Session ID
|
||||
*/
|
||||
protected function lockSession(string $sessionID): bool
|
||||
{
|
||||
// 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->lockKey === $this->keyPrefix . $sessionID . ':lock') {
|
||||
return $this->redis->expire($this->lockKey, 300);
|
||||
}
|
||||
|
||||
$lockKey = $this->keyPrefix . $sessionID . ':lock';
|
||||
$attempt = 0;
|
||||
|
||||
do {
|
||||
if (($ttl = $this->redis->ttl($lockKey)) > 0) {
|
||||
sleep(1);
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if (! $this->redis->setex($lockKey, 300, (string) time())) {
|
||||
$this->logger->error('Session: Error while trying to obtain lock for ' . $this->keyPrefix . $sessionID);
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
$this->lockKey = $lockKey;
|
||||
break;
|
||||
} while (++$attempt < 30);
|
||||
|
||||
if ($attempt === 30) {
|
||||
log_message('error', 'Session: Unable to obtain lock for ' . $this->keyPrefix . $sessionID . ' after 30 attempts, aborting.');
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
if ($ttl === -1) {
|
||||
log_message('debug', 'Session: Lock for ' . $this->keyPrefix . $sessionID . ' had no TTL, overriding.');
|
||||
}
|
||||
|
||||
$this->lock = true;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Releases a previously acquired lock
|
||||
*/
|
||||
protected function releaseLock(): bool
|
||||
{
|
||||
if (isset($this->redis, $this->lockKey) && $this->lock) {
|
||||
if (! $this->redis->del($this->lockKey)) {
|
||||
$this->logger->error('Session: Error while trying to free lock for ' . $this->lockKey);
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
$this->lockKey = null;
|
||||
$this->lock = false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
909
system/Session/Session.php
Normal file
909
system/Session/Session.php
Normal file
@@ -0,0 +1,909 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* This file is part of CodeIgniter 4 framework.
|
||||
*
|
||||
* (c) CodeIgniter Foundation <admin@codeigniter.com>
|
||||
*
|
||||
* For the full copyright and license information, please view
|
||||
* the LICENSE file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace CodeIgniter\Session;
|
||||
|
||||
use CodeIgniter\Cookie\Cookie;
|
||||
use Config\App;
|
||||
use Config\Cookie as CookieConfig;
|
||||
use Psr\Log\LoggerAwareTrait;
|
||||
use Psr\Log\LoggerInterface;
|
||||
use SessionHandlerInterface;
|
||||
|
||||
/**
|
||||
* Implementation of CodeIgniter session container.
|
||||
*
|
||||
* Session configuration is done through session variables and cookie related
|
||||
* variables in app/config/App.php
|
||||
*/
|
||||
class Session implements SessionInterface
|
||||
{
|
||||
use LoggerAwareTrait;
|
||||
|
||||
/**
|
||||
* Instance of the driver to use.
|
||||
*
|
||||
* @var SessionHandlerInterface
|
||||
*/
|
||||
protected $driver;
|
||||
|
||||
/**
|
||||
* The storage driver to use: files, database, redis, memcached
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $sessionDriverName;
|
||||
|
||||
/**
|
||||
* The session cookie name, must contain only [0-9a-z_-] characters.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $sessionCookieName = 'ci_session';
|
||||
|
||||
/**
|
||||
* The number of SECONDS you want the session to last.
|
||||
* Setting it to 0 (zero) means expire when the browser is closed.
|
||||
*
|
||||
* @var int
|
||||
*/
|
||||
protected $sessionExpiration = 7200;
|
||||
|
||||
/**
|
||||
* The location to save sessions to, driver dependent..
|
||||
*
|
||||
* For the 'files' driver, it's a path to a writable directory.
|
||||
* WARNING: Only absolute paths are supported!
|
||||
*
|
||||
* For the 'database' driver, it's a table name.
|
||||
*
|
||||
* @todo address memcache & redis needs
|
||||
*
|
||||
* IMPORTANT: You are REQUIRED to set a valid save path!
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $sessionSavePath;
|
||||
|
||||
/**
|
||||
* Whether to match the user's IP address when reading the session data.
|
||||
*
|
||||
* WARNING: If you're using the database driver, don't forget to update
|
||||
* your session table's PRIMARY KEY when changing this setting.
|
||||
*
|
||||
* @var bool
|
||||
*/
|
||||
protected $sessionMatchIP = false;
|
||||
|
||||
/**
|
||||
* How many seconds between CI regenerating the session ID.
|
||||
*
|
||||
* @var int
|
||||
*/
|
||||
protected $sessionTimeToUpdate = 300;
|
||||
|
||||
/**
|
||||
* Whether to destroy session data associated with the old session ID
|
||||
* when auto-regenerating the session ID. When set to FALSE, the data
|
||||
* will be later deleted by the garbage collector.
|
||||
*
|
||||
* @var bool
|
||||
*/
|
||||
protected $sessionRegenerateDestroy = false;
|
||||
|
||||
/**
|
||||
* The session cookie instance.
|
||||
*
|
||||
* @var Cookie
|
||||
*/
|
||||
protected $cookie;
|
||||
|
||||
/**
|
||||
* The domain name to use for cookies.
|
||||
* Set to .your-domain.com for site-wide cookies.
|
||||
*
|
||||
* @var string
|
||||
*
|
||||
* @deprecated
|
||||
*/
|
||||
protected $cookieDomain = '';
|
||||
|
||||
/**
|
||||
* Path used for storing cookies.
|
||||
* Typically will be a forward slash.
|
||||
*
|
||||
* @var string
|
||||
*
|
||||
* @deprecated
|
||||
*/
|
||||
protected $cookiePath = '/';
|
||||
|
||||
/**
|
||||
* Cookie will only be set if a secure HTTPS connection exists.
|
||||
*
|
||||
* @var bool
|
||||
*
|
||||
* @deprecated
|
||||
*/
|
||||
protected $cookieSecure = false;
|
||||
|
||||
/**
|
||||
* Cookie SameSite setting as described in RFC6265
|
||||
* Must be 'None', 'Lax' or 'Strict'.
|
||||
*
|
||||
* @var string
|
||||
*
|
||||
* @deprecated
|
||||
*/
|
||||
protected $cookieSameSite = Cookie::SAMESITE_LAX;
|
||||
|
||||
/**
|
||||
* sid regex expression
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $sidRegexp;
|
||||
|
||||
/**
|
||||
* Logger instance to record error messages and warnings.
|
||||
*
|
||||
* @var LoggerInterface
|
||||
*/
|
||||
protected $logger;
|
||||
|
||||
/**
|
||||
* Constructor.
|
||||
*
|
||||
* Extract configuration settings and save them here.
|
||||
*/
|
||||
public function __construct(SessionHandlerInterface $driver, App $config)
|
||||
{
|
||||
$this->driver = $driver;
|
||||
|
||||
$this->sessionDriverName = $config->sessionDriver;
|
||||
$this->sessionCookieName = $config->sessionCookieName ?? $this->sessionCookieName;
|
||||
$this->sessionExpiration = $config->sessionExpiration ?? $this->sessionExpiration;
|
||||
$this->sessionSavePath = $config->sessionSavePath;
|
||||
$this->sessionMatchIP = $config->sessionMatchIP ?? $this->sessionMatchIP;
|
||||
$this->sessionTimeToUpdate = $config->sessionTimeToUpdate ?? $this->sessionTimeToUpdate;
|
||||
$this->sessionRegenerateDestroy = $config->sessionRegenerateDestroy ?? $this->sessionRegenerateDestroy;
|
||||
|
||||
// DEPRECATED COOKIE MANAGEMENT
|
||||
$this->cookiePath = $config->cookiePath ?? $this->cookiePath;
|
||||
$this->cookieDomain = $config->cookieDomain ?? $this->cookieDomain;
|
||||
$this->cookieSecure = $config->cookieSecure ?? $this->cookieSecure;
|
||||
$this->cookieSameSite = $config->cookieSameSite ?? $this->cookieSameSite;
|
||||
|
||||
/** @var CookieConfig $cookie */
|
||||
$cookie = config('Cookie');
|
||||
|
||||
$this->cookie = new Cookie($this->sessionCookieName, '', [
|
||||
'expires' => $this->sessionExpiration === 0 ? 0 : time() + $this->sessionExpiration,
|
||||
'path' => $cookie->path ?? $config->cookiePath,
|
||||
'domain' => $cookie->domain ?? $config->cookieDomain,
|
||||
'secure' => $cookie->secure ?? $config->cookieSecure,
|
||||
'httponly' => true, // for security
|
||||
'samesite' => $cookie->samesite ?? $config->cookieSameSite ?? Cookie::SAMESITE_LAX,
|
||||
'raw' => $cookie->raw ?? false,
|
||||
]);
|
||||
|
||||
helper('array');
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize the session container and starts up the session.
|
||||
*
|
||||
* @return mixed
|
||||
*/
|
||||
public function start()
|
||||
{
|
||||
if (is_cli() && ENVIRONMENT !== 'testing') {
|
||||
// @codeCoverageIgnoreStart
|
||||
$this->logger->debug('Session: Initialization under CLI aborted.');
|
||||
|
||||
return;
|
||||
// @codeCoverageIgnoreEnd
|
||||
}
|
||||
|
||||
if ((bool) ini_get('session.auto_start')) {
|
||||
$this->logger->error('Session: session.auto_start is enabled in php.ini. Aborting.');
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (session_status() === PHP_SESSION_ACTIVE) {
|
||||
$this->logger->warning('Session: Sessions is enabled, and one exists.Please don\'t $session->start();');
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$this->configure();
|
||||
$this->setSaveHandler();
|
||||
|
||||
// Sanitize the cookie, because apparently PHP doesn't do that for userspace handlers
|
||||
if (isset($_COOKIE[$this->sessionCookieName])
|
||||
&& (! is_string($_COOKIE[$this->sessionCookieName]) || ! preg_match('#\A' . $this->sidRegexp . '\z#', $_COOKIE[$this->sessionCookieName]))
|
||||
) {
|
||||
unset($_COOKIE[$this->sessionCookieName]);
|
||||
}
|
||||
|
||||
$this->startSession();
|
||||
|
||||
// Is session ID auto-regeneration configured? (ignoring ajax requests)
|
||||
if ((empty($_SERVER['HTTP_X_REQUESTED_WITH']) || strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) !== 'xmlhttprequest')
|
||||
&& ($regenerateTime = $this->sessionTimeToUpdate) > 0
|
||||
) {
|
||||
if (! isset($_SESSION['__ci_last_regenerate'])) {
|
||||
$_SESSION['__ci_last_regenerate'] = time();
|
||||
} elseif ($_SESSION['__ci_last_regenerate'] < (time() - $regenerateTime)) {
|
||||
$this->regenerate((bool) $this->sessionRegenerateDestroy);
|
||||
}
|
||||
}
|
||||
// Another work-around ... PHP doesn't seem to send the session cookie
|
||||
// unless it is being currently created or regenerated
|
||||
elseif (isset($_COOKIE[$this->sessionCookieName]) && $_COOKIE[$this->sessionCookieName] === session_id()) {
|
||||
$this->setCookie();
|
||||
}
|
||||
|
||||
$this->initVars();
|
||||
$this->logger->info("Session: Class initialized using '" . $this->sessionDriverName . "' driver.");
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Does a full stop of the session:
|
||||
*
|
||||
* - destroys the session
|
||||
* - unsets the session id
|
||||
* - destroys the session cookie
|
||||
*/
|
||||
public function stop()
|
||||
{
|
||||
setcookie(
|
||||
$this->sessionCookieName,
|
||||
session_id(),
|
||||
['expires' => 1, 'path' => $this->cookie->getPath(), 'domain' => $this->cookie->getDomain(), 'secure' => $this->cookie->isSecure(), 'httponly' => true]
|
||||
);
|
||||
|
||||
session_regenerate_id(true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Configuration.
|
||||
*
|
||||
* Handle input binds and configuration defaults.
|
||||
*/
|
||||
protected function configure()
|
||||
{
|
||||
if (empty($this->sessionCookieName)) {
|
||||
$this->sessionCookieName = ini_get('session.name');
|
||||
} else {
|
||||
ini_set('session.name', $this->sessionCookieName);
|
||||
}
|
||||
|
||||
$sameSite = $this->cookie->getSameSite() ?: ucfirst(Cookie::SAMESITE_LAX);
|
||||
|
||||
$params = [
|
||||
'lifetime' => $this->sessionExpiration,
|
||||
'path' => $this->cookie->getPath(),
|
||||
'domain' => $this->cookie->getDomain(),
|
||||
'secure' => $this->cookie->isSecure(),
|
||||
'httponly' => true, // HTTP only; Yes, this is intentional and not configurable for security reasons.
|
||||
'samesite' => $sameSite,
|
||||
];
|
||||
|
||||
ini_set('session.cookie_samesite', $sameSite);
|
||||
session_set_cookie_params($params);
|
||||
|
||||
if (! isset($this->sessionExpiration)) {
|
||||
$this->sessionExpiration = (int) ini_get('session.gc_maxlifetime');
|
||||
} elseif ($this->sessionExpiration > 0) {
|
||||
ini_set('session.gc_maxlifetime', (string) $this->sessionExpiration);
|
||||
}
|
||||
|
||||
if (! empty($this->sessionSavePath)) {
|
||||
ini_set('session.save_path', $this->sessionSavePath);
|
||||
}
|
||||
|
||||
// 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->configureSidLength();
|
||||
}
|
||||
|
||||
/**
|
||||
* 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
|
||||
*/
|
||||
protected function configureSidLength()
|
||||
{
|
||||
$bitsPerCharacter = (int) (ini_get('session.sid_bits_per_character') !== false
|
||||
? ini_get('session.sid_bits_per_character')
|
||||
: 4);
|
||||
|
||||
$sidLength = (int) (ini_get('session.sid_length') !== false
|
||||
? ini_get('session.sid_length')
|
||||
: 40);
|
||||
|
||||
if (($sidLength * $bitsPerCharacter) < 160) {
|
||||
$bits = ($sidLength * $bitsPerCharacter);
|
||||
// Add as many more characters as necessary to reach at least 160 bits
|
||||
$sidLength += (int) ceil((160 % $bits) / $bitsPerCharacter);
|
||||
ini_set('session.sid_length', (string) $sidLength);
|
||||
}
|
||||
|
||||
// Yes, 4,5,6 are the only known possible values as of 2016-10-27
|
||||
switch ($bitsPerCharacter) {
|
||||
case 4:
|
||||
$this->sidRegexp = '[0-9a-f]';
|
||||
break;
|
||||
|
||||
case 5:
|
||||
$this->sidRegexp = '[0-9a-v]';
|
||||
break;
|
||||
|
||||
case 6:
|
||||
$this->sidRegexp = '[0-9a-zA-Z,-]';
|
||||
break;
|
||||
}
|
||||
|
||||
$this->sidRegexp .= '{' . $sidLength . '}';
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle temporary variables
|
||||
*
|
||||
* Clears old "flash" data, marks the new one for deletion and handles
|
||||
* "temp" data deletion.
|
||||
*/
|
||||
protected function initVars()
|
||||
{
|
||||
if (empty($_SESSION['__ci_vars'])) {
|
||||
return;
|
||||
}
|
||||
|
||||
$currentTime = time();
|
||||
|
||||
foreach ($_SESSION['__ci_vars'] as $key => &$value) {
|
||||
if ($value === 'new') {
|
||||
$_SESSION['__ci_vars'][$key] = 'old';
|
||||
}
|
||||
// DO NOT move this above the 'new' check!
|
||||
elseif ($value === 'old' || $value < $currentTime) {
|
||||
unset($_SESSION[$key], $_SESSION['__ci_vars'][$key]);
|
||||
}
|
||||
}
|
||||
|
||||
if (empty($_SESSION['__ci_vars'])) {
|
||||
unset($_SESSION['__ci_vars']);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Regenerates the session ID.
|
||||
*
|
||||
* @param bool $destroy Should old session data be destroyed?
|
||||
*/
|
||||
public function regenerate(bool $destroy = false)
|
||||
{
|
||||
$_SESSION['__ci_last_regenerate'] = time();
|
||||
session_regenerate_id($destroy);
|
||||
}
|
||||
|
||||
/**
|
||||
* Destroys the current session.
|
||||
*/
|
||||
public function destroy()
|
||||
{
|
||||
if (ENVIRONMENT === 'testing') {
|
||||
return;
|
||||
}
|
||||
|
||||
session_destroy();
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets user data into the session.
|
||||
*
|
||||
* If $data is a string, then it is interpreted as a session property
|
||||
* key, and $value is expected to be non-null.
|
||||
*
|
||||
* If $data is an array, it is expected to be an array of key/value pairs
|
||||
* to be set as session properties.
|
||||
*
|
||||
* @param array|string $data Property name or associative array of properties
|
||||
* @param mixed $value Property value if single key provided
|
||||
*/
|
||||
public function set($data, $value = null)
|
||||
{
|
||||
if (is_array($data)) {
|
||||
foreach ($data as $key => &$value) {
|
||||
if (is_int($key)) {
|
||||
$_SESSION[$value] = null;
|
||||
} else {
|
||||
$_SESSION[$key] = $value;
|
||||
}
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$_SESSION[$data] = $value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get user data that has been set in the session.
|
||||
*
|
||||
* If the property exists as "normal", returns it.
|
||||
* Otherwise, returns an array of any temp or flash data values with the
|
||||
* property key.
|
||||
*
|
||||
* Replaces the legacy method $session->userdata();
|
||||
*
|
||||
* @param string|null $key Identifier of the session property to retrieve
|
||||
*
|
||||
* @return mixed The property value(s)
|
||||
*/
|
||||
public function get(?string $key = null)
|
||||
{
|
||||
if (! empty($key) && (null !== ($value = $_SESSION[$key] ?? null) || null !== ($value = dot_array_search($key, $_SESSION ?? [])))) {
|
||||
return $value;
|
||||
}
|
||||
|
||||
if (empty($_SESSION)) {
|
||||
return $key === null ? [] : null;
|
||||
}
|
||||
|
||||
if (! empty($key)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$userdata = [];
|
||||
$_exclude = array_merge(['__ci_vars'], $this->getFlashKeys(), $this->getTempKeys());
|
||||
|
||||
$keys = array_keys($_SESSION);
|
||||
|
||||
foreach ($keys as $key) {
|
||||
if (! in_array($key, $_exclude, true)) {
|
||||
$userdata[$key] = $_SESSION[$key];
|
||||
}
|
||||
}
|
||||
|
||||
return $userdata;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns whether an index exists in the session array.
|
||||
*
|
||||
* @param string $key Identifier of the session property we are interested in.
|
||||
*/
|
||||
public function has(string $key): bool
|
||||
{
|
||||
return isset($_SESSION[$key]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Push new value onto session value that is array.
|
||||
*
|
||||
* @param string $key Identifier of the session property we are interested in.
|
||||
* @param array $data value to be pushed to existing session key.
|
||||
*/
|
||||
public function push(string $key, array $data)
|
||||
{
|
||||
if ($this->has($key) && is_array($value = $this->get($key))) {
|
||||
$this->set($key, array_merge($value, $data));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove one or more session properties.
|
||||
*
|
||||
* If $key is an array, it is interpreted as an array of string property
|
||||
* identifiers to remove. Otherwise, it is interpreted as the identifier
|
||||
* of a specific session property to remove.
|
||||
*
|
||||
* @param array|string $key Identifier of the session property or properties to remove.
|
||||
*/
|
||||
public function remove($key)
|
||||
{
|
||||
if (is_array($key)) {
|
||||
foreach ($key as $k) {
|
||||
unset($_SESSION[$k]);
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
unset($_SESSION[$key]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Magic method to set variables in the session by simply calling
|
||||
* $session->foo = bar;
|
||||
*
|
||||
* @param string $key Identifier of the session property to set.
|
||||
* @param array|string $value
|
||||
*/
|
||||
public function __set(string $key, $value)
|
||||
{
|
||||
$_SESSION[$key] = $value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Magic method to get session variables by simply calling
|
||||
* $foo = $session->foo;
|
||||
*
|
||||
* @param string $key Identifier of the session property to remove.
|
||||
*
|
||||
* @return string|null
|
||||
*/
|
||||
public function __get(string $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];
|
||||
}
|
||||
|
||||
if ($key === 'session_id') {
|
||||
return session_id();
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Magic method to check for session variables.
|
||||
* Different from has() in that it will validate 'session_id' as well.
|
||||
* Mostly used by internal PHP functions, users should stick to has()
|
||||
*
|
||||
* @param string $key Identifier of the session property to remove.
|
||||
*/
|
||||
public function __isset(string $key): bool
|
||||
{
|
||||
return isset($_SESSION[$key]) || ($key === 'session_id');
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets data into the session that will only last for a single request.
|
||||
* Perfect for use with single-use status update messages.
|
||||
*
|
||||
* If $data is an array, it is interpreted as an associative array of
|
||||
* key/value pairs for flashdata properties.
|
||||
* Otherwise, it is interpreted as the identifier of a specific
|
||||
* flashdata property, with $value containing the property value.
|
||||
*
|
||||
* @param array|string $data Property identifier or associative array of properties
|
||||
* @param array|string $value Property value if $data is a scalar
|
||||
*/
|
||||
public function setFlashdata($data, $value = null)
|
||||
{
|
||||
$this->set($data, $value);
|
||||
$this->markAsFlashdata(is_array($data) ? array_keys($data) : $data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve one or more items of flash data from the session.
|
||||
*
|
||||
* If the item key is null, return all flashdata.
|
||||
*
|
||||
* @param string $key Property identifier
|
||||
*
|
||||
* @return array|null The requested property value, or an associative array of them
|
||||
*/
|
||||
public function getFlashdata(?string $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 = [];
|
||||
|
||||
if (! empty($_SESSION['__ci_vars'])) {
|
||||
foreach ($_SESSION['__ci_vars'] as $key => &$value) {
|
||||
if (! is_int($value)) {
|
||||
$flashdata[$key] = $_SESSION[$key];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $flashdata;
|
||||
}
|
||||
|
||||
/**
|
||||
* Keeps a single piece of flash data alive for one more request.
|
||||
*
|
||||
* @param array|string $key Property identifier or array of them
|
||||
*/
|
||||
public function keepFlashdata($key)
|
||||
{
|
||||
$this->markAsFlashdata($key);
|
||||
}
|
||||
|
||||
/**
|
||||
* Mark a session property or properties as flashdata.
|
||||
*
|
||||
* @param array|string $key Property identifier or array of them
|
||||
*
|
||||
* @return bool False if any of the properties are not already set
|
||||
*/
|
||||
public function markAsFlashdata($key): bool
|
||||
{
|
||||
if (is_array($key)) {
|
||||
foreach ($key as $sessionKey) {
|
||||
if (! isset($_SESSION[$sessionKey])) {
|
||||
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;
|
||||
}
|
||||
|
||||
/**
|
||||
* Unmark data in the session as flashdata.
|
||||
*
|
||||
* @param mixed $key Property identifier or array of them
|
||||
*/
|
||||
public function unmarkFlashdata($key)
|
||||
{
|
||||
if (empty($_SESSION['__ci_vars'])) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (! is_array($key)) {
|
||||
$key = [$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']);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve all of the keys for session data marked as flashdata.
|
||||
*
|
||||
* @return array The property names of all flashdata
|
||||
*/
|
||||
public function getFlashKeys(): array
|
||||
{
|
||||
if (! isset($_SESSION['__ci_vars'])) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$keys = [];
|
||||
|
||||
foreach (array_keys($_SESSION['__ci_vars']) as $key) {
|
||||
if (! is_int($_SESSION['__ci_vars'][$key])) {
|
||||
$keys[] = $key;
|
||||
}
|
||||
}
|
||||
|
||||
return $keys;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets new data into the session, and marks it as temporary data
|
||||
* with a set lifespan.
|
||||
*
|
||||
* @param array|string $data Session data key or associative array of items
|
||||
* @param null $value Value to store
|
||||
* @param int $ttl Time-to-live in seconds
|
||||
*/
|
||||
public function setTempdata($data, $value = null, int $ttl = 300)
|
||||
{
|
||||
$this->set($data, $value);
|
||||
$this->markAsTempdata($data, $ttl);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns either a single piece of tempdata, or all temp data currently
|
||||
* in the session.
|
||||
*
|
||||
* @param string $key Session data key
|
||||
*
|
||||
* @return mixed Session data value or null if not found.
|
||||
*/
|
||||
public function getTempdata(?string $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 = [];
|
||||
|
||||
if (! empty($_SESSION['__ci_vars'])) {
|
||||
foreach ($_SESSION['__ci_vars'] as $key => &$value) {
|
||||
if (is_int($value)) {
|
||||
$tempdata[$key] = $_SESSION[$key];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $tempdata;
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes a single piece of temporary data from the session.
|
||||
*
|
||||
* @param string $key Session data key
|
||||
*/
|
||||
public function removeTempdata(string $key)
|
||||
{
|
||||
$this->unmarkTempdata($key);
|
||||
unset($_SESSION[$key]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Mark one of more pieces of data as being temporary, meaning that
|
||||
* it has a set lifespan within the session.
|
||||
*
|
||||
* @param array|string $key Property identifier or array of them
|
||||
* @param int $ttl Time to live, in seconds
|
||||
*
|
||||
* @return bool False if any of the properties were not set
|
||||
*/
|
||||
public function markAsTempdata($key, int $ttl = 300): bool
|
||||
{
|
||||
$ttl += time();
|
||||
|
||||
if (is_array($key)) {
|
||||
$temp = [];
|
||||
|
||||
foreach ($key as $k => $v) {
|
||||
// Do we have a key => ttl pair, or just a key?
|
||||
if (is_int($k)) {
|
||||
$k = $v;
|
||||
$v = $ttl;
|
||||
} elseif (is_string($v)) {
|
||||
$v = time() + $ttl;
|
||||
} else {
|
||||
$v += time();
|
||||
}
|
||||
|
||||
if (! array_key_exists($k, $_SESSION)) {
|
||||
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;
|
||||
}
|
||||
|
||||
/**
|
||||
* Unmarks temporary data in the session, effectively removing its
|
||||
* lifespan and allowing it to live as long as the session does.
|
||||
*
|
||||
* @param array|string $key Property identifier or array of them
|
||||
*/
|
||||
public function unmarkTempdata($key)
|
||||
{
|
||||
if (empty($_SESSION['__ci_vars'])) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (! is_array($key)) {
|
||||
$key = [$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']);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve the keys of all session data that have been marked as temporary data.
|
||||
*/
|
||||
public function getTempKeys(): array
|
||||
{
|
||||
if (! isset($_SESSION['__ci_vars'])) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$keys = [];
|
||||
|
||||
foreach (array_keys($_SESSION['__ci_vars']) as $key) {
|
||||
if (is_int($_SESSION['__ci_vars'][$key])) {
|
||||
$keys[] = $key;
|
||||
}
|
||||
}
|
||||
|
||||
return $keys;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the driver as the session handler in PHP.
|
||||
* Extracted for easier testing.
|
||||
*/
|
||||
protected function setSaveHandler()
|
||||
{
|
||||
session_set_save_handler($this->driver, true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Starts the session.
|
||||
* Extracted for testing reasons.
|
||||
*/
|
||||
protected function startSession()
|
||||
{
|
||||
if (ENVIRONMENT === 'testing') {
|
||||
$_SESSION = [];
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
session_start(); // @codeCoverageIgnore
|
||||
}
|
||||
|
||||
/**
|
||||
* Takes care of setting the cookie on the client side.
|
||||
*
|
||||
* @codeCoverageIgnore
|
||||
*/
|
||||
protected function setCookie()
|
||||
{
|
||||
$expiration = $this->sessionExpiration === 0 ? 0 : time() + $this->sessionExpiration;
|
||||
$this->cookie = $this->cookie->withValue(session_id())->withExpires($expiration);
|
||||
|
||||
cookies([$this->cookie], false)->dispatch();
|
||||
}
|
||||
}
|
||||
184
system/Session/SessionInterface.php
Normal file
184
system/Session/SessionInterface.php
Normal file
@@ -0,0 +1,184 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* This file is part of CodeIgniter 4 framework.
|
||||
*
|
||||
* (c) CodeIgniter Foundation <admin@codeigniter.com>
|
||||
*
|
||||
* For the full copyright and license information, please view
|
||||
* the LICENSE file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace CodeIgniter\Session;
|
||||
|
||||
/**
|
||||
* Expected behavior of a session container used with CodeIgniter.
|
||||
*/
|
||||
interface SessionInterface
|
||||
{
|
||||
/**
|
||||
* Regenerates the session ID.
|
||||
*
|
||||
* @param bool $destroy Should old session data be destroyed?
|
||||
*/
|
||||
public function regenerate(bool $destroy = false);
|
||||
|
||||
/**
|
||||
* Destroys the current session.
|
||||
*/
|
||||
public function destroy();
|
||||
|
||||
/**
|
||||
* Sets user data into the session.
|
||||
*
|
||||
* If $data is a string, then it is interpreted as a session property
|
||||
* key, and $value is expected to be non-null.
|
||||
*
|
||||
* If $data is an array, it is expected to be an array of key/value pairs
|
||||
* to be set as session properties.
|
||||
*
|
||||
* @param array|string $data Property name or associative array of properties
|
||||
* @param mixed $value Property value if single key provided
|
||||
*/
|
||||
public function set($data, $value = null);
|
||||
|
||||
/**
|
||||
* Get user data that has been set in the session.
|
||||
*
|
||||
* If the property exists as "normal", returns it.
|
||||
* Otherwise, returns an array of any temp or flash data values with the
|
||||
* property key.
|
||||
*
|
||||
* Replaces the legacy method $session->userdata();
|
||||
*
|
||||
* @param string $key Identifier of the session property to retrieve
|
||||
*
|
||||
* @return mixed The property value(s)
|
||||
*/
|
||||
public function get(?string $key = null);
|
||||
|
||||
/**
|
||||
* Returns whether an index exists in the session array.
|
||||
*
|
||||
* @param string $key Identifier of the session property we are interested in.
|
||||
*/
|
||||
public function has(string $key): bool;
|
||||
|
||||
/**
|
||||
* Remove one or more session properties.
|
||||
*
|
||||
* If $key is an array, it is interpreted as an array of string property
|
||||
* identifiers to remove. Otherwise, it is interpreted as the identifier
|
||||
* of a specific session property to remove.
|
||||
*
|
||||
* @param array|string $key Identifier of the session property or properties to remove.
|
||||
*/
|
||||
public function remove($key);
|
||||
|
||||
/**
|
||||
* Sets data into the session that will only last for a single request.
|
||||
* Perfect for use with single-use status update messages.
|
||||
*
|
||||
* If $data is an array, it is interpreted as an associative array of
|
||||
* key/value pairs for flashdata properties.
|
||||
* Otherwise, it is interpreted as the identifier of a specific
|
||||
* flashdata property, with $value containing the property value.
|
||||
*
|
||||
* @param array|string $data Property identifier or associative array of properties
|
||||
* @param array|string $value Property value if $data is a scalar
|
||||
*/
|
||||
public function setFlashdata($data, $value = null);
|
||||
|
||||
/**
|
||||
* Retrieve one or more items of flash data from the session.
|
||||
*
|
||||
* If the item key is null, return all flashdata.
|
||||
*
|
||||
* @param string $key Property identifier
|
||||
*
|
||||
* @return array|null The requested property value, or an associative
|
||||
* array of them
|
||||
*/
|
||||
public function getFlashdata(?string $key = null);
|
||||
|
||||
/**
|
||||
* Keeps a single piece of flash data alive for one more request.
|
||||
*
|
||||
* @param array|string $key Property identifier or array of them
|
||||
*/
|
||||
public function keepFlashdata($key);
|
||||
|
||||
/**
|
||||
* Mark a session property or properties as flashdata.
|
||||
*
|
||||
* @param array|string $key Property identifier or array of them
|
||||
*
|
||||
* @return false if any of the properties are not already set
|
||||
*/
|
||||
public function markAsFlashdata($key);
|
||||
|
||||
/**
|
||||
* Unmark data in the session as flashdata.
|
||||
*
|
||||
* @param array|string $key Property identifier or array of them
|
||||
*/
|
||||
public function unmarkFlashdata($key);
|
||||
|
||||
/**
|
||||
* Retrieve all of the keys for session data marked as flashdata.
|
||||
*
|
||||
* @return array The property names of all flashdata
|
||||
*/
|
||||
public function getFlashKeys(): array;
|
||||
|
||||
/**
|
||||
* Sets new data into the session, and marks it as temporary data
|
||||
* with a set lifespan.
|
||||
*
|
||||
* @param array|string $data Session data key or associative array of items
|
||||
* @param mixed $value Value to store
|
||||
* @param int $ttl Time-to-live in seconds
|
||||
*/
|
||||
public function setTempdata($data, $value = null, int $ttl = 300);
|
||||
|
||||
/**
|
||||
* Returns either a single piece of tempdata, or all temp data currently
|
||||
* in the session.
|
||||
*
|
||||
* @param string $key Session data key
|
||||
*
|
||||
* @return mixed Session data value or null if not found.
|
||||
*/
|
||||
public function getTempdata(?string $key = null);
|
||||
|
||||
/**
|
||||
* Removes a single piece of temporary data from the session.
|
||||
*
|
||||
* @param string $key Session data key
|
||||
*/
|
||||
public function removeTempdata(string $key);
|
||||
|
||||
/**
|
||||
* Mark one of more pieces of data as being temporary, meaning that
|
||||
* it has a set lifespan within the session.
|
||||
*
|
||||
* @param array|string $key Property identifier or array of them
|
||||
* @param int $ttl Time to live, in seconds
|
||||
*
|
||||
* @return bool False if any of the properties were not set
|
||||
*/
|
||||
public function markAsTempdata($key, int $ttl = 300);
|
||||
|
||||
/**
|
||||
* Unmarks temporary data in the session, effectively removing its
|
||||
* lifespan and allowing it to live as long as the session does.
|
||||
*
|
||||
* @param array|string $key Property identifier or array of them
|
||||
*/
|
||||
public function unmarkTempdata($key);
|
||||
|
||||
/**
|
||||
* Retrieve the keys of all session data that have been marked as temporary data.
|
||||
*/
|
||||
public function getTempKeys(): array;
|
||||
}
|
||||
Reference in New Issue
Block a user