SetCookie.php 16.5 KB
Newer Older
Ketan's avatar
Ketan committed
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
<?php
/**
 * @see       https://github.com/zendframework/zend-http for the canonical source repository
 * @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com)
 * @license   https://github.com/zendframework/zend-http/blob/master/LICENSE.md New BSD License
 */

namespace Zend\Http\Header;

use DateTime;
use Zend\Uri\UriFactory;

/**
 * @throws Exception\InvalidArgumentException
 * @see http://www.ietf.org/rfc/rfc2109.txt
 * @see http://www.w3.org/Protocols/rfc2109/rfc2109
 */
class SetCookie implements MultipleHeaderInterface
{
    /**
     * Cookie name
     *
     * @var string|null
     */
    protected $name;

    /**
     * Cookie value
     *
     * @var string|null
     */
    protected $value;

    /**
     * Version
     *
     * @var int|null
     */
    protected $version;

    /**
     * Max Age
     *
     * @var int|null
     */
    protected $maxAge;

    /**
     * Cookie expiry date
     *
     * @var int|null
     */
    protected $expires;

    /**
     * Cookie domain
     *
     * @var string|null
     */
    protected $domain;

    /**
     * Cookie path
     *
     * @var string|null
     */
    protected $path;

    /**
     * Whether the cookie is secure or not
     *
     * @var bool|null
     */
    protected $secure;

    /**
     * If the value need to be quoted or not
     *
     * @var bool
     */
    protected $quoteFieldValue = false;

    /**
     * @var bool|null
     */
    protected $httponly;

    /**
     * @static
     * @throws Exception\InvalidArgumentException
     * @param  $headerLine
     * @param  bool $bypassHeaderFieldName
     * @return array|SetCookie
     */
    public static function fromString($headerLine, $bypassHeaderFieldName = false)
    {
        static $setCookieProcessor = null;

        if ($setCookieProcessor === null) {
            $setCookieClass = get_called_class();
            $setCookieProcessor = function ($headerLine) use ($setCookieClass) {
                $header = new $setCookieClass();
                $keyValuePairs = preg_split('#;\s*#', $headerLine);

                foreach ($keyValuePairs as $keyValue) {
                    if (preg_match('#^(?P<headerKey>[^=]+)=\s*("?)(?P<headerValue>[^"]*)\2#', $keyValue, $matches)) {
                        $headerKey  = $matches['headerKey'];
                        $headerValue = $matches['headerValue'];
                    } else {
                        $headerKey = $keyValue;
                        $headerValue = null;
                    }

                    // First K=V pair is always the cookie name and value
                    if ($header->getName() === null) {
                        $header->setName($headerKey);
                        $header->setValue(urldecode($headerValue));
                        continue;
                    }

                    // Process the remaining elements
                    switch (str_replace(['-', '_'], '', strtolower($headerKey))) {
                        case 'expires':
                            $header->setExpires($headerValue);
                            break;
                        case 'domain':
                            $header->setDomain($headerValue);
                            break;
                        case 'path':
                            $header->setPath($headerValue);
                            break;
                        case 'secure':
                            $header->setSecure(true);
                            break;
                        case 'httponly':
                            $header->setHttponly(true);
                            break;
                        case 'version':
                            $header->setVersion((int) $headerValue);
                            break;
                        case 'maxage':
                            $header->setMaxAge($headerValue);
                            break;
                        default:
                            // Intentionally omitted
                    }
                }

                return $header;
            };
        }

        list($name, $value) = GenericHeader::splitHeaderLine($headerLine);
        HeaderValue::assertValid($value);

        // some sites return set-cookie::value, this is to get rid of the second :
        $name = strtolower($name) == 'set-cookie:' ? 'set-cookie' : $name;

        // check to ensure proper header type for this factory
        if (strtolower($name) !== 'set-cookie') {
            throw new Exception\InvalidArgumentException('Invalid header line for Set-Cookie string: "' . $name . '"');
        }

        $multipleHeaders = preg_split('#(?<!Sun|Mon|Tue|Wed|Thu|Fri|Sat),\s*#', $value);

        if (count($multipleHeaders) <= 1) {
            return $setCookieProcessor(array_pop($multipleHeaders));
        } else {
            $headers = [];
            foreach ($multipleHeaders as $headerLine) {
                $headers[] = $setCookieProcessor($headerLine);
            }
            return $headers;
        }
    }

    /**
     * Cookie object constructor
     *
     * @todo Add validation of each one of the parameters (legal domain, etc.)
     *
     * @param   string              $name
     * @param   string              $value
     * @param   int|string|DateTime $expires
     * @param   string              $path
     * @param   string              $domain
     * @param   bool                $secure
     * @param   bool                $httponly
     * @param   string              $maxAge
     * @param   int                 $version
     */
    public function __construct(
        $name = null,
        $value = null,
        $expires = null,
        $path = null,
        $domain = null,
        $secure = false,
        $httponly = false,
        $maxAge = null,
        $version = null
    ) {
        $this->type = 'Cookie';

        $this->setName($name)
             ->setValue($value)
             ->setVersion($version)
             ->setMaxAge($maxAge)
             ->setDomain($domain)
             ->setExpires($expires)
             ->setPath($path)
             ->setSecure($secure)
             ->setHttpOnly($httponly);
    }

    /**
     * @return string 'Set-Cookie'
     */
    public function getFieldName()
    {
        return 'Set-Cookie';
    }

    /**
     * @throws Exception\RuntimeException
     * @return string
     */
    public function getFieldValue()
    {
        if ($this->getName() == '') {
            return '';
        }

        $value = urlencode($this->getValue());
        if ($this->hasQuoteFieldValue()) {
            $value = '"' . $value . '"';
        }

        $fieldValue = $this->getName() . '=' . $value;

        $version = $this->getVersion();
        if ($version !== null) {
            $fieldValue .= '; Version=' . $version;
        }

        $maxAge = $this->getMaxAge();
        if ($maxAge !== null) {
            $fieldValue .= '; Max-Age=' . $maxAge;
        }

        $expires = $this->getExpires();
        if ($expires) {
            $fieldValue .= '; Expires=' . $expires;
        }

        $domain = $this->getDomain();
        if ($domain) {
            $fieldValue .= '; Domain=' . $domain;
        }

        $path = $this->getPath();
        if ($path) {
            $fieldValue .= '; Path=' . $path;
        }

        if ($this->isSecure()) {
            $fieldValue .= '; Secure';
        }

        if ($this->isHttponly()) {
            $fieldValue .= '; HttpOnly';
        }

        return $fieldValue;
    }

    /**
     * @param string $name
     * @throws Exception\InvalidArgumentException
     * @return SetCookie
     */
    public function setName($name)
    {
        HeaderValue::assertValid($name);
        $this->name = $name;
        return $this;
    }

    /**
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * @param string $value
     * @return SetCookie
     */
    public function setValue($value)
    {
        $this->value = $value;
        return $this;
    }

    /**
     * @return string
     */
    public function getValue()
    {
        return $this->value;
    }

    /**
     * Set version
     *
     * @param int $version
     * @throws Exception\InvalidArgumentException
     * @return SetCookie
     */
    public function setVersion($version)
    {
        if ($version !== null && ! is_int($version)) {
            throw new Exception\InvalidArgumentException('Invalid Version number specified');
        }
        $this->version = $version;
        return $this;
    }

    /**
     * Get version
     *
     * @return int
     */
    public function getVersion()
    {
        return $this->version;
    }

    /**
     * Set Max-Age
     *
     * @param int $maxAge
     * @return SetCookie
     */
    public function setMaxAge($maxAge)
    {
        if ($maxAge === null || ! is_numeric($maxAge)) {
            return $this;
        }

        $this->maxAge = max(0, (int) $maxAge);
        return $this;
    }

    /**
     * Get Max-Age
     *
     * @return int
     */
    public function getMaxAge()
    {
        return $this->maxAge;
    }

    /**
     * Set Expires
     *
     * @param int|string|DateTime $expires
     *
     * @return self
     *
     * @throws Exception\InvalidArgumentException
     */
    public function setExpires($expires)
    {
        if ($expires === null) {
            $this->expires = null;
            return $this;
        }

        if ($expires instanceof DateTime) {
            $expires = $expires->format(DateTime::COOKIE);
        }

        $tsExpires = $expires;

        if (is_string($expires)) {
            $tsExpires = strtotime($expires);

            // if $tsExpires is invalid and PHP is compiled as 32bit. Check if it fail reason is the 2038 bug
            if (! is_int($tsExpires) && PHP_INT_SIZE === 4) {
                $dateTime = new DateTime($expires);
                if ($dateTime->format('Y') > 2038) {
                    $tsExpires = PHP_INT_MAX;
                }
            }
        }

        if (! is_int($tsExpires) || $tsExpires < 0) {
            throw new Exception\InvalidArgumentException('Invalid expires time specified');
        }

        $this->expires = $tsExpires;

        return $this;
    }

    /**
     * @param bool $inSeconds
     * @return int|string
     */
    public function getExpires($inSeconds = false)
    {
        if ($this->expires === null) {
            return;
        }
        if ($inSeconds) {
            return $this->expires;
        }
        return gmdate('D, d-M-Y H:i:s', $this->expires) . ' GMT';
    }

    /**
     * @param string $domain
     * @return SetCookie
     */
    public function setDomain($domain)
    {
        HeaderValue::assertValid($domain);
        $this->domain = $domain;
        return $this;
    }

    /**
     * @return string
     */
    public function getDomain()
    {
        return $this->domain;
    }

    /**
     * @param string $path
     * @return SetCookie
     */
    public function setPath($path)
    {
        HeaderValue::assertValid($path);
        $this->path = $path;
        return $this;
    }

    /**
     * @return string
     */
    public function getPath()
    {
        return $this->path;
    }

    /**
     * @param  bool $secure
     * @return SetCookie
     */
    public function setSecure($secure)
    {
        if (null !== $secure) {
            $secure = (bool) $secure;
        }
        $this->secure = $secure;
        return $this;
    }

    /**
     * Set whether the value for this cookie should be quoted
     *
     * @param  bool $quotedValue
     * @return SetCookie
     */
    public function setQuoteFieldValue($quotedValue)
    {
        $this->quoteFieldValue = (bool) $quotedValue;
        return $this;
    }

    /**
     * @return bool
     */
    public function isSecure()
    {
        return $this->secure;
    }

    /**
     * @param  bool $httponly
     * @return SetCookie
     */
    public function setHttponly($httponly)
    {
        if (null !== $httponly) {
            $httponly = (bool) $httponly;
        }
        $this->httponly = $httponly;
        return $this;
    }

    /**
     * @return bool
     */
    public function isHttponly()
    {
        return $this->httponly;
    }

    /**
     * Check whether the cookie has expired
     *
     * Always returns false if the cookie is a session cookie (has no expiry time)
     *
     * @param int $now Timestamp to consider as "now"
     * @return bool
     */
    public function isExpired($now = null)
    {
        if ($now === null) {
            $now = time();
        }

        if (is_int($this->expires) && $this->expires < $now) {
            return true;
        }

        return false;
    }

    /**
     * Check whether the cookie is a session cookie (has no expiry time set)
     *
     * @return bool
     */
    public function isSessionCookie()
    {
        return ($this->expires === null);
    }

    /**
     * Check whether the value for this cookie should be quoted
     *
     * @return bool
     */
    public function hasQuoteFieldValue()
    {
        return $this->quoteFieldValue;
    }

    public function isValidForRequest($requestDomain, $path, $isSecure = false)
    {
        if ($this->getDomain() && (strrpos($requestDomain, $this->getDomain()) === false)) {
            return false;
        }

        if ($this->getPath() && (strpos($path, $this->getPath()) !== 0)) {
            return false;
        }

        if ($this->secure && $this->isSecure() !== $isSecure) {
            return false;
        }

        return true;
    }

    /**
     * Checks whether the cookie should be sent or not in a specific scenario
     *
     * @param string|\Zend\Uri\Uri $uri URI to check against (secure, domain, path)
     * @param bool $matchSessionCookies Whether to send session cookies
     * @param int $now Override the current time when checking for expiry time
     * @return bool
     * @throws Exception\InvalidArgumentException If URI does not have HTTP or HTTPS scheme.
     */
    public function match($uri, $matchSessionCookies = true, $now = null)
    {
        if (is_string($uri)) {
            $uri = UriFactory::factory($uri);
        }

        // Make sure we have a valid Zend_Uri_Http object
        if (! ($uri->isValid() && ($uri->getScheme() == 'http' || $uri->getScheme() == 'https'))) {
            throw new Exception\InvalidArgumentException('Passed URI is not a valid HTTP or HTTPS URI');
        }

        // Check that the cookie is secure (if required) and not expired
        if ($this->secure && $uri->getScheme() != 'https') {
            return false;
        }
        if ($this->isExpired($now)) {
            return false;
        }
        if ($this->isSessionCookie() && ! $matchSessionCookies) {
            return false;
        }

        // Check if the domain matches
        if (! self::matchCookieDomain($this->getDomain(), $uri->getHost())) {
            return false;
        }

        // Check that path matches using prefix match
        if (! self::matchCookiePath($this->getPath(), $uri->getPath())) {
            return false;
        }

        // If we didn't die until now, return true.
        return true;
    }

    /**
     * Check if a cookie's domain matches a host name.
     *
     * Used by Zend\Http\Cookies for cookie matching
     *
     * @param  string $cookieDomain
     * @param  string $host
     *
     * @return bool
     */
    public static function matchCookieDomain($cookieDomain, $host)
    {
        $cookieDomain = strtolower($cookieDomain);
        $host = strtolower($host);
        // Check for either exact match or suffix match
        return $cookieDomain == $host
            || preg_match('/' . preg_quote($cookieDomain) . '$/', $host);
    }

    /**
     * Check if a cookie's path matches a URL path
     *
     * Used by Zend\Http\Cookies for cookie matching
     *
     * @param  string $cookiePath
     * @param  string $path
     * @return bool
     */
    public static function matchCookiePath($cookiePath, $path)
    {
        return (strpos($path, $cookiePath) === 0);
    }

    public function toString()
    {
        return 'Set-Cookie: ' . $this->getFieldValue();
    }

    public function toStringMultipleHeaders(array $headers)
    {
        $headerLine = $this->toString();
        /* @var $header SetCookie */
        foreach ($headers as $header) {
            if (! $header instanceof SetCookie) {
                throw new Exception\RuntimeException(
                    'The SetCookie multiple header implementation can only accept an array of SetCookie headers'
                );
            }
            $headerLine .= "\n" . $header->toString();
        }
        return $headerLine;
    }
}