Subversion-Projekte lars-tiefland.laravel_shop

Revision

Revision 148 | Details | Vergleich mit vorheriger | Letzte Änderung | Log anzeigen | RSS feed

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