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@14
|
41 class PdoSessionHandler extends AbstractSessionHandler
|
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@17
|
74 * @var string|false|null 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@17
|
121 private $connectionOptions = [];
|
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@17
|
133 private $unlockStatements = [];
|
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 * You can either pass an existing database connection as PDO instance or
|
Chris@0
|
152 * pass a DSN string that will be used to lazy-connect to the database
|
Chris@0
|
153 * when the session is actually used. Furthermore it's possible to pass null
|
Chris@0
|
154 * which will then use the session.save_path ini setting as PDO DSN parameter.
|
Chris@0
|
155 *
|
Chris@0
|
156 * List of available options:
|
Chris@0
|
157 * * db_table: The name of the table [default: sessions]
|
Chris@0
|
158 * * db_id_col: The column where to store the session id [default: sess_id]
|
Chris@0
|
159 * * db_data_col: The column where to store the session data [default: sess_data]
|
Chris@0
|
160 * * db_lifetime_col: The column where to store the lifetime [default: sess_lifetime]
|
Chris@0
|
161 * * db_time_col: The column where to store the timestamp [default: sess_time]
|
Chris@0
|
162 * * db_username: The username when lazy-connect [default: '']
|
Chris@0
|
163 * * db_password: The password when lazy-connect [default: '']
|
Chris@17
|
164 * * db_connection_options: An array of driver-specific connection options [default: []]
|
Chris@0
|
165 * * lock_mode: The strategy for locking, see constants [default: LOCK_TRANSACTIONAL]
|
Chris@0
|
166 *
|
Chris@14
|
167 * @param \PDO|string|null $pdoOrDsn A \PDO instance or DSN string or URL string or null
|
Chris@0
|
168 * @param array $options An associative array of options
|
Chris@0
|
169 *
|
Chris@0
|
170 * @throws \InvalidArgumentException When PDO error mode is not PDO::ERRMODE_EXCEPTION
|
Chris@0
|
171 */
|
Chris@17
|
172 public function __construct($pdoOrDsn = null, array $options = [])
|
Chris@0
|
173 {
|
Chris@0
|
174 if ($pdoOrDsn instanceof \PDO) {
|
Chris@0
|
175 if (\PDO::ERRMODE_EXCEPTION !== $pdoOrDsn->getAttribute(\PDO::ATTR_ERRMODE)) {
|
Chris@0
|
176 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
|
177 }
|
Chris@0
|
178
|
Chris@0
|
179 $this->pdo = $pdoOrDsn;
|
Chris@0
|
180 $this->driver = $this->pdo->getAttribute(\PDO::ATTR_DRIVER_NAME);
|
Chris@17
|
181 } elseif (\is_string($pdoOrDsn) && false !== strpos($pdoOrDsn, '://')) {
|
Chris@14
|
182 $this->dsn = $this->buildDsnFromUrl($pdoOrDsn);
|
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@14
|
265 $this->sessionExpired = false;
|
Chris@14
|
266
|
Chris@0
|
267 if (null === $this->pdo) {
|
Chris@0
|
268 $this->connect($this->dsn ?: $savePath);
|
Chris@0
|
269 }
|
Chris@0
|
270
|
Chris@14
|
271 return parent::open($savePath, $sessionName);
|
Chris@0
|
272 }
|
Chris@0
|
273
|
Chris@0
|
274 /**
|
Chris@0
|
275 * {@inheritdoc}
|
Chris@0
|
276 */
|
Chris@0
|
277 public function read($sessionId)
|
Chris@0
|
278 {
|
Chris@0
|
279 try {
|
Chris@14
|
280 return parent::read($sessionId);
|
Chris@0
|
281 } catch (\PDOException $e) {
|
Chris@0
|
282 $this->rollback();
|
Chris@0
|
283
|
Chris@0
|
284 throw $e;
|
Chris@0
|
285 }
|
Chris@0
|
286 }
|
Chris@0
|
287
|
Chris@0
|
288 /**
|
Chris@0
|
289 * {@inheritdoc}
|
Chris@0
|
290 */
|
Chris@0
|
291 public function gc($maxlifetime)
|
Chris@0
|
292 {
|
Chris@0
|
293 // We delay gc() to close() so that it is executed outside the transactional and blocking read-write process.
|
Chris@0
|
294 // This way, pruning expired sessions does not block them from being started while the current session is used.
|
Chris@0
|
295 $this->gcCalled = true;
|
Chris@0
|
296
|
Chris@0
|
297 return true;
|
Chris@0
|
298 }
|
Chris@0
|
299
|
Chris@0
|
300 /**
|
Chris@0
|
301 * {@inheritdoc}
|
Chris@0
|
302 */
|
Chris@14
|
303 protected function doDestroy($sessionId)
|
Chris@0
|
304 {
|
Chris@0
|
305 // delete the record associated with this id
|
Chris@0
|
306 $sql = "DELETE FROM $this->table WHERE $this->idCol = :id";
|
Chris@0
|
307
|
Chris@0
|
308 try {
|
Chris@0
|
309 $stmt = $this->pdo->prepare($sql);
|
Chris@0
|
310 $stmt->bindParam(':id', $sessionId, \PDO::PARAM_STR);
|
Chris@0
|
311 $stmt->execute();
|
Chris@0
|
312 } catch (\PDOException $e) {
|
Chris@0
|
313 $this->rollback();
|
Chris@0
|
314
|
Chris@0
|
315 throw $e;
|
Chris@0
|
316 }
|
Chris@0
|
317
|
Chris@0
|
318 return true;
|
Chris@0
|
319 }
|
Chris@0
|
320
|
Chris@0
|
321 /**
|
Chris@0
|
322 * {@inheritdoc}
|
Chris@0
|
323 */
|
Chris@14
|
324 protected function doWrite($sessionId, $data)
|
Chris@0
|
325 {
|
Chris@0
|
326 $maxlifetime = (int) ini_get('session.gc_maxlifetime');
|
Chris@0
|
327
|
Chris@0
|
328 try {
|
Chris@0
|
329 // We use a single MERGE SQL query when supported by the database.
|
Chris@0
|
330 $mergeStmt = $this->getMergeStatement($sessionId, $data, $maxlifetime);
|
Chris@0
|
331 if (null !== $mergeStmt) {
|
Chris@0
|
332 $mergeStmt->execute();
|
Chris@0
|
333
|
Chris@0
|
334 return true;
|
Chris@0
|
335 }
|
Chris@0
|
336
|
Chris@14
|
337 $updateStmt = $this->getUpdateStatement($sessionId, $data, $maxlifetime);
|
Chris@0
|
338 $updateStmt->execute();
|
Chris@0
|
339
|
Chris@0
|
340 // When MERGE is not supported, like in Postgres < 9.5, we have to use this approach that can result in
|
Chris@0
|
341 // duplicate key errors when the same session is written simultaneously (given the LOCK_NONE behavior).
|
Chris@0
|
342 // We can just catch such an error and re-execute the update. This is similar to a serializable
|
Chris@0
|
343 // transaction with retry logic on serialization failures but without the overhead and without possible
|
Chris@0
|
344 // false positives due to longer gap locking.
|
Chris@0
|
345 if (!$updateStmt->rowCount()) {
|
Chris@0
|
346 try {
|
Chris@14
|
347 $insertStmt = $this->getInsertStatement($sessionId, $data, $maxlifetime);
|
Chris@0
|
348 $insertStmt->execute();
|
Chris@0
|
349 } catch (\PDOException $e) {
|
Chris@0
|
350 // Handle integrity violation SQLSTATE 23000 (or a subclass like 23505 in Postgres) for duplicate keys
|
Chris@0
|
351 if (0 === strpos($e->getCode(), '23')) {
|
Chris@0
|
352 $updateStmt->execute();
|
Chris@0
|
353 } else {
|
Chris@0
|
354 throw $e;
|
Chris@0
|
355 }
|
Chris@0
|
356 }
|
Chris@0
|
357 }
|
Chris@0
|
358 } catch (\PDOException $e) {
|
Chris@0
|
359 $this->rollback();
|
Chris@0
|
360
|
Chris@0
|
361 throw $e;
|
Chris@0
|
362 }
|
Chris@0
|
363
|
Chris@0
|
364 return true;
|
Chris@0
|
365 }
|
Chris@0
|
366
|
Chris@0
|
367 /**
|
Chris@0
|
368 * {@inheritdoc}
|
Chris@0
|
369 */
|
Chris@14
|
370 public function updateTimestamp($sessionId, $data)
|
Chris@14
|
371 {
|
Chris@14
|
372 $maxlifetime = (int) ini_get('session.gc_maxlifetime');
|
Chris@14
|
373
|
Chris@14
|
374 try {
|
Chris@14
|
375 $updateStmt = $this->pdo->prepare(
|
Chris@14
|
376 "UPDATE $this->table SET $this->lifetimeCol = :lifetime, $this->timeCol = :time WHERE $this->idCol = :id"
|
Chris@14
|
377 );
|
Chris@14
|
378 $updateStmt->bindParam(':id', $sessionId, \PDO::PARAM_STR);
|
Chris@14
|
379 $updateStmt->bindParam(':lifetime', $maxlifetime, \PDO::PARAM_INT);
|
Chris@14
|
380 $updateStmt->bindValue(':time', time(), \PDO::PARAM_INT);
|
Chris@14
|
381 $updateStmt->execute();
|
Chris@14
|
382 } catch (\PDOException $e) {
|
Chris@14
|
383 $this->rollback();
|
Chris@14
|
384
|
Chris@14
|
385 throw $e;
|
Chris@14
|
386 }
|
Chris@14
|
387
|
Chris@14
|
388 return true;
|
Chris@14
|
389 }
|
Chris@14
|
390
|
Chris@14
|
391 /**
|
Chris@14
|
392 * {@inheritdoc}
|
Chris@14
|
393 */
|
Chris@0
|
394 public function close()
|
Chris@0
|
395 {
|
Chris@0
|
396 $this->commit();
|
Chris@0
|
397
|
Chris@0
|
398 while ($unlockStmt = array_shift($this->unlockStatements)) {
|
Chris@0
|
399 $unlockStmt->execute();
|
Chris@0
|
400 }
|
Chris@0
|
401
|
Chris@0
|
402 if ($this->gcCalled) {
|
Chris@0
|
403 $this->gcCalled = false;
|
Chris@0
|
404
|
Chris@0
|
405 // delete the session records that have expired
|
Chris@14
|
406 if ('mysql' === $this->driver) {
|
Chris@14
|
407 $sql = "DELETE FROM $this->table WHERE $this->lifetimeCol + $this->timeCol < :time";
|
Chris@14
|
408 } else {
|
Chris@14
|
409 $sql = "DELETE FROM $this->table WHERE $this->lifetimeCol < :time - $this->timeCol";
|
Chris@14
|
410 }
|
Chris@0
|
411
|
Chris@0
|
412 $stmt = $this->pdo->prepare($sql);
|
Chris@0
|
413 $stmt->bindValue(':time', time(), \PDO::PARAM_INT);
|
Chris@0
|
414 $stmt->execute();
|
Chris@0
|
415 }
|
Chris@0
|
416
|
Chris@0
|
417 if (false !== $this->dsn) {
|
Chris@0
|
418 $this->pdo = null; // only close lazy-connection
|
Chris@0
|
419 }
|
Chris@0
|
420
|
Chris@0
|
421 return true;
|
Chris@0
|
422 }
|
Chris@0
|
423
|
Chris@0
|
424 /**
|
Chris@0
|
425 * Lazy-connects to the database.
|
Chris@0
|
426 *
|
Chris@0
|
427 * @param string $dsn DSN string
|
Chris@0
|
428 */
|
Chris@0
|
429 private function connect($dsn)
|
Chris@0
|
430 {
|
Chris@0
|
431 $this->pdo = new \PDO($dsn, $this->username, $this->password, $this->connectionOptions);
|
Chris@0
|
432 $this->pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
|
Chris@0
|
433 $this->driver = $this->pdo->getAttribute(\PDO::ATTR_DRIVER_NAME);
|
Chris@0
|
434 }
|
Chris@0
|
435
|
Chris@0
|
436 /**
|
Chris@14
|
437 * Builds a PDO DSN from a URL-like connection string.
|
Chris@14
|
438 *
|
Chris@14
|
439 * @param string $dsnOrUrl
|
Chris@14
|
440 *
|
Chris@14
|
441 * @return string
|
Chris@14
|
442 *
|
Chris@14
|
443 * @todo implement missing support for oci DSN (which look totally different from other PDO ones)
|
Chris@14
|
444 */
|
Chris@14
|
445 private function buildDsnFromUrl($dsnOrUrl)
|
Chris@14
|
446 {
|
Chris@14
|
447 // (pdo_)?sqlite3?:///... => (pdo_)?sqlite3?://localhost/... or else the URL will be invalid
|
Chris@14
|
448 $url = preg_replace('#^((?:pdo_)?sqlite3?):///#', '$1://localhost/', $dsnOrUrl);
|
Chris@14
|
449
|
Chris@14
|
450 $params = parse_url($url);
|
Chris@14
|
451
|
Chris@14
|
452 if (false === $params) {
|
Chris@14
|
453 return $dsnOrUrl; // If the URL is not valid, let's assume it might be a DSN already.
|
Chris@14
|
454 }
|
Chris@14
|
455
|
Chris@14
|
456 $params = array_map('rawurldecode', $params);
|
Chris@14
|
457
|
Chris@14
|
458 // Override the default username and password. Values passed through options will still win over these in the constructor.
|
Chris@14
|
459 if (isset($params['user'])) {
|
Chris@14
|
460 $this->username = $params['user'];
|
Chris@14
|
461 }
|
Chris@14
|
462
|
Chris@14
|
463 if (isset($params['pass'])) {
|
Chris@14
|
464 $this->password = $params['pass'];
|
Chris@14
|
465 }
|
Chris@14
|
466
|
Chris@14
|
467 if (!isset($params['scheme'])) {
|
Chris@14
|
468 throw new \InvalidArgumentException('URLs without scheme are not supported to configure the PdoSessionHandler');
|
Chris@14
|
469 }
|
Chris@14
|
470
|
Chris@17
|
471 $driverAliasMap = [
|
Chris@14
|
472 'mssql' => 'sqlsrv',
|
Chris@14
|
473 'mysql2' => 'mysql', // Amazon RDS, for some weird reason
|
Chris@14
|
474 'postgres' => 'pgsql',
|
Chris@14
|
475 'postgresql' => 'pgsql',
|
Chris@14
|
476 'sqlite3' => 'sqlite',
|
Chris@17
|
477 ];
|
Chris@14
|
478
|
Chris@14
|
479 $driver = isset($driverAliasMap[$params['scheme']]) ? $driverAliasMap[$params['scheme']] : $params['scheme'];
|
Chris@14
|
480
|
Chris@14
|
481 // Doctrine DBAL supports passing its internal pdo_* driver names directly too (allowing both dashes and underscores). This allows supporting the same here.
|
Chris@14
|
482 if (0 === strpos($driver, 'pdo_') || 0 === strpos($driver, 'pdo-')) {
|
Chris@14
|
483 $driver = substr($driver, 4);
|
Chris@14
|
484 }
|
Chris@14
|
485
|
Chris@14
|
486 switch ($driver) {
|
Chris@14
|
487 case 'mysql':
|
Chris@14
|
488 case 'pgsql':
|
Chris@14
|
489 $dsn = $driver.':';
|
Chris@14
|
490
|
Chris@14
|
491 if (isset($params['host']) && '' !== $params['host']) {
|
Chris@14
|
492 $dsn .= 'host='.$params['host'].';';
|
Chris@14
|
493 }
|
Chris@14
|
494
|
Chris@14
|
495 if (isset($params['port']) && '' !== $params['port']) {
|
Chris@14
|
496 $dsn .= 'port='.$params['port'].';';
|
Chris@14
|
497 }
|
Chris@14
|
498
|
Chris@14
|
499 if (isset($params['path'])) {
|
Chris@14
|
500 $dbName = substr($params['path'], 1); // Remove the leading slash
|
Chris@14
|
501 $dsn .= 'dbname='.$dbName.';';
|
Chris@14
|
502 }
|
Chris@14
|
503
|
Chris@14
|
504 return $dsn;
|
Chris@14
|
505
|
Chris@14
|
506 case 'sqlite':
|
Chris@14
|
507 return 'sqlite:'.substr($params['path'], 1);
|
Chris@14
|
508
|
Chris@14
|
509 case 'sqlsrv':
|
Chris@14
|
510 $dsn = 'sqlsrv:server=';
|
Chris@14
|
511
|
Chris@14
|
512 if (isset($params['host'])) {
|
Chris@14
|
513 $dsn .= $params['host'];
|
Chris@14
|
514 }
|
Chris@14
|
515
|
Chris@14
|
516 if (isset($params['port']) && '' !== $params['port']) {
|
Chris@14
|
517 $dsn .= ','.$params['port'];
|
Chris@14
|
518 }
|
Chris@14
|
519
|
Chris@14
|
520 if (isset($params['path'])) {
|
Chris@14
|
521 $dbName = substr($params['path'], 1); // Remove the leading slash
|
Chris@14
|
522 $dsn .= ';Database='.$dbName;
|
Chris@14
|
523 }
|
Chris@14
|
524
|
Chris@14
|
525 return $dsn;
|
Chris@14
|
526
|
Chris@14
|
527 default:
|
Chris@14
|
528 throw new \InvalidArgumentException(sprintf('The scheme "%s" is not supported by the PdoSessionHandler URL configuration. Pass a PDO DSN directly.', $params['scheme']));
|
Chris@14
|
529 }
|
Chris@14
|
530 }
|
Chris@14
|
531
|
Chris@14
|
532 /**
|
Chris@0
|
533 * Helper method to begin a transaction.
|
Chris@0
|
534 *
|
Chris@0
|
535 * Since SQLite does not support row level locks, we have to acquire a reserved lock
|
Chris@0
|
536 * on the database immediately. Because of https://bugs.php.net/42766 we have to create
|
Chris@0
|
537 * such a transaction manually which also means we cannot use PDO::commit or
|
Chris@0
|
538 * PDO::rollback or PDO::inTransaction for SQLite.
|
Chris@0
|
539 *
|
Chris@0
|
540 * Also MySQLs default isolation, REPEATABLE READ, causes deadlock for different sessions
|
Chris@0
|
541 * due to http://www.mysqlperformanceblog.com/2013/12/12/one-more-innodb-gap-lock-to-avoid/ .
|
Chris@0
|
542 * So we change it to READ COMMITTED.
|
Chris@0
|
543 */
|
Chris@0
|
544 private function beginTransaction()
|
Chris@0
|
545 {
|
Chris@0
|
546 if (!$this->inTransaction) {
|
Chris@0
|
547 if ('sqlite' === $this->driver) {
|
Chris@0
|
548 $this->pdo->exec('BEGIN IMMEDIATE TRANSACTION');
|
Chris@0
|
549 } else {
|
Chris@0
|
550 if ('mysql' === $this->driver) {
|
Chris@0
|
551 $this->pdo->exec('SET TRANSACTION ISOLATION LEVEL READ COMMITTED');
|
Chris@0
|
552 }
|
Chris@0
|
553 $this->pdo->beginTransaction();
|
Chris@0
|
554 }
|
Chris@0
|
555 $this->inTransaction = true;
|
Chris@0
|
556 }
|
Chris@0
|
557 }
|
Chris@0
|
558
|
Chris@0
|
559 /**
|
Chris@0
|
560 * Helper method to commit a transaction.
|
Chris@0
|
561 */
|
Chris@0
|
562 private function commit()
|
Chris@0
|
563 {
|
Chris@0
|
564 if ($this->inTransaction) {
|
Chris@0
|
565 try {
|
Chris@0
|
566 // commit read-write transaction which also releases the lock
|
Chris@0
|
567 if ('sqlite' === $this->driver) {
|
Chris@0
|
568 $this->pdo->exec('COMMIT');
|
Chris@0
|
569 } else {
|
Chris@0
|
570 $this->pdo->commit();
|
Chris@0
|
571 }
|
Chris@0
|
572 $this->inTransaction = false;
|
Chris@0
|
573 } catch (\PDOException $e) {
|
Chris@0
|
574 $this->rollback();
|
Chris@0
|
575
|
Chris@0
|
576 throw $e;
|
Chris@0
|
577 }
|
Chris@0
|
578 }
|
Chris@0
|
579 }
|
Chris@0
|
580
|
Chris@0
|
581 /**
|
Chris@0
|
582 * Helper method to rollback a transaction.
|
Chris@0
|
583 */
|
Chris@0
|
584 private function rollback()
|
Chris@0
|
585 {
|
Chris@0
|
586 // We only need to rollback if we are in a transaction. Otherwise the resulting
|
Chris@0
|
587 // error would hide the real problem why rollback was called. We might not be
|
Chris@0
|
588 // in a transaction when not using the transactional locking behavior or when
|
Chris@0
|
589 // two callbacks (e.g. destroy and write) are invoked that both fail.
|
Chris@0
|
590 if ($this->inTransaction) {
|
Chris@0
|
591 if ('sqlite' === $this->driver) {
|
Chris@0
|
592 $this->pdo->exec('ROLLBACK');
|
Chris@0
|
593 } else {
|
Chris@0
|
594 $this->pdo->rollBack();
|
Chris@0
|
595 }
|
Chris@0
|
596 $this->inTransaction = false;
|
Chris@0
|
597 }
|
Chris@0
|
598 }
|
Chris@0
|
599
|
Chris@0
|
600 /**
|
Chris@0
|
601 * Reads the session data in respect to the different locking strategies.
|
Chris@0
|
602 *
|
Chris@0
|
603 * We need to make sure we do not return session data that is already considered garbage according
|
Chris@0
|
604 * to the session.gc_maxlifetime setting because gc() is called after read() and only sometimes.
|
Chris@0
|
605 *
|
Chris@0
|
606 * @param string $sessionId Session ID
|
Chris@0
|
607 *
|
Chris@0
|
608 * @return string The session data
|
Chris@0
|
609 */
|
Chris@14
|
610 protected function doRead($sessionId)
|
Chris@0
|
611 {
|
Chris@0
|
612 if (self::LOCK_ADVISORY === $this->lockMode) {
|
Chris@0
|
613 $this->unlockStatements[] = $this->doAdvisoryLock($sessionId);
|
Chris@0
|
614 }
|
Chris@0
|
615
|
Chris@0
|
616 $selectSql = $this->getSelectSql();
|
Chris@0
|
617 $selectStmt = $this->pdo->prepare($selectSql);
|
Chris@0
|
618 $selectStmt->bindParam(':id', $sessionId, \PDO::PARAM_STR);
|
Chris@16
|
619 $insertStmt = null;
|
Chris@0
|
620
|
Chris@0
|
621 do {
|
Chris@0
|
622 $selectStmt->execute();
|
Chris@0
|
623 $sessionRows = $selectStmt->fetchAll(\PDO::FETCH_NUM);
|
Chris@0
|
624
|
Chris@0
|
625 if ($sessionRows) {
|
Chris@0
|
626 if ($sessionRows[0][1] + $sessionRows[0][2] < time()) {
|
Chris@0
|
627 $this->sessionExpired = true;
|
Chris@0
|
628
|
Chris@0
|
629 return '';
|
Chris@0
|
630 }
|
Chris@0
|
631
|
Chris@17
|
632 return \is_resource($sessionRows[0][0]) ? stream_get_contents($sessionRows[0][0]) : $sessionRows[0][0];
|
Chris@0
|
633 }
|
Chris@0
|
634
|
Chris@16
|
635 if (null !== $insertStmt) {
|
Chris@16
|
636 $this->rollback();
|
Chris@16
|
637 throw new \RuntimeException('Failed to read session: INSERT reported a duplicate id but next SELECT did not return any data.');
|
Chris@16
|
638 }
|
Chris@16
|
639
|
Chris@17
|
640 if (!filter_var(ini_get('session.use_strict_mode'), FILTER_VALIDATE_BOOLEAN) && self::LOCK_TRANSACTIONAL === $this->lockMode && 'sqlite' !== $this->driver) {
|
Chris@14
|
641 // In strict mode, session fixation is not possible: new sessions always start with a unique
|
Chris@14
|
642 // random id, so that concurrency is not possible and this code path can be skipped.
|
Chris@0
|
643 // Exclusive-reading of non-existent rows does not block, so we need to do an insert to block
|
Chris@0
|
644 // until other connections to the session are committed.
|
Chris@0
|
645 try {
|
Chris@14
|
646 $insertStmt = $this->getInsertStatement($sessionId, '', 0);
|
Chris@0
|
647 $insertStmt->execute();
|
Chris@0
|
648 } catch (\PDOException $e) {
|
Chris@0
|
649 // Catch duplicate key error because other connection created the session already.
|
Chris@0
|
650 // It would only not be the case when the other connection destroyed the session.
|
Chris@0
|
651 if (0 === strpos($e->getCode(), '23')) {
|
Chris@0
|
652 // Retrieve finished session data written by concurrent connection by restarting the loop.
|
Chris@0
|
653 // We have to start a new transaction as a failed query will mark the current transaction as
|
Chris@0
|
654 // aborted in PostgreSQL and disallow further queries within it.
|
Chris@0
|
655 $this->rollback();
|
Chris@0
|
656 $this->beginTransaction();
|
Chris@0
|
657 continue;
|
Chris@0
|
658 }
|
Chris@0
|
659
|
Chris@0
|
660 throw $e;
|
Chris@0
|
661 }
|
Chris@0
|
662 }
|
Chris@0
|
663
|
Chris@0
|
664 return '';
|
Chris@0
|
665 } while (true);
|
Chris@0
|
666 }
|
Chris@0
|
667
|
Chris@0
|
668 /**
|
Chris@0
|
669 * Executes an application-level lock on the database.
|
Chris@0
|
670 *
|
Chris@0
|
671 * @param string $sessionId Session ID
|
Chris@0
|
672 *
|
Chris@0
|
673 * @return \PDOStatement The statement that needs to be executed later to release the lock
|
Chris@0
|
674 *
|
Chris@0
|
675 * @throws \DomainException When an unsupported PDO driver is used
|
Chris@0
|
676 *
|
Chris@0
|
677 * @todo implement missing advisory locks
|
Chris@0
|
678 * - for oci using DBMS_LOCK.REQUEST
|
Chris@0
|
679 * - for sqlsrv using sp_getapplock with LockOwner = Session
|
Chris@0
|
680 */
|
Chris@0
|
681 private function doAdvisoryLock($sessionId)
|
Chris@0
|
682 {
|
Chris@0
|
683 switch ($this->driver) {
|
Chris@0
|
684 case 'mysql':
|
Chris@16
|
685 // MySQL 5.7.5 and later enforces a maximum length on lock names of 64 characters. Previously, no limit was enforced.
|
Chris@16
|
686 $lockId = \substr($sessionId, 0, 64);
|
Chris@0
|
687 // should we handle the return value? 0 on timeout, null on error
|
Chris@0
|
688 // we use a timeout of 50 seconds which is also the default for innodb_lock_wait_timeout
|
Chris@0
|
689 $stmt = $this->pdo->prepare('SELECT GET_LOCK(:key, 50)');
|
Chris@16
|
690 $stmt->bindValue(':key', $lockId, \PDO::PARAM_STR);
|
Chris@0
|
691 $stmt->execute();
|
Chris@0
|
692
|
Chris@0
|
693 $releaseStmt = $this->pdo->prepare('DO RELEASE_LOCK(:key)');
|
Chris@16
|
694 $releaseStmt->bindValue(':key', $lockId, \PDO::PARAM_STR);
|
Chris@0
|
695
|
Chris@0
|
696 return $releaseStmt;
|
Chris@0
|
697 case 'pgsql':
|
Chris@0
|
698 // Obtaining an exclusive session level advisory lock requires an integer key.
|
Chris@14
|
699 // When session.sid_bits_per_character > 4, the session id can contain non-hex-characters.
|
Chris@14
|
700 // So we cannot just use hexdec().
|
Chris@14
|
701 if (4 === \PHP_INT_SIZE) {
|
Chris@14
|
702 $sessionInt1 = $this->convertStringToInt($sessionId);
|
Chris@14
|
703 $sessionInt2 = $this->convertStringToInt(substr($sessionId, 4, 4));
|
Chris@0
|
704
|
Chris@0
|
705 $stmt = $this->pdo->prepare('SELECT pg_advisory_lock(:key1, :key2)');
|
Chris@0
|
706 $stmt->bindValue(':key1', $sessionInt1, \PDO::PARAM_INT);
|
Chris@0
|
707 $stmt->bindValue(':key2', $sessionInt2, \PDO::PARAM_INT);
|
Chris@0
|
708 $stmt->execute();
|
Chris@0
|
709
|
Chris@0
|
710 $releaseStmt = $this->pdo->prepare('SELECT pg_advisory_unlock(:key1, :key2)');
|
Chris@0
|
711 $releaseStmt->bindValue(':key1', $sessionInt1, \PDO::PARAM_INT);
|
Chris@0
|
712 $releaseStmt->bindValue(':key2', $sessionInt2, \PDO::PARAM_INT);
|
Chris@0
|
713 } else {
|
Chris@14
|
714 $sessionBigInt = $this->convertStringToInt($sessionId);
|
Chris@0
|
715
|
Chris@0
|
716 $stmt = $this->pdo->prepare('SELECT pg_advisory_lock(:key)');
|
Chris@0
|
717 $stmt->bindValue(':key', $sessionBigInt, \PDO::PARAM_INT);
|
Chris@0
|
718 $stmt->execute();
|
Chris@0
|
719
|
Chris@0
|
720 $releaseStmt = $this->pdo->prepare('SELECT pg_advisory_unlock(:key)');
|
Chris@0
|
721 $releaseStmt->bindValue(':key', $sessionBigInt, \PDO::PARAM_INT);
|
Chris@0
|
722 }
|
Chris@0
|
723
|
Chris@0
|
724 return $releaseStmt;
|
Chris@0
|
725 case 'sqlite':
|
Chris@0
|
726 throw new \DomainException('SQLite does not support advisory locks.');
|
Chris@0
|
727 default:
|
Chris@0
|
728 throw new \DomainException(sprintf('Advisory locks are currently not implemented for PDO driver "%s".', $this->driver));
|
Chris@0
|
729 }
|
Chris@0
|
730 }
|
Chris@0
|
731
|
Chris@0
|
732 /**
|
Chris@14
|
733 * Encodes the first 4 (when PHP_INT_SIZE == 4) or 8 characters of the string as an integer.
|
Chris@14
|
734 *
|
Chris@14
|
735 * Keep in mind, PHP integers are signed.
|
Chris@14
|
736 *
|
Chris@14
|
737 * @param string $string
|
Chris@14
|
738 *
|
Chris@14
|
739 * @return int
|
Chris@14
|
740 */
|
Chris@14
|
741 private function convertStringToInt($string)
|
Chris@14
|
742 {
|
Chris@14
|
743 if (4 === \PHP_INT_SIZE) {
|
Chris@17
|
744 return (\ord($string[3]) << 24) + (\ord($string[2]) << 16) + (\ord($string[1]) << 8) + \ord($string[0]);
|
Chris@14
|
745 }
|
Chris@14
|
746
|
Chris@17
|
747 $int1 = (\ord($string[7]) << 24) + (\ord($string[6]) << 16) + (\ord($string[5]) << 8) + \ord($string[4]);
|
Chris@17
|
748 $int2 = (\ord($string[3]) << 24) + (\ord($string[2]) << 16) + (\ord($string[1]) << 8) + \ord($string[0]);
|
Chris@14
|
749
|
Chris@14
|
750 return $int2 + ($int1 << 32);
|
Chris@14
|
751 }
|
Chris@14
|
752
|
Chris@14
|
753 /**
|
Chris@0
|
754 * Return a locking or nonlocking SQL query to read session information.
|
Chris@0
|
755 *
|
Chris@0
|
756 * @return string The SQL string
|
Chris@0
|
757 *
|
Chris@0
|
758 * @throws \DomainException When an unsupported PDO driver is used
|
Chris@0
|
759 */
|
Chris@0
|
760 private function getSelectSql()
|
Chris@0
|
761 {
|
Chris@0
|
762 if (self::LOCK_TRANSACTIONAL === $this->lockMode) {
|
Chris@0
|
763 $this->beginTransaction();
|
Chris@0
|
764
|
Chris@0
|
765 switch ($this->driver) {
|
Chris@0
|
766 case 'mysql':
|
Chris@0
|
767 case 'oci':
|
Chris@0
|
768 case 'pgsql':
|
Chris@0
|
769 return "SELECT $this->dataCol, $this->lifetimeCol, $this->timeCol FROM $this->table WHERE $this->idCol = :id FOR UPDATE";
|
Chris@0
|
770 case 'sqlsrv':
|
Chris@0
|
771 return "SELECT $this->dataCol, $this->lifetimeCol, $this->timeCol FROM $this->table WITH (UPDLOCK, ROWLOCK) WHERE $this->idCol = :id";
|
Chris@0
|
772 case 'sqlite':
|
Chris@0
|
773 // we already locked when starting transaction
|
Chris@0
|
774 break;
|
Chris@0
|
775 default:
|
Chris@0
|
776 throw new \DomainException(sprintf('Transactional locks are currently not implemented for PDO driver "%s".', $this->driver));
|
Chris@0
|
777 }
|
Chris@0
|
778 }
|
Chris@0
|
779
|
Chris@0
|
780 return "SELECT $this->dataCol, $this->lifetimeCol, $this->timeCol FROM $this->table WHERE $this->idCol = :id";
|
Chris@0
|
781 }
|
Chris@0
|
782
|
Chris@0
|
783 /**
|
Chris@14
|
784 * Returns an insert statement supported by the database for writing session data.
|
Chris@14
|
785 *
|
Chris@14
|
786 * @param string $sessionId Session ID
|
Chris@14
|
787 * @param string $sessionData Encoded session data
|
Chris@14
|
788 * @param int $maxlifetime session.gc_maxlifetime
|
Chris@14
|
789 *
|
Chris@14
|
790 * @return \PDOStatement The insert statement
|
Chris@14
|
791 */
|
Chris@14
|
792 private function getInsertStatement($sessionId, $sessionData, $maxlifetime)
|
Chris@14
|
793 {
|
Chris@14
|
794 switch ($this->driver) {
|
Chris@14
|
795 case 'oci':
|
Chris@14
|
796 $data = fopen('php://memory', 'r+');
|
Chris@14
|
797 fwrite($data, $sessionData);
|
Chris@14
|
798 rewind($data);
|
Chris@14
|
799 $sql = "INSERT INTO $this->table ($this->idCol, $this->dataCol, $this->lifetimeCol, $this->timeCol) VALUES (:id, EMPTY_BLOB(), :lifetime, :time) RETURNING $this->dataCol into :data";
|
Chris@14
|
800 break;
|
Chris@14
|
801 default:
|
Chris@14
|
802 $data = $sessionData;
|
Chris@14
|
803 $sql = "INSERT INTO $this->table ($this->idCol, $this->dataCol, $this->lifetimeCol, $this->timeCol) VALUES (:id, :data, :lifetime, :time)";
|
Chris@14
|
804 break;
|
Chris@14
|
805 }
|
Chris@14
|
806
|
Chris@14
|
807 $stmt = $this->pdo->prepare($sql);
|
Chris@14
|
808 $stmt->bindParam(':id', $sessionId, \PDO::PARAM_STR);
|
Chris@14
|
809 $stmt->bindParam(':data', $data, \PDO::PARAM_LOB);
|
Chris@14
|
810 $stmt->bindParam(':lifetime', $maxlifetime, \PDO::PARAM_INT);
|
Chris@14
|
811 $stmt->bindValue(':time', time(), \PDO::PARAM_INT);
|
Chris@14
|
812
|
Chris@14
|
813 return $stmt;
|
Chris@14
|
814 }
|
Chris@14
|
815
|
Chris@14
|
816 /**
|
Chris@14
|
817 * Returns an update statement supported by the database for writing session data.
|
Chris@14
|
818 *
|
Chris@14
|
819 * @param string $sessionId Session ID
|
Chris@14
|
820 * @param string $sessionData Encoded session data
|
Chris@14
|
821 * @param int $maxlifetime session.gc_maxlifetime
|
Chris@14
|
822 *
|
Chris@14
|
823 * @return \PDOStatement The update statement
|
Chris@14
|
824 */
|
Chris@14
|
825 private function getUpdateStatement($sessionId, $sessionData, $maxlifetime)
|
Chris@14
|
826 {
|
Chris@14
|
827 switch ($this->driver) {
|
Chris@14
|
828 case 'oci':
|
Chris@14
|
829 $data = fopen('php://memory', 'r+');
|
Chris@14
|
830 fwrite($data, $sessionData);
|
Chris@14
|
831 rewind($data);
|
Chris@14
|
832 $sql = "UPDATE $this->table SET $this->dataCol = EMPTY_BLOB(), $this->lifetimeCol = :lifetime, $this->timeCol = :time WHERE $this->idCol = :id RETURNING $this->dataCol into :data";
|
Chris@14
|
833 break;
|
Chris@14
|
834 default:
|
Chris@14
|
835 $data = $sessionData;
|
Chris@14
|
836 $sql = "UPDATE $this->table SET $this->dataCol = :data, $this->lifetimeCol = :lifetime, $this->timeCol = :time WHERE $this->idCol = :id";
|
Chris@14
|
837 break;
|
Chris@14
|
838 }
|
Chris@14
|
839
|
Chris@14
|
840 $stmt = $this->pdo->prepare($sql);
|
Chris@14
|
841 $stmt->bindParam(':id', $sessionId, \PDO::PARAM_STR);
|
Chris@14
|
842 $stmt->bindParam(':data', $data, \PDO::PARAM_LOB);
|
Chris@14
|
843 $stmt->bindParam(':lifetime', $maxlifetime, \PDO::PARAM_INT);
|
Chris@14
|
844 $stmt->bindValue(':time', time(), \PDO::PARAM_INT);
|
Chris@14
|
845
|
Chris@14
|
846 return $stmt;
|
Chris@14
|
847 }
|
Chris@14
|
848
|
Chris@14
|
849 /**
|
Chris@0
|
850 * Returns a merge/upsert (i.e. insert or update) statement when supported by the database for writing session data.
|
Chris@0
|
851 *
|
Chris@0
|
852 * @param string $sessionId Session ID
|
Chris@0
|
853 * @param string $data Encoded session data
|
Chris@0
|
854 * @param int $maxlifetime session.gc_maxlifetime
|
Chris@0
|
855 *
|
Chris@0
|
856 * @return \PDOStatement|null The merge statement or null when not supported
|
Chris@0
|
857 */
|
Chris@0
|
858 private function getMergeStatement($sessionId, $data, $maxlifetime)
|
Chris@0
|
859 {
|
Chris@0
|
860 switch (true) {
|
Chris@0
|
861 case 'mysql' === $this->driver:
|
Chris@0
|
862 $mergeSql = "INSERT INTO $this->table ($this->idCol, $this->dataCol, $this->lifetimeCol, $this->timeCol) VALUES (:id, :data, :lifetime, :time) ".
|
Chris@0
|
863 "ON DUPLICATE KEY UPDATE $this->dataCol = VALUES($this->dataCol), $this->lifetimeCol = VALUES($this->lifetimeCol), $this->timeCol = VALUES($this->timeCol)";
|
Chris@0
|
864 break;
|
Chris@0
|
865 case 'sqlsrv' === $this->driver && version_compare($this->pdo->getAttribute(\PDO::ATTR_SERVER_VERSION), '10', '>='):
|
Chris@0
|
866 // MERGE is only available since SQL Server 2008 and must be terminated by semicolon
|
Chris@0
|
867 // It also requires HOLDLOCK according to http://weblogs.sqlteam.com/dang/archive/2009/01/31/UPSERT-Race-Condition-With-MERGE.aspx
|
Chris@0
|
868 $mergeSql = "MERGE INTO $this->table WITH (HOLDLOCK) USING (SELECT 1 AS dummy) AS src ON ($this->idCol = ?) ".
|
Chris@0
|
869 "WHEN NOT MATCHED THEN INSERT ($this->idCol, $this->dataCol, $this->lifetimeCol, $this->timeCol) VALUES (?, ?, ?, ?) ".
|
Chris@0
|
870 "WHEN MATCHED THEN UPDATE SET $this->dataCol = ?, $this->lifetimeCol = ?, $this->timeCol = ?;";
|
Chris@0
|
871 break;
|
Chris@0
|
872 case 'sqlite' === $this->driver:
|
Chris@0
|
873 $mergeSql = "INSERT OR REPLACE INTO $this->table ($this->idCol, $this->dataCol, $this->lifetimeCol, $this->timeCol) VALUES (:id, :data, :lifetime, :time)";
|
Chris@0
|
874 break;
|
Chris@0
|
875 case 'pgsql' === $this->driver && version_compare($this->pdo->getAttribute(\PDO::ATTR_SERVER_VERSION), '9.5', '>='):
|
Chris@0
|
876 $mergeSql = "INSERT INTO $this->table ($this->idCol, $this->dataCol, $this->lifetimeCol, $this->timeCol) VALUES (:id, :data, :lifetime, :time) ".
|
Chris@0
|
877 "ON CONFLICT ($this->idCol) DO UPDATE SET ($this->dataCol, $this->lifetimeCol, $this->timeCol) = (EXCLUDED.$this->dataCol, EXCLUDED.$this->lifetimeCol, EXCLUDED.$this->timeCol)";
|
Chris@0
|
878 break;
|
Chris@14
|
879 default:
|
Chris@14
|
880 // MERGE is not supported with LOBs: http://www.oracle.com/technetwork/articles/fuecks-lobs-095315.html
|
Chris@14
|
881 return null;
|
Chris@0
|
882 }
|
Chris@0
|
883
|
Chris@14
|
884 $mergeStmt = $this->pdo->prepare($mergeSql);
|
Chris@0
|
885
|
Chris@14
|
886 if ('sqlsrv' === $this->driver) {
|
Chris@14
|
887 $mergeStmt->bindParam(1, $sessionId, \PDO::PARAM_STR);
|
Chris@14
|
888 $mergeStmt->bindParam(2, $sessionId, \PDO::PARAM_STR);
|
Chris@14
|
889 $mergeStmt->bindParam(3, $data, \PDO::PARAM_LOB);
|
Chris@14
|
890 $mergeStmt->bindParam(4, $maxlifetime, \PDO::PARAM_INT);
|
Chris@14
|
891 $mergeStmt->bindValue(5, time(), \PDO::PARAM_INT);
|
Chris@14
|
892 $mergeStmt->bindParam(6, $data, \PDO::PARAM_LOB);
|
Chris@14
|
893 $mergeStmt->bindParam(7, $maxlifetime, \PDO::PARAM_INT);
|
Chris@14
|
894 $mergeStmt->bindValue(8, time(), \PDO::PARAM_INT);
|
Chris@14
|
895 } else {
|
Chris@14
|
896 $mergeStmt->bindParam(':id', $sessionId, \PDO::PARAM_STR);
|
Chris@14
|
897 $mergeStmt->bindParam(':data', $data, \PDO::PARAM_LOB);
|
Chris@14
|
898 $mergeStmt->bindParam(':lifetime', $maxlifetime, \PDO::PARAM_INT);
|
Chris@14
|
899 $mergeStmt->bindValue(':time', time(), \PDO::PARAM_INT);
|
Chris@14
|
900 }
|
Chris@0
|
901
|
Chris@14
|
902 return $mergeStmt;
|
Chris@0
|
903 }
|
Chris@0
|
904
|
Chris@0
|
905 /**
|
Chris@0
|
906 * Return a PDO instance.
|
Chris@0
|
907 *
|
Chris@0
|
908 * @return \PDO
|
Chris@0
|
909 */
|
Chris@0
|
910 protected function getConnection()
|
Chris@0
|
911 {
|
Chris@0
|
912 if (null === $this->pdo) {
|
Chris@0
|
913 $this->connect($this->dsn ?: ini_get('session.save_path'));
|
Chris@0
|
914 }
|
Chris@0
|
915
|
Chris@0
|
916 return $this->pdo;
|
Chris@0
|
917 }
|
Chris@0
|
918 }
|