Chris@0
|
1 <?php
|
Chris@0
|
2
|
Chris@0
|
3 /*
|
Chris@0
|
4 * This file is part of the Symfony package.
|
Chris@0
|
5 *
|
Chris@0
|
6 * (c) Fabien Potencier <fabien@symfony.com>
|
Chris@0
|
7 *
|
Chris@0
|
8 * For the full copyright and license information, please view the LICENSE
|
Chris@0
|
9 * file that was distributed with this source code.
|
Chris@0
|
10 */
|
Chris@0
|
11
|
Chris@0
|
12 namespace Symfony\Component\HttpFoundation\Session\Storage\Handler;
|
Chris@0
|
13
|
Chris@0
|
14 /**
|
Chris@0
|
15 * Session handler using a PDO connection to read and write data.
|
Chris@0
|
16 *
|
Chris@0
|
17 * It works with MySQL, PostgreSQL, Oracle, SQL Server and SQLite and implements
|
Chris@0
|
18 * different locking strategies to handle concurrent access to the same session.
|
Chris@0
|
19 * Locking is necessary to prevent loss of data due to race conditions and to keep
|
Chris@0
|
20 * the session data consistent between read() and write(). With locking, requests
|
Chris@0
|
21 * for the same session will wait until the other one finished writing. For this
|
Chris@0
|
22 * reason it's best practice to close a session as early as possible to improve
|
Chris@0
|
23 * concurrency. PHPs internal files session handler also implements locking.
|
Chris@0
|
24 *
|
Chris@0
|
25 * Attention: Since SQLite does not support row level locks but locks the whole database,
|
Chris@0
|
26 * it means only one session can be accessed at a time. Even different sessions would wait
|
Chris@0
|
27 * for another to finish. So saving session in SQLite should only be considered for
|
Chris@0
|
28 * development or prototypes.
|
Chris@0
|
29 *
|
Chris@0
|
30 * Session data is a binary string that can contain non-printable characters like the null byte.
|
Chris@0
|
31 * For this reason it must be saved in a binary column in the database like BLOB in MySQL.
|
Chris@0
|
32 * Saving it in a character column could corrupt the data. You can use createTable()
|
Chris@0
|
33 * to initialize a correctly defined table.
|
Chris@0
|
34 *
|
Chris@0
|
35 * @see http://php.net/sessionhandlerinterface
|
Chris@0
|
36 *
|
Chris@0
|
37 * @author Fabien Potencier <fabien@symfony.com>
|
Chris@0
|
38 * @author Michael Williams <michael.williams@funsational.com>
|
Chris@0
|
39 * @author Tobias Schultze <http://tobion.de>
|
Chris@0
|
40 */
|
Chris@0
|
41 class PdoSessionHandler implements \SessionHandlerInterface
|
Chris@0
|
42 {
|
Chris@0
|
43 /**
|
Chris@0
|
44 * No locking is done. This means sessions are prone to loss of data due to
|
Chris@0
|
45 * race conditions of concurrent requests to the same session. The last session
|
Chris@0
|
46 * write will win in this case. It might be useful when you implement your own
|
Chris@0
|
47 * logic to deal with this like an optimistic approach.
|
Chris@0
|
48 */
|
Chris@0
|
49 const LOCK_NONE = 0;
|
Chris@0
|
50
|
Chris@0
|
51 /**
|
Chris@0
|
52 * Creates an application-level lock on a session. The disadvantage is that the
|
Chris@0
|
53 * lock is not enforced by the database and thus other, unaware parts of the
|
Chris@0
|
54 * application could still concurrently modify the session. The advantage is it
|
Chris@0
|
55 * does not require a transaction.
|
Chris@0
|
56 * This mode is not available for SQLite and not yet implemented for oci and sqlsrv.
|
Chris@0
|
57 */
|
Chris@0
|
58 const LOCK_ADVISORY = 1;
|
Chris@0
|
59
|
Chris@0
|
60 /**
|
Chris@0
|
61 * Issues a real row lock. Since it uses a transaction between opening and
|
Chris@0
|
62 * closing a session, you have to be careful when you use same database connection
|
Chris@0
|
63 * that you also use for your application logic. This mode is the default because
|
Chris@0
|
64 * it's the only reliable solution across DBMSs.
|
Chris@0
|
65 */
|
Chris@0
|
66 const LOCK_TRANSACTIONAL = 2;
|
Chris@0
|
67
|
Chris@0
|
68 /**
|
Chris@0
|
69 * @var \PDO|null PDO instance or null when not connected yet
|
Chris@0
|
70 */
|
Chris@0
|
71 private $pdo;
|
Chris@0
|
72
|
Chris@0
|
73 /**
|
Chris@0
|
74 * @var string|null|false DSN string or null for session.save_path or false when lazy connection disabled
|
Chris@0
|
75 */
|
Chris@0
|
76 private $dsn = false;
|
Chris@0
|
77
|
Chris@0
|
78 /**
|
Chris@0
|
79 * @var string Database driver
|
Chris@0
|
80 */
|
Chris@0
|
81 private $driver;
|
Chris@0
|
82
|
Chris@0
|
83 /**
|
Chris@0
|
84 * @var string Table name
|
Chris@0
|
85 */
|
Chris@0
|
86 private $table = 'sessions';
|
Chris@0
|
87
|
Chris@0
|
88 /**
|
Chris@0
|
89 * @var string Column for session id
|
Chris@0
|
90 */
|
Chris@0
|
91 private $idCol = 'sess_id';
|
Chris@0
|
92
|
Chris@0
|
93 /**
|
Chris@0
|
94 * @var string Column for session data
|
Chris@0
|
95 */
|
Chris@0
|
96 private $dataCol = 'sess_data';
|
Chris@0
|
97
|
Chris@0
|
98 /**
|
Chris@0
|
99 * @var string Column for lifetime
|
Chris@0
|
100 */
|
Chris@0
|
101 private $lifetimeCol = 'sess_lifetime';
|
Chris@0
|
102
|
Chris@0
|
103 /**
|
Chris@0
|
104 * @var string Column for timestamp
|
Chris@0
|
105 */
|
Chris@0
|
106 private $timeCol = 'sess_time';
|
Chris@0
|
107
|
Chris@0
|
108 /**
|
Chris@0
|
109 * @var string Username when lazy-connect
|
Chris@0
|
110 */
|
Chris@0
|
111 private $username = '';
|
Chris@0
|
112
|
Chris@0
|
113 /**
|
Chris@0
|
114 * @var string Password when lazy-connect
|
Chris@0
|
115 */
|
Chris@0
|
116 private $password = '';
|
Chris@0
|
117
|
Chris@0
|
118 /**
|
Chris@0
|
119 * @var array Connection options when lazy-connect
|
Chris@0
|
120 */
|
Chris@0
|
121 private $connectionOptions = array();
|
Chris@0
|
122
|
Chris@0
|
123 /**
|
Chris@0
|
124 * @var int The strategy for locking, see constants
|
Chris@0
|
125 */
|
Chris@0
|
126 private $lockMode = self::LOCK_TRANSACTIONAL;
|
Chris@0
|
127
|
Chris@0
|
128 /**
|
Chris@0
|
129 * It's an array to support multiple reads before closing which is manual, non-standard usage.
|
Chris@0
|
130 *
|
Chris@0
|
131 * @var \PDOStatement[] An array of statements to release advisory locks
|
Chris@0
|
132 */
|
Chris@0
|
133 private $unlockStatements = array();
|
Chris@0
|
134
|
Chris@0
|
135 /**
|
Chris@0
|
136 * @var bool True when the current session exists but expired according to session.gc_maxlifetime
|
Chris@0
|
137 */
|
Chris@0
|
138 private $sessionExpired = false;
|
Chris@0
|
139
|
Chris@0
|
140 /**
|
Chris@0
|
141 * @var bool Whether a transaction is active
|
Chris@0
|
142 */
|
Chris@0
|
143 private $inTransaction = false;
|
Chris@0
|
144
|
Chris@0
|
145 /**
|
Chris@0
|
146 * @var bool Whether gc() has been called
|
Chris@0
|
147 */
|
Chris@0
|
148 private $gcCalled = false;
|
Chris@0
|
149
|
Chris@0
|
150 /**
|
Chris@0
|
151 * Constructor.
|
Chris@0
|
152 *
|
Chris@0
|
153 * You can either pass an existing database connection as PDO instance or
|
Chris@0
|
154 * pass a DSN string that will be used to lazy-connect to the database
|
Chris@0
|
155 * when the session is actually used. Furthermore it's possible to pass null
|
Chris@0
|
156 * which will then use the session.save_path ini setting as PDO DSN parameter.
|
Chris@0
|
157 *
|
Chris@0
|
158 * List of available options:
|
Chris@0
|
159 * * db_table: The name of the table [default: sessions]
|
Chris@0
|
160 * * db_id_col: The column where to store the session id [default: sess_id]
|
Chris@0
|
161 * * db_data_col: The column where to store the session data [default: sess_data]
|
Chris@0
|
162 * * db_lifetime_col: The column where to store the lifetime [default: sess_lifetime]
|
Chris@0
|
163 * * db_time_col: The column where to store the timestamp [default: sess_time]
|
Chris@0
|
164 * * db_username: The username when lazy-connect [default: '']
|
Chris@0
|
165 * * db_password: The password when lazy-connect [default: '']
|
Chris@0
|
166 * * db_connection_options: An array of driver-specific connection options [default: array()]
|
Chris@0
|
167 * * lock_mode: The strategy for locking, see constants [default: LOCK_TRANSACTIONAL]
|
Chris@0
|
168 *
|
Chris@0
|
169 * @param \PDO|string|null $pdoOrDsn A \PDO instance or DSN string or null
|
Chris@0
|
170 * @param array $options An associative array of options
|
Chris@0
|
171 *
|
Chris@0
|
172 * @throws \InvalidArgumentException When PDO error mode is not PDO::ERRMODE_EXCEPTION
|
Chris@0
|
173 */
|
Chris@0
|
174 public function __construct($pdoOrDsn = null, array $options = array())
|
Chris@0
|
175 {
|
Chris@0
|
176 if ($pdoOrDsn instanceof \PDO) {
|
Chris@0
|
177 if (\PDO::ERRMODE_EXCEPTION !== $pdoOrDsn->getAttribute(\PDO::ATTR_ERRMODE)) {
|
Chris@0
|
178 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__));
|
Chris@0
|
179 }
|
Chris@0
|
180
|
Chris@0
|
181 $this->pdo = $pdoOrDsn;
|
Chris@0
|
182 $this->driver = $this->pdo->getAttribute(\PDO::ATTR_DRIVER_NAME);
|
Chris@0
|
183 } else {
|
Chris@0
|
184 $this->dsn = $pdoOrDsn;
|
Chris@0
|
185 }
|
Chris@0
|
186
|
Chris@0
|
187 $this->table = isset($options['db_table']) ? $options['db_table'] : $this->table;
|
Chris@0
|
188 $this->idCol = isset($options['db_id_col']) ? $options['db_id_col'] : $this->idCol;
|
Chris@0
|
189 $this->dataCol = isset($options['db_data_col']) ? $options['db_data_col'] : $this->dataCol;
|
Chris@0
|
190 $this->lifetimeCol = isset($options['db_lifetime_col']) ? $options['db_lifetime_col'] : $this->lifetimeCol;
|
Chris@0
|
191 $this->timeCol = isset($options['db_time_col']) ? $options['db_time_col'] : $this->timeCol;
|
Chris@0
|
192 $this->username = isset($options['db_username']) ? $options['db_username'] : $this->username;
|
Chris@0
|
193 $this->password = isset($options['db_password']) ? $options['db_password'] : $this->password;
|
Chris@0
|
194 $this->connectionOptions = isset($options['db_connection_options']) ? $options['db_connection_options'] : $this->connectionOptions;
|
Chris@0
|
195 $this->lockMode = isset($options['lock_mode']) ? $options['lock_mode'] : $this->lockMode;
|
Chris@0
|
196 }
|
Chris@0
|
197
|
Chris@0
|
198 /**
|
Chris@0
|
199 * Creates the table to store sessions which can be called once for setup.
|
Chris@0
|
200 *
|
Chris@0
|
201 * Session ID is saved in a column of maximum length 128 because that is enough even
|
Chris@0
|
202 * for a 512 bit configured session.hash_function like Whirlpool. Session data is
|
Chris@0
|
203 * saved in a BLOB. One could also use a shorter inlined varbinary column
|
Chris@0
|
204 * if one was sure the data fits into it.
|
Chris@0
|
205 *
|
Chris@0
|
206 * @throws \PDOException When the table already exists
|
Chris@0
|
207 * @throws \DomainException When an unsupported PDO driver is used
|
Chris@0
|
208 */
|
Chris@0
|
209 public function createTable()
|
Chris@0
|
210 {
|
Chris@0
|
211 // connect if we are not yet
|
Chris@0
|
212 $this->getConnection();
|
Chris@0
|
213
|
Chris@0
|
214 switch ($this->driver) {
|
Chris@0
|
215 case 'mysql':
|
Chris@0
|
216 // We use varbinary for the ID column because it prevents unwanted conversions:
|
Chris@0
|
217 // - character set conversions between server and client
|
Chris@0
|
218 // - trailing space removal
|
Chris@0
|
219 // - case-insensitivity
|
Chris@0
|
220 // - language processing like é == e
|
Chris@0
|
221 $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";
|
Chris@0
|
222 break;
|
Chris@0
|
223 case 'sqlite':
|
Chris@0
|
224 $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)";
|
Chris@0
|
225 break;
|
Chris@0
|
226 case 'pgsql':
|
Chris@0
|
227 $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)";
|
Chris@0
|
228 break;
|
Chris@0
|
229 case 'oci':
|
Chris@0
|
230 $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)";
|
Chris@0
|
231 break;
|
Chris@0
|
232 case 'sqlsrv':
|
Chris@0
|
233 $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)";
|
Chris@0
|
234 break;
|
Chris@0
|
235 default:
|
Chris@0
|
236 throw new \DomainException(sprintf('Creating the session table is currently not implemented for PDO driver "%s".', $this->driver));
|
Chris@0
|
237 }
|
Chris@0
|
238
|
Chris@0
|
239 try {
|
Chris@0
|
240 $this->pdo->exec($sql);
|
Chris@0
|
241 } catch (\PDOException $e) {
|
Chris@0
|
242 $this->rollback();
|
Chris@0
|
243
|
Chris@0
|
244 throw $e;
|
Chris@0
|
245 }
|
Chris@0
|
246 }
|
Chris@0
|
247
|
Chris@0
|
248 /**
|
Chris@0
|
249 * Returns true when the current session exists but expired according to session.gc_maxlifetime.
|
Chris@0
|
250 *
|
Chris@0
|
251 * Can be used to distinguish between a new session and one that expired due to inactivity.
|
Chris@0
|
252 *
|
Chris@0
|
253 * @return bool Whether current session expired
|
Chris@0
|
254 */
|
Chris@0
|
255 public function isSessionExpired()
|
Chris@0
|
256 {
|
Chris@0
|
257 return $this->sessionExpired;
|
Chris@0
|
258 }
|
Chris@0
|
259
|
Chris@0
|
260 /**
|
Chris@0
|
261 * {@inheritdoc}
|
Chris@0
|
262 */
|
Chris@0
|
263 public function open($savePath, $sessionName)
|
Chris@0
|
264 {
|
Chris@0
|
265 if (null === $this->pdo) {
|
Chris@0
|
266 $this->connect($this->dsn ?: $savePath);
|
Chris@0
|
267 }
|
Chris@0
|
268
|
Chris@0
|
269 return true;
|
Chris@0
|
270 }
|
Chris@0
|
271
|
Chris@0
|
272 /**
|
Chris@0
|
273 * {@inheritdoc}
|
Chris@0
|
274 */
|
Chris@0
|
275 public function read($sessionId)
|
Chris@0
|
276 {
|
Chris@0
|
277 try {
|
Chris@0
|
278 return $this->doRead($sessionId);
|
Chris@0
|
279 } catch (\PDOException $e) {
|
Chris@0
|
280 $this->rollback();
|
Chris@0
|
281
|
Chris@0
|
282 throw $e;
|
Chris@0
|
283 }
|
Chris@0
|
284 }
|
Chris@0
|
285
|
Chris@0
|
286 /**
|
Chris@0
|
287 * {@inheritdoc}
|
Chris@0
|
288 */
|
Chris@0
|
289 public function gc($maxlifetime)
|
Chris@0
|
290 {
|
Chris@0
|
291 // We delay gc() to close() so that it is executed outside the transactional and blocking read-write process.
|
Chris@0
|
292 // This way, pruning expired sessions does not block them from being started while the current session is used.
|
Chris@0
|
293 $this->gcCalled = true;
|
Chris@0
|
294
|
Chris@0
|
295 return true;
|
Chris@0
|
296 }
|
Chris@0
|
297
|
Chris@0
|
298 /**
|
Chris@0
|
299 * {@inheritdoc}
|
Chris@0
|
300 */
|
Chris@0
|
301 public function destroy($sessionId)
|
Chris@0
|
302 {
|
Chris@0
|
303 // delete the record associated with this id
|
Chris@0
|
304 $sql = "DELETE FROM $this->table WHERE $this->idCol = :id";
|
Chris@0
|
305
|
Chris@0
|
306 try {
|
Chris@0
|
307 $stmt = $this->pdo->prepare($sql);
|
Chris@0
|
308 $stmt->bindParam(':id', $sessionId, \PDO::PARAM_STR);
|
Chris@0
|
309 $stmt->execute();
|
Chris@0
|
310 } catch (\PDOException $e) {
|
Chris@0
|
311 $this->rollback();
|
Chris@0
|
312
|
Chris@0
|
313 throw $e;
|
Chris@0
|
314 }
|
Chris@0
|
315
|
Chris@0
|
316 return true;
|
Chris@0
|
317 }
|
Chris@0
|
318
|
Chris@0
|
319 /**
|
Chris@0
|
320 * {@inheritdoc}
|
Chris@0
|
321 */
|
Chris@0
|
322 public function write($sessionId, $data)
|
Chris@0
|
323 {
|
Chris@0
|
324 $maxlifetime = (int) ini_get('session.gc_maxlifetime');
|
Chris@0
|
325
|
Chris@0
|
326 try {
|
Chris@0
|
327 // We use a single MERGE SQL query when supported by the database.
|
Chris@0
|
328 $mergeStmt = $this->getMergeStatement($sessionId, $data, $maxlifetime);
|
Chris@0
|
329 if (null !== $mergeStmt) {
|
Chris@0
|
330 $mergeStmt->execute();
|
Chris@0
|
331
|
Chris@0
|
332 return true;
|
Chris@0
|
333 }
|
Chris@0
|
334
|
Chris@0
|
335 $updateStmt = $this->pdo->prepare(
|
Chris@0
|
336 "UPDATE $this->table SET $this->dataCol = :data, $this->lifetimeCol = :lifetime, $this->timeCol = :time WHERE $this->idCol = :id"
|
Chris@0
|
337 );
|
Chris@0
|
338 $updateStmt->bindParam(':id', $sessionId, \PDO::PARAM_STR);
|
Chris@0
|
339 $updateStmt->bindParam(':data', $data, \PDO::PARAM_LOB);
|
Chris@0
|
340 $updateStmt->bindParam(':lifetime', $maxlifetime, \PDO::PARAM_INT);
|
Chris@0
|
341 $updateStmt->bindValue(':time', time(), \PDO::PARAM_INT);
|
Chris@0
|
342 $updateStmt->execute();
|
Chris@0
|
343
|
Chris@0
|
344 // When MERGE is not supported, like in Postgres < 9.5, we have to use this approach that can result in
|
Chris@0
|
345 // duplicate key errors when the same session is written simultaneously (given the LOCK_NONE behavior).
|
Chris@0
|
346 // We can just catch such an error and re-execute the update. This is similar to a serializable
|
Chris@0
|
347 // transaction with retry logic on serialization failures but without the overhead and without possible
|
Chris@0
|
348 // false positives due to longer gap locking.
|
Chris@0
|
349 if (!$updateStmt->rowCount()) {
|
Chris@0
|
350 try {
|
Chris@0
|
351 $insertStmt = $this->pdo->prepare(
|
Chris@0
|
352 "INSERT INTO $this->table ($this->idCol, $this->dataCol, $this->lifetimeCol, $this->timeCol) VALUES (:id, :data, :lifetime, :time)"
|
Chris@0
|
353 );
|
Chris@0
|
354 $insertStmt->bindParam(':id', $sessionId, \PDO::PARAM_STR);
|
Chris@0
|
355 $insertStmt->bindParam(':data', $data, \PDO::PARAM_LOB);
|
Chris@0
|
356 $insertStmt->bindParam(':lifetime', $maxlifetime, \PDO::PARAM_INT);
|
Chris@0
|
357 $insertStmt->bindValue(':time', time(), \PDO::PARAM_INT);
|
Chris@0
|
358 $insertStmt->execute();
|
Chris@0
|
359 } catch (\PDOException $e) {
|
Chris@0
|
360 // Handle integrity violation SQLSTATE 23000 (or a subclass like 23505 in Postgres) for duplicate keys
|
Chris@0
|
361 if (0 === strpos($e->getCode(), '23')) {
|
Chris@0
|
362 $updateStmt->execute();
|
Chris@0
|
363 } else {
|
Chris@0
|
364 throw $e;
|
Chris@0
|
365 }
|
Chris@0
|
366 }
|
Chris@0
|
367 }
|
Chris@0
|
368 } catch (\PDOException $e) {
|
Chris@0
|
369 $this->rollback();
|
Chris@0
|
370
|
Chris@0
|
371 throw $e;
|
Chris@0
|
372 }
|
Chris@0
|
373
|
Chris@0
|
374 return true;
|
Chris@0
|
375 }
|
Chris@0
|
376
|
Chris@0
|
377 /**
|
Chris@0
|
378 * {@inheritdoc}
|
Chris@0
|
379 */
|
Chris@0
|
380 public function close()
|
Chris@0
|
381 {
|
Chris@0
|
382 $this->commit();
|
Chris@0
|
383
|
Chris@0
|
384 while ($unlockStmt = array_shift($this->unlockStatements)) {
|
Chris@0
|
385 $unlockStmt->execute();
|
Chris@0
|
386 }
|
Chris@0
|
387
|
Chris@0
|
388 if ($this->gcCalled) {
|
Chris@0
|
389 $this->gcCalled = false;
|
Chris@0
|
390
|
Chris@0
|
391 // delete the session records that have expired
|
Chris@0
|
392 $sql = "DELETE FROM $this->table WHERE $this->lifetimeCol + $this->timeCol < :time";
|
Chris@0
|
393
|
Chris@0
|
394 $stmt = $this->pdo->prepare($sql);
|
Chris@0
|
395 $stmt->bindValue(':time', time(), \PDO::PARAM_INT);
|
Chris@0
|
396 $stmt->execute();
|
Chris@0
|
397 }
|
Chris@0
|
398
|
Chris@0
|
399 if (false !== $this->dsn) {
|
Chris@0
|
400 $this->pdo = null; // only close lazy-connection
|
Chris@0
|
401 }
|
Chris@0
|
402
|
Chris@0
|
403 return true;
|
Chris@0
|
404 }
|
Chris@0
|
405
|
Chris@0
|
406 /**
|
Chris@0
|
407 * Lazy-connects to the database.
|
Chris@0
|
408 *
|
Chris@0
|
409 * @param string $dsn DSN string
|
Chris@0
|
410 */
|
Chris@0
|
411 private function connect($dsn)
|
Chris@0
|
412 {
|
Chris@0
|
413 $this->pdo = new \PDO($dsn, $this->username, $this->password, $this->connectionOptions);
|
Chris@0
|
414 $this->pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
|
Chris@0
|
415 $this->driver = $this->pdo->getAttribute(\PDO::ATTR_DRIVER_NAME);
|
Chris@0
|
416 }
|
Chris@0
|
417
|
Chris@0
|
418 /**
|
Chris@0
|
419 * Helper method to begin a transaction.
|
Chris@0
|
420 *
|
Chris@0
|
421 * Since SQLite does not support row level locks, we have to acquire a reserved lock
|
Chris@0
|
422 * on the database immediately. Because of https://bugs.php.net/42766 we have to create
|
Chris@0
|
423 * such a transaction manually which also means we cannot use PDO::commit or
|
Chris@0
|
424 * PDO::rollback or PDO::inTransaction for SQLite.
|
Chris@0
|
425 *
|
Chris@0
|
426 * Also MySQLs default isolation, REPEATABLE READ, causes deadlock for different sessions
|
Chris@0
|
427 * due to http://www.mysqlperformanceblog.com/2013/12/12/one-more-innodb-gap-lock-to-avoid/ .
|
Chris@0
|
428 * So we change it to READ COMMITTED.
|
Chris@0
|
429 */
|
Chris@0
|
430 private function beginTransaction()
|
Chris@0
|
431 {
|
Chris@0
|
432 if (!$this->inTransaction) {
|
Chris@0
|
433 if ('sqlite' === $this->driver) {
|
Chris@0
|
434 $this->pdo->exec('BEGIN IMMEDIATE TRANSACTION');
|
Chris@0
|
435 } else {
|
Chris@0
|
436 if ('mysql' === $this->driver) {
|
Chris@0
|
437 $this->pdo->exec('SET TRANSACTION ISOLATION LEVEL READ COMMITTED');
|
Chris@0
|
438 }
|
Chris@0
|
439 $this->pdo->beginTransaction();
|
Chris@0
|
440 }
|
Chris@0
|
441 $this->inTransaction = true;
|
Chris@0
|
442 }
|
Chris@0
|
443 }
|
Chris@0
|
444
|
Chris@0
|
445 /**
|
Chris@0
|
446 * Helper method to commit a transaction.
|
Chris@0
|
447 */
|
Chris@0
|
448 private function commit()
|
Chris@0
|
449 {
|
Chris@0
|
450 if ($this->inTransaction) {
|
Chris@0
|
451 try {
|
Chris@0
|
452 // commit read-write transaction which also releases the lock
|
Chris@0
|
453 if ('sqlite' === $this->driver) {
|
Chris@0
|
454 $this->pdo->exec('COMMIT');
|
Chris@0
|
455 } else {
|
Chris@0
|
456 $this->pdo->commit();
|
Chris@0
|
457 }
|
Chris@0
|
458 $this->inTransaction = false;
|
Chris@0
|
459 } catch (\PDOException $e) {
|
Chris@0
|
460 $this->rollback();
|
Chris@0
|
461
|
Chris@0
|
462 throw $e;
|
Chris@0
|
463 }
|
Chris@0
|
464 }
|
Chris@0
|
465 }
|
Chris@0
|
466
|
Chris@0
|
467 /**
|
Chris@0
|
468 * Helper method to rollback a transaction.
|
Chris@0
|
469 */
|
Chris@0
|
470 private function rollback()
|
Chris@0
|
471 {
|
Chris@0
|
472 // We only need to rollback if we are in a transaction. Otherwise the resulting
|
Chris@0
|
473 // error would hide the real problem why rollback was called. We might not be
|
Chris@0
|
474 // in a transaction when not using the transactional locking behavior or when
|
Chris@0
|
475 // two callbacks (e.g. destroy and write) are invoked that both fail.
|
Chris@0
|
476 if ($this->inTransaction) {
|
Chris@0
|
477 if ('sqlite' === $this->driver) {
|
Chris@0
|
478 $this->pdo->exec('ROLLBACK');
|
Chris@0
|
479 } else {
|
Chris@0
|
480 $this->pdo->rollBack();
|
Chris@0
|
481 }
|
Chris@0
|
482 $this->inTransaction = false;
|
Chris@0
|
483 }
|
Chris@0
|
484 }
|
Chris@0
|
485
|
Chris@0
|
486 /**
|
Chris@0
|
487 * Reads the session data in respect to the different locking strategies.
|
Chris@0
|
488 *
|
Chris@0
|
489 * We need to make sure we do not return session data that is already considered garbage according
|
Chris@0
|
490 * to the session.gc_maxlifetime setting because gc() is called after read() and only sometimes.
|
Chris@0
|
491 *
|
Chris@0
|
492 * @param string $sessionId Session ID
|
Chris@0
|
493 *
|
Chris@0
|
494 * @return string The session data
|
Chris@0
|
495 */
|
Chris@0
|
496 private function doRead($sessionId)
|
Chris@0
|
497 {
|
Chris@0
|
498 $this->sessionExpired = false;
|
Chris@0
|
499
|
Chris@0
|
500 if (self::LOCK_ADVISORY === $this->lockMode) {
|
Chris@0
|
501 $this->unlockStatements[] = $this->doAdvisoryLock($sessionId);
|
Chris@0
|
502 }
|
Chris@0
|
503
|
Chris@0
|
504 $selectSql = $this->getSelectSql();
|
Chris@0
|
505 $selectStmt = $this->pdo->prepare($selectSql);
|
Chris@0
|
506 $selectStmt->bindParam(':id', $sessionId, \PDO::PARAM_STR);
|
Chris@0
|
507
|
Chris@0
|
508 do {
|
Chris@0
|
509 $selectStmt->execute();
|
Chris@0
|
510 $sessionRows = $selectStmt->fetchAll(\PDO::FETCH_NUM);
|
Chris@0
|
511
|
Chris@0
|
512 if ($sessionRows) {
|
Chris@0
|
513 if ($sessionRows[0][1] + $sessionRows[0][2] < time()) {
|
Chris@0
|
514 $this->sessionExpired = true;
|
Chris@0
|
515
|
Chris@0
|
516 return '';
|
Chris@0
|
517 }
|
Chris@0
|
518
|
Chris@0
|
519 return is_resource($sessionRows[0][0]) ? stream_get_contents($sessionRows[0][0]) : $sessionRows[0][0];
|
Chris@0
|
520 }
|
Chris@0
|
521
|
Chris@0
|
522 if (self::LOCK_TRANSACTIONAL === $this->lockMode && 'sqlite' !== $this->driver) {
|
Chris@0
|
523 // Exclusive-reading of non-existent rows does not block, so we need to do an insert to block
|
Chris@0
|
524 // until other connections to the session are committed.
|
Chris@0
|
525 try {
|
Chris@0
|
526 $insertStmt = $this->pdo->prepare(
|
Chris@0
|
527 "INSERT INTO $this->table ($this->idCol, $this->dataCol, $this->lifetimeCol, $this->timeCol) VALUES (:id, :data, :lifetime, :time)"
|
Chris@0
|
528 );
|
Chris@0
|
529 $insertStmt->bindParam(':id', $sessionId, \PDO::PARAM_STR);
|
Chris@0
|
530 $insertStmt->bindValue(':data', '', \PDO::PARAM_LOB);
|
Chris@0
|
531 $insertStmt->bindValue(':lifetime', 0, \PDO::PARAM_INT);
|
Chris@0
|
532 $insertStmt->bindValue(':time', time(), \PDO::PARAM_INT);
|
Chris@0
|
533 $insertStmt->execute();
|
Chris@0
|
534 } catch (\PDOException $e) {
|
Chris@0
|
535 // Catch duplicate key error because other connection created the session already.
|
Chris@0
|
536 // It would only not be the case when the other connection destroyed the session.
|
Chris@0
|
537 if (0 === strpos($e->getCode(), '23')) {
|
Chris@0
|
538 // Retrieve finished session data written by concurrent connection by restarting the loop.
|
Chris@0
|
539 // We have to start a new transaction as a failed query will mark the current transaction as
|
Chris@0
|
540 // aborted in PostgreSQL and disallow further queries within it.
|
Chris@0
|
541 $this->rollback();
|
Chris@0
|
542 $this->beginTransaction();
|
Chris@0
|
543 continue;
|
Chris@0
|
544 }
|
Chris@0
|
545
|
Chris@0
|
546 throw $e;
|
Chris@0
|
547 }
|
Chris@0
|
548 }
|
Chris@0
|
549
|
Chris@0
|
550 return '';
|
Chris@0
|
551 } while (true);
|
Chris@0
|
552 }
|
Chris@0
|
553
|
Chris@0
|
554 /**
|
Chris@0
|
555 * Executes an application-level lock on the database.
|
Chris@0
|
556 *
|
Chris@0
|
557 * @param string $sessionId Session ID
|
Chris@0
|
558 *
|
Chris@0
|
559 * @return \PDOStatement The statement that needs to be executed later to release the lock
|
Chris@0
|
560 *
|
Chris@0
|
561 * @throws \DomainException When an unsupported PDO driver is used
|
Chris@0
|
562 *
|
Chris@0
|
563 * @todo implement missing advisory locks
|
Chris@0
|
564 * - for oci using DBMS_LOCK.REQUEST
|
Chris@0
|
565 * - for sqlsrv using sp_getapplock with LockOwner = Session
|
Chris@0
|
566 */
|
Chris@0
|
567 private function doAdvisoryLock($sessionId)
|
Chris@0
|
568 {
|
Chris@0
|
569 switch ($this->driver) {
|
Chris@0
|
570 case 'mysql':
|
Chris@0
|
571 // should we handle the return value? 0 on timeout, null on error
|
Chris@0
|
572 // we use a timeout of 50 seconds which is also the default for innodb_lock_wait_timeout
|
Chris@0
|
573 $stmt = $this->pdo->prepare('SELECT GET_LOCK(:key, 50)');
|
Chris@0
|
574 $stmt->bindValue(':key', $sessionId, \PDO::PARAM_STR);
|
Chris@0
|
575 $stmt->execute();
|
Chris@0
|
576
|
Chris@0
|
577 $releaseStmt = $this->pdo->prepare('DO RELEASE_LOCK(:key)');
|
Chris@0
|
578 $releaseStmt->bindValue(':key', $sessionId, \PDO::PARAM_STR);
|
Chris@0
|
579
|
Chris@0
|
580 return $releaseStmt;
|
Chris@0
|
581 case 'pgsql':
|
Chris@0
|
582 // Obtaining an exclusive session level advisory lock requires an integer key.
|
Chris@0
|
583 // So we convert the HEX representation of the session id to an integer.
|
Chris@0
|
584 // Since integers are signed, we have to skip one hex char to fit in the range.
|
Chris@0
|
585 if (4 === PHP_INT_SIZE) {
|
Chris@0
|
586 $sessionInt1 = hexdec(substr($sessionId, 0, 7));
|
Chris@0
|
587 $sessionInt2 = hexdec(substr($sessionId, 7, 7));
|
Chris@0
|
588
|
Chris@0
|
589 $stmt = $this->pdo->prepare('SELECT pg_advisory_lock(:key1, :key2)');
|
Chris@0
|
590 $stmt->bindValue(':key1', $sessionInt1, \PDO::PARAM_INT);
|
Chris@0
|
591 $stmt->bindValue(':key2', $sessionInt2, \PDO::PARAM_INT);
|
Chris@0
|
592 $stmt->execute();
|
Chris@0
|
593
|
Chris@0
|
594 $releaseStmt = $this->pdo->prepare('SELECT pg_advisory_unlock(:key1, :key2)');
|
Chris@0
|
595 $releaseStmt->bindValue(':key1', $sessionInt1, \PDO::PARAM_INT);
|
Chris@0
|
596 $releaseStmt->bindValue(':key2', $sessionInt2, \PDO::PARAM_INT);
|
Chris@0
|
597 } else {
|
Chris@0
|
598 $sessionBigInt = hexdec(substr($sessionId, 0, 15));
|
Chris@0
|
599
|
Chris@0
|
600 $stmt = $this->pdo->prepare('SELECT pg_advisory_lock(:key)');
|
Chris@0
|
601 $stmt->bindValue(':key', $sessionBigInt, \PDO::PARAM_INT);
|
Chris@0
|
602 $stmt->execute();
|
Chris@0
|
603
|
Chris@0
|
604 $releaseStmt = $this->pdo->prepare('SELECT pg_advisory_unlock(:key)');
|
Chris@0
|
605 $releaseStmt->bindValue(':key', $sessionBigInt, \PDO::PARAM_INT);
|
Chris@0
|
606 }
|
Chris@0
|
607
|
Chris@0
|
608 return $releaseStmt;
|
Chris@0
|
609 case 'sqlite':
|
Chris@0
|
610 throw new \DomainException('SQLite does not support advisory locks.');
|
Chris@0
|
611 default:
|
Chris@0
|
612 throw new \DomainException(sprintf('Advisory locks are currently not implemented for PDO driver "%s".', $this->driver));
|
Chris@0
|
613 }
|
Chris@0
|
614 }
|
Chris@0
|
615
|
Chris@0
|
616 /**
|
Chris@0
|
617 * Return a locking or nonlocking SQL query to read session information.
|
Chris@0
|
618 *
|
Chris@0
|
619 * @return string The SQL string
|
Chris@0
|
620 *
|
Chris@0
|
621 * @throws \DomainException When an unsupported PDO driver is used
|
Chris@0
|
622 */
|
Chris@0
|
623 private function getSelectSql()
|
Chris@0
|
624 {
|
Chris@0
|
625 if (self::LOCK_TRANSACTIONAL === $this->lockMode) {
|
Chris@0
|
626 $this->beginTransaction();
|
Chris@0
|
627
|
Chris@0
|
628 switch ($this->driver) {
|
Chris@0
|
629 case 'mysql':
|
Chris@0
|
630 case 'oci':
|
Chris@0
|
631 case 'pgsql':
|
Chris@0
|
632 return "SELECT $this->dataCol, $this->lifetimeCol, $this->timeCol FROM $this->table WHERE $this->idCol = :id FOR UPDATE";
|
Chris@0
|
633 case 'sqlsrv':
|
Chris@0
|
634 return "SELECT $this->dataCol, $this->lifetimeCol, $this->timeCol FROM $this->table WITH (UPDLOCK, ROWLOCK) WHERE $this->idCol = :id";
|
Chris@0
|
635 case 'sqlite':
|
Chris@0
|
636 // we already locked when starting transaction
|
Chris@0
|
637 break;
|
Chris@0
|
638 default:
|
Chris@0
|
639 throw new \DomainException(sprintf('Transactional locks are currently not implemented for PDO driver "%s".', $this->driver));
|
Chris@0
|
640 }
|
Chris@0
|
641 }
|
Chris@0
|
642
|
Chris@0
|
643 return "SELECT $this->dataCol, $this->lifetimeCol, $this->timeCol FROM $this->table WHERE $this->idCol = :id";
|
Chris@0
|
644 }
|
Chris@0
|
645
|
Chris@0
|
646 /**
|
Chris@0
|
647 * Returns a merge/upsert (i.e. insert or update) statement when supported by the database for writing session data.
|
Chris@0
|
648 *
|
Chris@0
|
649 * @param string $sessionId Session ID
|
Chris@0
|
650 * @param string $data Encoded session data
|
Chris@0
|
651 * @param int $maxlifetime session.gc_maxlifetime
|
Chris@0
|
652 *
|
Chris@0
|
653 * @return \PDOStatement|null The merge statement or null when not supported
|
Chris@0
|
654 */
|
Chris@0
|
655 private function getMergeStatement($sessionId, $data, $maxlifetime)
|
Chris@0
|
656 {
|
Chris@0
|
657 $mergeSql = null;
|
Chris@0
|
658 switch (true) {
|
Chris@0
|
659 case 'mysql' === $this->driver:
|
Chris@0
|
660 $mergeSql = "INSERT INTO $this->table ($this->idCol, $this->dataCol, $this->lifetimeCol, $this->timeCol) VALUES (:id, :data, :lifetime, :time) ".
|
Chris@0
|
661 "ON DUPLICATE KEY UPDATE $this->dataCol = VALUES($this->dataCol), $this->lifetimeCol = VALUES($this->lifetimeCol), $this->timeCol = VALUES($this->timeCol)";
|
Chris@0
|
662 break;
|
Chris@0
|
663 case 'oci' === $this->driver:
|
Chris@0
|
664 // DUAL is Oracle specific dummy table
|
Chris@0
|
665 $mergeSql = "MERGE INTO $this->table USING DUAL ON ($this->idCol = ?) ".
|
Chris@0
|
666 "WHEN NOT MATCHED THEN INSERT ($this->idCol, $this->dataCol, $this->lifetimeCol, $this->timeCol) VALUES (?, ?, ?, ?) ".
|
Chris@0
|
667 "WHEN MATCHED THEN UPDATE SET $this->dataCol = ?, $this->lifetimeCol = ?, $this->timeCol = ?";
|
Chris@0
|
668 break;
|
Chris@0
|
669 case 'sqlsrv' === $this->driver && version_compare($this->pdo->getAttribute(\PDO::ATTR_SERVER_VERSION), '10', '>='):
|
Chris@0
|
670 // MERGE is only available since SQL Server 2008 and must be terminated by semicolon
|
Chris@0
|
671 // It also requires HOLDLOCK according to http://weblogs.sqlteam.com/dang/archive/2009/01/31/UPSERT-Race-Condition-With-MERGE.aspx
|
Chris@0
|
672 $mergeSql = "MERGE INTO $this->table WITH (HOLDLOCK) USING (SELECT 1 AS dummy) AS src ON ($this->idCol = ?) ".
|
Chris@0
|
673 "WHEN NOT MATCHED THEN INSERT ($this->idCol, $this->dataCol, $this->lifetimeCol, $this->timeCol) VALUES (?, ?, ?, ?) ".
|
Chris@0
|
674 "WHEN MATCHED THEN UPDATE SET $this->dataCol = ?, $this->lifetimeCol = ?, $this->timeCol = ?;";
|
Chris@0
|
675 break;
|
Chris@0
|
676 case 'sqlite' === $this->driver:
|
Chris@0
|
677 $mergeSql = "INSERT OR REPLACE INTO $this->table ($this->idCol, $this->dataCol, $this->lifetimeCol, $this->timeCol) VALUES (:id, :data, :lifetime, :time)";
|
Chris@0
|
678 break;
|
Chris@0
|
679 case 'pgsql' === $this->driver && version_compare($this->pdo->getAttribute(\PDO::ATTR_SERVER_VERSION), '9.5', '>='):
|
Chris@0
|
680 $mergeSql = "INSERT INTO $this->table ($this->idCol, $this->dataCol, $this->lifetimeCol, $this->timeCol) VALUES (:id, :data, :lifetime, :time) ".
|
Chris@0
|
681 "ON CONFLICT ($this->idCol) DO UPDATE SET ($this->dataCol, $this->lifetimeCol, $this->timeCol) = (EXCLUDED.$this->dataCol, EXCLUDED.$this->lifetimeCol, EXCLUDED.$this->timeCol)";
|
Chris@0
|
682 break;
|
Chris@0
|
683 }
|
Chris@0
|
684
|
Chris@0
|
685 if (null !== $mergeSql) {
|
Chris@0
|
686 $mergeStmt = $this->pdo->prepare($mergeSql);
|
Chris@0
|
687
|
Chris@0
|
688 if ('sqlsrv' === $this->driver || 'oci' === $this->driver) {
|
Chris@0
|
689 $mergeStmt->bindParam(1, $sessionId, \PDO::PARAM_STR);
|
Chris@0
|
690 $mergeStmt->bindParam(2, $sessionId, \PDO::PARAM_STR);
|
Chris@0
|
691 $mergeStmt->bindParam(3, $data, \PDO::PARAM_LOB);
|
Chris@0
|
692 $mergeStmt->bindParam(4, $maxlifetime, \PDO::PARAM_INT);
|
Chris@0
|
693 $mergeStmt->bindValue(5, time(), \PDO::PARAM_INT);
|
Chris@0
|
694 $mergeStmt->bindParam(6, $data, \PDO::PARAM_LOB);
|
Chris@0
|
695 $mergeStmt->bindParam(7, $maxlifetime, \PDO::PARAM_INT);
|
Chris@0
|
696 $mergeStmt->bindValue(8, time(), \PDO::PARAM_INT);
|
Chris@0
|
697 } else {
|
Chris@0
|
698 $mergeStmt->bindParam(':id', $sessionId, \PDO::PARAM_STR);
|
Chris@0
|
699 $mergeStmt->bindParam(':data', $data, \PDO::PARAM_LOB);
|
Chris@0
|
700 $mergeStmt->bindParam(':lifetime', $maxlifetime, \PDO::PARAM_INT);
|
Chris@0
|
701 $mergeStmt->bindValue(':time', time(), \PDO::PARAM_INT);
|
Chris@0
|
702 }
|
Chris@0
|
703
|
Chris@0
|
704 return $mergeStmt;
|
Chris@0
|
705 }
|
Chris@0
|
706 }
|
Chris@0
|
707
|
Chris@0
|
708 /**
|
Chris@0
|
709 * Return a PDO instance.
|
Chris@0
|
710 *
|
Chris@0
|
711 * @return \PDO
|
Chris@0
|
712 */
|
Chris@0
|
713 protected function getConnection()
|
Chris@0
|
714 {
|
Chris@0
|
715 if (null === $this->pdo) {
|
Chris@0
|
716 $this->connect($this->dsn ?: ini_get('session.save_path'));
|
Chris@0
|
717 }
|
Chris@0
|
718
|
Chris@0
|
719 return $this->pdo;
|
Chris@0
|
720 }
|
Chris@0
|
721 }
|