first commit

This commit is contained in:
CHIEFSOFT\ameye
2025-01-18 18:33:45 -05:00
commit e8d16deefd
684 changed files with 120708 additions and 0 deletions
@@ -0,0 +1,54 @@
<?php
declare(strict_types=1);
/**
* 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]));
}
}
+93
View File
@@ -0,0 +1,93 @@
<?php
declare(strict_types=1);
/**
* 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;
}
}
+177
View File
@@ -0,0 +1,177 @@
<?php
declare(strict_types=1);
/**
* 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\Cookie as CookieConfig;
use Config\Session as SessionConfig;
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 bool|string
*/
protected $lock = false;
/**
* Cookie prefix
*
* The Config\Cookie::$prefix setting is completely ignored.
* See https://codeigniter.com/user_guide/libraries/sessions.html#session-preferences
*
* @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|null
*/
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(SessionConfig $config, string $ipAddress)
{
// Store Session configurations
$this->cookieName = $config->cookieName;
$this->matchIP = $config->matchIP;
$this->savePath = $config->savePath;
$cookie = config(CookieConfig::class);
// Session cookies have no prefix.
$this->cookieDomain = $cookie->domain;
$this->cookiePath = $cookie->path;
$this->cookieSecure = $cookie->secure;
$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;
}
}
@@ -0,0 +1,57 @@
<?php
declare(strict_types=1);
/**
* 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\Database;
use CodeIgniter\Session\Handlers\DatabaseHandler;
/**
* Session handler for MySQLi
*
* @see \CodeIgniter\Session\Handlers\Database\MySQLiHandlerTest
*/
class MySQLiHandler extends DatabaseHandler
{
/**
* Lock the session.
*/
protected function lockSession(string $sessionID): bool
{
$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();
}
/**
* Releases the lock, if any.
*/
protected function releaseLock(): bool
{
if (! $this->lock) {
return true;
}
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();
}
}
@@ -0,0 +1,104 @@
<?php
declare(strict_types=1);
/**
* 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\Database;
use CodeIgniter\Database\BaseBuilder;
use CodeIgniter\Session\Handlers\DatabaseHandler;
use ReturnTypeWillChange;
/**
* Session handler for Postgre
*
* @see \CodeIgniter\Session\Handlers\Database\PostgreHandlerTest
*/
class PostgreHandler extends DatabaseHandler
{
/**
* Sets SELECT clause
*/
protected function setSelect(BaseBuilder $builder)
{
$builder->select("encode(data, 'base64') AS data");
}
/**
* Decodes column data
*
* @param string $data
*
* @return false|string
*/
protected function decodeData($data)
{
return base64_decode(rtrim($data), true);
}
/**
* Prepare data to insert/update
*/
protected function prepareData(string $data): string
{
return '\x' . bin2hex($data);
}
/**
* 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 = '\'';
$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
{
$arg = "hashtext('{$sessionID}')" . ($this->matchIP ? ", hashtext('{$this->ipAddress}')" : '');
if ($this->db->simpleQuery("SELECT pg_advisory_lock({$arg})") !== false) {
$this->lock = $arg;
return true;
}
return $this->fail();
}
/**
* Releases the lock, if any.
*/
protected function releaseLock(): bool
{
if (! $this->lock) {
return true;
}
if ($this->db->simpleQuery("SELECT pg_advisory_unlock({$this->lock})") !== false) {
$this->lock = false;
return true;
}
return $this->fail();
}
}
+304
View File
@@ -0,0 +1,304 @@
<?php
declare(strict_types=1);
/**
* 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\BaseBuilder;
use CodeIgniter\Database\BaseConnection;
use CodeIgniter\Session\Exceptions\SessionException;
use Config\Database;
use Config\Session as SessionConfig;
use ReturnTypeWillChange;
/**
* Base database session handler
*
* Do not use this class. Use database specific handler class.
*/
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
*
* @var string
*/
protected $platform;
/**
* Row exists flag
*
* @var bool
*/
protected $rowExists = false;
/**
* ID prefix for multiple session cookies
*/
protected string $idPrefix;
/**
* @throws SessionException
*/
public function __construct(SessionConfig $config, string $ipAddress)
{
parent::__construct($config, $ipAddress);
// Store Session configurations
$this->DBGroup = $config->DBGroup ?? config(Database::class)->defaultGroup;
// Add sessionCookieName for multiple session cookies.
$this->idPrefix = $config->cookieName . ':';
$this->table = $this->savePath;
if (empty($this->table)) {
throw SessionException::forMissingDatabaseTable();
}
$this->db = Database::connect($this->DBGroup);
$this->platform = $this->db->getPlatform();
}
/**
* 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)->where('id', $this->idPrefix . $id);
if ($this->matchIP) {
$builder = $builder->where('ip_address', $this->ipAddress);
}
$this->setSelect($builder);
$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 '';
}
$result = is_bool($result) ? '' : $this->decodeData($result->data);
$this->fingerprint = md5($result);
$this->rowExists = true;
return $result;
}
/**
* Sets SELECT clause
*/
protected function setSelect(BaseBuilder $builder)
{
$builder->select('data');
}
/**
* Decodes column data
*
* @param string $data
*
* @return false|string
*/
protected function decodeData($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 ($this->lock === false) {
return $this->fail();
}
if ($this->sessionID !== $id) {
$this->rowExists = false;
$this->sessionID = $id;
}
if ($this->rowExists === false) {
$insertData = [
'id' => $this->idPrefix . $id,
'ip_address' => $this->ipAddress,
'data' => $this->prepareData($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', $this->idPrefix . $id);
if ($this->matchIP) {
$builder = $builder->where('ip_address', $this->ipAddress);
}
$updateData = [];
if ($this->fingerprint !== md5($data)) {
$updateData['data'] = $this->prepareData($data);
}
if (! $builder->set('timestamp', 'now()', false)->update($updateData)) {
return $this->fail();
}
$this->fingerprint = md5($data);
return true;
}
/**
* Prepare data to insert/update
*/
protected function prepareData(string $data): string
{
return $data;
}
/**
* 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', $this->idPrefix . $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)
{
return $this->db->table($this->table)->where(
'timestamp <',
"now() - INTERVAL {$max_lifetime} second",
false
)->delete() ? 1 : $this->fail();
}
/**
* Releases the lock, if any.
*/
protected function releaseLock(): bool
{
if (! $this->lock) {
return true;
}
// Unsupported DB? Let the parent handle the simple version.
return parent::releaseLock();
}
}
+340
View File
@@ -0,0 +1,340 @@
<?php
declare(strict_types=1);
/**
* 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\I18n\Time;
use CodeIgniter\Session\Exceptions\SessionException;
use Config\Session as SessionConfig;
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(SessionConfig $config, string $ipAddress)
{
parent::__construct($config, $ipAddress);
if (! empty($this->savePath)) {
$this->savePath = rtrim($this->savePath, '/\\');
ini_set('session.save_path', $this->savePath);
} else {
$sessionPath = rtrim(ini_get('session.save_path'), '/\\');
if ($sessionPath === '') {
$sessionPath = WRITEPATH . 'session';
}
$this->savePath = $sessionPath;
}
$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::now()->getTimestamp() - $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) !== 1
|| ! 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 . '}';
}
}
@@ -0,0 +1,324 @@
<?php
declare(strict_types=1);
/**
* 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\I18n\Time;
use CodeIgniter\Session\Exceptions\SessionException;
use Config\Session as SessionConfig;
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(SessionConfig $config, string $ipAddress)
{
parent::__construct($config, $ipAddress);
$this->sessionExpiration = $config->expiration;
if (empty($this->savePath)) {
throw SessionException::forEmptySavepath();
}
// Add sessionCookieName for multiple session cookies.
$this->keyPrefix .= $config->cookieName . ':';
if ($this->matchIP === true) {
$this->keyPrefix .= $this->ipAddress . ':';
}
ini_set('memcached.sess_prefix', $this->keyPrefix);
}
/**
* 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
) === 0
) {
$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], (int) $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 ($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::now()->getTimestamp(), 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::now()->getTimestamp(), 300);
}
$lockKey = $this->keyPrefix . $sessionID . ':lock';
$attempt = 0;
do {
if ($this->memcached->get($lockKey) !== false) {
sleep(1);
continue;
}
if (! $this->memcached->set($lockKey, Time::now()->getTimestamp(), 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;
}
}
+419
View File
@@ -0,0 +1,419 @@
<?php
declare(strict_types=1);
/**
* 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\I18n\Time;
use CodeIgniter\Session\Exceptions\SessionException;
use Config\Session as SessionConfig;
use Redis;
use RedisException;
use ReturnTypeWillChange;
/**
* Session handler using Redis for persistence
*/
class RedisHandler extends BaseHandler
{
private const DEFAULT_PORT = 6379;
private const DEFAULT_PROTOCOL = 'tcp';
/**
* 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;
/**
* Time (microseconds) to wait if lock cannot be acquired.
*/
private int $lockRetryInterval = 100_000;
/**
* Maximum number of lock acquisition attempts.
*/
private int $lockMaxRetries = 300;
/**
* @param string $ipAddress User's IP address
*
* @throws SessionException
*/
public function __construct(SessionConfig $config, string $ipAddress)
{
parent::__construct($config, $ipAddress);
// Store Session configurations
$this->sessionExpiration = ($config->expiration === 0)
? (int) ini_get('session.gc_maxlifetime')
: $config->expiration;
// Add sessionCookieName for multiple session cookies.
$this->keyPrefix .= $config->cookieName . ':';
$this->setSavePath();
if ($this->matchIP === true) {
$this->keyPrefix .= $this->ipAddress . ':';
}
$this->lockRetryInterval = $config->lockWait ?? $this->lockRetryInterval;
$this->lockMaxRetries = $config->lockAttempts ?? $this->lockMaxRetries;
}
protected function setSavePath(): void
{
if (empty($this->savePath)) {
throw SessionException::forEmptySavepath();
}
$url = parse_url($this->savePath);
$query = [];
if ($url === false) {
// Unix domain socket like `unix:///var/run/redis/redis.sock?persistent=1`.
if (preg_match('#unix://(/[^:?]+)(\?.+)?#', $this->savePath, $matches)) {
$host = $matches[1];
$port = 0;
if (isset($matches[2])) {
parse_str(ltrim($matches[2], '?'), $query);
}
} else {
throw SessionException::forInvalidSavePathFormat($this->savePath);
}
} else {
// Also accepts `/var/run/redis.sock` for backward compatibility.
if (isset($url['path']) && $url['path'][0] === '/') {
$host = $url['path'];
$port = 0;
} else {
// TCP connection.
if (! isset($url['host'])) {
throw SessionException::forInvalidSavePathFormat($this->savePath);
}
$protocol = $url['scheme'] ?? self::DEFAULT_PROTOCOL;
$host = $protocol . '://' . $url['host'];
$port = $url['port'] ?? self::DEFAULT_PORT;
}
if (isset($url['query'])) {
parse_str($url['query'], $query);
}
}
$password = $query['auth'] ?? null;
$database = isset($query['database']) ? (int) $query['database'] : 0;
$timeout = isset($query['timeout']) ? (float) $query['timeout'] : 0.0;
$prefix = $query['prefix'] ?? null;
$this->savePath = [
'host' => $host,
'port' => $port,
'password' => $password,
'database' => $database,
'timeout' => $timeout,
];
if ($prefix !== null) {
$this->keyPrefix = $prefix;
}
}
/**
* 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 RedisException
*/
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.
*
* @throws RedisException
*/
#[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 false;
}
/**
* Writes the session data to the session storage.
*
* @param string $id The session ID
* @param string $data The encoded session data
*
* @throws RedisException
*/
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->releaseLock()) {
return false;
}
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
*
* @throws RedisException
*/
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
*
* @throws RedisException
*/
protected function lockSession(string $sessionID): bool
{
$lockKey = $this->keyPrefix . $sessionID . ':lock';
// 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 === $lockKey) {
// If there is the lock, make the ttl longer.
return $this->redis->expire($this->lockKey, 300);
}
$attempt = 0;
do {
$result = $this->redis->set(
$lockKey,
(string) Time::now()->getTimestamp(),
// NX -- Only set the key if it does not already exist.
// EX seconds -- Set the specified expire time, in seconds.
['nx', 'ex' => 300]
);
if (! $result) {
usleep($this->lockRetryInterval);
continue;
}
$this->lockKey = $lockKey;
break;
} while (++$attempt < $this->lockMaxRetries);
if ($attempt === 300) {
$this->logger->error(
'Session: Unable to obtain lock for ' . $this->keyPrefix . $sessionID
. ' after 300 attempts, aborting.'
);
return false;
}
$this->lock = true;
return true;
}
/**
* Releases a previously acquired lock
*
* @throws RedisException
*/
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;
}
}
+936
View File
@@ -0,0 +1,936 @@
<?php
declare(strict_types=1);
/**
* 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 CodeIgniter\I18n\Time;
use Config\Cookie as CookieConfig;
use Config\Session as SessionConfig;
use Psr\Log\LoggerAwareTrait;
use SessionHandlerInterface;
/**
* Implementation of CodeIgniter session container.
*
* Session configuration is done through session variables and cookie related
* variables in app/config/App.php
*
* @property string $session_id
* @see \CodeIgniter\Session\SessionTest
*/
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
*
* @deprecated Use $this->config->driver.
*/
protected $sessionDriverName;
/**
* The session cookie name, must contain only [0-9a-z_-] characters.
*
* @var string
*
* @deprecated Use $this->config->cookieName.
*/
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
*
* @deprecated Use $this->config->expiration.
*/
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
*
* @deprecated Use $this->config->savePath.
*/
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
*
* @deprecated Use $this->config->matchIP.
*/
protected $sessionMatchIP = false;
/**
* How many seconds between CI regenerating the session ID.
*
* @var int
*
* @deprecated Use $this->config->timeToUpdate.
*/
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
*
* @deprecated Use $this->config->regenerateDestroy.
*/
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 No longer used.
*/
protected $cookieDomain = '';
/**
* Path used for storing cookies.
* Typically will be a forward slash.
*
* @var string
*
* @deprecated No longer used.
*/
protected $cookiePath = '/';
/**
* Cookie will only be set if a secure HTTPS connection exists.
*
* @var bool
*
* @deprecated No longer used.
*/
protected $cookieSecure = false;
/**
* Cookie SameSite setting as described in RFC6265
* Must be 'None', 'Lax' or 'Strict'.
*
* @var string
*
* @deprecated No longer used.
*/
protected $cookieSameSite = Cookie::SAMESITE_LAX;
/**
* sid regex expression
*
* @var string
*/
protected $sidRegexp;
/**
* Session Config
*/
protected SessionConfig $config;
/**
* Constructor.
*
* Extract configuration settings and save them here.
*/
public function __construct(SessionHandlerInterface $driver, SessionConfig $config)
{
$this->driver = $driver;
$this->config = $config;
$cookie = config(CookieConfig::class);
$this->cookie = (new Cookie($this->config->cookieName, '', [
'expires' => $this->config->expiration === 0 ? 0 : Time::now()->getTimestamp() + $this->config->expiration,
'path' => $cookie->path,
'domain' => $cookie->domain,
'secure' => $cookie->secure,
'httponly' => true, // for security
'samesite' => $cookie->samesite ?? Cookie::SAMESITE_LAX,
'raw' => $cookie->raw ?? false,
]))->withPrefix(''); // Cookie prefix should be ignored.
helper('array');
}
/**
* Initialize the session container and starts up the session.
*
* @return $this|void
*/
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->config->cookieName])
&& (! is_string($_COOKIE[$this->config->cookieName]) || preg_match('#\A' . $this->sidRegexp . '\z#', $_COOKIE[$this->config->cookieName]) !== 1)
) {
unset($_COOKIE[$this->config->cookieName]);
}
$this->startSession();
// Is session ID auto-regeneration configured? (ignoring ajax requests)
if ((! isset($_SERVER['HTTP_X_REQUESTED_WITH']) || strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) !== 'xmlhttprequest')
&& ($regenerateTime = $this->config->timeToUpdate) > 0
) {
if (! isset($_SESSION['__ci_last_regenerate'])) {
$_SESSION['__ci_last_regenerate'] = Time::now()->getTimestamp();
} elseif ($_SESSION['__ci_last_regenerate'] < (Time::now()->getTimestamp() - $regenerateTime)) {
$this->regenerate($this->config->regenerateDestroy);
}
}
// 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->cookieName]) && $_COOKIE[$this->config->cookieName] === session_id()) {
$this->setCookie();
}
$this->initVars();
$this->logger->debug("Session: Class initialized using '" . $this->config->driver . "' driver.");
return $this;
}
/**
* Destroys the current session.
*
* @deprecated Use destroy() instead.
*/
public function stop()
{
$this->destroy();
}
/**
* Configuration.
*
* Handle input binds and configuration defaults.
*/
protected function configure()
{
ini_set('session.name', $this->config->cookieName);
$sameSite = $this->cookie->getSameSite() ?: ucfirst(Cookie::SAMESITE_LAX);
$params = [
'lifetime' => $this->config->expiration,
'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 ($this->config->expiration > 0) {
ini_set('session.gc_maxlifetime', (string) $this->config->expiration);
}
if ($this->config->savePath !== '') {
ini_set('session.save_path', $this->config->savePath);
}
// 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 (! isset($_SESSION['__ci_vars'])) {
return;
}
$currentTime = Time::now()->getTimestamp();
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 ($_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::now()->getTimestamp();
session_regenerate_id($destroy);
$this->removeOldSessionCookie();
}
private function removeOldSessionCookie(): void
{
$response = service('response');
$cookieStoreInResponse = $response->getCookieStore();
if (! $cookieStoreInResponse->has($this->config->cookieName)) {
return;
}
// CookieStore is immutable.
$newCookieStore = $cookieStoreInResponse->remove($this->config->cookieName);
// But clear() method clears cookies in the object (not immutable).
$cookieStoreInResponse->clear();
foreach ($newCookieStore as $cookie) {
$response->setCookie($cookie);
}
}
/**
* Destroys the current session.
*/
public function destroy()
{
if (ENVIRONMENT === 'testing') {
return;
}
session_destroy();
}
/**
* Writes session data and close the current session.
*
* @return void
*/
public function close()
{
if (ENVIRONMENT === 'testing') {
return;
}
session_write_close();
}
/**
* 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 array|bool|float|int|object|string|null $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 non-empty-string|null $key Identifier of the session property to retrieve
*
* @return array|bool|float|int|object|string|null The property value(s)
*/
public function get(?string $key = null)
{
if ($key !== null && $key !== '' && (null !== ($value = $_SESSION[$key] ?? null) || null !== ($value = dot_array_search($key, $_SESSION ?? [])))) {
return $value;
}
if (! isset($_SESSION) || $_SESSION === []) {
return $key === null ? [] : null;
}
if ($key !== null && $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|bool|float|int|object|string|null $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 (isset($_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 array|string $key Property identifier or array of them
*/
public function unmarkFlashdata($key)
{
if (! isset($_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 ($_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 array|bool|float|int|object|string|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 array|bool|float|int|object|string|null 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 (isset($_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::now()->getTimestamp();
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::now()->getTimestamp() + $ttl;
} else {
$v += Time::now()->getTimestamp();
}
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 (! isset($_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 ($_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->config->expiration === 0 ? 0 : Time::now()->getTimestamp() + $this->config->expiration;
$this->cookie = $this->cookie->withValue(session_id())->withExpires($expiration);
$response = service('response');
$response->setCookie($this->cookie);
}
}
+186
View File
@@ -0,0 +1,186 @@
<?php
declare(strict_types=1);
/**
* 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 array|bool|float|int|object|string|null $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 non-empty-string|null $key Identifier of the session property to retrieve
*
* @return array|bool|float|int|object|string|null 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 array|bool|float|int|object|string|null $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 array|bool|float|int|object|string|null 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;
}