123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696 |
- <?php
- namespace Symfony\Component\HttpFoundation\Session\Storage\Handler;
- class PdoSessionHandler implements \SessionHandlerInterface
- {
-
- const LOCK_NONE = 0;
-
- const LOCK_ADVISORY = 1;
-
- const LOCK_TRANSACTIONAL = 2;
-
- private $pdo;
-
- private $dsn = false;
-
- private $driver;
-
- private $table = 'sessions';
-
- private $idCol = 'sess_id';
-
- private $dataCol = 'sess_data';
-
- private $lifetimeCol = 'sess_lifetime';
-
- private $timeCol = 'sess_time';
-
- private $username = '';
-
- private $password = '';
-
- private $connectionOptions = array();
-
- private $lockMode = self::LOCK_TRANSACTIONAL;
-
- private $unlockStatements = array();
-
- private $sessionExpired = false;
-
- private $inTransaction = false;
-
- private $gcCalled = false;
-
- public function __construct($pdoOrDsn = null, array $options = array())
- {
- if ($pdoOrDsn instanceof \PDO) {
- if (\PDO::ERRMODE_EXCEPTION !== $pdoOrDsn->getAttribute(\PDO::ATTR_ERRMODE)) {
- throw new \InvalidArgumentException(sprintf('"%s" requires PDO error mode attribute be set to throw Exceptions (i.e. $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION))', __CLASS__));
- }
- $this->pdo = $pdoOrDsn;
- $this->driver = $this->pdo->getAttribute(\PDO::ATTR_DRIVER_NAME);
- } else {
- $this->dsn = $pdoOrDsn;
- }
- $this->table = isset($options['db_table']) ? $options['db_table'] : $this->table;
- $this->idCol = isset($options['db_id_col']) ? $options['db_id_col'] : $this->idCol;
- $this->dataCol = isset($options['db_data_col']) ? $options['db_data_col'] : $this->dataCol;
- $this->lifetimeCol = isset($options['db_lifetime_col']) ? $options['db_lifetime_col'] : $this->lifetimeCol;
- $this->timeCol = isset($options['db_time_col']) ? $options['db_time_col'] : $this->timeCol;
- $this->username = isset($options['db_username']) ? $options['db_username'] : $this->username;
- $this->password = isset($options['db_password']) ? $options['db_password'] : $this->password;
- $this->connectionOptions = isset($options['db_connection_options']) ? $options['db_connection_options'] : $this->connectionOptions;
- $this->lockMode = isset($options['lock_mode']) ? $options['lock_mode'] : $this->lockMode;
- }
-
- public function createTable()
- {
-
- $this->getConnection();
- switch ($this->driver) {
- case 'mysql':
-
-
-
-
-
- $sql = "CREATE TABLE $this->table ($this->idCol VARBINARY(128) NOT NULL PRIMARY KEY, $this->dataCol BLOB NOT NULL, $this->lifetimeCol MEDIUMINT NOT NULL, $this->timeCol INTEGER UNSIGNED NOT NULL) COLLATE utf8_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));
- }
- try {
- $this->pdo->exec($sql);
- } catch (\PDOException $e) {
- $this->rollback();
- throw $e;
- }
- }
-
- public function isSessionExpired()
- {
- return $this->sessionExpired;
- }
-
- public function open($savePath, $sessionName)
- {
- if (null === $this->pdo) {
- $this->connect($this->dsn ?: $savePath);
- }
- return true;
- }
-
- public function read($sessionId)
- {
- try {
- return $this->doRead($sessionId);
- } catch (\PDOException $e) {
- $this->rollback();
- throw $e;
- }
- }
-
- public function gc($maxlifetime)
- {
-
-
- $this->gcCalled = true;
- return true;
- }
-
- public function destroy($sessionId)
- {
-
- $sql = "DELETE FROM $this->table WHERE $this->idCol = :id";
- try {
- $stmt = $this->pdo->prepare($sql);
- $stmt->bindParam(':id', $sessionId, \PDO::PARAM_STR);
- $stmt->execute();
- } catch (\PDOException $e) {
- $this->rollback();
- throw $e;
- }
- return true;
- }
-
- public function write($sessionId, $data)
- {
- $maxlifetime = (int) ini_get('session.gc_maxlifetime');
- try {
-
- $mergeSql = $this->getMergeSql();
- if (null !== $mergeSql) {
- $mergeStmt = $this->pdo->prepare($mergeSql);
- $mergeStmt->bindParam(':id', $sessionId, \PDO::PARAM_STR);
- $mergeStmt->bindParam(':data', $data, \PDO::PARAM_LOB);
- $mergeStmt->bindParam(':lifetime', $maxlifetime, \PDO::PARAM_INT);
- $mergeStmt->bindValue(':time', time(), \PDO::PARAM_INT);
- $mergeStmt->execute();
- return true;
- }
- $updateStmt = $this->pdo->prepare(
- "UPDATE $this->table SET $this->dataCol = :data, $this->lifetimeCol = :lifetime, $this->timeCol = :time WHERE $this->idCol = :id"
- );
- $updateStmt->bindParam(':id', $sessionId, \PDO::PARAM_STR);
- $updateStmt->bindParam(':data', $data, \PDO::PARAM_LOB);
- $updateStmt->bindParam(':lifetime', $maxlifetime, \PDO::PARAM_INT);
- $updateStmt->bindValue(':time', time(), \PDO::PARAM_INT);
- $updateStmt->execute();
-
-
-
-
-
- if (!$updateStmt->rowCount()) {
- try {
- $insertStmt = $this->pdo->prepare(
- "INSERT INTO $this->table ($this->idCol, $this->dataCol, $this->lifetimeCol, $this->timeCol) VALUES (:id, :data, :lifetime, :time)"
- );
- $insertStmt->bindParam(':id', $sessionId, \PDO::PARAM_STR);
- $insertStmt->bindParam(':data', $data, \PDO::PARAM_LOB);
- $insertStmt->bindParam(':lifetime', $maxlifetime, \PDO::PARAM_INT);
- $insertStmt->bindValue(':time', time(), \PDO::PARAM_INT);
- $insertStmt->execute();
- } catch (\PDOException $e) {
-
- if (0 === strpos($e->getCode(), '23')) {
- $updateStmt->execute();
- } else {
- throw $e;
- }
- }
- }
- } catch (\PDOException $e) {
- $this->rollback();
- throw $e;
- }
- return true;
- }
-
- public function close()
- {
- $this->commit();
- while ($unlockStmt = array_shift($this->unlockStatements)) {
- $unlockStmt->execute();
- }
- if ($this->gcCalled) {
- $this->gcCalled = false;
-
- $sql = "DELETE FROM $this->table WHERE $this->lifetimeCol + $this->timeCol < :time";
- $stmt = $this->pdo->prepare($sql);
- $stmt->bindValue(':time', time(), \PDO::PARAM_INT);
- $stmt->execute();
- }
- if (false !== $this->dsn) {
- $this->pdo = null;
- }
- return true;
- }
-
- private function connect($dsn)
- {
- $this->pdo = new \PDO($dsn, $this->username, $this->password, $this->connectionOptions);
- $this->pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
- $this->driver = $this->pdo->getAttribute(\PDO::ATTR_DRIVER_NAME);
- }
-
- private function beginTransaction()
- {
- if (!$this->inTransaction) {
- if ('sqlite' === $this->driver) {
- $this->pdo->exec('BEGIN IMMEDIATE TRANSACTION');
- } else {
- if ('mysql' === $this->driver) {
- $this->pdo->exec('SET TRANSACTION ISOLATION LEVEL READ COMMITTED');
- }
- $this->pdo->beginTransaction();
- }
- $this->inTransaction = true;
- }
- }
-
- private function commit()
- {
- if ($this->inTransaction) {
- try {
-
- if ('sqlite' === $this->driver) {
- $this->pdo->exec('COMMIT');
- } else {
- $this->pdo->commit();
- }
- $this->inTransaction = false;
- } catch (\PDOException $e) {
- $this->rollback();
- throw $e;
- }
- }
- }
-
- private function rollback()
- {
-
-
-
-
- if ($this->inTransaction) {
- if ('sqlite' === $this->driver) {
- $this->pdo->exec('ROLLBACK');
- } else {
- $this->pdo->rollBack();
- }
- $this->inTransaction = false;
- }
- }
-
- private function doRead($sessionId)
- {
- $this->sessionExpired = false;
- if (self::LOCK_ADVISORY === $this->lockMode) {
- $this->unlockStatements[] = $this->doAdvisoryLock($sessionId);
- }
- $selectSql = $this->getSelectSql();
- $selectStmt = $this->pdo->prepare($selectSql);
- $selectStmt->bindParam(':id', $sessionId, \PDO::PARAM_STR);
- $selectStmt->execute();
- $sessionRows = $selectStmt->fetchAll(\PDO::FETCH_NUM);
- if ($sessionRows) {
- if ($sessionRows[0][1] + $sessionRows[0][2] < time()) {
- $this->sessionExpired = true;
- return '';
- }
- return is_resource($sessionRows[0][0]) ? stream_get_contents($sessionRows[0][0]) : $sessionRows[0][0];
- }
- if (self::LOCK_TRANSACTIONAL === $this->lockMode && 'sqlite' !== $this->driver) {
-
-
- try {
- $insertStmt = $this->pdo->prepare(
- "INSERT INTO $this->table ($this->idCol, $this->dataCol, $this->lifetimeCol, $this->timeCol) VALUES (:id, :data, :lifetime, :time)"
- );
- $insertStmt->bindParam(':id', $sessionId, \PDO::PARAM_STR);
- $insertStmt->bindValue(':data', '', \PDO::PARAM_LOB);
- $insertStmt->bindValue(':lifetime', 0, \PDO::PARAM_INT);
- $insertStmt->bindValue(':time', time(), \PDO::PARAM_INT);
- $insertStmt->execute();
- } catch (\PDOException $e) {
-
-
- if (0 === strpos($e->getCode(), '23')) {
-
-
-
- $selectStmt->execute();
- $sessionRows = $selectStmt->fetchAll(\PDO::FETCH_NUM);
- if ($sessionRows) {
- return is_resource($sessionRows[0][0]) ? stream_get_contents($sessionRows[0][0]) : $sessionRows[0][0];
- }
- return '';
- }
- throw $e;
- }
- }
- return '';
- }
-
- private function doAdvisoryLock($sessionId)
- {
- switch ($this->driver) {
- case 'mysql':
-
-
- $stmt = $this->pdo->prepare('SELECT GET_LOCK(:key, 50)');
- $stmt->bindValue(':key', $sessionId, \PDO::PARAM_STR);
- $stmt->execute();
- $releaseStmt = $this->pdo->prepare('DO RELEASE_LOCK(:key)');
- $releaseStmt->bindValue(':key', $sessionId, \PDO::PARAM_STR);
- return $releaseStmt;
- case 'pgsql':
-
-
-
- if (4 === PHP_INT_SIZE) {
- $sessionInt1 = hexdec(substr($sessionId, 0, 7));
- $sessionInt2 = hexdec(substr($sessionId, 7, 7));
- $stmt = $this->pdo->prepare('SELECT pg_advisory_lock(:key1, :key2)');
- $stmt->bindValue(':key1', $sessionInt1, \PDO::PARAM_INT);
- $stmt->bindValue(':key2', $sessionInt2, \PDO::PARAM_INT);
- $stmt->execute();
- $releaseStmt = $this->pdo->prepare('SELECT pg_advisory_unlock(:key1, :key2)');
- $releaseStmt->bindValue(':key1', $sessionInt1, \PDO::PARAM_INT);
- $releaseStmt->bindValue(':key2', $sessionInt2, \PDO::PARAM_INT);
- } else {
- $sessionBigInt = hexdec(substr($sessionId, 0, 15));
- $stmt = $this->pdo->prepare('SELECT pg_advisory_lock(:key)');
- $stmt->bindValue(':key', $sessionBigInt, \PDO::PARAM_INT);
- $stmt->execute();
- $releaseStmt = $this->pdo->prepare('SELECT pg_advisory_unlock(:key)');
- $releaseStmt->bindValue(':key', $sessionBigInt, \PDO::PARAM_INT);
- }
- return $releaseStmt;
- case 'sqlite':
- throw new \DomainException('SQLite does not support advisory locks.');
- default:
- throw new \DomainException(sprintf('Advisory locks are currently not implemented for PDO driver "%s".', $this->driver));
- }
- }
-
- private function getSelectSql()
- {
- if (self::LOCK_TRANSACTIONAL === $this->lockMode) {
- $this->beginTransaction();
- 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";
- case 'sqlsrv':
- return "SELECT $this->dataCol, $this->lifetimeCol, $this->timeCol FROM $this->table WITH (UPDLOCK, ROWLOCK) WHERE $this->idCol = :id";
- case 'sqlite':
-
- break;
- default:
- throw new \DomainException(sprintf('Transactional locks are currently not implemented for PDO driver "%s".', $this->driver));
- }
- }
- return "SELECT $this->dataCol, $this->lifetimeCol, $this->timeCol FROM $this->table WHERE $this->idCol = :id";
- }
-
- private function getMergeSql()
- {
- switch ($this->driver) {
- case 'mysql':
- return "INSERT INTO $this->table ($this->idCol, $this->dataCol, $this->lifetimeCol, $this->timeCol) VALUES (:id, :data, :lifetime, :time) ".
- "ON DUPLICATE KEY UPDATE $this->dataCol = VALUES($this->dataCol), $this->lifetimeCol = VALUES($this->lifetimeCol), $this->timeCol = VALUES($this->timeCol)";
- case 'oci':
-
- return "MERGE INTO $this->table USING DUAL ON ($this->idCol = :id) ".
- "WHEN NOT MATCHED THEN INSERT ($this->idCol, $this->dataCol, $this->lifetimeCol, $this->timeCol) VALUES (:id, :data, :lifetime, :time) ".
- "WHEN MATCHED THEN UPDATE SET $this->dataCol = :data, $this->lifetimeCol = :lifetime, $this->timeCol = :time";
- case 'sqlsrv' === $this->driver && version_compare($this->pdo->getAttribute(\PDO::ATTR_SERVER_VERSION), '10', '>='):
-
-
- return "MERGE INTO $this->table WITH (HOLDLOCK) USING (SELECT 1 AS dummy) AS src ON ($this->idCol = :id) ".
- "WHEN NOT MATCHED THEN INSERT ($this->idCol, $this->dataCol, $this->lifetimeCol, $this->timeCol) VALUES (:id, :data, :lifetime, :time) ".
- "WHEN MATCHED THEN UPDATE SET $this->dataCol = :data, $this->lifetimeCol = :lifetime, $this->timeCol = :time;";
- case 'sqlite':
- return "INSERT OR REPLACE INTO $this->table ($this->idCol, $this->dataCol, $this->lifetimeCol, $this->timeCol) VALUES (:id, :data, :lifetime, :time)";
- }
- }
-
- protected function getConnection()
- {
- if (null === $this->pdo) {
- $this->connect($this->dsn ?: ini_get('session.save_path'));
- }
- return $this->pdo;
- }
- }
|