LegacyPdoSessionHandler.php 10 KB

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