PageRenderTime 26ms CodeModel.GetById 11ms RepoModel.GetById 0ms app.codeStats 0ms

/vendor/symfony/http-foundation/Symfony/Component/HttpFoundation/Session/Storage/Handler/PdoSessionHandler.php

https://gitlab.com/oytunistrator/92five
PHP | 255 lines | 138 code | 31 blank | 86 comment | 9 complexity | 2a4d6f01189c176f63eaadffbfb14e30 MD5 | raw file
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\HttpFoundation\Session\Storage\Handler;
  11. /**
  12. * Session handler using a PDO connection to read and write data.
  13. *
  14. * Session data is a binary string that can contain non-printable characters like the null byte.
  15. * For this reason this handler base64 encodes the data to be able to save it in a character column.
  16. *
  17. * This version of the PdoSessionHandler does NOT implement locking. So concurrent requests to the
  18. * same session can result in data loss due to race conditions.
  19. *
  20. * @author Fabien Potencier <fabien@symfony.com>
  21. * @author Michael Williams <michael.williams@funsational.com>
  22. * @author Tobias Schultze <http://tobion.de>
  23. */
  24. class PdoSessionHandler implements \SessionHandlerInterface
  25. {
  26. /**
  27. * @var \PDO PDO instance
  28. */
  29. private $pdo;
  30. /**
  31. * @var string Table name
  32. */
  33. private $table;
  34. /**
  35. * @var string Column for session id
  36. */
  37. private $idCol;
  38. /**
  39. * @var string Column for session data
  40. */
  41. private $dataCol;
  42. /**
  43. * @var string Column for timestamp
  44. */
  45. private $timeCol;
  46. /**
  47. * Constructor.
  48. *
  49. * List of available options:
  50. * * db_table: The name of the table [required]
  51. * * db_id_col: The column where to store the session id [default: sess_id]
  52. * * db_data_col: The column where to store the session data [default: sess_data]
  53. * * db_time_col: The column where to store the timestamp [default: sess_time]
  54. *
  55. * @param \PDO $pdo A \PDO instance
  56. * @param array $dbOptions An associative array of DB options
  57. *
  58. * @throws \InvalidArgumentException When "db_table" option is not provided
  59. */
  60. public function __construct(\PDO $pdo, array $dbOptions = array())
  61. {
  62. if (!array_key_exists('db_table', $dbOptions)) {
  63. throw new \InvalidArgumentException('You must provide the "db_table" option for a PdoSessionStorage.');
  64. }
  65. if (\PDO::ERRMODE_EXCEPTION !== $pdo->getAttribute(\PDO::ATTR_ERRMODE)) {
  66. 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__));
  67. }
  68. $this->pdo = $pdo;
  69. $dbOptions = array_merge(array(
  70. 'db_id_col' => 'sess_id',
  71. 'db_data_col' => 'sess_data',
  72. 'db_time_col' => 'sess_time',
  73. ), $dbOptions);
  74. $this->table = $dbOptions['db_table'];
  75. $this->idCol = $dbOptions['db_id_col'];
  76. $this->dataCol = $dbOptions['db_data_col'];
  77. $this->timeCol = $dbOptions['db_time_col'];
  78. }
  79. /**
  80. * {@inheritdoc}
  81. */
  82. public function open($savePath, $sessionName)
  83. {
  84. return true;
  85. }
  86. /**
  87. * {@inheritdoc}
  88. */
  89. public function close()
  90. {
  91. return true;
  92. }
  93. /**
  94. * {@inheritdoc}
  95. */
  96. public function destroy($sessionId)
  97. {
  98. // delete the record associated with this id
  99. $sql = "DELETE FROM $this->table WHERE $this->idCol = :id";
  100. try {
  101. $stmt = $this->pdo->prepare($sql);
  102. $stmt->bindParam(':id', $sessionId, \PDO::PARAM_STR);
  103. $stmt->execute();
  104. } catch (\PDOException $e) {
  105. throw new \RuntimeException(sprintf('PDOException was thrown when trying to delete a session: %s', $e->getMessage()), 0, $e);
  106. }
  107. return true;
  108. }
  109. /**
  110. * {@inheritdoc}
  111. */
  112. public function gc($maxlifetime)
  113. {
  114. // delete the session records that have expired
  115. $sql = "DELETE FROM $this->table WHERE $this->timeCol < :time";
  116. try {
  117. $stmt = $this->pdo->prepare($sql);
  118. $stmt->bindValue(':time', time() - $maxlifetime, \PDO::PARAM_INT);
  119. $stmt->execute();
  120. } catch (\PDOException $e) {
  121. throw new \RuntimeException(sprintf('PDOException was thrown when trying to delete expired sessions: %s', $e->getMessage()), 0, $e);
  122. }
  123. return true;
  124. }
  125. /**
  126. * {@inheritdoc}
  127. */
  128. public function read($sessionId)
  129. {
  130. $sql = "SELECT $this->dataCol FROM $this->table WHERE $this->idCol = :id";
  131. try {
  132. $stmt = $this->pdo->prepare($sql);
  133. $stmt->bindParam(':id', $sessionId, \PDO::PARAM_STR);
  134. $stmt->execute();
  135. // We use fetchAll instead of fetchColumn to make sure the DB cursor gets closed
  136. $sessionRows = $stmt->fetchAll(\PDO::FETCH_NUM);
  137. if ($sessionRows) {
  138. return base64_decode($sessionRows[0][0]);
  139. }
  140. return '';
  141. } catch (\PDOException $e) {
  142. throw new \RuntimeException(sprintf('PDOException was thrown when trying to read the session data: %s', $e->getMessage()), 0, $e);
  143. }
  144. }
  145. /**
  146. * {@inheritdoc}
  147. */
  148. public function write($sessionId, $data)
  149. {
  150. $encoded = base64_encode($data);
  151. try {
  152. // We use a single MERGE SQL query when supported by the database.
  153. $mergeSql = $this->getMergeSql();
  154. if (null !== $mergeSql) {
  155. $mergeStmt = $this->pdo->prepare($mergeSql);
  156. $mergeStmt->bindParam(':id', $sessionId, \PDO::PARAM_STR);
  157. $mergeStmt->bindParam(':data', $encoded, \PDO::PARAM_STR);
  158. $mergeStmt->bindValue(':time', time(), \PDO::PARAM_INT);
  159. $mergeStmt->execute();
  160. return true;
  161. }
  162. $updateStmt = $this->pdo->prepare(
  163. "UPDATE $this->table SET $this->dataCol = :data, $this->timeCol = :time WHERE $this->idCol = :id"
  164. );
  165. $updateStmt->bindParam(':id', $sessionId, \PDO::PARAM_STR);
  166. $updateStmt->bindParam(':data', $encoded, \PDO::PARAM_STR);
  167. $updateStmt->bindValue(':time', time(), \PDO::PARAM_INT);
  168. $updateStmt->execute();
  169. // When MERGE is not supported, like in Postgres, we have to use this approach that can result in
  170. // duplicate key errors when the same session is written simultaneously. We can just catch such an
  171. // error and re-execute the update. This is similar to a serializable transaction with retry logic
  172. // on serialization failures but without the overhead and without possible false positives due to
  173. // longer gap locking.
  174. if (!$updateStmt->rowCount()) {
  175. try {
  176. $insertStmt = $this->pdo->prepare(
  177. "INSERT INTO $this->table ($this->idCol, $this->dataCol, $this->timeCol) VALUES (:id, :data, :time)"
  178. );
  179. $insertStmt->bindParam(':id', $sessionId, \PDO::PARAM_STR);
  180. $insertStmt->bindParam(':data', $encoded, \PDO::PARAM_STR);
  181. $insertStmt->bindValue(':time', time(), \PDO::PARAM_INT);
  182. $insertStmt->execute();
  183. } catch (\PDOException $e) {
  184. // Handle integrity violation SQLSTATE 23000 (or a subclass like 23505 in Postgres) for duplicate keys
  185. if (0 === strpos($e->getCode(), '23')) {
  186. $updateStmt->execute();
  187. } else {
  188. throw $e;
  189. }
  190. }
  191. }
  192. } catch (\PDOException $e) {
  193. throw new \RuntimeException(sprintf('PDOException was thrown when trying to write the session data: %s', $e->getMessage()), 0, $e);
  194. }
  195. return true;
  196. }
  197. /**
  198. * Returns a merge/upsert (i.e. insert or update) SQL query when supported by the database.
  199. *
  200. * @return string|null The SQL string or null when not supported
  201. */
  202. private function getMergeSql()
  203. {
  204. $driver = $this->pdo->getAttribute(\PDO::ATTR_DRIVER_NAME);
  205. switch ($driver) {
  206. case 'mysql':
  207. return "INSERT INTO $this->table ($this->idCol, $this->dataCol, $this->timeCol) VALUES (:id, :data, :time) " .
  208. "ON DUPLICATE KEY UPDATE $this->dataCol = VALUES($this->dataCol), $this->timeCol = VALUES($this->timeCol)";
  209. case 'oci':
  210. // DUAL is Oracle specific dummy table
  211. return "MERGE INTO $this->table USING DUAL ON ($this->idCol = :id) " .
  212. "WHEN NOT MATCHED THEN INSERT ($this->idCol, $this->dataCol, $this->timeCol) VALUES (:id, :data, :time) " .
  213. "WHEN MATCHED THEN UPDATE SET $this->dataCol = :data, $this->timeCol = :time";
  214. case 'sqlsrv' === $driver && version_compare($this->pdo->getAttribute(\PDO::ATTR_SERVER_VERSION), '10', '>='):
  215. // MERGE is only available since SQL Server 2008 and must be terminated by semicolon
  216. // It also requires HOLDLOCK according to http://weblogs.sqlteam.com/dang/archive/2009/01/31/UPSERT-Race-Condition-With-MERGE.aspx
  217. return "MERGE INTO $this->table WITH (HOLDLOCK) USING (SELECT 1 AS dummy) AS src ON ($this->idCol = :id) " .
  218. "WHEN NOT MATCHED THEN INSERT ($this->idCol, $this->dataCol, $this->timeCol) VALUES (:id, :data, :time) " .
  219. "WHEN MATCHED THEN UPDATE SET $this->dataCol = :data, $this->timeCol = :time;";
  220. case 'sqlite':
  221. return "INSERT OR REPLACE INTO $this->table ($this->idCol, $this->dataCol, $this->timeCol) VALUES (:id, :data, :time)";
  222. }
  223. }
  224. }