/
Cookie.php
833 lines (731 loc) · 20.6 KB
/
Cookie.php
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
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
<?php
declare(strict_types=1);
/**
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @since 3.5.0
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
namespace Cake\Http\Cookie;
use Cake\Utility\Hash;
use DateTimeImmutable;
use DateTimeInterface;
use DateTimeZone;
use InvalidArgumentException;
/**
* Cookie object to build a cookie and turn it into a header value
*
* An HTTP cookie (also called web cookie, Internet cookie, browser cookie or
* simply cookie) is a small piece of data sent from a website and stored on
* the user's computer by the user's web browser while the user is browsing.
*
* Cookies were designed to be a reliable mechanism for websites to remember
* stateful information (such as items added in the shopping cart in an online
* store) or to record the user's browsing activity (including clicking
* particular buttons, logging in, or recording which pages were visited in
* the past). They can also be used to remember arbitrary pieces of information
* that the user previously entered into form fields such as names, and preferences.
*
* Cookie objects are immutable, and you must re-assign variables when modifying
* cookie objects:
*
* ```
* $cookie = $cookie->withValue('0');
* ```
*
* @link https://tools.ietf.org/html/draft-ietf-httpbis-rfc6265bis-03
* @link https://en.wikipedia.org/wiki/HTTP_cookie
* @see \Cake\Http\Cookie\CookieCollection for working with collections of cookies.
* @see \Cake\Http\Response::getCookieCollection() for working with response cookies.
*/
class Cookie implements CookieInterface
{
/**
* Cookie name
*
* @var string
*/
protected $name = '';
/**
* Raw Cookie value.
*
* @var string|array
*/
protected $value = '';
/**
* Whether or not a JSON value has been expanded into an array.
*
* @var bool
*/
protected $isExpanded = false;
/**
* Expiration time
*
* @var \DateTime|\DateTimeImmutable|null
*/
protected $expiresAt;
/**
* Path
*
* @var string
*/
protected $path = '/';
/**
* Domain
*
* @var string
*/
protected $domain = '';
/**
* Secure
*
* @var bool
*/
protected $secure = false;
/**
* HTTP only
*
* @var bool
*/
protected $httpOnly = false;
/**
* Samesite
*
* @var string|null
*/
protected $sameSite = null;
/**
* Default attributes for a cookie.
*
* @var array
* @see \Cake\Cookie\Cookie::setDefaults()
*/
protected static $defaults = [
'expires' => null,
'path' => '/',
'domain' => '',
'secure' => false,
'httponly' => false,
'samesite' => null,
];
/**
* Constructor
*
* The constructors args are similar to the native PHP `setcookie()` method.
* The only difference is the 3rd argument which excepts null or an
* DateTime or DateTimeImmutable object instead an integer.
*
* @link http://php.net/manual/en/function.setcookie.php
* @param string $name Cookie name
* @param string|array $value Value of the cookie
* @param \DateTime|\DateTimeImmutable|null $expiresAt Expiration time and date
* @param string|null $path Path
* @param string|null $domain Domain
* @param bool|null $secure Is secure
* @param bool|null $httpOnly HTTP Only
* @param string|null $sameSite Samesite
*/
public function __construct(
string $name,
$value = '',
?DateTimeInterface $expiresAt = null,
?string $path = null,
?string $domain = null,
?bool $secure = null,
?bool $httpOnly = null,
?string $sameSite = null
) {
$this->validateName($name);
$this->name = $name;
$this->_setValue($value);
$this->domain = $domain ?? static::$defaults['domain'];
$this->httpOnly = $httpOnly ?? static::$defaults['httponly'];
$this->path = $path ?? static::$defaults['path'];
$this->secure = $secure ?? static::$defaults['secure'];
if ($sameSite === null) {
$this->sameSite = static::$defaults['samesite'];
} else {
$this->validateSameSiteValue($sameSite);
$this->sameSite = $sameSite;
}
if ($expiresAt) {
$expiresAt = $expiresAt->setTimezone(new DateTimeZone('GMT'));
} else {
$expiresAt = static::$defaults['expires'];
}
$this->expiresAt = $expiresAt;
}
/**
* Set default options for the cookies.
*
* Valid option keys are:
*
* - `expires`: Can be a UNIX timestamp or `strtotime()` compatible string or `DateTimeInterface` instance or `null`.
* - `path`: A path string. Defauts to `'/'`.
* - `domain`: Domain name string. Defaults to `''`.
* - `httponly`: Boolean. Defaults to `false`.
* - `secure`: Boolean. Defaults to `false`.
* - `samesite`: Can be one of `CookieInterface::SAMESITE_LAX`, `CookieInterface::SAMESITE_STRICT`,
* `CookieInterface::SAMESITE_NONE` or `null`. Defaults to `null`.
*
* @param array $options Default options.
* @return void
*/
public static function setDefaults(array $options): void
{
if (isset($options['expires'])) {
$options['expires'] = static::dateTimeInstance($options['expires']);
}
if (isset($options['samesite'])) {
static::validateSameSiteValue($options['samesite']);
}
static::$defaults = $options + static::$defaults;
}
/**
* Factory method to create Cookie instances.
*
* @param string $name Cookie name
* @param string|array $value Value of the cookie
* @param array $options Cookies options.
* @return static
* @see \Cake\Cookie\Cookie::setDefaults()
*/
public static function create(string $name, $value, array $options = [])
{
$options += static::$defaults;
$options['expires'] = static::dateTimeInstance($options['expires']);
return new static(
$name,
$value,
$options['expires'],
$options['path'],
$options['domain'],
$options['secure'],
$options['httponly'],
$options['samesite']
);
}
/**
* Converts non null expiry value into DateTimeInterface instance.
*
* @param mixed $expires Expiry value.
* @return \DateTime|\DatetimeImmutable|null
*/
protected static function dateTimeInstance($expires): ?DateTimeInterface
{
if ($expires === null) {
return $expires;
}
if ($expires instanceof DateTimeInterface) {
/** @psalm-suppress UndefinedInterfaceMethod */
return $expires->setTimezone(new DateTimeZone('GMT'));
}
if (!is_string($expires) && !is_int($expires)) {
throw new InvalidArgumentException(sprintf(
'Invalid type `%s` for expires. Expected an string, integer or DateTime object.',
getTypeName($expires)
));
}
if (!is_numeric($expires)) {
$expires = strtotime($expires) ?: null;
}
if ($expires !== null) {
$expires = new DateTimeImmutable('@' . (string)$expires);
}
return $expires;
}
/**
* Create Cookie instance from "set-cookie" header string.
*
* @param string $cookie Cookie header string.
* @param array $defaults Default attributes.
* @return static
* @see \Cake\Cookie\Cookie::setDefaults()
*/
public static function createFromHeaderString(string $cookie, array $defaults = [])
{
if (strpos($cookie, '";"') !== false) {
$cookie = str_replace('";"', '{__cookie_replace__}', $cookie);
$parts = str_replace('{__cookie_replace__}', '";"', explode(';', $cookie));
} else {
$parts = preg_split('/\;[ \t]*/', $cookie);
}
[$name, $value] = explode('=', array_shift($parts), 2);
$data = [
'name' => urldecode($name),
'value' => urldecode($value),
] + $defaults;
foreach ($parts as $part) {
if (strpos($part, '=') !== false) {
[$key, $value] = explode('=', $part);
} else {
$key = $part;
$value = true;
}
$key = strtolower($key);
$data[$key] = $value;
}
if (isset($data['max-age'])) {
$data['expires'] = time() + (int)$data['max-age'];
unset($data['max-age']);
}
if (isset($data['samesite'])) {
// Ignore invalid value when parsing headers
// https://tools.ietf.org/html/draft-west-first-party-cookies-07#section-4.1
if (!in_array($data['samesite'], CookieInterface::SAMESITE_VALUES, true)) {
unset($data['samesite']);
}
}
$name = (string)$data['name'];
$value = (string)$data['value'];
unset($data['name'], $data['value']);
return Cookie::create(
$name,
$value,
$data
);
}
/**
* Returns a header value as string
*
* @return string
*/
public function toHeaderValue(): string
{
$value = $this->value;
if ($this->isExpanded) {
/** @psalm-suppress PossiblyInvalidArgument */
$value = $this->_flatten($this->value);
}
$headerValue = [];
/** @psalm-suppress PossiblyInvalidArgument */
$headerValue[] = sprintf('%s=%s', $this->name, rawurlencode($value));
if ($this->expiresAt) {
$headerValue[] = sprintf('expires=%s', $this->getFormattedExpires());
}
if ($this->path !== '') {
$headerValue[] = sprintf('path=%s', $this->path);
}
if ($this->domain !== '') {
$headerValue[] = sprintf('domain=%s', $this->domain);
}
if ($this->sameSite) {
$headerValue[] = sprintf('samesite=%s', $this->sameSite);
}
if ($this->secure) {
$headerValue[] = 'secure';
}
if ($this->httpOnly) {
$headerValue[] = 'httponly';
}
return implode('; ', $headerValue);
}
/**
* @inheritDoc
*/
public function withName(string $name)
{
$this->validateName($name);
$new = clone $this;
$new->name = $name;
return $new;
}
/**
* @inheritDoc
*/
public function getId(): string
{
return "{$this->name};{$this->domain};{$this->path}";
}
/**
* @inheritDoc
*/
public function getName(): string
{
return $this->name;
}
/**
* Validates the cookie name
*
* @param string $name Name of the cookie
* @return void
* @throws \InvalidArgumentException
* @link https://tools.ietf.org/html/rfc2616#section-2.2 Rules for naming cookies.
*/
protected function validateName(string $name): void
{
if (preg_match("/[=,;\t\r\n\013\014]/", $name)) {
throw new InvalidArgumentException(
sprintf('The cookie name `%s` contains invalid characters.', $name)
);
}
if (empty($name)) {
throw new InvalidArgumentException('The cookie name cannot be empty.');
}
}
/**
* @inheritDoc
*/
public function getValue()
{
return $this->value;
}
/**
* Gets the cookie value as a string.
*
* This will collapse any complex data in the cookie with json_encode()
*
* @return mixed
* @deprecated 4.0.0 Use {@link getScalarValue()} instead.
*/
public function getStringValue()
{
deprecationWarning('Cookie::getStringValue() is deprecated. Use getScalarValue() instead.');
return $this->getScalarValue();
}
/**
* @inheritDoc
*/
public function getScalarValue()
{
if ($this->isExpanded) {
/** @psalm-suppress PossiblyInvalidArgument */
return $this->_flatten($this->value);
}
return $this->value;
}
/**
* @inheritDoc
*/
public function withValue($value)
{
$new = clone $this;
$new->_setValue($value);
return $new;
}
/**
* Setter for the value attribute.
*
* @param string|array $value The value to store.
* @return void
*/
protected function _setValue($value): void
{
$this->isExpanded = is_array($value);
$this->value = $value;
}
/**
* @inheritDoc
*/
public function withPath(string $path)
{
$new = clone $this;
$new->path = $path;
return $new;
}
/**
* @inheritDoc
*/
public function getPath(): string
{
return $this->path;
}
/**
* @inheritDoc
*/
public function withDomain(string $domain)
{
$new = clone $this;
$new->domain = $domain;
return $new;
}
/**
* @inheritDoc
*/
public function getDomain(): string
{
return $this->domain;
}
/**
* @inheritDoc
*/
public function isSecure(): bool
{
return $this->secure;
}
/**
* @inheritDoc
*/
public function withSecure(bool $secure)
{
$new = clone $this;
$new->secure = $secure;
return $new;
}
/**
* @inheritDoc
*/
public function withHttpOnly(bool $httpOnly)
{
$new = clone $this;
$new->httpOnly = $httpOnly;
return $new;
}
/**
* @inheritDoc
*/
public function isHttpOnly(): bool
{
return $this->httpOnly;
}
/**
* @inheritDoc
*/
public function withExpiry($dateTime)
{
$new = clone $this;
$new->expiresAt = $dateTime->setTimezone(new DateTimeZone('GMT'));
return $new;
}
/**
* @inheritDoc
*/
public function getExpiry()
{
return $this->expiresAt;
}
/**
* @inheritDoc
*/
public function getExpiresTimestamp(): ?int
{
if (!$this->expiresAt) {
return null;
}
return (int)$this->expiresAt->format('U');
}
/**
* @inheritDoc
*/
public function getFormattedExpires(): string
{
if (!$this->expiresAt) {
return '';
}
return $this->expiresAt->format(static::EXPIRES_FORMAT);
}
/**
* @inheritDoc
*/
public function isExpired($time = null): bool
{
$time = $time ?: new DateTimeImmutable('now', new DateTimeZone('UTC'));
if (!$this->expiresAt) {
return false;
}
return $this->expiresAt < $time;
}
/**
* @inheritDoc
*/
public function withNeverExpire()
{
$new = clone $this;
$new->expiresAt = new DateTimeImmutable('2038-01-01');
return $new;
}
/**
* @inheritDoc
*/
public function withExpired()
{
$new = clone $this;
$new->expiresAt = new DateTimeImmutable('1970-01-01 00:00:01');
return $new;
}
/**
* @inheritDoc
*/
public function getSameSite(): ?string
{
return $this->sameSite;
}
/**
* @inheritDoc
*/
public function withSameSite(?string $sameSite)
{
if ($sameSite !== null) {
$this->validateSameSiteValue($sameSite);
}
$new = clone $this;
$new->sameSite = $sameSite;
return $new;
}
/**
* Check that value passed for SameSite is valid.
*
* @param string $sameSite SameSite value
* @return void
* @throws \InvalidArgumentException
*/
protected static function validateSameSiteValue(string $sameSite)
{
if (!in_array($sameSite, CookieInterface::SAMESITE_VALUES, true)) {
throw new InvalidArgumentException(
'Samesite value must be either of: ' . implode(', ', CookieInterface::SAMESITE_VALUES)
);
}
}
/**
* Checks if a value exists in the cookie data.
*
* This method will expand serialized complex data,
* on first use.
*
* @param string $path Path to check
* @return bool
*/
public function check(string $path): bool
{
if ($this->isExpanded === false) {
/** @psalm-suppress PossiblyInvalidArgument */
$this->value = $this->_expand($this->value);
}
/** @psalm-suppress PossiblyInvalidArgument */
return Hash::check($this->value, $path);
}
/**
* Create a new cookie with updated data.
*
* @param string $path Path to write to
* @param mixed $value Value to write
* @return static
*/
public function withAddedValue(string $path, $value)
{
$new = clone $this;
if ($new->isExpanded === false) {
/** @psalm-suppress PossiblyInvalidArgument */
$new->value = $new->_expand($new->value);
}
/** @psalm-suppress PossiblyInvalidArgument */
$new->value = Hash::insert($new->value, $path, $value);
return $new;
}
/**
* Create a new cookie without a specific path
*
* @param string $path Path to remove
* @return static
*/
public function withoutAddedValue(string $path)
{
$new = clone $this;
if ($new->isExpanded === false) {
/** @psalm-suppress PossiblyInvalidArgument */
$new->value = $new->_expand($new->value);
}
/** @psalm-suppress PossiblyInvalidArgument */
$new->value = Hash::remove($new->value, $path);
return $new;
}
/**
* Read data from the cookie
*
* This method will expand serialized complex data,
* on first use.
*
* @param string $path Path to read the data from
* @return mixed
*/
public function read(?string $path = null)
{
if ($this->isExpanded === false) {
/** @psalm-suppress PossiblyInvalidArgument */
$this->value = $this->_expand($this->value);
}
if ($path === null) {
return $this->value;
}
/** @psalm-suppress PossiblyInvalidArgument */
return Hash::get($this->value, $path);
}
/**
* Checks if the cookie value was expanded
*
* @return bool
*/
public function isExpanded(): bool
{
return $this->isExpanded;
}
/**
* @inheritDoc
*/
public function getOptions(): array
{
$options = [
'expires' => (int)$this->getExpiresTimestamp(),
'path' => $this->path,
'domain' => $this->domain,
'secure' => $this->secure,
'httponly' => $this->httpOnly,
];
if ($this->sameSite !== null) {
$options['samesite'] = $this->sameSite;
}
return $options;
}
/**
* @inheritDoc
*/
public function toArray(): array
{
return [
'name' => $this->name,
'value' => $this->getScalarValue(),
] + $this->getOptions();
}
/**
* Implode method to keep keys are multidimensional arrays
*
* @param array $array Map of key and values
* @return string A JSON encoded string.
*/
protected function _flatten(array $array): string
{
return json_encode($array);
}
/**
* Explode method to return array from string set in CookieComponent::_flatten()
* Maintains reading backwards compatibility with 1.x CookieComponent::_flatten().
*
* @param string $string A string containing JSON encoded data, or a bare string.
* @return string|array Map of key and values
*/
protected function _expand(string $string)
{
$this->isExpanded = true;
$first = substr($string, 0, 1);
if ($first === '{' || $first === '[') {
$ret = json_decode($string, true);
return $ret ?? $string;
}
$array = [];
foreach (explode(',', $string) as $pair) {
$key = explode('|', $pair);
if (!isset($key[1])) {
return $key[0];
}
$array[$key[0]] = $key[1];
}
return $array;
}
}