package and depencies

This commit is contained in:
RafficMohammed
2023-01-08 02:57:24 +05:30
parent d5332eb421
commit 1d54b8bc7f
4309 changed files with 193331 additions and 172289 deletions

View File

@@ -65,105 +65,66 @@ class PdoSessionHandler extends AbstractSessionHandler
*/
public const LOCK_TRANSACTIONAL = 2;
private const MAX_LIFETIME = 315576000;
/**
* @var \PDO|null PDO instance or null when not connected yet
*/
private $pdo;
private \PDO $pdo;
/**
* DSN string or null for session.save_path or false when lazy connection disabled.
*
* @var string|false|null
*/
private $dsn = false;
private string|false|null $dsn = false;
private string $driver;
private string $table = 'sessions';
private string $idCol = 'sess_id';
private string $dataCol = 'sess_data';
private string $lifetimeCol = 'sess_lifetime';
private string $timeCol = 'sess_time';
/**
* @var string|null
* Time to live in seconds.
*/
private $driver;
/**
* @var string
*/
private $table = 'sessions';
/**
* @var string
*/
private $idCol = 'sess_id';
/**
* @var string
*/
private $dataCol = 'sess_data';
/**
* @var string
*/
private $lifetimeCol = 'sess_lifetime';
/**
* @var string
*/
private $timeCol = 'sess_time';
private int|\Closure|null $ttl;
/**
* Username when lazy-connect.
*
* @var string
*/
private $username = '';
private string $username = '';
/**
* Password when lazy-connect.
*
* @var string
*/
private $password = '';
private string $password = '';
/**
* Connection options when lazy-connect.
*
* @var array
*/
private $connectionOptions = [];
private array $connectionOptions = [];
/**
* The strategy for locking, see constants.
*
* @var int
*/
private $lockMode = self::LOCK_TRANSACTIONAL;
private int $lockMode = self::LOCK_TRANSACTIONAL;
/**
* It's an array to support multiple reads before closing which is manual, non-standard usage.
*
* @var \PDOStatement[] An array of statements to release advisory locks
*/
private $unlockStatements = [];
private array $unlockStatements = [];
/**
* True when the current session exists but expired according to session.gc_maxlifetime.
*
* @var bool
*/
private $sessionExpired = false;
private bool $sessionExpired = false;
/**
* Whether a transaction is active.
*
* @var bool
*/
private $inTransaction = false;
private bool $inTransaction = false;
/**
* Whether gc() has been called.
*
* @var bool
*/
private $gcCalled = false;
private bool $gcCalled = false;
/**
* You can either pass an existing database connection as PDO instance or
@@ -181,12 +142,13 @@ class PdoSessionHandler extends AbstractSessionHandler
* * db_password: The password when lazy-connect [default: '']
* * db_connection_options: An array of driver-specific connection options [default: []]
* * lock_mode: The strategy for locking, see constants [default: LOCK_TRANSACTIONAL]
* * ttl: The time to live in seconds.
*
* @param \PDO|string|null $pdoOrDsn A \PDO instance or DSN string or URL string or null
*
* @throws \InvalidArgumentException When PDO error mode is not PDO::ERRMODE_EXCEPTION
*/
public function __construct($pdoOrDsn = null, array $options = [])
public function __construct(\PDO|string $pdoOrDsn = null, array $options = [])
{
if ($pdoOrDsn instanceof \PDO) {
if (\PDO::ERRMODE_EXCEPTION !== $pdoOrDsn->getAttribute(\PDO::ATTR_ERRMODE)) {
@@ -210,6 +172,7 @@ class PdoSessionHandler extends AbstractSessionHandler
$this->password = $options['db_password'] ?? $this->password;
$this->connectionOptions = $options['db_connection_options'] ?? $this->connectionOptions;
$this->lockMode = $options['lock_mode'] ?? $this->lockMode;
$this->ttl = $options['ttl'] ?? null;
}
/**
@@ -228,34 +191,23 @@ class PdoSessionHandler extends AbstractSessionHandler
// connect if we are not yet
$this->getConnection();
switch ($this->driver) {
case 'mysql':
// We use varbinary for the ID column because it prevents unwanted conversions:
// - character set conversions between server and client
// - trailing space removal
// - case-insensitivity
// - language processing like é == e
$sql = "CREATE TABLE $this->table ($this->idCol VARBINARY(128) NOT NULL PRIMARY KEY, $this->dataCol BLOB NOT NULL, $this->lifetimeCol INTEGER UNSIGNED NOT NULL, $this->timeCol INTEGER UNSIGNED NOT NULL) COLLATE utf8mb4_bin, ENGINE = InnoDB";
break;
case 'sqlite':
$sql = "CREATE TABLE $this->table ($this->idCol TEXT NOT NULL PRIMARY KEY, $this->dataCol BLOB NOT NULL, $this->lifetimeCol INTEGER NOT NULL, $this->timeCol INTEGER NOT NULL)";
break;
case 'pgsql':
$sql = "CREATE TABLE $this->table ($this->idCol VARCHAR(128) NOT NULL PRIMARY KEY, $this->dataCol BYTEA NOT NULL, $this->lifetimeCol INTEGER NOT NULL, $this->timeCol INTEGER NOT NULL)";
break;
case 'oci':
$sql = "CREATE TABLE $this->table ($this->idCol VARCHAR2(128) NOT NULL PRIMARY KEY, $this->dataCol BLOB NOT NULL, $this->lifetimeCol INTEGER NOT NULL, $this->timeCol INTEGER NOT NULL)";
break;
case 'sqlsrv':
$sql = "CREATE TABLE $this->table ($this->idCol VARCHAR(128) NOT NULL PRIMARY KEY, $this->dataCol VARBINARY(MAX) NOT NULL, $this->lifetimeCol INTEGER NOT NULL, $this->timeCol INTEGER NOT NULL)";
break;
default:
throw new \DomainException(sprintf('Creating the session table is currently not implemented for PDO driver "%s".', $this->driver));
}
$sql = match ($this->driver) {
// We use varbinary for the ID column because it prevents unwanted conversions:
// - character set conversions between server and client
// - trailing space removal
// - case-insensitivity
// - language processing like é == e
'mysql' => "CREATE TABLE $this->table ($this->idCol VARBINARY(128) NOT NULL PRIMARY KEY, $this->dataCol BLOB NOT NULL, $this->lifetimeCol INTEGER UNSIGNED NOT NULL, $this->timeCol INTEGER UNSIGNED NOT NULL) COLLATE utf8mb4_bin, ENGINE = InnoDB",
'sqlite' => "CREATE TABLE $this->table ($this->idCol TEXT NOT NULL PRIMARY KEY, $this->dataCol BLOB NOT NULL, $this->lifetimeCol INTEGER NOT NULL, $this->timeCol INTEGER NOT NULL)",
'pgsql' => "CREATE TABLE $this->table ($this->idCol VARCHAR(128) NOT NULL PRIMARY KEY, $this->dataCol BYTEA NOT NULL, $this->lifetimeCol INTEGER NOT NULL, $this->timeCol INTEGER NOT NULL)",
'oci' => "CREATE TABLE $this->table ($this->idCol VARCHAR2(128) NOT NULL PRIMARY KEY, $this->dataCol BLOB NOT NULL, $this->lifetimeCol INTEGER NOT NULL, $this->timeCol INTEGER NOT NULL)",
'sqlsrv' => "CREATE TABLE $this->table ($this->idCol VARCHAR(128) NOT NULL PRIMARY KEY, $this->dataCol VARBINARY(MAX) NOT NULL, $this->lifetimeCol INTEGER NOT NULL, $this->timeCol INTEGER NOT NULL)",
default => throw new \DomainException(sprintf('Creating the session table is currently not implemented for PDO driver "%s".', $this->driver)),
};
try {
$this->pdo->exec($sql);
$this->pdo->exec("CREATE INDEX EXPIRY ON $this->table ($this->lifetimeCol)");
$this->pdo->exec("CREATE INDEX expiry ON $this->table ($this->lifetimeCol)");
} catch (\PDOException $e) {
$this->rollback();
@@ -267,34 +219,24 @@ class PdoSessionHandler extends AbstractSessionHandler
* Returns true when the current session exists but expired according to session.gc_maxlifetime.
*
* Can be used to distinguish between a new session and one that expired due to inactivity.
*
* @return bool
*/
public function isSessionExpired()
public function isSessionExpired(): bool
{
return $this->sessionExpired;
}
/**
* @return bool
*/
#[\ReturnTypeWillChange]
public function open($savePath, $sessionName)
public function open(string $savePath, string $sessionName): bool
{
$this->sessionExpired = false;
if (null === $this->pdo) {
if (!isset($this->pdo)) {
$this->connect($this->dsn ?: $savePath);
}
return parent::open($savePath, $sessionName);
}
/**
* @return string
*/
#[\ReturnTypeWillChange]
public function read($sessionId)
public function read(string $sessionId): string
{
try {
return parent::read($sessionId);
@@ -305,11 +247,7 @@ class PdoSessionHandler extends AbstractSessionHandler
}
}
/**
* @return int|false
*/
#[\ReturnTypeWillChange]
public function gc($maxlifetime)
public function gc(int $maxlifetime): int|false
{
// We delay gc() to close() so that it is executed outside the transactional and blocking read-write process.
// This way, pruning expired sessions does not block them from being started while the current session is used.
@@ -318,10 +256,7 @@ class PdoSessionHandler extends AbstractSessionHandler
return 0;
}
/**
* {@inheritdoc}
*/
protected function doDestroy(string $sessionId)
protected function doDestroy(string $sessionId): bool
{
// delete the record associated with this id
$sql = "DELETE FROM $this->table WHERE $this->idCol = :id";
@@ -339,12 +274,9 @@ class PdoSessionHandler extends AbstractSessionHandler
return true;
}
/**
* {@inheritdoc}
*/
protected function doWrite(string $sessionId, string $data)
protected function doWrite(string $sessionId, string $data): bool
{
$maxlifetime = (int) \ini_get('session.gc_maxlifetime');
$maxlifetime = (int) (($this->ttl instanceof \Closure ? ($this->ttl)() : $this->ttl) ?? \ini_get('session.gc_maxlifetime'));
try {
// We use a single MERGE SQL query when supported by the database.
@@ -385,13 +317,9 @@ class PdoSessionHandler extends AbstractSessionHandler
return true;
}
/**
* @return bool
*/
#[\ReturnTypeWillChange]
public function updateTimestamp($sessionId, $data)
public function updateTimestamp(string $sessionId, string $data): bool
{
$expiry = time() + (int) \ini_get('session.gc_maxlifetime');
$expiry = time() + (int) (($this->ttl instanceof \Closure ? ($this->ttl)() : $this->ttl) ?? \ini_get('session.gc_maxlifetime'));
try {
$updateStmt = $this->pdo->prepare(
@@ -410,11 +338,7 @@ class PdoSessionHandler extends AbstractSessionHandler
return true;
}
/**
* @return bool
*/
#[\ReturnTypeWillChange]
public function close()
public function close(): bool
{
$this->commit();
@@ -426,27 +350,14 @@ class PdoSessionHandler extends AbstractSessionHandler
$this->gcCalled = false;
// delete the session records that have expired
$sql = "DELETE FROM $this->table WHERE $this->lifetimeCol < :time AND $this->lifetimeCol > :min";
$sql = "DELETE FROM $this->table WHERE $this->lifetimeCol < :time";
$stmt = $this->pdo->prepare($sql);
$stmt->bindValue(':time', time(), \PDO::PARAM_INT);
$stmt->bindValue(':min', self::MAX_LIFETIME, \PDO::PARAM_INT);
$stmt->execute();
// to be removed in 6.0
if ('mysql' === $this->driver) {
$legacySql = "DELETE FROM $this->table WHERE $this->lifetimeCol <= :min AND $this->lifetimeCol + $this->timeCol < :time";
} else {
$legacySql = "DELETE FROM $this->table WHERE $this->lifetimeCol <= :min AND $this->lifetimeCol < :time - $this->timeCol";
}
$stmt = $this->pdo->prepare($legacySql);
$stmt->bindValue(':time', time(), \PDO::PARAM_INT);
$stmt->bindValue(':min', self::MAX_LIFETIME, \PDO::PARAM_INT);
$stmt->execute();
}
if (false !== $this->dsn) {
$this->pdo = null; // only close lazy-connection
$this->driver = null;
unset($this->pdo, $this->driver); // only close lazy-connection
}
return true;
@@ -533,7 +444,7 @@ class PdoSessionHandler extends AbstractSessionHandler
// If "unix_socket" is not in the query, we continue with the same process as pgsql
// no break
case 'pgsql':
$dsn ?? $dsn = 'pgsql:';
$dsn ??= 'pgsql:';
if (isset($params['host']) && '' !== $params['host']) {
$dsn .= 'host='.$params['host'].';';
@@ -649,10 +560,8 @@ class PdoSessionHandler extends AbstractSessionHandler
*
* We need to make sure we do not return session data that is already considered garbage according
* to the session.gc_maxlifetime setting because gc() is called after read() and only sometimes.
*
* @return string
*/
protected function doRead(string $sessionId)
protected function doRead(string $sessionId): string
{
if (self::LOCK_ADVISORY === $this->lockMode) {
$this->unlockStatements[] = $this->doAdvisoryLock($sessionId);
@@ -669,9 +578,6 @@ class PdoSessionHandler extends AbstractSessionHandler
if ($sessionRows) {
$expiry = (int) $sessionRows[0][1];
if ($expiry <= self::MAX_LIFETIME) {
$expiry += $sessionRows[0][2];
}
if ($expiry < time()) {
$this->sessionExpired = true;
@@ -687,7 +593,7 @@ class PdoSessionHandler extends AbstractSessionHandler
throw new \RuntimeException('Failed to read session: INSERT reported a duplicate id but next SELECT did not return any data.');
}
if (!filter_var(\ini_get('session.use_strict_mode'), \FILTER_VALIDATE_BOOLEAN) && self::LOCK_TRANSACTIONAL === $this->lockMode && 'sqlite' !== $this->driver) {
if (!filter_var(\ini_get('session.use_strict_mode'), \FILTER_VALIDATE_BOOL) && self::LOCK_TRANSACTIONAL === $this->lockMode && 'sqlite' !== $this->driver) {
// In strict mode, session fixation is not possible: new sessions always start with a unique
// random id, so that concurrency is not possible and this code path can be skipped.
// Exclusive-reading of non-existent rows does not block, so we need to do an insert to block
@@ -804,14 +710,13 @@ class PdoSessionHandler extends AbstractSessionHandler
if (self::LOCK_TRANSACTIONAL === $this->lockMode) {
$this->beginTransaction();
// selecting the time column should be removed in 6.0
switch ($this->driver) {
case 'mysql':
case 'oci':
case 'pgsql':
return "SELECT $this->dataCol, $this->lifetimeCol, $this->timeCol FROM $this->table WHERE $this->idCol = :id FOR UPDATE";
return "SELECT $this->dataCol, $this->lifetimeCol FROM $this->table WHERE $this->idCol = :id FOR UPDATE";
case 'sqlsrv':
return "SELECT $this->dataCol, $this->lifetimeCol, $this->timeCol FROM $this->table WITH (UPDLOCK, ROWLOCK) WHERE $this->idCol = :id";
return "SELECT $this->dataCol, $this->lifetimeCol FROM $this->table WITH (UPDLOCK, ROWLOCK) WHERE $this->idCol = :id";
case 'sqlite':
// we already locked when starting transaction
break;
@@ -820,7 +725,7 @@ class PdoSessionHandler extends AbstractSessionHandler
}
}
return "SELECT $this->dataCol, $this->lifetimeCol, $this->timeCol FROM $this->table WHERE $this->idCol = :id";
return "SELECT $this->dataCol, $this->lifetimeCol FROM $this->table WHERE $this->idCol = :id";
}
/**
@@ -929,12 +834,10 @@ class PdoSessionHandler extends AbstractSessionHandler
/**
* Return a PDO instance.
*
* @return \PDO
*/
protected function getConnection()
protected function getConnection(): \PDO
{
if (null === $this->pdo) {
if (!isset($this->pdo)) {
$this->connect($this->dsn ?: \ini_get('session.save_path'));
}