-
-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathSession.php
More file actions
620 lines (579 loc) · 16.1 KB
/
Copy pathSession.php
File metadata and controls
620 lines (579 loc) · 16.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
<?php declare(strict_types=1);
/*
* This file is part of Aplus Framework Session Library.
*
* (c) Natan Felles <natanfelles@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Framework\Session;
use Framework\Session\Debug\SessionCollector;
use JetBrains\PhpStorm\Pure;
use LogicException;
use RuntimeException;
/**
* Class Session.
*
* @package session
*/
class Session
{
/**
* @var array<string,mixed>
*/
protected array $options = [];
protected SaveHandler $saveHandler;
protected SessionCollector $debugCollector;
/**
* Session constructor.
*
* @param array<string,int|string> $options
* @param SaveHandler|null $handler
*/
public function __construct(array $options = [], ?SaveHandler $handler = null)
{
$this->setOptions($options);
if ($handler) {
$this->saveHandler = $handler;
\session_set_save_handler($handler);
}
}
public function __destruct()
{
$this->stop();
}
public function __get(string $key) : mixed
{
return $this->get($key);
}
public function __set(string $key, mixed $value) : void
{
$this->set($key, $value);
}
public function __isset(string $key) : bool
{
return $this->has($key);
}
public function __unset(string $key) : void
{
$this->remove($key);
}
/**
* @see http://php.net/manual/en/session.security.ini.php
*
* @param array<string,int|string> $custom
*/
protected function setOptions(array $custom) : void
{
$serializer = \ini_get('session.serialize_handler');
$serializer = $serializer === 'php' ? 'php_serialize' : $serializer;
$secure = (isset($_SERVER['REQUEST_SCHEME']) && $_SERVER['REQUEST_SCHEME'] === 'https')
|| (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on');
$default = [
'name' => 'session_id',
'serialize_handler' => $serializer,
'cookie_domain' => '',
'cookie_httponly' => 1,
'cookie_lifetime' => 7200,
'cookie_path' => '/',
'cookie_samesite' => 'Strict',
'cookie_secure' => $secure,
'referer_check' => '',
'use_cookies' => 1,
'use_only_cookies' => 1,
'use_strict_mode' => 1,
'use_trans_sid' => 0,
// used to auto-regenerate the session id:
'auto_regenerate_maxlifetime' => 0,
'auto_regenerate_destroy' => true,
'set_cookie_permanent' => false,
];
if (\PHP_VERSION_ID < 80400) {
$default['sid_bits_per_character'] = 6;
$default['sid_length'] = 48;
}
$this->options = $custom
? \array_replace($default, $custom)
: $default;
}
/**
* @param array<string,mixed> $custom
*
* @return array<string,mixed>
*/
protected function getOptions(array $custom = []) : array
{
$options = $custom
? \array_replace($this->options, $custom)
: $this->options;
unset(
$options['auto_regenerate_maxlifetime'],
$options['auto_regenerate_destroy'],
$options['set_cookie_permanent'],
);
return $options;
}
/**
* @param array<string,int|string> $customOptions
*
* @throws LogicException if session was already active
* @throws RuntimeException if session could not be started
*
* @return bool
*/
public function start(array $customOptions = []) : bool
{
if ($this->isActive()) {
throw new LogicException('Session was already active');
}
if (!@\session_start($this->getOptions($customOptions))) {
$message = '';
if (\error_get_last()) {
$message = ': ' . \error_get_last()['message'];
}
throw new RuntimeException(
'Session could not be started' . $message
);
}
$time = \time();
$this->setPermanentCookie($time);
$this->autoRegenerate($time);
$this->clearTemp($time);
$this->clearFlash();
return true;
}
/**
* Make sure the session is active.
*
* If it is not active, it will start it.
*
* @throws RuntimeException if session could not be started
*
* @return bool
*/
public function activate() : bool
{
if ($this->isActive()) {
return true;
}
return $this->start();
}
/**
* @param int $time
*
* @see https://www.php.net/manual/en/function.session-set-cookie-params.php#100657
* @see https://stackoverflow.com/a/34252812/6027968
*/
protected function setPermanentCookie(int $time) : void
{
$setCookie = (bool) $this->options['set_cookie_permanent'];
if ($setCookie === false) {
return;
}
$params = \session_get_cookie_params();
\setcookie(
\session_name(), // @phpstan-ignore-line
\session_id(), // @phpstan-ignore-line
[ // @phpstan-ignore-line
'expires' => $time + $this->options['cookie_lifetime'],
'path' => $params['path'],
'domain' => $params['domain'],
'secure' => $params['secure'],
'httponly' => $params['httponly'],
'samesite' => $params['samesite'],
]
);
}
/**
* Auto regenerate the session id.
*
* @param int $time
*
* @see https://owasp.org/www-community/attacks/Session_fixation
*/
protected function autoRegenerate(int $time) : void
{
$maxlifetime = (int) $this->options['auto_regenerate_maxlifetime'];
$isActive = $maxlifetime > 0;
if (($isActive && empty($_SESSION['$']['regenerated_at']))
|| ($isActive && $_SESSION['$']['regenerated_at'] < ($time - $maxlifetime))
) {
$this->regenerateId((bool) $this->options['auto_regenerate_destroy']);
}
}
/**
* Clears the Flash Data.
*/
protected function clearFlash() : void
{
unset($_SESSION['$']['flash']['old']);
if (isset($_SESSION['$']['flash']['new'])) {
foreach ($_SESSION['$']['flash']['new'] as $key => $value) {
$_SESSION['$']['flash']['old'][$key] = $value;
}
}
unset($_SESSION['$']['flash']['new']);
if (empty($_SESSION['$']['flash'])) {
unset($_SESSION['$']['flash']);
}
}
/**
* Clears the Temp Data.
*
* @param int $time The max time to temp data survive
*/
protected function clearTemp(int $time) : void
{
if (isset($_SESSION['$']['temp'])) {
foreach ($_SESSION['$']['temp'] as $key => $value) {
if ($value['ttl'] < $time) {
unset($_SESSION['$']['temp'][$key]);
}
}
}
if (empty($_SESSION['$']['temp'])) {
unset($_SESSION['$']['temp']);
}
}
/**
* Tells if sessions are enabled, and one exists.
*
* @return bool
*/
public function isActive() : bool
{
return \session_status() === \PHP_SESSION_ACTIVE;
}
/**
* Destroys all data registered to a session.
*
* @return bool true on success or false on failure
*/
public function destroy() : bool
{
if ($this->isActive()) {
$destroyed = \session_destroy();
}
unset($_SESSION);
return $destroyed ?? true;
}
/**
* Sets a Cookie with the session name to be destroyed in the user-agent.
*
* @throws RuntimeException If it could not get the session name
*
* @return bool True if the Set-Cookie header was set to invalidate the
* session cookie, false if output exists
*/
public function destroyCookie() : bool
{
$name = \session_name();
if ($name === false) {
throw new RuntimeException('Could not get the session name');
}
$params = \session_get_cookie_params();
// @phpstan-ignore-next-line
return \setcookie($name, '', [
'expires' => 0,
'path' => $params['path'],
'domain' => $params['domain'],
'secure' => $params['secure'],
'httponly' => $params['httponly'],
'samesite' => $params['samesite'],
]);
}
/**
* Write session data and end session.
*
* @return bool returns true on success or false on failure
*/
public function stop() : bool
{
if ($this->isActive()) {
$closed = \session_write_close();
}
return $closed ?? true;
}
/**
* Discard session data changes and end session.
*
* @return bool returns true on success or false on failure
*/
public function abort() : bool
{
if ($this->isActive()) {
$aborted = \session_abort();
}
return $aborted ?? true;
}
/**
* Tells if the session has an item.
*
* @param string $key The item key name
*
* @return bool True if it has, otherwise false
*/
#[Pure]
public function has(string $key) : bool
{
return isset($_SESSION[$key]);
}
/**
* Gets one session item.
*
* @param string $key The item key name
*
* @return mixed The item value or null if no set
*/
#[Pure]
public function get(string $key) : mixed
{
return $_SESSION[$key] ?? null;
}
/**
* Get all session items.
*
* @return array<mixed> The value of the $_SESSION global
*/
#[Pure]
public function getAll() : array
{
return $_SESSION;
}
/**
* Get multiple session items.
*
* @param array<string> $keys An array of key item names
*
* @return array<string,mixed> An associative array with items keys and
* values. Item not set will return as null.
*/
#[Pure]
public function getMulti(array $keys) : array
{
$items = [];
foreach ($keys as $key) {
$items[$key] = $this->get($key);
}
return $items;
}
/**
* Set a session item.
*
* @param string $key The item key name
* @param mixed $value The item value
*
* @rerun static
*/
public function set(string $key, mixed $value) : static
{
$_SESSION[$key] = $value;
return $this;
}
/**
* Set multiple session items.
*
* @param array<string,mixed> $items An associative array of items keys and
* values
*
* @rerun static
*/
public function setMulti(array $items) : static
{
foreach ($items as $key => $value) {
$this->set($key, $value);
}
return $this;
}
/**
* Remove (unset) a session item.
*
* @param string $key The item key name
*
* @rerun static
*/
public function remove(string $key) : static
{
unset($_SESSION[$key]);
return $this;
}
/**
* Remove (unset) multiple session items.
*
* @param array<string> $keys A list of items keys names
*
* @rerun static
*/
public function removeMulti(array $keys) : static
{
foreach ($keys as $key) {
$this->remove($key);
}
return $this;
}
/**
* Remove (unset) all session items.
*
* @rerun static
*/
public function removeAll() : static
{
@\session_unset();
$_SESSION = [];
return $this;
}
/**
* Update the current session id with a newly generated one.
*
* @param bool $deleteOldSession Whether to delete the old associated session item or not
*
* @return bool
*/
public function regenerateId(bool $deleteOldSession = false) : bool
{
$regenerated = \session_regenerate_id($deleteOldSession);
if ($regenerated) {
$_SESSION['$']['regenerated_at'] = \time();
}
return $regenerated;
}
/**
* Re-initialize session array with original values.
*
* @return bool true if the session was successfully reinitialized or false on failure
*/
public function reset() : bool
{
return \session_reset();
}
/**
* Get a Flash Data item.
*
* @param string $key The Flash item key name
*
* @return mixed The item value or null if not exists
*/
#[Pure]
public function getFlash(string $key) : mixed
{
return $_SESSION['$']['flash']['new'][$key]
?? $_SESSION['$']['flash']['old'][$key]
?? null;
}
/**
* Set a Flash Data item, available only in the next time the session is started.
*
* @param string $key The Flash Data item key name
* @param mixed $value The item value
*
* @rerun static
*/
public function setFlash(string $key, mixed $value) : static
{
$_SESSION['$']['flash']['new'][$key] = $value;
return $this;
}
/**
* Remove a Flash Data item.
*
* @param string $key The item key name
*
* @rerun static
*/
public function removeFlash(string $key) : static
{
unset(
$_SESSION['$']['flash']['old'][$key],
$_SESSION['$']['flash']['new'][$key]
);
return $this;
}
/**
* Get a Temp Data item.
*
* @param string $key The item key name
*
* @return mixed The item value or null if it is expired or not set
*/
public function getTemp(string $key) : mixed
{
if (isset($_SESSION['$']['temp'][$key])) {
if ($_SESSION['$']['temp'][$key]['ttl'] > \time()) {
return $_SESSION['$']['temp'][$key]['data'];
}
unset($_SESSION['$']['temp'][$key]);
}
return null;
}
/**
* Set a Temp Data item.
*
* @param string $key The item key name
* @param mixed $value The item value
* @param int $ttl The Time-To-Live of the item, in seconds
*
* @rerun static
*/
public function setTemp(string $key, mixed $value, int $ttl = 60) : static
{
$_SESSION['$']['temp'][$key] = [
'ttl' => \time() + $ttl,
'data' => $value,
];
return $this;
}
/**
* Remove (unset) a Temp Data item.
*
* @param string $key The item key name
*
* @rerun static
*/
public function removeTemp(string $key) : static
{
unset($_SESSION['$']['temp'][$key]);
return $this;
}
/**
* Get/Set the session id.
*
* @param string|null $newId [optional] The new session id
*
* @throws LogicException when trying to set a new id and the session is active
*
* @return false|string The old session id or false on failure. Note: If a
* $newId is set, it is accepted but not validated. When session_start is
* called, the id is only used if it is valid
*/
public function id(?string $newId = null) : false | string
{
if ($newId !== null && $this->isActive()) {
throw new LogicException(
'Session ID cannot be changed when a session is active'
);
}
return \session_id($newId);
}
/**
* Perform session data garbage collection.
*
* If return false, use {@see error_get_last()} to get error details.
*
* @return false|int Returns the number of deleted session data for success,
* false for failure
*/
public function gc() : false | int
{
return @\session_gc();
}
public function setDebugCollector(SessionCollector $collector) : static
{
$this->debugCollector = $collector;
$this->debugCollector->setSession($this)->setOptions($this->options);
if (isset($this->saveHandler)) {
$this->debugCollector->setSaveHandler($this->saveHandler);
}
return $this;
}
}