| [ Index ] |
PHP Cross Reference of WordPress Trunk (Updated Daily) |
[Summary view] [Print] [Text view]
1 <?php 2 /** 3 * Cookie storage object 4 * 5 * @package Requests\Cookies 6 */ 7 8 namespace WpOrg\Requests; 9 10 use WpOrg\Requests\Exception\InvalidArgument; 11 use WpOrg\Requests\Iri; 12 use WpOrg\Requests\Response\Headers; 13 use WpOrg\Requests\Utility\CaseInsensitiveDictionary; 14 use WpOrg\Requests\Utility\InputValidator; 15 use WpOrg\Requests\Utility\Trim; 16 17 /** 18 * Cookie storage object 19 * 20 * @package Requests\Cookies 21 */ 22 class Cookie { 23 /** 24 * Cookie name. 25 * 26 * @var string 27 */ 28 public $name; 29 30 /** 31 * Cookie value. 32 * 33 * @var string 34 */ 35 public $value; 36 37 /** 38 * Cookie attributes 39 * 40 * Valid keys are `'path'`, `'domain'`, `'expires'`, `'max-age'`, `'secure'` and 41 * `'httponly'`. 42 * 43 * @var \WpOrg\Requests\Utility\CaseInsensitiveDictionary|array Array-like object 44 */ 45 public $attributes = []; 46 47 /** 48 * Cookie flags 49 * 50 * Valid keys are `'creation'`, `'last-access'`, `'persistent'` and `'host-only'`. 51 * 52 * @var array 53 */ 54 public $flags = []; 55 56 /** 57 * Reference time for relative calculations 58 * 59 * This is used in place of `time()` when calculating Max-Age expiration and 60 * checking time validity. 61 * 62 * @var int 63 */ 64 public $reference_time = 0; 65 66 /** 67 * Create a new cookie object 68 * 69 * @param string $name The name of the cookie. 70 * @param string $value The value for the cookie. 71 * @param array|\WpOrg\Requests\Utility\CaseInsensitiveDictionary $attributes Associative array of attribute data 72 * @param array $flags The flags for the cookie. 73 * Valid keys are `'creation'`, `'last-access'`, 74 * `'persistent'` and `'host-only'`. 75 * @param int|null $reference_time Reference time for relative calculations. 76 * 77 * @throws \WpOrg\Requests\Exception\InvalidArgument When the passed $name argument is not a string. 78 * @throws \WpOrg\Requests\Exception\InvalidArgument When the passed $value argument is not a string. 79 * @throws \WpOrg\Requests\Exception\InvalidArgument When the passed $attributes argument is not an array or iterable object with array access. 80 * @throws \WpOrg\Requests\Exception\InvalidArgument When the passed $flags argument is not an array. 81 * @throws \WpOrg\Requests\Exception\InvalidArgument When the passed $reference_time argument is not an integer or null. 82 */ 83 public function __construct($name, $value, $attributes = [], $flags = [], $reference_time = null) { 84 if (is_string($name) === false) { 85 throw InvalidArgument::create(1, '$name', 'string', gettype($name)); 86 } 87 88 if (is_string($value) === false) { 89 throw InvalidArgument::create(2, '$value', 'string', gettype($value)); 90 } 91 92 if (InputValidator::has_array_access($attributes) === false || InputValidator::is_iterable($attributes) === false) { 93 throw InvalidArgument::create(3, '$attributes', 'array|ArrayAccess&Traversable', gettype($attributes)); 94 } 95 96 if (is_array($flags) === false) { 97 throw InvalidArgument::create(4, '$flags', 'array', gettype($flags)); 98 } 99 100 if ($reference_time !== null && is_int($reference_time) === false) { 101 throw InvalidArgument::create(5, '$reference_time', 'integer|null', gettype($reference_time)); 102 } 103 104 $this->name = $name; 105 $this->value = $value; 106 $this->attributes = $attributes; 107 $default_flags = [ 108 'creation' => time(), 109 'last-access' => time(), 110 'persistent' => false, 111 'host-only' => true, 112 ]; 113 $this->flags = array_merge($default_flags, $flags); 114 115 $this->reference_time = time(); 116 if ($reference_time !== null) { 117 $this->reference_time = $reference_time; 118 } 119 120 $this->normalize(); 121 } 122 123 /** 124 * Get the cookie value 125 * 126 * Attributes and other data can be accessed via methods. 127 */ 128 public function __toString() { 129 return $this->value; 130 } 131 132 /** 133 * Check if a cookie is expired. 134 * 135 * Checks the age against $this->reference_time to determine if the cookie 136 * is expired. 137 * 138 * @return boolean True if expired, false if time is valid. 139 */ 140 public function is_expired() { 141 // RFC6265, s. 4.1.2.2: 142 // If a cookie has both the Max-Age and the Expires attribute, the Max- 143 // Age attribute has precedence and controls the expiration date of the 144 // cookie. 145 if (isset($this->attributes['max-age'])) { 146 $max_age = $this->attributes['max-age']; 147 return $max_age < $this->reference_time; 148 } 149 150 if (isset($this->attributes['expires'])) { 151 $expires = $this->attributes['expires']; 152 return $expires < $this->reference_time; 153 } 154 155 return false; 156 } 157 158 /** 159 * Check if a cookie is valid for a given URI 160 * 161 * @param \WpOrg\Requests\Iri $uri URI to check 162 * @return boolean Whether the cookie is valid for the given URI 163 */ 164 public function uri_matches(Iri $uri) { 165 if (!$this->domain_matches($uri->host)) { 166 return false; 167 } 168 169 if (!$this->path_matches($uri->path)) { 170 return false; 171 } 172 173 return empty($this->attributes['secure']) || $uri->scheme === 'https'; 174 } 175 176 /** 177 * Check if a cookie is valid for a given domain 178 * 179 * @param string $domain Domain to check 180 * @return boolean Whether the cookie is valid for the given domain 181 */ 182 public function domain_matches($domain) { 183 if (is_string($domain) === false) { 184 return false; 185 } 186 187 if (!isset($this->attributes['domain'])) { 188 // Cookies created manually; cookies created by Requests will set 189 // the domain to the requested domain 190 return true; 191 } 192 193 $cookie_domain = $this->attributes['domain']; 194 if ($cookie_domain === $domain) { 195 // The cookie domain and the passed domain are identical. 196 return true; 197 } 198 199 // If the cookie is marked as host-only and we don't have an exact 200 // match, reject the cookie 201 if ($this->flags['host-only'] === true) { 202 return false; 203 } 204 205 if (strlen($domain) <= strlen($cookie_domain)) { 206 // For obvious reasons, the cookie domain cannot be a suffix if the passed domain 207 // is shorter than the cookie domain 208 return false; 209 } 210 211 if (substr($domain, -1 * strlen($cookie_domain)) !== $cookie_domain) { 212 // The cookie domain should be a suffix of the passed domain. 213 return false; 214 } 215 216 $prefix = substr($domain, 0, strlen($domain) - strlen($cookie_domain)); 217 if (substr($prefix, -1) !== '.') { 218 // The last character of the passed domain that is not included in the 219 // domain string should be a %x2E (".") character. 220 return false; 221 } 222 223 // The passed domain should be a host name (i.e., not an IP address). 224 return !preg_match('#^(.+\.)\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$#', $domain); 225 } 226 227 /** 228 * Check if a cookie is valid for a given path 229 * 230 * From the path-match check in RFC 6265 section 5.1.4 231 * 232 * @param string $request_path Path to check 233 * @return boolean Whether the cookie is valid for the given path 234 */ 235 public function path_matches($request_path) { 236 if (empty($request_path)) { 237 // Normalize empty path to root 238 $request_path = '/'; 239 } 240 241 if (!isset($this->attributes['path'])) { 242 // Cookies created manually; cookies created by Requests will set 243 // the path to the requested path 244 return true; 245 } 246 247 if (is_scalar($request_path) === false) { 248 return false; 249 } 250 251 $cookie_path = $this->attributes['path']; 252 253 if ($cookie_path === $request_path) { 254 // The cookie-path and the request-path are identical. 255 return true; 256 } 257 258 if (strlen($request_path) > strlen($cookie_path) && substr($request_path, 0, strlen($cookie_path)) === $cookie_path) { 259 if (substr($cookie_path, -1) === '/') { 260 // The cookie-path is a prefix of the request-path, and the last 261 // character of the cookie-path is %x2F ("/"). 262 return true; 263 } 264 265 if (substr($request_path, strlen($cookie_path), 1) === '/') { 266 // The cookie-path is a prefix of the request-path, and the 267 // first character of the request-path that is not included in 268 // the cookie-path is a %x2F ("/") character. 269 return true; 270 } 271 } 272 273 return false; 274 } 275 276 /** 277 * Normalize cookie and attributes 278 * 279 * @return boolean Whether the cookie was successfully normalized 280 */ 281 public function normalize() { 282 foreach ($this->attributes as $key => $value) { 283 $orig_value = $value; 284 285 if (is_string($key)) { 286 $value = $this->normalize_attribute($key, $value); 287 } 288 289 if ($value === null) { 290 unset($this->attributes[$key]); 291 continue; 292 } 293 294 if ($value !== $orig_value) { 295 $this->attributes[$key] = $value; 296 } 297 } 298 299 return true; 300 } 301 302 /** 303 * Parse an individual cookie attribute 304 * 305 * Handles parsing individual attributes from the cookie values. 306 * 307 * @param string $name Attribute name 308 * @param string|int|bool $value Attribute value (string/integer value, or true if empty/flag) 309 * @return mixed Value if available, or null if the attribute value is invalid (and should be skipped) 310 */ 311 protected function normalize_attribute($name, $value) { 312 switch (strtolower($name)) { 313 case 'expires': 314 // Expiration parsing, as per RFC 6265 section 5.2.1 315 if (is_int($value)) { 316 return $value; 317 } 318 319 $expiry_time = strtotime($value); 320 if ($expiry_time === false) { 321 return null; 322 } 323 324 return $expiry_time; 325 326 case 'max-age': 327 // Expiration parsing, as per RFC 6265 section 5.2.2 328 if (is_int($value)) { 329 return $value; 330 } 331 332 // Check that we have a valid age 333 if (!preg_match('/^-?\d+$/', $value)) { 334 return null; 335 } 336 337 $delta_seconds = (int) $value; 338 if ($delta_seconds <= 0) { 339 $expiry_time = 0; 340 } else { 341 $expiry_time = $this->reference_time + $delta_seconds; 342 } 343 344 return $expiry_time; 345 346 case 'domain': 347 // Domains are not required as per RFC 6265 section 5.2.3 348 if (empty($value)) { 349 return null; 350 } 351 352 // Domain normalization, as per RFC 6265 section 5.2.3 353 if ($value[0] === '.') { 354 $value = substr($value, 1); 355 } 356 357 return $value; 358 359 default: 360 return $value; 361 } 362 } 363 364 /** 365 * Format a cookie for a Cookie header 366 * 367 * This is used when sending cookies to a server. 368 * 369 * @return string Cookie formatted for Cookie header 370 */ 371 public function format_for_header() { 372 return sprintf('%s=%s', $this->name, $this->value); 373 } 374 375 /** 376 * Format a cookie for a Set-Cookie header 377 * 378 * This is used when sending cookies to clients. This isn't really 379 * applicable to client-side usage, but might be handy for debugging. 380 * 381 * @return string Cookie formatted for Set-Cookie header 382 */ 383 public function format_for_set_cookie() { 384 $header_value = $this->format_for_header(); 385 if (!empty($this->attributes)) { 386 $parts = []; 387 foreach ($this->attributes as $key => $value) { 388 // Ignore non-associative attributes 389 if (is_numeric($key)) { 390 $parts[] = $value; 391 } else { 392 $parts[] = sprintf('%s=%s', $key, $value); 393 } 394 } 395 396 $header_value .= '; ' . implode('; ', $parts); 397 } 398 399 return $header_value; 400 } 401 402 /** 403 * Parse a cookie string into a cookie object 404 * 405 * Based on Mozilla's parsing code in Firefox and related projects, which 406 * is an intentional deviation from RFC 2109 and RFC 2616. RFC 6265 407 * specifies some of this handling, but not in a thorough manner. 408 * 409 * @param string $cookie_header Cookie header value (from a Set-Cookie header) 410 * @param string $name 411 * @param int|null $reference_time 412 * @return \WpOrg\Requests\Cookie Parsed cookie object 413 * 414 * @throws \WpOrg\Requests\Exception\InvalidArgument When the passed $cookie_header argument is not a string. 415 * @throws \WpOrg\Requests\Exception\InvalidArgument When the passed $name argument is not a string. 416 */ 417 public static function parse($cookie_header, $name = '', $reference_time = null) { 418 if (is_string($cookie_header) === false) { 419 throw InvalidArgument::create(1, '$cookie_header', 'string', gettype($cookie_header)); 420 } 421 422 if (is_string($name) === false) { 423 throw InvalidArgument::create(2, '$name', 'string', gettype($name)); 424 } 425 426 $parts = explode(';', $cookie_header); 427 $kvparts = array_shift($parts); 428 429 if (!empty($name)) { 430 $value = $cookie_header; 431 } elseif (strpos($kvparts, '=') === false) { 432 // Some sites might only have a value without the equals separator. 433 // Deviate from RFC 6265 and pretend it was actually a blank name 434 // (`=foo`) 435 // 436 // https://bugzilla.mozilla.org/show_bug.cgi?id=169091 437 $name = ''; 438 $value = $kvparts; 439 } else { 440 list($name, $value) = explode('=', $kvparts, 2); 441 } 442 443 $name = trim($name, Trim::WHITESPACE_CHARS_NO_FF); 444 $value = trim($value, Trim::WHITESPACE_CHARS_NO_FF); 445 446 // Attribute keys are handled case-insensitively 447 $attributes = new CaseInsensitiveDictionary(); 448 449 if (!empty($parts)) { 450 foreach ($parts as $part) { 451 if (strpos($part, '=') === false) { 452 $part_key = $part; 453 $part_value = true; 454 } else { 455 list($part_key, $part_value) = explode('=', $part, 2); 456 $part_value = trim($part_value, Trim::WHITESPACE_CHARS_NO_FF); 457 } 458 459 $part_key = trim($part_key, Trim::WHITESPACE_CHARS_NO_FF); 460 $attributes[$part_key] = $part_value; 461 } 462 } 463 464 return new static($name, $value, $attributes, [], $reference_time); 465 } 466 467 /** 468 * Parse all Set-Cookie headers from request headers 469 * 470 * @param \WpOrg\Requests\Response\Headers $headers Headers to parse from 471 * @param \WpOrg\Requests\Iri|null $origin URI for comparing cookie origins 472 * @param int|null $time Reference time for expiration calculation 473 * @return array 474 * 475 * @throws \WpOrg\Requests\Exception\InvalidArgument When the passed $origin argument is not null or an instance of the Iri class. 476 */ 477 public static function parse_from_headers(Headers $headers, $origin = null, $time = null) { 478 $cookie_headers = $headers->getValues('Set-Cookie'); 479 if (empty($cookie_headers)) { 480 return []; 481 } 482 483 if ($origin !== null && !($origin instanceof Iri)) { 484 throw InvalidArgument::create(2, '$origin', Iri::class . ' or null', gettype($origin)); 485 } 486 487 $cookies = []; 488 foreach ($cookie_headers as $header) { 489 $parsed = self::parse($header, '', $time); 490 491 // Default domain/path attributes 492 if (empty($parsed->attributes['domain']) && !empty($origin)) { 493 $parsed->attributes['domain'] = $origin->host; 494 $parsed->flags['host-only'] = true; 495 } else { 496 $parsed->flags['host-only'] = false; 497 } 498 499 $path_is_valid = (!empty($parsed->attributes['path']) && $parsed->attributes['path'][0] === '/'); 500 if (!$path_is_valid && !empty($origin)) { 501 $path = $origin->path; 502 503 // Default path normalization as per RFC 6265 section 5.1.4 504 if (substr($path, 0, 1) !== '/') { 505 // If the uri-path is empty or if the first character of 506 // the uri-path is not a %x2F ("/") character, output 507 // %x2F ("/") and skip the remaining steps. 508 $path = '/'; 509 } elseif (substr_count($path, '/') === 1) { 510 // If the uri-path contains no more than one %x2F ("/") 511 // character, output %x2F ("/") and skip the remaining 512 // step. 513 $path = '/'; 514 } else { 515 // Output the characters of the uri-path from the first 516 // character up to, but not including, the right-most 517 // %x2F ("/"). 518 $path = substr($path, 0, strrpos($path, '/')); 519 } 520 521 $parsed->attributes['path'] = $path; 522 } 523 524 // Reject invalid cookie domains 525 if (!empty($origin) && !$parsed->domain_matches($origin->host)) { 526 continue; 527 } 528 529 $cookies[$parsed->name] = $parsed; 530 } 531 532 return $cookies; 533 } 534 }
title
Description
Body
title
Description
Body
title
Description
Body
title
Body
| Generated : Sat Nov 28 08:20:01 2026 | Cross-referenced by PHPXref |