Update to Kirby 4.7.0

This commit is contained in:
Paul Nicoué 2025-04-21 18:57:21 +02:00
parent 02a9ab387c
commit ba25a9a198
509 changed files with 26604 additions and 14872 deletions

View file

@ -13,10 +13,10 @@ namespace Kirby\Session;
*/
class AutoSession
{
protected $sessions;
protected $options;
protected Sessions $sessions;
protected array $options;
protected $createdSession;
protected Session $createdSession;
/**
* Creates a new AutoSession instance
@ -29,8 +29,10 @@ class AutoSession
* - `cookieName`: Name to use for the session cookie; defaults to `kirby_session`
* - `gcInterval`: How often should the garbage collector be run?; integer or `false` for never; defaults to `100`
*/
public function __construct($store, array $options = [])
{
public function __construct(
SessionStore|string $store,
array $options = []
) {
// merge options with defaults
$this->options = array_merge([
'durationNormal' => 7200,
@ -54,9 +56,8 @@ class AutoSession
* - `detect`: Whether to allow sessions in the `Authorization` HTTP header (`true`) or only in the session cookie (`false`); defaults to `false`
* - `createMode`: When creating a new session, should it be set as a cookie or is it going to be transmitted manually to be used in a header?; defaults to `cookie`
* - `long`: Whether the session is a long "remember me" session or a normal session; defaults to `false`
* @return \Kirby\Session\Session
*/
public function get(array $options = [])
public function get(array $options = []): Session
{
// merge options with defaults
$options = array_merge([
@ -90,7 +91,8 @@ class AutoSession
'renewable' => true,
]);
// cache the newly created session to ensure that we don't create multiple
// cache the newly created session to ensure
// that we don't create multiple
$this->createdSession = $session;
}
@ -132,9 +134,8 @@ class AutoSession
* - `expiryTime`: Time the session expires (date string or timestamp); defaults to `+ 2 hours`
* - `timeout`: Activity timeout in seconds (integer or false for none); defaults to `1800` (half an hour)
* - `renewable`: Should it be possible to extend the expiry date?; defaults to `true`
* @return \Kirby\Session\Session
*/
public function createManually(array $options = [])
public function createManually(array $options = []): Session
{
// only ever allow manual transmission mode
// to prevent overwriting our "auto" session
@ -148,9 +149,8 @@ class AutoSession
* @since 3.3.1
*
* @param string $token Session token, either including or without the key
* @return \Kirby\Session\Session
*/
public function getManually(string $token)
public function getManually(string $token): Session
{
return $this->sessions->get($token, 'manual');
}
@ -160,10 +160,8 @@ class AutoSession
*
* If the `gcInterval` is configured, this is done automatically
* when initializing the AutoSession class
*
* @return void
*/
public function collectGarbage()
public function collectGarbage(): void
{
$this->sessions->collectGarbage();
}

View file

@ -19,11 +19,11 @@ use Kirby\Toolkit\Str;
*/
class FileSessionStore extends SessionStore
{
protected $path;
protected string $path;
// state of the session files
protected $handles = [];
protected $isLocked = [];
protected array $handles = [];
protected array $isLocked = [];
/**
* Creates a new instance of the file session store
@ -39,7 +39,7 @@ class FileSessionStore extends SessionStore
$this->path = realpath($path);
// make sure it is usable for storage
if (!is_writable($this->path)) {
if (is_writable($this->path) === false) {
throw new Exception([
'key' => 'session.filestore.dirNotWritable',
'data' => ['path' => $this->path],
@ -64,8 +64,7 @@ class FileSessionStore extends SessionStore
clearstatcache();
do {
// use helper from the abstract SessionStore class
$id = static::generateId();
$id = static::generateId();
$name = $this->name($expiryTime, $id);
$path = $this->path($name);
} while (file_exists($path));
@ -111,14 +110,13 @@ class FileSessionStore extends SessionStore
*
* @param int $expiryTime Timestamp
* @param string $id Session ID
* @return void
*/
public function lock(int $expiryTime, string $id)
public function lock(int $expiryTime, string $id): void
{
$name = $this->name($expiryTime, $id);
// check if the file is already locked
if (isset($this->isLocked[$name])) {
if (isset($this->isLocked[$name]) === true) {
return;
}
@ -126,19 +124,19 @@ class FileSessionStore extends SessionStore
$handle = $this->handle($name);
$result = flock($handle, LOCK_EX);
// make a note that the file is now locked
if ($result === true) {
$this->isLocked[$name] = true;
} else {
// @codeCoverageIgnoreStart
// @codeCoverageIgnoreStart
if ($result !== true) {
throw new Exception([
'key' => 'session.filestore.unexpectedFilesystemError',
'fallback' => 'Unexpected file system error',
'translate' => false,
'httpCode' => 500
]);
// @codeCoverageIgnoreEnd
}
// @codeCoverageIgnoreEnd
// make a note that the file is now locked
$this->isLocked[$name] = true;
}
/**
@ -148,14 +146,13 @@ class FileSessionStore extends SessionStore
*
* @param int $expiryTime Timestamp
* @param string $id Session ID
* @return void
*/
public function unlock(int $expiryTime, string $id)
public function unlock(int $expiryTime, string $id): void
{
$name = $this->name($expiryTime, $id);
// check if the file is already unlocked or doesn't exist
if (!isset($this->isLocked[$name])) {
if (isset($this->isLocked[$name]) === false) {
return;
}
@ -168,19 +165,19 @@ class FileSessionStore extends SessionStore
$handle = $this->handle($name);
$result = flock($handle, LOCK_UN);
// make a note that the file is no longer locked
if ($result === true) {
unset($this->isLocked[$name]);
} else {
// @codeCoverageIgnoreStart
// @codeCoverageIgnoreStart
if ($result !== true) {
throw new Exception([
'key' => 'session.filestore.unexpectedFilesystemError',
'fallback' => 'Unexpected file system error',
'translate' => false,
'httpCode' => 500
]);
// @codeCoverageIgnoreEnd
}
// @codeCoverageIgnoreEnd
// make a note that the file is no longer locked
unset($this->isLocked[$name]);
}
/**
@ -190,7 +187,6 @@ class FileSessionStore extends SessionStore
*
* @param int $expiryTime Timestamp
* @param string $id Session ID
* @return string
*/
public function get(int $expiryTime, string $id): string
{
@ -200,7 +196,7 @@ class FileSessionStore extends SessionStore
// set read lock to prevent other threads from corrupting the data while we read it
// only if we don't already have a write lock, which is even better
if (!isset($this->isLocked[$name])) {
if (isset($this->isLocked[$name]) === false) {
$result = flock($handle, LOCK_SH);
if ($result !== true) {
@ -227,7 +223,7 @@ class FileSessionStore extends SessionStore
}
// remove the shared lock if we set one above
if (!isset($this->isLocked[$name])) {
if (isset($this->isLocked[$name]) === false) {
$result = flock($handle, LOCK_UN);
if ($result !== true) {
@ -254,15 +250,14 @@ class FileSessionStore extends SessionStore
* @param int $expiryTime Timestamp
* @param string $id Session ID
* @param string $data Session data to write
* @return void
*/
public function set(int $expiryTime, string $id, string $data)
public function set(int $expiryTime, string $id, string $data): void
{
$name = $this->name($expiryTime, $id);
$handle = $this->handle($name);
// validate that we have an exclusive lock already
if (!isset($this->isLocked[$name])) {
if (isset($this->isLocked[$name]) === false) {
throw new LogicException([
'key' => 'session.filestore.notLocked',
'data' => ['name' => $name],
@ -286,7 +281,7 @@ class FileSessionStore extends SessionStore
// write the new contents
$result = fwrite($handle, $data);
if (!is_int($result) || $result === 0) {
if (is_int($result) === false || $result === 0) {
// @codeCoverageIgnoreStart
throw new Exception([
'key' => 'session.filestore.unexpectedFilesystemError',
@ -305,9 +300,8 @@ class FileSessionStore extends SessionStore
*
* @param int $expiryTime Timestamp
* @param string $id Session ID
* @return void
*/
public function destroy(int $expiryTime, string $id)
public function destroy(int $expiryTime, string $id): void
{
$name = $this->name($expiryTime, $id);
$path = $this->path($name);
@ -341,10 +335,8 @@ class FileSessionStore extends SessionStore
* Deletes all expired sessions
*
* Needs to throw an Exception on error.
*
* @return void
*/
public function collectGarbage()
public function collectGarbage(): void
{
$iterator = new FilesystemIterator($this->path);
@ -394,7 +386,6 @@ class FileSessionStore extends SessionStore
*
* @param int $expiryTime Timestamp
* @param string $id Session ID
* @return string
*/
protected function name(int $expiryTime, string $id): string
{
@ -405,7 +396,6 @@ class FileSessionStore extends SessionStore
* Returns the full path to the session file
*
* @param string $name Combined name
* @return string
*/
protected function path(string $name): string
{
@ -424,7 +414,7 @@ class FileSessionStore extends SessionStore
// ensures thread-safeness for recently deleted sessions, see $this->destroy()
$path = $this->path($name);
clearstatcache();
if (!is_file($path)) {
if (is_file($path) === false) {
throw new NotFoundException([
'key' => 'session.filestore.notFound',
'data' => ['name' => $name],
@ -435,13 +425,13 @@ class FileSessionStore extends SessionStore
}
// return from cache
if (isset($this->handles[$name])) {
if (isset($this->handles[$name]) === true) {
return $this->handles[$name];
}
// open a new handle
$handle = @fopen($path, 'r+b');
if (!is_resource($handle)) {
if (is_resource($handle) === false) {
throw new Exception([
'key' => 'session.filestore.notOpened',
'data' => ['name' => $name],
@ -458,11 +448,10 @@ class FileSessionStore extends SessionStore
* Closes an open file handle
*
* @param string $name Combined name
* @return void
*/
protected function closeHandle(string $name)
protected function closeHandle(string $name): void
{
if (!isset($this->handles[$name])) {
if (isset($this->handles[$name]) === false) {
return;
}
$handle = $this->handles[$name];

View file

@ -11,7 +11,6 @@ use Kirby\Http\Cookie;
use Kirby\Http\Url;
use Kirby\Toolkit\Str;
use Kirby\Toolkit\SymmetricCrypto;
use Throwable;
/**
* @package Kirby Session
@ -23,29 +22,29 @@ use Throwable;
class Session
{
// parent data
protected $sessions;
protected $mode;
protected Sessions $sessions;
protected string $mode;
// parts of the token
protected $tokenExpiry;
protected $tokenId;
protected $tokenKey;
protected int|null $tokenExpiry = null;
protected string|null $tokenId = null;
protected string|null $tokenKey = null;
// persistent data
protected $startTime;
protected $expiryTime;
protected $duration;
protected $timeout;
protected $lastActivity;
protected $renewable;
protected $data;
protected array|null $newSession;
protected int $startTime;
protected int $expiryTime;
protected int $duration;
protected int|false $timeout = false;
protected int|null $lastActivity = null;
protected bool $renewable;
protected SessionData $data;
protected array|null $newSession = null;
// temporary state flags
protected $updatingLastActivity = false;
protected $destroyed = false;
protected $writeMode = false;
protected $needsRetransmission = false;
protected bool $updatingLastActivity = false;
protected bool $destroyed = false;
protected bool $writeMode = false;
protected bool $needsRetransmission = false;
/**
* Creates a new Session instance
@ -59,12 +58,18 @@ class Session
* - `timeout`: Activity timeout in seconds (integer or false for none); defaults to `1800` (half an hour)
* - `renewable`: Should it be possible to extend the expiry date?; defaults to `true`
*/
public function __construct(Sessions $sessions, $token, array $options)
{
public function __construct(
Sessions $sessions,
string|null $token,
array $options
) {
$this->sessions = $sessions;
$this->mode = $options['mode'] ?? 'cookie';
if (is_string($token)) {
// ensure that all changes are committed on script termination
register_shutdown_function([$this, 'commit']);
if (is_string($token) === true) {
// existing session
// set the token as instance vars
@ -73,76 +78,65 @@ class Session
// initialize, but only try to write to the session if not read-only
// (only the case for moved sessions)
$this->init();
if ($this->tokenKey !== null) {
$this->autoRenew();
}
} elseif ($token === null) {
// new session
// set data based on options
$this->startTime = static::timeToTimestamp($options['startTime'] ?? time());
$this->expiryTime = static::timeToTimestamp($options['expiryTime'] ?? '+ 2 hours', $this->startTime);
$this->duration = $this->expiryTime - $this->startTime;
$this->timeout = $options['timeout'] ?? 1800;
$this->renewable = $options['renewable'] ?? true;
$this->data = new SessionData($this, []);
return;
}
// validate persistent data
if (time() > $this->expiryTime) {
// session must not already be expired, but the start time may be in the future
throw new InvalidArgumentException([
'data' => ['method' => 'Session::__construct', 'argument' => '$options[\'expiryTime\']'],
'translate' => false
]);
}
if ($this->duration < 0) {
// expiry time must be after start time
throw new InvalidArgumentException([
'data' => ['method' => 'Session::__construct', 'argument' => '$options[\'startTime\' & \'expiryTime\']'],
'translate' => false
]);
}
if (!is_int($this->timeout) && $this->timeout !== false) {
throw new InvalidArgumentException([
'data' => ['method' => 'Session::__construct', 'argument' => '$options[\'timeout\']'],
'translate' => false
]);
}
if (!is_bool($this->renewable)) {
throw new InvalidArgumentException([
'data' => ['method' => 'Session::__construct', 'argument' => '$options[\'renewable\']'],
'translate' => false
]);
}
// new session ($token = null)
// set activity time if a timeout was requested
if (is_int($this->timeout)) {
$this->lastActivity = time();
}
} else {
// set data based on options
$this->startTime = static::timeToTimestamp($options['startTime'] ?? time());
$this->expiryTime = static::timeToTimestamp($options['expiryTime'] ?? '+ 2 hours', $this->startTime);
$this->duration = $this->expiryTime - $this->startTime;
$this->timeout = $options['timeout'] ?? 1800;
$this->renewable = $options['renewable'] ?? true;
$this->data = new SessionData($this, []);
// validate persistent data
if (time() > $this->expiryTime) {
// session must not already be expired, but the start time may be in the future
throw new InvalidArgumentException([
'data' => ['method' => 'Session::__construct', 'argument' => '$token'],
'data' => [
'method' => 'Session::__construct',
'argument' => '$options[\'expiryTime\']'
],
'translate' => false
]);
}
if ($this->duration < 0) {
// expiry time must be after start time
throw new InvalidArgumentException([
'data' => [
'method' => 'Session::__construct',
'argument' => '$options[\'startTime\' & \'expiryTime\']'
],
'translate' => false
]);
}
// ensure that all changes are committed on script termination
register_shutdown_function([$this, 'commit']);
// set activity time if a timeout was requested
if (is_int($this->timeout) === true) {
$this->lastActivity = time();
}
}
/**
* Gets the session token or null if the session doesn't have a token yet
*
* @return string|null
*/
public function token()
public function token(): string|null
{
if ($this->tokenExpiry !== null) {
if (is_string($this->tokenKey)) {
return $this->tokenExpiry . '.' . $this->tokenId . '.' . $this->tokenKey;
$token = $this->tokenExpiry . '.' . $this->tokenId;
if (is_string($this->tokenKey) === true) {
$token .= '.' . $this->tokenKey;
}
return $this->tokenExpiry . '.' . $this->tokenId;
return $token;
}
return null;
@ -152,12 +146,12 @@ class Session
* Gets or sets the transmission mode
* Setting only works for new sessions that haven't been transmitted yet
*
* @param string $mode Optional new transmission mode
* @param string|null $mode Optional new transmission mode
* @return string Transmission mode
*/
public function mode(string $mode = null)
public function mode(string|null $mode = null): string
{
if (is_string($mode)) {
if ($mode !== null) {
// only allow this if this is a new session, otherwise the change
// might not be applied correctly to the current request
if ($this->token() !== null) {
@ -187,12 +181,12 @@ class Session
* Gets or sets the session expiry time
* Setting the expiry time also updates the duration and regenerates the session token
*
* @param string|int $expiryTime Optional new expiry timestamp or time string to set
* @param string|int|null $expiryTime Optional new expiry timestamp or time string to set
* @return int Timestamp
*/
public function expiryTime($expiryTime = null): int
public function expiryTime(string|int|null $expiryTime = null): int
{
if (is_string($expiryTime) || is_int($expiryTime)) {
if ($expiryTime !== null) {
// convert to a timestamp
$expiryTime = static::timeToTimestamp($expiryTime);
@ -208,11 +202,6 @@ class Session
$this->expiryTime = $expiryTime;
$this->duration = $expiryTime - time();
$this->regenerateTokenIfNotNew();
} elseif ($expiryTime !== null) {
throw new InvalidArgumentException([
'data' => ['method' => 'Session::expiryTime', 'argument' => '$expiryTime'],
'translate' => false
]);
}
return $this->expiryTime;
@ -222,12 +211,12 @@ class Session
* Gets or sets the session duration
* Setting the duration also updates the expiry time and regenerates the session token
*
* @param int $duration Optional new duration in seconds to set
* @param int|null $duration Optional new duration in seconds to set
* @return int Number of seconds
*/
public function duration(int $duration = null): int
public function duration(int|null $duration = null): int
{
if (is_int($duration)) {
if ($duration !== null) {
// verify that the duration is at least 1 second
if ($duration < 1) {
throw new InvalidArgumentException([
@ -248,14 +237,14 @@ class Session
/**
* Gets or sets the session timeout
*
* @param int|false $timeout Optional new timeout to set or false to disable timeout
* @param int|false|null $timeout Optional new timeout to set or false to disable timeout
* @return int|false Number of seconds or false for "no timeout"
*/
public function timeout($timeout = null)
public function timeout(int|false|null $timeout = null): int|false
{
if (is_int($timeout) || $timeout === false) {
if ($timeout !== null) {
// verify that the timeout is at least 1 second
if (is_int($timeout) && $timeout < 1) {
if (is_int($timeout) === true && $timeout < 1) {
throw new InvalidArgumentException([
'data' => ['method' => 'Session::timeout', 'argument' => '$timeout'],
'translate' => false
@ -263,18 +252,8 @@ class Session
}
$this->prepareForWriting();
$this->timeout = $timeout;
if (is_int($timeout)) {
$this->lastActivity = time();
} else {
$this->lastActivity = null;
}
} elseif ($timeout !== null) {
throw new InvalidArgumentException([
'data' => ['method' => 'Session::timeout', 'argument' => '$timeout'],
'translate' => false
]);
$this->timeout = $timeout;
$this->lastActivity = is_int($timeout) ? time() : null;
}
return $this->timeout;
@ -284,12 +263,11 @@ class Session
* Gets or sets the renewable flag
* Automatically renews the session if renewing gets enabled
*
* @param bool $renewable Optional new renewable flag to set
* @return bool
* @param bool|null $renewable Optional new renewable flag to set
*/
public function renewable(bool $renewable = null): bool
public function renewable(bool|null $renewable = null): bool
{
if (is_bool($renewable)) {
if ($renewable !== null) {
$this->prepareForWriting();
$this->renewable = $renewable;
$this->autoRenew();
@ -313,12 +291,21 @@ class Session
*
* @param string $name Method name (one of set, increment, decrement, get, pull, remove, clear)
* @param array $arguments Method arguments
* @return mixed
*/
public function __call(string $name, array $arguments)
public function __call(string $name, array $arguments): mixed
{
// validate that we can handle the called method
if (!in_array($name, ['set', 'increment', 'decrement', 'get', 'pull', 'remove', 'clear'])) {
$methods = [
'clear',
'decrement',
'get',
'increment',
'pull',
'remove',
'set'
];
if (in_array($name, $methods) === false) {
throw new BadMethodCallException([
'data' => ['method' => 'Session::' . $name],
'translate' => false
@ -330,10 +317,8 @@ class Session
/**
* Writes all changes to the session to the session store
*
* @return void
*/
public function commit()
public function commit(): void
{
// nothing to do if nothing changed or the session has been just created or destroyed
/**
@ -349,7 +334,7 @@ class Session
}
// collect all data
if (isset($this->newSession) === true) {
if ($this->newSession !== null) {
// the token has changed
// we are writing to the old session: it only gets the reference to the new session
// and a shortened expiry time (30 second grace period)
@ -394,10 +379,8 @@ class Session
/**
* Entirely destroys the session
*
* @return void
*/
public function destroy()
public function destroy(): void
{
// no need to destroy new or destroyed sessions
if ($this->tokenExpiry === null || $this->destroyed === true) {
@ -419,10 +402,8 @@ class Session
/**
* Renews the session with the same session duration
* Renewing also regenerates the session token
*
* @return void
*/
public function renew()
public function renew(): void
{
if ($this->renewable() !== true) {
throw new LogicException([
@ -440,10 +421,8 @@ class Session
/**
* Regenerates the session token
* The old token will keep its validity for a 30 second grace period
*
* @return void
*/
public function regenerateToken()
public function regenerateToken(): void
{
// don't do anything for destroyed sessions
if ($this->destroyed === true) {
@ -494,8 +473,6 @@ class Session
/**
* Returns whether the session token needs to be retransmitted to the client
* Only relevant in header and manual modes
*
* @return bool
*/
public function needsRetransmission(): bool
{
@ -503,7 +480,10 @@ class Session
}
/**
* Ensures that all pending changes are written to disk before the object is destructed
* Ensures that all pending changes are written
* to disk before the object is destructed
*
* @return void
*/
public function __destruct()
{
@ -513,10 +493,8 @@ class Session
/**
* Initially generates the token for new sessions
* Used internally
*
* @return void
*/
public function ensureToken()
public function ensureToken(): void
{
if ($this->tokenExpiry === null) {
$this->regenerateToken();
@ -524,12 +502,11 @@ class Session
}
/**
* Puts the session into write mode by acquiring a lock and reloading the data
* Used internally
*
* @return void
* Puts the session into write mode by acquiring a lock
* and reloading the data
* @internal
*/
public function prepareForWriting()
public function prepareForWriting(): void
{
// verify that we need to get into write mode:
// - new sessions are only written to if the token has explicitly been ensured
@ -589,9 +566,8 @@ class Session
*
* @param string $token Session token
* @param bool $withoutKey If true, $token is passed without key
* @return void
*/
protected function parseToken(string $token, bool $withoutKey = false)
protected function parseToken(string $token, bool $withoutKey = false): void
{
// split the token into its parts
$parts = explode('.', $token);
@ -630,44 +606,35 @@ class Session
* Makes sure that the given value is a valid timestamp
*
* @param string|int $time Timestamp or date string (must be supported by `strtotime()`)
* @param int $now Timestamp to use as a base for the calculation of relative dates
* @param int|null $now Timestamp to use as a base for the calculation of relative dates
* @return int Timestamp value
*/
protected static function timeToTimestamp($time, int $now = null): int
{
protected static function timeToTimestamp(
string|int $time,
int|null $now = null
): int {
// default to current time as $now
if (!is_int($now)) {
$now = time();
}
$now ??= time();
// convert date strings to a timestamp first
if (is_string($time)) {
if (is_string($time) === true) {
$time = strtotime($time, $now);
}
// now make sure that we have a valid timestamp
if (is_int($time)) {
return $time;
}
throw new InvalidArgumentException([
'data' => [
'method' => 'Session::timeToTimestamp',
'argument' => '$time'
],
'translate' => false
]);
return $time;
}
/**
* Loads the session data from the session store
*
* @return void
*/
protected function init()
protected function init(): void
{
// sessions that are new, written to or that have been destroyed should never be initialized
if ($this->tokenExpiry === null || $this->writeMode === true || $this->destroyed === true) {
if (
$this->tokenExpiry === null ||
$this->writeMode === true ||
$this->destroyed === true
) {
// unexpected error that shouldn't occur
throw new Exception(['translate' => false]); // @codeCoverageIgnore
}
@ -684,13 +651,20 @@ class Session
}
// get the session data from the store
$data = $this->sessions->store()->get($this->tokenExpiry, $this->tokenId);
$data = $this->sessions->store()->get(
$this->tokenExpiry,
$this->tokenId
);
// verify HMAC
// skip if we don't have the key (only the case for moved sessions)
$hmac = Str::before($data, "\n");
$data = trim(Str::after($data, "\n"));
if ($this->tokenKey !== null && hash_equals(hash_hmac('sha256', $data, $this->tokenKey), $hmac) !== true) {
if (
$this->tokenKey !== null &&
hash_equals(hash_hmac('sha256', $data, $this->tokenKey), $hmac) !== true
) {
throw new LogicException([
'key' => 'session.invalid',
'data' => ['token' => $this->token()],
@ -701,21 +675,23 @@ class Session
}
// decode the serialized data
try {
$data = unserialize($data);
} catch (Throwable $e) {
$data = @unserialize($data);
if ($data === false) {
throw new LogicException([
'key' => 'session.invalid',
'data' => ['token' => $this->token()],
'fallback' => 'Session "' . $this->token() . '" is invalid',
'translate' => false,
'httpCode' => 500,
'previous' => $e
'httpCode' => 500
]);
}
// verify start and expiry time
if (time() < $data['startTime'] || time() > $data['expiryTime']) {
if (
time() < $data['startTime'] ||
time() > $data['expiryTime']
) {
throw new LogicException([
'key' => 'session.invalid',
'data' => ['token' => $this->token()],
@ -726,7 +702,7 @@ class Session
}
// follow to the new session if there is one
if (isset($data['newSession'])) {
if (isset($data['newSession']) === true) {
// decrypt the token key if provided and we have access to
// the PHP `sodium` extension for decryption
if (
@ -747,7 +723,7 @@ class Session
}
// verify timeout
if (is_int($data['timeout'])) {
if (is_int($data['timeout']) === true) {
if (time() - $data['lastActivity'] > $data['timeout']) {
throw new LogicException([
'key' => 'session.invalid',
@ -761,7 +737,11 @@ class Session
// set a new activity timestamp, but only every few minutes for better performance
// don't do this if another call to init() is already doing it to prevent endless loops;
// also don't do this for read-only sessions
if ($this->updatingLastActivity === false && $this->tokenKey !== null && time() - $data['lastActivity'] > $data['timeout'] / 15) {
if (
$this->updatingLastActivity === false &&
$this->tokenKey !== null &&
time() - $data['lastActivity'] > $data['timeout'] / 15
) {
$this->updatingLastActivity = true;
$this->prepareForWriting();
@ -781,7 +761,7 @@ class Session
$this->renewable = $data['renewable'];
// reload data into existing object to avoid breaking memory references
if ($this->data instanceof SessionData) {
if (isset($this->data) === true) {
$this->data()->reload($data['data']);
} else {
$this->data = new SessionData($this, $data['data']);
@ -790,10 +770,8 @@ class Session
/**
* Regenerate session token, but only if there is already one
*
* @return void
*/
protected function regenerateTokenIfNotNew()
protected function regenerateTokenIfNotNew(): void
{
if ($this->tokenExpiry !== null) {
$this->regenerateToken();
@ -802,10 +780,8 @@ class Session
/**
* Automatically renews the session if possible and necessary
*
* @return void
*/
protected function autoRenew()
protected function autoRenew(): void
{
// check if the session needs renewal at all
if ($this->needsRenewal() !== true) {
@ -815,6 +791,7 @@ class Session
// re-load the session and check again to make sure that no other thread
// already renewed the session in the meantime
$this->prepareForWriting();
if ($this->needsRenewal() === true) {
$this->renew();
}
@ -823,11 +800,11 @@ class Session
/**
* Checks if the session can be renewed and if the last renewal
* was more than half a session duration ago
*
* @return bool
*/
protected function needsRenewal(): bool
{
return $this->renewable() === true && $this->expiryTime() - time() < $this->duration() / 2;
return
$this->renewable() === true &&
$this->expiryTime() - time() < $this->duration() / 2;
}
}

View file

@ -2,8 +2,8 @@
namespace Kirby\Session;
use Kirby\Exception\InvalidArgumentException;
use Kirby\Exception\LogicException;
use Kirby\Toolkit\A;
/**
* The session object can be used to
@ -18,9 +18,6 @@ use Kirby\Exception\LogicException;
*/
class SessionData
{
protected $session;
protected $data;
/**
* Creates a new SessionData instance
*
@ -28,10 +25,10 @@ class SessionData
* @param \Kirby\Session\Session $session Session object this data belongs to
* @param array $data Currently stored session data
*/
public function __construct(Session $session, array $data)
{
$this->session = $session;
$this->data = $data;
public function __construct(
protected Session $session,
protected array $data
) {
}
/**
@ -39,22 +36,18 @@ class SessionData
*
* @param string|array $key The key to define or a key-value array with multiple values
* @param mixed $value The value for the passed key (only if one $key is passed)
* @return void
*/
public function set($key, $value = null)
{
public function set(
string|array $key,
mixed $value = null
): void {
$this->session->ensureToken();
$this->session->prepareForWriting();
if (is_string($key)) {
if (is_string($key) === true) {
$this->data[$key] = $value;
} elseif (is_array($key)) {
$this->data = array_merge($this->data, $key);
} else {
throw new InvalidArgumentException([
'data' => ['method' => 'SessionData::set', 'argument' => 'key'],
'translate' => false
]);
$this->data = array_replace($this->data, $key);
}
}
@ -63,53 +56,45 @@ class SessionData
*
* @param string|array $key The key to increment or an array with multiple keys
* @param int $by Increment by which amount?
* @param int $max Maximum amount (value is not incremented further)
* @return void
* @param int|null $max Maximum amount (value is not incremented further)
*/
public function increment($key, int $by = 1, $max = null)
{
if ($max !== null && !is_int($max)) {
throw new InvalidArgumentException([
'data' => ['method' => 'SessionData::increment', 'argument' => 'max'],
'translate' => false
]);
}
if (is_string($key)) {
// make sure we have the correct values before getting
$this->session->prepareForWriting();
$value = $this->get($key, 0);
if (!is_int($value)) {
throw new LogicException([
'key' => 'session.data.increment.nonInt',
'data' => ['key' => $key],
'fallback' => 'Session value "' . $key . '" is not an integer and cannot be incremented',
'translate' => false
]);
}
// increment the value, but ensure $max constraint
if (is_int($max) && $value + $by > $max) {
// set the value to $max
// but not if the current $value is already larger than $max
$value = max($value, $max);
} else {
$value += $by;
}
$this->set($key, $value);
} elseif (is_array($key)) {
public function increment(
string|array $key,
int $by = 1,
int|null $max = null
): void {
// if array passed, call method recursively
if (is_array($key) === true) {
foreach ($key as $k) {
$this->increment($k, $by, $max);
}
} else {
throw new InvalidArgumentException([
'data' => ['method' => 'SessionData::increment', 'argument' => 'key'],
return;
}
// make sure we have the correct values before getting
$this->session->prepareForWriting();
$value = $this->get($key, 0);
if (is_int($value) === false) {
throw new LogicException([
'key' => 'session.data.increment.nonInt',
'data' => ['key' => $key],
'fallback' => 'Session value "' . $key . '" is not an integer and cannot be incremented',
'translate' => false
]);
}
// increment the value, but ensure $max constraint
if (is_int($max) === true && $value + $by > $max) {
// set the value to $max
// but not if the current $value is already larger than $max
$value = max($value, $max);
} else {
$value += $by;
}
$this->set($key, $value);
}
/**
@ -117,53 +102,45 @@ class SessionData
*
* @param string|array $key The key to decrement or an array with multiple keys
* @param int $by Decrement by which amount?
* @param int $min Minimum amount (value is not decremented further)
* @return void
* @param int|null $min Minimum amount (value is not decremented further)
*/
public function decrement($key, int $by = 1, $min = null)
{
if ($min !== null && !is_int($min)) {
throw new InvalidArgumentException([
'data' => ['method' => 'SessionData::decrement', 'argument' => 'min'],
'translate' => false
]);
}
if (is_string($key)) {
// make sure we have the correct values before getting
$this->session->prepareForWriting();
$value = $this->get($key, 0);
if (!is_int($value)) {
throw new LogicException([
'key' => 'session.data.decrement.nonInt',
'data' => ['key' => $key],
'fallback' => 'Session value "' . $key . '" is not an integer and cannot be decremented',
'translate' => false
]);
}
// decrement the value, but ensure $min constraint
if (is_int($min) && $value - $by < $min) {
// set the value to $min
// but not if the current $value is already smaller than $min
$value = min($value, $min);
} else {
$value -= $by;
}
$this->set($key, $value);
} elseif (is_array($key)) {
public function decrement(
string|array $key,
int $by = 1,
int|null $min = null
): void {
// if array passed, call method recursively
if (is_array($key) === true) {
foreach ($key as $k) {
$this->decrement($k, $by, $min);
}
} else {
throw new InvalidArgumentException([
'data' => ['method' => 'SessionData::decrement', 'argument' => 'key'],
return;
}
// make sure we have the correct values before getting
$this->session->prepareForWriting();
$value = $this->get($key, 0);
if (is_int($value) === false) {
throw new LogicException([
'key' => 'session.data.decrement.nonInt',
'data' => ['key' => $key],
'fallback' => 'Session value "' . $key . '" is not an integer and cannot be decremented',
'translate' => false
]);
}
// decrement the value, but ensure $min constraint
if (is_int($min) === true && $value - $by < $min) {
// set the value to $min
// but not if the current $value is already smaller than $min
$value = min($value, $min);
} else {
$value -= $by;
}
$this->set($key, $value);
}
/**
@ -171,25 +148,16 @@ class SessionData
*
* @param string|null $key The key to get or null for the entire data array
* @param mixed $default Optional default value to return if the key is not defined
* @return mixed
*/
public function get($key = null, $default = null)
{
if (is_string($key)) {
return $this->data[$key] ?? $default;
}
public function get(
string|null $key = null,
mixed $default = null
): mixed {
if ($key === null) {
return $this->data;
}
throw new InvalidArgumentException([
'data' => [
'method' => 'SessionData::get',
'argument' => 'key'
],
'translate' => false
]);
return $this->data[$key] ?? $default;
}
/**
@ -197,9 +165,8 @@ class SessionData
*
* @param string $key The key to get
* @param mixed $default Optional default value to return if the key is not defined
* @return mixed
*/
public function pull(string $key, $default = null)
public function pull(string $key, mixed $default = null): mixed
{
// make sure we have the correct value before getting
// we do this here (but not in get) as we need to write anyway
@ -214,35 +181,22 @@ class SessionData
* Removes one or multiple session values by key
*
* @param string|array $key The key to remove or an array with multiple keys
* @return void
*/
public function remove($key)
public function remove(string|array $key): void
{
$this->session->prepareForWriting();
if (is_string($key)) {
unset($this->data[$key]);
} elseif (is_array($key)) {
foreach ($key as $k) {
unset($this->data[$k]);
}
} else {
throw new InvalidArgumentException([
'data' => ['method' => 'SessionData::remove', 'argument' => 'key'],
'translate' => false
]);
foreach (A::wrap($key) as $k) {
unset($this->data[$k]);
}
}
/**
* Clears all session data
*
* @return void
*/
public function clear()
public function clear(): void
{
$this->session->prepareForWriting();
$this->data = [];
}
@ -251,9 +205,8 @@ class SessionData
* Only used internally
*
* @param array $data Currently stored session data
* @return void
*/
public function reload(array $data)
public function reload(array $data): void
{
$this->data = $data;
}

View file

@ -39,9 +39,8 @@ abstract class SessionStore
*
* @param int $expiryTime Timestamp
* @param string $id Session ID
* @return void
*/
abstract public function lock(int $expiryTime, string $id);
abstract public function lock(int $expiryTime, string $id): void;
/**
* Removes all locks on the given session
@ -50,9 +49,8 @@ abstract class SessionStore
*
* @param int $expiryTime Timestamp
* @param string $id Session ID
* @return void
*/
abstract public function unlock(int $expiryTime, string $id);
abstract public function unlock(int $expiryTime, string $id): void;
/**
* Returns the stored session data of the given session
@ -61,7 +59,6 @@ abstract class SessionStore
*
* @param int $expiryTime Timestamp
* @param string $id Session ID
* @return string
*/
abstract public function get(int $expiryTime, string $id): string;
@ -74,9 +71,8 @@ abstract class SessionStore
* @param int $expiryTime Timestamp
* @param string $id Session ID
* @param string $data Session data to write
* @return void
*/
abstract public function set(int $expiryTime, string $id, string $data);
abstract public function set(int $expiryTime, string $id, string $data): void;
/**
* Deletes the given session
@ -85,18 +81,15 @@ abstract class SessionStore
*
* @param int $expiryTime Timestamp
* @param string $id Session ID
* @return void
*/
abstract public function destroy(int $expiryTime, string $id);
abstract public function destroy(int $expiryTime, string $id): void;
/**
* Deletes all expired sessions
*
* Needs to throw an Exception on error.
*
* @return void
*/
abstract public function collectGarbage();
abstract public function collectGarbage(): void;
/**
* Securely generates a random session ID

View file

@ -21,11 +21,11 @@ use Throwable;
*/
class Sessions
{
protected $store;
protected $mode;
protected $cookieName;
protected SessionStore $store;
protected string $mode;
protected string $cookieName;
protected $cache = [];
protected array $cache = [];
/**
* Creates a new Sessions instance
@ -36,39 +36,30 @@ class Sessions
* - `cookieName`: Name to use for the session cookie; defaults to `kirby_session`
* - `gcInterval`: How often should the garbage collector be run?; integer or `false` for never; defaults to `100`
*/
public function __construct($store, array $options = [])
public function __construct(SessionStore|string $store, array $options = [])
{
if (is_string($store)) {
$this->store = new FileSessionStore($store);
} elseif ($store instanceof SessionStore) {
$this->store = $store;
} else {
throw new InvalidArgumentException([
'data' => ['method' => 'Sessions::__construct', 'argument' => 'store'],
'translate' => false
]);
}
$this->store = match (is_string($store)) {
true => new FileSessionStore($store),
default => $store
};
$this->mode = $options['mode'] ?? 'cookie';
$this->cookieName = $options['cookieName'] ?? 'kirby_session';
$gcInterval = $options['gcInterval'] ?? 100;
// validate options
if (!in_array($this->mode, ['cookie', 'header', 'manual'])) {
if (in_array($this->mode, ['cookie', 'header', 'manual']) === false) {
throw new InvalidArgumentException([
'data' => ['method' => 'Sessions::__construct', 'argument' => '$options[\'mode\']'],
'translate' => false
]);
}
if (!is_string($this->cookieName)) {
throw new InvalidArgumentException([
'data' => ['method' => 'Sessions::__construct', 'argument' => '$options[\'cookieName\']'],
'data' => [
'method' => 'Sessions::__construct',
'argument' => '$options[\'mode\']'
],
'translate' => false
]);
}
// trigger automatic garbage collection with the given probability
if (is_int($gcInterval) && $gcInterval > 0) {
if (is_int($gcInterval) === true && $gcInterval > 0) {
// convert the interval into a probability between 0 and 1
$gcProbability = 1 / $gcInterval;
@ -81,7 +72,10 @@ class Sessions
}
} elseif ($gcInterval !== false) {
throw new InvalidArgumentException([
'data' => ['method' => 'Sessions::__construct', 'argument' => '$options[\'gcInterval\']'],
'data' => [
'method' => 'Sessions::__construct',
'argument' => '$options[\'gcInterval\']'
],
'translate' => false
]);
}
@ -96,9 +90,8 @@ class Sessions
* - `expiryTime`: Time the session expires (date string or timestamp); defaults to `+ 2 hours`
* - `timeout`: Activity timeout in seconds (integer or false for none); defaults to `1800` (half an hour)
* - `renewable`: Should it be possible to extend the expiry date?; defaults to `true`
* @return \Kirby\Session\Session
*/
public function create(array $options = [])
public function create(array $options = []): Session
{
// fall back to default mode
$options['mode'] ??= $this->mode;
@ -110,12 +103,15 @@ class Sessions
* Returns the specified Session object
*
* @param string $token Session token, either including or without the key
* @param string $mode Optional transmission mode override
* @return \Kirby\Session\Session
* @param string|null $mode Optional transmission mode override
*/
public function get(string $token, string $mode = null)
public function get(string $token, string|null $mode = null): Session
{
return $this->cache[$token] ??= new Session($this, $token, ['mode' => $mode ?? $this->mode]);
return $this->cache[$token] ??= new Session(
$this,
$token,
['mode' => $mode ?? $this->mode]
);
}
/**
@ -128,7 +124,7 @@ class Sessions
* @throws \Kirby\Exception\Exception
* @throws \Kirby\Exception\LogicException
*/
public function current()
public function current(): Session|null
{
$token = match ($this->mode) {
'cookie' => $this->tokenFromCookie(),
@ -164,7 +160,7 @@ class Sessions
*
* @return \Kirby\Session\Session|null Either the current session or null in case there isn't one
*/
public function currentDetected()
public function currentDetected(): Session|null
{
$tokenFromHeader = $this->tokenFromHeader();
$tokenFromCookie = $this->tokenFromCookie();
@ -173,13 +169,13 @@ class Sessions
$token = $tokenFromHeader ?? $tokenFromCookie;
// no token was found, no session
if (!is_string($token)) {
if (is_string($token) === false) {
return null;
}
// token was found, try to get the session
try {
$mode = (is_string($tokenFromHeader)) ? 'header' : 'cookie';
$mode = is_string($tokenFromHeader) ? 'header' : 'cookie';
return $this->get($token, $mode);
} catch (Throwable) {
return null;
@ -188,20 +184,16 @@ class Sessions
/**
* Getter for the session store instance
* Used internally
*
* @return \Kirby\Session\SessionStore
* @internal
*/
public function store()
public function store(): SessionStore
{
return $this->store;
}
/**
* Getter for the cookie name
* Used internally
*
* @return string
* @internal
*/
public function cookieName(): string
{
@ -213,10 +205,8 @@ class Sessions
*
* If the `gcInterval` is configured, this is done automatically
* on init of the Sessions object.
*
* @return void
*/
public function collectGarbage()
public function collectGarbage(): void
{
$this->store()->collectGarbage();
}
@ -228,17 +218,15 @@ class Sessions
* @internal
* @param \Kirby\Session\Session $session Session instance to push to the cache
*/
public function updateCache(Session $session)
public function updateCache(Session $session): void
{
$this->cache[$session->token()] = $session;
}
/**
* Returns the auth token from the cookie
*
* @return string|null
*/
protected function tokenFromCookie()
protected function tokenFromCookie(): string|null
{
$value = Cookie::get($this->cookieName());
@ -251,26 +239,23 @@ class Sessions
/**
* Returns the auth token from the Authorization header
*
* @return string|null
*/
protected function tokenFromHeader()
protected function tokenFromHeader(): string|null
{
$request = new Request();
$headers = $request->headers();
// check if the header exists at all
if (isset($headers['Authorization']) === false) {
return null;
if ($header = $headers['Authorization'] ?? null) {
// check if the header uses the "Session" scheme
if (Str::startsWith($header, 'Session ', true) !== true) {
return null;
}
// return the part after the scheme
return substr($header, 8);
}
// check if the header uses the "Session" scheme
$header = $headers['Authorization'];
if (Str::startsWith($header, 'Session ', true) !== true) {
return null;
}
// return the part after the scheme
return substr($header, 8);
return null;
}
}