vendor/guzzlehttp/guzzle/src/Cookie/SetCookie.php

611 lines · 18502 bytes

  1<?php
  2
  3namespace GuzzleHttp\Cookie;
  4
  5use GuzzleHttp\Handler\HostValidator;
  6use GuzzleHttp\Psr7;
  7
  8/**
  9 * Set-Cookie object
 10 */
 11class SetCookie
 12{
 13    /**
 14     * @var array
 15     */
 16    private static $defaults = [
 17        'Name' => null,
 18        'Value' => null,
 19        'Domain' => null,
 20        'Path' => '/',
 21        'Max-Age' => null,
 22        'Expires' => null,
 23        'Secure' => false,
 24        'Discard' => false,
 25        'HttpOnly' => false,
 26    ];
 27
 28    /**
 29     * @var array Cookie data
 30     */
 31    private $data;
 32
 33    /**
 34     * @var bool Whether this cookie was set without a Domain attribute
 35     */
 36    private $hostOnly = false;
 37
 38    /**
 39     * Create a new SetCookie object from a string.
 40     *
 41     * @param string $cookie Set-Cookie header string
 42     */
 43    public static function fromString(string $cookie): self
 44    {
 45        // Create the default return array
 46        $data = self::$defaults;
 47        // Explode the cookie string using a series of semicolons
 48        $pieces = \array_filter(\array_map(static function (string $piece): string {
 49            return \trim($piece, " \n\r\t\0\x0B");
 50        }, \explode(';', $cookie)));
 51        // The name of the cookie (first kvp) must exist and include an equal sign.
 52        if (!isset($pieces[0]) || \strpos($pieces[0], '=') === false) {
 53            return new self($data);
 54        }
 55
 56        // Add the cookie pieces into the parsed data array
 57        foreach ($pieces as $part) {
 58            $cookieParts = \explode('=', $part, 2);
 59            $key = \trim($cookieParts[0], " \n\r\t\0\x0B");
 60            $value = isset($cookieParts[1])
 61                ? \trim($cookieParts[1], " \n\r\t\0\x0B")
 62                : true;
 63
 64            // Only check for non-cookies when cookies have been found
 65            if (!isset($data['Name'])) {
 66                $data['Name'] = $key;
 67                $data['Value'] = $value;
 68            } else {
 69                foreach (\array_keys(self::$defaults) as $search) {
 70                    if (Psr7\Utils::caselessEquals($search, $key)) {
 71                        if ($search === 'Max-Age') {
 72                            if (is_numeric($value)) {
 73                                $data[$search] = (int) $value;
 74                            }
 75                        } elseif ($search === 'Secure' || $search === 'Discard' || $search === 'HttpOnly') {
 76                            if ($value) {
 77                                $data[$search] = true;
 78                            }
 79                        } else {
 80                            $data[$search] = $value;
 81                        }
 82                        continue 2;
 83                    }
 84                }
 85                if (Psr7\Utils::caselessEquals('HostOnly', $key)) {
 86                    continue;
 87                }
 88                $data[$key] = $value;
 89            }
 90        }
 91
 92        return new self($data);
 93    }
 94
 95    /**
 96     * @param array $data Array of cookie data provided by a Cookie parser
 97     */
 98    public function __construct(array $data = [])
 99    {
100        $this->data = self::$defaults;
101
102        if (\array_key_exists('HostOnly', $data)) {
103            if (!\is_bool($data['HostOnly'])) {
104                throw new \InvalidArgumentException('Cookie field "HostOnly" must be a boolean');
105            }
106            $this->setHostOnly($data['HostOnly']);
107            unset($data['HostOnly']);
108        }
109
110        if (isset($data['Name'])) {
111            $this->setName($data['Name']);
112        }
113
114        if (isset($data['Value'])) {
115            $this->setValue($data['Value']);
116        }
117
118        if (isset($data['Domain'])) {
119            $this->setDomain($data['Domain']);
120        }
121
122        if (isset($data['Path'])) {
123            $this->setPath($data['Path']);
124        }
125
126        if (isset($data['Max-Age'])) {
127            $this->setMaxAge($data['Max-Age']);
128        }
129
130        if (isset($data['Expires'])) {
131            $this->setExpires($data['Expires']);
132        }
133
134        if (isset($data['Secure'])) {
135            $this->setSecure($data['Secure']);
136        }
137
138        if (isset($data['Discard'])) {
139            $this->setDiscard($data['Discard']);
140        }
141
142        if (isset($data['HttpOnly'])) {
143            $this->setHttpOnly($data['HttpOnly']);
144        }
145
146        // Set the remaining values that don't have extra validation logic
147        foreach (array_diff(array_keys($data), array_keys(self::$defaults)) as $key) {
148            $this->data[$key] = $data[$key];
149        }
150
151        // Extract the Expires value and turn it into a UNIX timestamp if needed
152        $maxAge = $this->getMaxAge();
153        if (!$this->getExpires() && $maxAge !== null) {
154            // Calculate the Expires date
155            $this->setExpires(self::maxAgeToExpires($maxAge, \time()));
156        } elseif (null !== ($expires = $this->getExpires()) && !\is_numeric($expires)) {
157            $this->setExpires($expires);
158        }
159    }
160
161    private static function maxAgeToExpires(int $maxAge, int $now): int
162    {
163        if ($maxAge <= 0) {
164            return $now - 1;
165        }
166        if ($maxAge > \PHP_INT_MAX - $now) {
167            return \PHP_INT_MAX;
168        }
169
170        return $now + $maxAge;
171    }
172
173    public function __toString()
174    {
175        $str = $this->data['Name'].'='.($this->data['Value'] ?? '').'; ';
176        foreach ($this->data as $k => $v) {
177            if ($k === 'Domain' && $this->getHostOnly()) {
178                continue;
179            }
180            if ($k !== 'Name' && $k !== 'Value' && $v !== null && $v !== false) {
181                if ($k === 'Expires') {
182                    $str .= 'Expires='.\gmdate('D, d M Y H:i:s \G\M\T', $v).'; ';
183                } else {
184                    $str .= ($v === true ? $k : "{$k}={$v}").'; ';
185                }
186            }
187        }
188
189        return \rtrim($str, '; ');
190    }
191
192    public function toArray(): array
193    {
194        $data = $this->data;
195        if ($this->getHostOnly()) {
196            $data['HostOnly'] = true;
197        }
198
199        return $data;
200    }
201
202    /**
203     * Get the cookie name.
204     *
205     * @return string
206     */
207    public function getName()
208    {
209        return $this->data['Name'];
210    }
211
212    /**
213     * Set the cookie name.
214     *
215     * @param string $name Cookie name
216     */
217    public function setName($name): void
218    {
219        if (!is_string($name)) {
220            \trigger_deprecation('guzzlehttp/guzzle', '7.4', 'Not passing a string to %s::%s() is deprecated and will cause an error in 8.0.', __CLASS__, __FUNCTION__);
221        }
222
223        $this->data['Name'] = (string) $name;
224    }
225
226    /**
227     * Get the cookie value.
228     *
229     * @return string|null
230     */
231    public function getValue()
232    {
233        return $this->data['Value'];
234    }
235
236    /**
237     * Set the cookie value.
238     *
239     * @param string $value Cookie value
240     */
241    public function setValue($value): void
242    {
243        if (!is_string($value)) {
244            \trigger_deprecation('guzzlehttp/guzzle', '7.4', 'Not passing a string to %s::%s() is deprecated and will cause an error in 8.0.', __CLASS__, __FUNCTION__);
245        }
246
247        $this->data['Value'] = (string) $value;
248    }
249
250    /**
251     * Get the domain.
252     *
253     * @return string|null
254     */
255    public function getDomain()
256    {
257        return $this->data['Domain'];
258    }
259
260    /**
261     * Set the domain of the cookie.
262     *
263     * @param string|null $domain
264     */
265    public function setDomain($domain): void
266    {
267        if (!is_string($domain) && null !== $domain) {
268            \trigger_deprecation('guzzlehttp/guzzle', '7.4', 'Not passing a string or null to %s::%s() is deprecated and will cause an error in 8.0.', __CLASS__, __FUNCTION__);
269        }
270
271        $this->data['Domain'] = null === $domain ? null : (string) $domain;
272    }
273
274    /**
275     * Get whether this cookie is scoped to the origin host only.
276     *
277     * @return bool
278     */
279    public function getHostOnly()
280    {
281        return $this->hostOnly;
282    }
283
284    /**
285     * Set whether this cookie is scoped to the origin host only.
286     *
287     * @param bool $hostOnly Set to true for host-only cookies
288     */
289    public function setHostOnly(bool $hostOnly): void
290    {
291        $this->hostOnly = $hostOnly;
292    }
293
294    /**
295     * Get the path.
296     *
297     * @return string
298     */
299    public function getPath()
300    {
301        return $this->data['Path'];
302    }
303
304    /**
305     * Set the path of the cookie.
306     *
307     * @param string $path Path of the cookie
308     */
309    public function setPath($path): void
310    {
311        if (!is_string($path)) {
312            \trigger_deprecation('guzzlehttp/guzzle', '7.4', 'Not passing a string to %s::%s() is deprecated and will cause an error in 8.0.', __CLASS__, __FUNCTION__);
313        }
314
315        $this->data['Path'] = (string) $path;
316    }
317
318    /**
319     * Maximum lifetime of the cookie in seconds.
320     *
321     * @return int|null
322     */
323    public function getMaxAge()
324    {
325        return null === $this->data['Max-Age'] ? null : (int) $this->data['Max-Age'];
326    }
327
328    /**
329     * Set the max-age of the cookie.
330     *
331     * @param int|null $maxAge Max age of the cookie in seconds
332     */
333    public function setMaxAge($maxAge): void
334    {
335        if (!is_int($maxAge) && null !== $maxAge) {
336            \trigger_deprecation('guzzlehttp/guzzle', '7.4', 'Not passing an int or null to %s::%s() is deprecated and will cause an error in 8.0.', __CLASS__, __FUNCTION__);
337        }
338
339        $this->data['Max-Age'] = $maxAge === null ? null : (int) $maxAge;
340    }
341
342    /**
343     * The UNIX timestamp when the cookie Expires.
344     *
345     * @return string|int|null
346     */
347    public function getExpires()
348    {
349        return $this->data['Expires'];
350    }
351
352    /**
353     * Set the unix timestamp for which the cookie will expire.
354     *
355     * @param int|string|null $timestamp Unix timestamp or any English textual datetime description.
356     */
357    public function setExpires($timestamp): void
358    {
359        if (!is_int($timestamp) && !is_string($timestamp) && null !== $timestamp) {
360            \trigger_deprecation('guzzlehttp/guzzle', '7.4', 'Not passing an int, string or null to %s::%s() is deprecated and will cause an error in 8.0.', __CLASS__, __FUNCTION__);
361        }
362
363        if (null === $timestamp) {
364            $this->data['Expires'] = null;
365        } elseif (\is_numeric($timestamp)) {
366            $this->data['Expires'] = (int) $timestamp;
367        } else {
368            // Store unparseable dates as session cookies, not as expired cookies.
369            $expires = \strtotime((string) $timestamp);
370            $this->data['Expires'] = $expires === false ? null : $expires;
371        }
372    }
373
374    /**
375     * Get whether or not this is a secure cookie.
376     *
377     * @return bool
378     */
379    public function getSecure()
380    {
381        return $this->data['Secure'];
382    }
383
384    /**
385     * Set whether or not the cookie is secure.
386     *
387     * @param bool $secure Set to true or false if secure
388     */
389    public function setSecure($secure): void
390    {
391        if (!is_bool($secure)) {
392            \trigger_deprecation('guzzlehttp/guzzle', '7.4', 'Not passing a bool to %s::%s() is deprecated and will cause an error in 8.0.', __CLASS__, __FUNCTION__);
393        }
394
395        $this->data['Secure'] = (bool) $secure;
396    }
397
398    /**
399     * Get whether or not this is a session cookie.
400     *
401     * @return bool|null
402     */
403    public function getDiscard()
404    {
405        return $this->data['Discard'];
406    }
407
408    /**
409     * Set whether or not this is a session cookie.
410     *
411     * @param bool $discard Set to true or false if this is a session cookie
412     */
413    public function setDiscard($discard): void
414    {
415        if (!is_bool($discard)) {
416            \trigger_deprecation('guzzlehttp/guzzle', '7.4', 'Not passing a bool to %s::%s() is deprecated and will cause an error in 8.0.', __CLASS__, __FUNCTION__);
417        }
418
419        $this->data['Discard'] = (bool) $discard;
420    }
421
422    /**
423     * Get whether or not this is an HTTP only cookie.
424     *
425     * @return bool
426     */
427    public function getHttpOnly()
428    {
429        return $this->data['HttpOnly'];
430    }
431
432    /**
433     * Set whether or not this is an HTTP only cookie.
434     *
435     * @param bool $httpOnly Set to true or false if this is HTTP only
436     */
437    public function setHttpOnly($httpOnly): void
438    {
439        if (!is_bool($httpOnly)) {
440            \trigger_deprecation('guzzlehttp/guzzle', '7.4', 'Not passing a bool to %s::%s() is deprecated and will cause an error in 8.0.', __CLASS__, __FUNCTION__);
441        }
442
443        $this->data['HttpOnly'] = (bool) $httpOnly;
444    }
445
446    /**
447     * Check if the cookie matches a path value.
448     *
449     * A request-path path-matches a given cookie-path if at least one of
450     * the following conditions holds:
451     *
452     * - The cookie-path and the request-path are identical.
453     * - The cookie-path is a prefix of the request-path, and the last
454     *   character of the cookie-path is %x2F ("/").
455     * - The cookie-path is a prefix of the request-path, and the first
456     *   character of the request-path that is not included in the cookie-
457     *   path is a %x2F ("/") character.
458     *
459     * @param string $requestPath Path to check against
460     */
461    public function matchesPath(string $requestPath): bool
462    {
463        $cookiePath = $this->getPath();
464
465        // Match on exact matches or when path is the default empty "/"
466        if ($cookiePath === '/' || $cookiePath === $requestPath) {
467            return true;
468        }
469
470        // Ensure that the cookie-path is a prefix of the request path.
471        if (0 !== \strpos($requestPath, $cookiePath)) {
472            return false;
473        }
474
475        // Match if the last character of the cookie-path is "/"
476        if (\substr($cookiePath, -1, 1) === '/') {
477            return true;
478        }
479
480        // Match if the first character not included in cookie path is "/"
481        return \substr($requestPath, \strlen($cookiePath), 1) === '/';
482    }
483
484    /**
485     * Check if the cookie matches a domain value.
486     *
487     * @param string $domain Domain to check against
488     */
489    public function matchesDomain(string $domain): bool
490    {
491        $cookieDomain = $this->getDomain();
492        if (null === $cookieDomain) {
493            return !$this->getHostOnly();
494        }
495
496        if ($this->getHostOnly()) {
497            return Psr7\Utils::asciiToLower($domain) === Psr7\Utils::asciiToLower($cookieDomain);
498        }
499
500        // Remove the leading '.' as per spec in RFC 6265.
501        // https://datatracker.ietf.org/doc/html/rfc6265#section-5.2.3
502        $cookieDomain = Psr7\Utils::asciiToLower($cookieDomain);
503        if ($cookieDomain !== '' && $cookieDomain[0] === '.') {
504            /** @var string */
505            $cookieDomain = \substr($cookieDomain, 1);
506        }
507        if ('' === $cookieDomain) {
508            return false;
509        }
510
511        $domain = Psr7\Utils::asciiToLower($domain);
512        if ($domain === $cookieDomain) {
513            return true;
514        }
515
516        // A percent-escaped cookie domain can decode to another host spelling.
517        // Keep it exact-match-only to avoid extending that host's cookie scope.
518        if (\strpos($cookieDomain, '%') !== false) {
519            return false;
520        }
521
522        // IP literals and numeric hosts are exact-match-only per RFC 6265.
523        // Only the exact match above may succeed for those cookie domains.
524        if (self::isIpAddressOrNumericHost($cookieDomain)) {
525            return false;
526        }
527
528        // Matching the subdomain according to RFC 6265.
529        // https://datatracker.ietf.org/doc/html/rfc6265#section-5.1.3
530        if (\filter_var($domain, \FILTER_VALIDATE_IP)) {
531            return false;
532        }
533
534        return (bool) \preg_match('/\.'.\preg_quote($cookieDomain, '/').'$/D', $domain);
535    }
536
537    private static function isIpAddressOrNumericHost(string $host): bool
538    {
539        // Strip one root dot before detection so trailing-dot numeric hosts
540        // still cannot be matched by subdomains.
541        if ($host !== '' && \str_ends_with($host, '.')) {
542            $host = \substr($host, 0, -1);
543        }
544
545        if (\str_starts_with($host, '[') && \str_ends_with($host, ']')) {
546            $host = \substr($host, 1, -1);
547        }
548
549        if (\filter_var($host, \FILTER_VALIDATE_IP) !== false) {
550            return true;
551        }
552
553        // Public DNS names do not have an all-numeric rightmost label; treat
554        // those private/internal hosts as exact-match-only too.
555        $labels = \explode('.', $host);
556        $last = (string) \end($labels);
557
558        if ($last !== '' && \ctype_digit($last)) {
559            return true;
560        }
561
562        // Apply the transport's decimal, octal and hexadecimal inet_aton-style
563        // grammar. Omitting range checks conservatively holds some names to an
564        // exact match.
565        return HostValidator::isNumericIpv4Host(\rtrim($host, '.'));
566    }
567
568    /**
569     * Check if the cookie is expired.
570     */
571    public function isExpired(): bool
572    {
573        return $this->getExpires() !== null && \time() > $this->getExpires();
574    }
575
576    /**
577     * Check if the cookie is valid according to RFC 6265.
578     *
579     * @return bool|string Returns true if valid or an error message if invalid
580     */
581    public function validate()
582    {
583        $name = $this->getName();
584        if ($name === '') {
585            return 'The cookie name must not be empty';
586        }
587
588        // Check if any of the invalid characters are present in the cookie name
589        if (\preg_match('/[\x00-\x20\x22\x28-\x29\x2c\x2f\x3a-\x40\x5c\x7b\x7d\x7f]/', $name) !== 0) {
590            return 'Cookie name must not contain invalid characters: ASCII '
591                .'Control characters (0-31;127), space, tab and the '
592                .'following characters: ()<>@,;:\"/?={}';
593        }
594
595        // Value must not be null. 0 and empty string are valid. Empty strings
596        // are technically against RFC 6265, but known to happen in the wild.
597        $value = $this->getValue();
598        if ($value === null) {
599            return 'The cookie value must not be empty';
600        }
601
602        // Domains must not be empty, but may be omitted. "0" is not a valid
603        // internet domain, but may be used as server name in a private network.
604        $domain = $this->getDomain();
605        if ($domain === '' || (null !== $domain && '' === \ltrim(\trim($domain, " \n\r\t\0\x0B"), '.'))) {
606            return 'The cookie domain must not be empty';
607        }
608
609        return true;
610    }
611}