LegacyPdoSessionHandler.php 10.0 KB

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