1<?php 2 3/* 4 * This file is part of the Symfony package. 5 * 6 * (c) Fabien Potencier <fabien@symfony.com> 7 * 8 * For the full copyright and license information, please view the LICENSE 9 * file that was distributed with this source code. 10 */ 11 12namespace Symfony\Component\HttpFoundation; 13 14use Symfony\Component\HttpFoundation\Exception\ConflictingHeadersException; 15use Symfony\Component\HttpFoundation\Exception\SuspiciousOperationException; 16use Symfony\Component\HttpFoundation\Session\SessionInterface; 17 18// Help opcache.preload discover always-needed symbols 19class_exists(AcceptHeader::class); 20class_exists(FileBag::class); 21class_exists(HeaderBag::class); 22class_exists(HeaderUtils::class); 23class_exists(ParameterBag::class); 24class_exists(ServerBag::class); 25 26/** 27 * Request represents an HTTP request. 28 * 29 * The methods dealing with URL accept / return a raw path (% encoded): 30 * * getBasePath 31 * * getBaseUrl 32 * * getPathInfo 33 * * getRequestUri 34 * * getUri 35 * * getUriForPath 36 * 37 * @author Fabien Potencier <fabien@symfony.com> 38 */ 39class Request 40{ 41 const HEADER_FORWARDED = 0b00001; // When using RFC 7239 42 const HEADER_X_FORWARDED_FOR = 0b00010; 43 const HEADER_X_FORWARDED_HOST = 0b00100; 44 const HEADER_X_FORWARDED_PROTO = 0b01000; 45 const HEADER_X_FORWARDED_PORT = 0b10000; 46 const HEADER_X_FORWARDED_ALL = 0b11110; // All "X-Forwarded-*" headers 47 const HEADER_X_FORWARDED_AWS_ELB = 0b11010; // AWS ELB doesn't send X-Forwarded-Host 48 49 const METHOD_HEAD = 'HEAD'; 50 const METHOD_GET = 'GET'; 51 const METHOD_POST = 'POST'; 52 const METHOD_PUT = 'PUT'; 53 const METHOD_PATCH = 'PATCH'; 54 const METHOD_DELETE = 'DELETE'; 55 const METHOD_PURGE = 'PURGE'; 56 const METHOD_OPTIONS = 'OPTIONS'; 57 const METHOD_TRACE = 'TRACE'; 58 const METHOD_CONNECT = 'CONNECT'; 59 60 /** 61 * @var string[] 62 */ 63 protected static $trustedProxies = []; 64 65 /** 66 * @var string[] 67 */ 68 protected static $trustedHostPatterns = []; 69 70 /** 71 * @var string[] 72 */ 73 protected static $trustedHosts = []; 74 75 protected static $httpMethodParameterOverride = false; 76 77 /** 78 * Custom parameters. 79 * 80 * @var ParameterBag 81 */ 82 public $attributes; 83 84 /** 85 * Request body parameters ($_POST). 86 * 87 * @var ParameterBag 88 */ 89 public $request; 90 91 /** 92 * Query string parameters ($_GET). 93 * 94 * @var ParameterBag 95 */ 96 public $query; 97 98 /** 99 * Server and execution environment parameters ($_SERVER). 100 * 101 * @var ServerBag 102 */ 103 public $server; 104 105 /** 106 * Uploaded files ($_FILES). 107 * 108 * @var FileBag 109 */ 110 public $files; 111 112 /** 113 * Cookies ($_COOKIE). 114 * 115 * @var ParameterBag 116 */ 117 public $cookies; 118 119 /** 120 * Headers (taken from the $_SERVER). 121 * 122 * @var HeaderBag 123 */ 124 public $headers; 125 126 /** 127 * @var string|resource|false|null 128 */ 129 protected $content; 130 131 /** 132 * @var array 133 */ 134 protected $languages; 135 136 /** 137 * @var array 138 */ 139 protected $charsets; 140 141 /** 142 * @var array 143 */ 144 protected $encodings; 145 146 /** 147 * @var array 148 */ 149 protected $acceptableContentTypes; 150 151 /** 152 * @var string 153 */ 154 protected $pathInfo; 155 156 /** 157 * @var string 158 */ 159 protected $requestUri; 160 161 /** 162 * @var string 163 */ 164 protected $baseUrl; 165 166 /** 167 * @var string 168 */ 169 protected $basePath; 170 171 /** 172 * @var string 173 */ 174 protected $method; 175 176 /** 177 * @var string 178 */ 179 protected $format; 180 181 /** 182 * @var SessionInterface 183 */ 184 protected $session; 185 186 /** 187 * @var string 188 */ 189 protected $locale; 190 191 /** 192 * @var string 193 */ 194 protected $defaultLocale = 'en'; 195 196 /** 197 * @var array 198 */ 199 protected static $formats; 200 201 protected static $requestFactory; 202 203 /** 204 * @var string|null 205 */ 206 private $preferredFormat; 207 private $isHostValid = true; 208 private $isForwardedValid = true; 209 210 private static $trustedHeaderSet = -1; 211 212 private static $forwardedParams = [ 213 self::HEADER_X_FORWARDED_FOR => 'for', 214 self::HEADER_X_FORWARDED_HOST => 'host', 215 self::HEADER_X_FORWARDED_PROTO => 'proto', 216 self::HEADER_X_FORWARDED_PORT => 'host', 217 ]; 218 219 /** 220 * Names for headers that can be trusted when 221 * using trusted proxies. 222 * 223 * The FORWARDED header is the standard as of rfc7239. 224 * 225 * The other headers are non-standard, but widely used 226 * by popular reverse proxies (like Apache mod_proxy or Amazon EC2). 227 */ 228 private static $trustedHeaders = [ 229 self::HEADER_FORWARDED => 'FORWARDED', 230 self::HEADER_X_FORWARDED_FOR => 'X_FORWARDED_FOR', 231 self::HEADER_X_FORWARDED_HOST => 'X_FORWARDED_HOST', 232 self::HEADER_X_FORWARDED_PROTO => 'X_FORWARDED_PROTO', 233 self::HEADER_X_FORWARDED_PORT => 'X_FORWARDED_PORT', 234 ]; 235 236 /** 237 * @param array $query The GET parameters 238 * @param array $request The POST parameters 239 * @param array $attributes The request attributes (parameters parsed from the PATH_INFO, ...) 240 * @param array $cookies The COOKIE parameters 241 * @param array $files The FILES parameters 242 * @param array $server The SERVER parameters 243 * @param string|resource|null $content The raw body data 244 */ 245 public function __construct(array $query = [], array $request = [], array $attributes = [], array $cookies = [], array $files = [], array $server = [], $content = null) 246 { 247 $this->initialize($query, $request, $attributes, $cookies, $files, $server, $content); 248 } 249 250 /** 251 * Sets the parameters for this request. 252 * 253 * This method also re-initializes all properties. 254 * 255 * @param array $query The GET parameters 256 * @param array $request The POST parameters 257 * @param array $attributes The request attributes (parameters parsed from the PATH_INFO, ...) 258 * @param array $cookies The COOKIE parameters 259 * @param array $files The FILES parameters 260 * @param array $server The SERVER parameters 261 * @param string|resource|null $content The raw body data 262 */ 263 public function initialize(array $query = [], array $request = [], array $attributes = [], array $cookies = [], array $files = [], array $server = [], $content = null) 264 { 265 $this->request = new ParameterBag($request); 266 $this->query = new ParameterBag($query); 267 $this->attributes = new ParameterBag($attributes); 268 $this->cookies = new ParameterBag($cookies); 269 $this->files = new FileBag($files); 270 $this->server = new ServerBag($server); 271 $this->headers = new HeaderBag($this->server->getHeaders()); 272 273 $this->content = $content; 274 $this->languages = null; 275 $this->charsets = null; 276 $this->encodings = null; 277 $this->acceptableContentTypes = null; 278 $this->pathInfo = null; 279 $this->requestUri = null; 280 $this->baseUrl = null; 281 $this->basePath = null; 282 $this->method = null; 283 $this->format = null; 284 } 285 286 /** 287 * Creates a new request with values from PHP's super globals. 288 * 289 * @return static 290 */ 291 public static function createFromGlobals() 292 { 293 $request = self::createRequestFromFactory($_GET, $_POST, [], $_COOKIE, $_FILES, $_SERVER); 294 295 if (0 === strpos($request->headers->get('CONTENT_TYPE'), 'application/x-www-form-urlencoded') 296 && \in_array(strtoupper($request->server->get('REQUEST_METHOD', 'GET')), ['PUT', 'DELETE', 'PATCH']) 297 ) { 298 parse_str($request->getContent(), $data); 299 $request->request = new ParameterBag($data); 300 } 301 302 return $request; 303 } 304 305 /** 306 * Creates a Request based on a given URI and configuration. 307 * 308 * The information contained in the URI always take precedence 309 * over the other information (server and parameters). 310 * 311 * @param string $uri The URI 312 * @param string $method The HTTP method 313 * @param array $parameters The query (GET) or request (POST) parameters 314 * @param array $cookies The request cookies ($_COOKIE) 315 * @param array $files The request files ($_FILES) 316 * @param array $server The server parameters ($_SERVER) 317 * @param string|resource|null $content The raw body data 318 * 319 * @return static 320 */ 321 public static function create(string $uri, string $method = 'GET', array $parameters = [], array $cookies = [], array $files = [], array $server = [], $content = null) 322 { 323 $server = array_replace([ 324 'SERVER_NAME' => 'localhost', 325 'SERVER_PORT' => 80, 326 'HTTP_HOST' => 'localhost', 327 'HTTP_USER_AGENT' => 'Symfony', 328 'HTTP_ACCEPT' => 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 329 'HTTP_ACCEPT_LANGUAGE' => 'en-us,en;q=0.5', 330 'HTTP_ACCEPT_CHARSET' => 'ISO-8859-1,utf-8;q=0.7,*;q=0.7', 331 'REMOTE_ADDR' => '127.0.0.1', 332 'SCRIPT_NAME' => '', 333 'SCRIPT_FILENAME' => '', 334 'SERVER_PROTOCOL' => 'HTTP/1.1', 335 'REQUEST_TIME' => time(), 336 ], $server); 337 338 $server['PATH_INFO'] = ''; 339 $server['REQUEST_METHOD'] = strtoupper($method); 340 341 $components = parse_url($uri); 342 if (isset($components['host'])) { 343 $server['SERVER_NAME'] = $components['host']; 344 $server['HTTP_HOST'] = $components['host']; 345 } 346 347 if (isset($components['scheme'])) { 348 if ('https' === $components['scheme']) { 349 $server['HTTPS'] = 'on'; 350 $server['SERVER_PORT'] = 443; 351 } else { 352 unset($server['HTTPS']); 353 $server['SERVER_PORT'] = 80; 354 } 355 } 356 357 if (isset($components['port'])) { 358 $server['SERVER_PORT'] = $components['port']; 359 $server['HTTP_HOST'] .= ':'.$components['port']; 360 } 361 362 if (isset($components['user'])) { 363 $server['PHP_AUTH_USER'] = $components['user']; 364 } 365 366 if (isset($components['pass'])) { 367 $server['PHP_AUTH_PW'] = $components['pass']; 368 } 369 370 if (!isset($components['path'])) { 371 $components['path'] = '/'; 372 } 373 374 switch (strtoupper($method)) { 375 case 'POST': 376 case 'PUT': 377 case 'DELETE': 378 if (!isset($server['CONTENT_TYPE'])) { 379 $server['CONTENT_TYPE'] = 'application/x-www-form-urlencoded'; 380 } 381 // no break 382 case 'PATCH': 383 $request = $parameters; 384 $query = []; 385 break; 386 default: 387 $request = []; 388 $query = $parameters; 389 break; 390 } 391 392 $queryString = ''; 393 if (isset($components['query'])) { 394 parse_str(html_entity_decode($components['query']), $qs); 395 396 if ($query) { 397 $query = array_replace($qs, $query); 398 $queryString = http_build_query($query, '', '&'); 399 } else { 400 $query = $qs; 401 $queryString = $components['query']; 402 } 403 } elseif ($query) { 404 $queryString = http_build_query($query, '', '&'); 405 } 406 407 $server['REQUEST_URI'] = $components['path'].('' !== $queryString ? '?'.$queryString : ''); 408 $server['QUERY_STRING'] = $queryString; 409 410 return self::createRequestFromFactory($query, $request, [], $cookies, $files, $server, $content); 411 } 412 413 /** 414 * Sets a callable able to create a Request instance. 415 * 416 * This is mainly useful when you need to override the Request class 417 * to keep BC with an existing system. It should not be used for any 418 * other purpose. 419 */ 420 public static function setFactory(?callable $callable) 421 { 422 self::$requestFactory = $callable; 423 } 424 425 /** 426 * Clones a request and overrides some of its parameters. 427 * 428 * @param array $query The GET parameters 429 * @param array $request The POST parameters 430 * @param array $attributes The request attributes (parameters parsed from the PATH_INFO, ...) 431 * @param array $cookies The COOKIE parameters 432 * @param array $files The FILES parameters 433 * @param array $server The SERVER parameters 434 * 435 * @return static 436 */ 437 public function duplicate(array $query = null, array $request = null, array $attributes = null, array $cookies = null, array $files = null, array $server = null) 438 { 439 $dup = clone $this; 440 if (null !== $query) { 441 $dup->query = new ParameterBag($query); 442 } 443 if (null !== $request) { 444 $dup->request = new ParameterBag($request); 445 } 446 if (null !== $attributes) { 447 $dup->attributes = new ParameterBag($attributes); 448 } 449 if (null !== $cookies) { 450 $dup->cookies = new ParameterBag($cookies); 451 } 452 if (null !== $files) { 453 $dup->files = new FileBag($files); 454 } 455 if (null !== $server) { 456 $dup->server = new ServerBag($server); 457 $dup->headers = new HeaderBag($dup->server->getHeaders()); 458 } 459 $dup->languages = null; 460 $dup->charsets = null; 461 $dup->encodings = null; 462 $dup->acceptableContentTypes = null; 463 $dup->pathInfo = null; 464 $dup->requestUri = null; 465 $dup->baseUrl = null; 466 $dup->basePath = null; 467 $dup->method = null; 468 $dup->format = null; 469 470 if (!$dup->get('_format') && $this->get('_format')) { 471 $dup->attributes->set('_format', $this->get('_format')); 472 } 473 474 if (!$dup->getRequestFormat(null)) { 475 $dup->setRequestFormat($this->getRequestFormat(null)); 476 } 477 478 return $dup; 479 } 480 481 /** 482 * Clones the current request. 483 * 484 * Note that the session is not cloned as duplicated requests 485 * are most of the time sub-requests of the main one. 486 */ 487 public function __clone() 488 { 489 $this->query = clone $this->query; 490 $this->request = clone $this->request; 491 $this->attributes = clone $this->attributes; 492 $this->cookies = clone $this->cookies; 493 $this->files = clone $this->files; 494 $this->server = clone $this->server; 495 $this->headers = clone $this->headers; 496 } 497 498 /** 499 * Returns the request as a string. 500 * 501 * @return string The request 502 */ 503 public function __toString() 504 { 505 try { 506 $content = $this->getContent(); 507 } catch (\LogicException $e) { 508 if (\PHP_VERSION_ID >= 70400) { 509 throw $e; 510 } 511 512 return trigger_error($e, E_USER_ERROR); 513 } 514 515 $cookieHeader = ''; 516 $cookies = []; 517 518 foreach ($this->cookies as $k => $v) { 519 $cookies[] = $k.'='.$v; 520 } 521 522 if (!empty($cookies)) { 523 $cookieHeader = 'Cookie: '.implode('; ', $cookies)."\r\n"; 524 } 525 526 return 527 sprintf('%s %s %s', $this->getMethod(), $this->getRequestUri(), $this->server->get('SERVER_PROTOCOL'))."\r\n". 528 $this->headers. 529 $cookieHeader."\r\n". 530 $content; 531 } 532 533 /** 534 * Overrides the PHP global variables according to this request instance. 535 * 536 * It overrides $_GET, $_POST, $_REQUEST, $_SERVER, $_COOKIE. 537 * $_FILES is never overridden, see rfc1867 538 */ 539 public function overrideGlobals() 540 { 541 $this->server->set('QUERY_STRING', static::normalizeQueryString(http_build_query($this->query->all(), '', '&'))); 542 543 $_GET = $this->query->all(); 544 $_POST = $this->request->all(); 545 $_SERVER = $this->server->all(); 546 $_COOKIE = $this->cookies->all(); 547 548 foreach ($this->headers->all() as $key => $value) { 549 $key = strtoupper(str_replace('-', '_', $key)); 550 if (\in_array($key, ['CONTENT_TYPE', 'CONTENT_LENGTH', 'CONTENT_MD5'], true)) { 551 $_SERVER[$key] = implode(', ', $value); 552 } else { 553 $_SERVER['HTTP_'.$key] = implode(', ', $value); 554 } 555 } 556 557 $request = ['g' => $_GET, 'p' => $_POST, 'c' => $_COOKIE]; 558 559 $requestOrder = ini_get('request_order') ?: ini_get('variables_order'); 560 $requestOrder = preg_replace('#[^cgp]#', '', strtolower($requestOrder)) ?: 'gp'; 561 562 $_REQUEST = [[]]; 563 564 foreach (str_split($requestOrder) as $order) { 565 $_REQUEST[] = $request[$order]; 566 } 567 568 $_REQUEST = array_merge(...$_REQUEST); 569 } 570 571 /** 572 * Sets a list of trusted proxies. 573 * 574 * You should only list the reverse proxies that you manage directly. 575 * 576 * @param array $proxies A list of trusted proxies, the string 'REMOTE_ADDR' will be replaced with $_SERVER['REMOTE_ADDR'] 577 * @param int $trustedHeaderSet A bit field of Request::HEADER_*, to set which headers to trust from your proxies 578 * 579 * @throws \InvalidArgumentException When $trustedHeaderSet is invalid 580 */ 581 public static function setTrustedProxies(array $proxies, int $trustedHeaderSet) 582 { 583 self::$trustedProxies = array_reduce($proxies, function ($proxies, $proxy) { 584 if ('REMOTE_ADDR' !== $proxy) { 585 $proxies[] = $proxy; 586 } elseif (isset($_SERVER['REMOTE_ADDR'])) { 587 $proxies[] = $_SERVER['REMOTE_ADDR']; 588 } 589 590 return $proxies; 591 }, []); 592 self::$trustedHeaderSet = $trustedHeaderSet; 593 } 594 595 /** 596 * Gets the list of trusted proxies. 597 * 598 * @return array An array of trusted proxies 599 */ 600 public static function getTrustedProxies() 601 { 602 return self::$trustedProxies; 603 } 604 605 /** 606 * Gets the set of trusted headers from trusted proxies. 607 * 608 * @return int A bit field of Request::HEADER_* that defines which headers are trusted from your proxies 609 */ 610 public static function getTrustedHeaderSet() 611 { 612 return self::$trustedHeaderSet; 613 } 614 615 /** 616 * Sets a list of trusted host patterns. 617 * 618 * You should only list the hosts you manage using regexs. 619 * 620 * @param array $hostPatterns A list of trusted host patterns 621 */ 622 public static function setTrustedHosts(array $hostPatterns) 623 { 624 self::$trustedHostPatterns = array_map(function ($hostPattern) { 625 return sprintf('{%s}i', $hostPattern); 626 }, $hostPatterns); 627 // we need to reset trusted hosts on trusted host patterns change 628 self::$trustedHosts = []; 629 } 630 631 /** 632 * Gets the list of trusted host patterns. 633 * 634 * @return array An array of trusted host patterns 635 */ 636 public static function getTrustedHosts() 637 { 638 return self::$trustedHostPatterns; 639 } 640 641 /** 642 * Normalizes a query string. 643 * 644 * It builds a normalized query string, where keys/value pairs are alphabetized, 645 * have consistent escaping and unneeded delimiters are removed. 646 * 647 * @return string A normalized query string for the Request 648 */ 649 public static function normalizeQueryString(?string $qs) 650 { 651 if ('' === ($qs ?? '')) { 652 return ''; 653 } 654 655 parse_str($qs, $qs); 656 ksort($qs); 657 658 return http_build_query($qs, '', '&', PHP_QUERY_RFC3986); 659 } 660 661 /** 662 * Enables support for the _method request parameter to determine the intended HTTP method. 663 * 664 * Be warned that enabling this feature might lead to CSRF issues in your code. 665 * Check that you are using CSRF tokens when required. 666 * If the HTTP method parameter override is enabled, an html-form with method "POST" can be altered 667 * and used to send a "PUT" or "DELETE" request via the _method request parameter. 668 * If these methods are not protected against CSRF, this presents a possible vulnerability. 669 * 670 * The HTTP method can only be overridden when the real HTTP method is POST. 671 */ 672 public static function enableHttpMethodParameterOverride() 673 { 674 self::$httpMethodParameterOverride = true; 675 } 676 677 /** 678 * Checks whether support for the _method request parameter is enabled. 679 * 680 * @return bool True when the _method request parameter is enabled, false otherwise 681 */ 682 public static function getHttpMethodParameterOverride() 683 { 684 return self::$httpMethodParameterOverride; 685 } 686 687 /** 688 * Gets a "parameter" value from any bag. 689 * 690 * This method is mainly useful for libraries that want to provide some flexibility. If you don't need the 691 * flexibility in controllers, it is better to explicitly get request parameters from the appropriate 692 * public property instead (attributes, query, request). 693 * 694 * Order of precedence: PATH (routing placeholders or custom attributes), GET, BODY 695 * 696 * @param mixed $default The default value if the parameter key does not exist 697 * 698 * @return mixed 699 */ 700 public function get(string $key, $default = null) 701 { 702 if ($this !== $result = $this->attributes->get($key, $this)) { 703 return $result; 704 } 705 706 if ($this !== $result = $this->query->get($key, $this)) { 707 return $result; 708 } 709 710 if ($this !== $result = $this->request->get($key, $this)) { 711 return $result; 712 } 713 714 return $default; 715 } 716 717 /** 718 * Gets the Session. 719 * 720 * @return SessionInterface The session 721 */ 722 public function getSession() 723 { 724 $session = $this->session; 725 if (!$session instanceof SessionInterface && null !== $session) { 726 $this->setSession($session = $session()); 727 } 728 729 if (null === $session) { 730 throw new \BadMethodCallException('Session has not been set.'); 731 } 732 733 return $session; 734 } 735 736 /** 737 * Whether the request contains a Session which was started in one of the 738 * previous requests. 739 * 740 * @return bool 741 */ 742 public function hasPreviousSession() 743 { 744 // the check for $this->session avoids malicious users trying to fake a session cookie with proper name 745 return $this->hasSession() && $this->cookies->has($this->getSession()->getName()); 746 } 747 748 /** 749 * Whether the request contains a Session object. 750 * 751 * This method does not give any information about the state of the session object, 752 * like whether the session is started or not. It is just a way to check if this Request 753 * is associated with a Session instance. 754 * 755 * @return bool true when the Request contains a Session object, false otherwise 756 */ 757 public function hasSession() 758 { 759 return null !== $this->session; 760 } 761 762 public function setSession(SessionInterface $session) 763 { 764 $this->session = $session; 765 } 766 767 /** 768 * @internal 769 */ 770 public function setSessionFactory(callable $factory) 771 { 772 $this->session = $factory; 773 } 774 775 /** 776 * Returns the client IP addresses. 777 * 778 * In the returned array the most trusted IP address is first, and the 779 * least trusted one last. The "real" client IP address is the last one, 780 * but this is also the least trusted one. Trusted proxies are stripped. 781 * 782 * Use this method carefully; you should use getClientIp() instead. 783 * 784 * @return array The client IP addresses 785 * 786 * @see getClientIp() 787 */ 788 public function getClientIps() 789 { 790 $ip = $this->server->get('REMOTE_ADDR'); 791 792 if (!$this->isFromTrustedProxy()) { 793 return [$ip]; 794 } 795 796 return $this->getTrustedValues(self::HEADER_X_FORWARDED_FOR, $ip) ?: [$ip]; 797 } 798 799 /** 800 * Returns the client IP address. 801 * 802 * This method can read the client IP address from the "X-Forwarded-For" header 803 * when trusted proxies were set via "setTrustedProxies()". The "X-Forwarded-For" 804 * header value is a comma+space separated list of IP addresses, the left-most 805 * being the original client, and each successive proxy that passed the request 806 * adding the IP address where it received the request from. 807 * 808 * If your reverse proxy uses a different header name than "X-Forwarded-For", 809 * ("Client-Ip" for instance), configure it via the $trustedHeaderSet 810 * argument of the Request::setTrustedProxies() method instead. 811 * 812 * @return string|null The client IP address 813 * 814 * @see getClientIps() 815 * @see https://wikipedia.org/wiki/X-Forwarded-For 816 */ 817 public function getClientIp() 818 { 819 $ipAddresses = $this->getClientIps(); 820 821 return $ipAddresses[0]; 822 } 823 824 /** 825 * Returns current script name. 826 * 827 * @return string 828 */ 829 public function getScriptName() 830 { 831 return $this->server->get('SCRIPT_NAME', $this->server->get('ORIG_SCRIPT_NAME', '')); 832 } 833 834 /** 835 * Returns the path being requested relative to the executed script. 836 * 837 * The path info always starts with a /. 838 * 839 * Suppose this request is instantiated from /mysite on localhost: 840 * 841 * * http://localhost/mysite returns an empty string 842 * * http://localhost/mysite/about returns '/about' 843 * * http://localhost/mysite/enco%20ded returns '/enco%20ded' 844 * * http://localhost/mysite/about?var=1 returns '/about' 845 * 846 * @return string The raw path (i.e. not urldecoded) 847 */ 848 public function getPathInfo() 849 { 850 if (null === $this->pathInfo) { 851 $this->pathInfo = $this->preparePathInfo(); 852 } 853 854 return $this->pathInfo; 855 } 856 857 /** 858 * Returns the root path from which this request is executed. 859 * 860 * Suppose that an index.php file instantiates this request object: 861 * 862 * * http://localhost/index.php returns an empty string 863 * * http://localhost/index.php/page returns an empty string 864 * * http://localhost/web/index.php returns '/web' 865 * * http://localhost/we%20b/index.php returns '/we%20b' 866 * 867 * @return string The raw path (i.e. not urldecoded) 868 */ 869 public function getBasePath() 870 { 871 if (null === $this->basePath) { 872 $this->basePath = $this->prepareBasePath(); 873 } 874 875 return $this->basePath; 876 } 877 878 /** 879 * Returns the root URL from which this request is executed. 880 * 881 * The base URL never ends with a /. 882 * 883 * This is similar to getBasePath(), except that it also includes the 884 * script filename (e.g. index.php) if one exists. 885 * 886 * @return string The raw URL (i.e. not urldecoded) 887 */ 888 public function getBaseUrl() 889 { 890 if (null === $this->baseUrl) { 891 $this->baseUrl = $this->prepareBaseUrl(); 892 } 893 894 return $this->baseUrl; 895 } 896 897 /** 898 * Gets the request's scheme. 899 * 900 * @return string 901 */ 902 public function getScheme() 903 { 904 return $this->isSecure() ? 'https' : 'http'; 905 } 906 907 /** 908 * Returns the port on which the request is made. 909 * 910 * This method can read the client port from the "X-Forwarded-Port" header 911 * when trusted proxies were set via "setTrustedProxies()". 912 * 913 * The "X-Forwarded-Port" header must contain the client port. 914 * 915 * @return int|string can be a string if fetched from the server bag 916 */ 917 public function getPort() 918 { 919 if ($this->isFromTrustedProxy() && $host = $this->getTrustedValues(self::HEADER_X_FORWARDED_PORT)) { 920 $host = $host[0]; 921 } elseif ($this->isFromTrustedProxy() && $host = $this->getTrustedValues(self::HEADER_X_FORWARDED_HOST)) { 922 $host = $host[0]; 923 } elseif (!$host = $this->headers->get('HOST')) { 924 return $this->server->get('SERVER_PORT'); 925 } 926 927 if ('[' === $host[0]) { 928 $pos = strpos($host, ':', strrpos($host, ']')); 929 } else { 930 $pos = strrpos($host, ':'); 931 } 932 933 if (false !== $pos && $port = substr($host, $pos + 1)) { 934 return (int) $port; 935 } 936 937 return 'https' === $this->getScheme() ? 443 : 80; 938 } 939 940 /** 941 * Returns the user. 942 * 943 * @return string|null 944 */ 945 public function getUser() 946 { 947 return $this->headers->get('PHP_AUTH_USER'); 948 } 949 950 /** 951 * Returns the password. 952 * 953 * @return string|null 954 */ 955 public function getPassword() 956 { 957 return $this->headers->get('PHP_AUTH_PW'); 958 } 959 960 /** 961 * Gets the user info. 962 * 963 * @return string A user name and, optionally, scheme-specific information about how to gain authorization to access the server 964 */ 965 public function getUserInfo() 966 { 967 $userinfo = $this->getUser(); 968 969 $pass = $this->getPassword(); 970 if ('' != $pass) { 971 $userinfo .= ":$pass"; 972 } 973 974 return $userinfo; 975 } 976 977 /** 978 * Returns the HTTP host being requested. 979 * 980 * The port name will be appended to the host if it's non-standard. 981 * 982 * @return string 983 */ 984 public function getHttpHost() 985 { 986 $scheme = $this->getScheme(); 987 $port = $this->getPort(); 988 989 if (('http' == $scheme && 80 == $port) || ('https' == $scheme && 443 == $port)) { 990 return $this->getHost(); 991 } 992 993 return $this->getHost().':'.$port; 994 } 995 996 /** 997 * Returns the requested URI (path and query string). 998 * 999 * @return string The raw URI (i.e. not URI decoded) 1000 */ 1001 public function getRequestUri() 1002 { 1003 if (null === $this->requestUri) { 1004 $this->requestUri = $this->prepareRequestUri(); 1005 } 1006 1007 return $this->requestUri; 1008 } 1009 1010 /** 1011 * Gets the scheme and HTTP host. 1012 * 1013 * If the URL was called with basic authentication, the user 1014 * and the password are not added to the generated string. 1015 * 1016 * @return string The scheme and HTTP host 1017 */ 1018 public function getSchemeAndHttpHost() 1019 { 1020 return $this->getScheme().'://'.$this->getHttpHost(); 1021 } 1022 1023 /** 1024 * Generates a normalized URI (URL) for the Request. 1025 * 1026 * @return string A normalized URI (URL) for the Request 1027 * 1028 * @see getQueryString() 1029 */ 1030 public function getUri() 1031 { 1032 if (null !== $qs = $this->getQueryString()) { 1033 $qs = '?'.$qs; 1034 } 1035 1036 return $this->getSchemeAndHttpHost().$this->getBaseUrl().$this->getPathInfo().$qs; 1037 } 1038 1039 /** 1040 * Generates a normalized URI for the given path. 1041 * 1042 * @param string $path A path to use instead of the current one 1043 * 1044 * @return string The normalized URI for the path 1045 */ 1046 public function getUriForPath(string $path) 1047 { 1048 return $this->getSchemeAndHttpHost().$this->getBaseUrl().$path; 1049 } 1050 1051 /** 1052 * Returns the path as relative reference from the current Request path. 1053 * 1054 * Only the URIs path component (no schema, host etc.) is relevant and must be given. 1055 * Both paths must be absolute and not contain relative parts. 1056 * Relative URLs from one resource to another are useful when generating self-contained downloadable document archives. 1057 * Furthermore, they can be used to reduce the link size in documents. 1058 * 1059 * Example target paths, given a base path of "/a/b/c/d": 1060 * - "/a/b/c/d" -> "" 1061 * - "/a/b/c/" -> "./" 1062 * - "/a/b/" -> "../" 1063 * - "/a/b/c/other" -> "other" 1064 * - "/a/x/y" -> "../../x/y" 1065 * 1066 * @return string The relative target path 1067 */ 1068 public function getRelativeUriForPath(string $path) 1069 { 1070 // be sure that we are dealing with an absolute path 1071 if (!isset($path[0]) || '/' !== $path[0]) { 1072 return $path; 1073 } 1074 1075 if ($path === $basePath = $this->getPathInfo()) { 1076 return ''; 1077 } 1078 1079 $sourceDirs = explode('/', isset($basePath[0]) && '/' === $basePath[0] ? substr($basePath, 1) : $basePath); 1080 $targetDirs = explode('/', substr($path, 1)); 1081 array_pop($sourceDirs); 1082 $targetFile = array_pop($targetDirs); 1083 1084 foreach ($sourceDirs as $i => $dir) { 1085 if (isset($targetDirs[$i]) && $dir === $targetDirs[$i]) { 1086 unset($sourceDirs[$i], $targetDirs[$i]); 1087 } else { 1088 break; 1089 } 1090 } 1091 1092 $targetDirs[] = $targetFile; 1093 $path = str_repeat('../', \count($sourceDirs)).implode('/', $targetDirs); 1094 1095 // A reference to the same base directory or an empty subdirectory must be prefixed with "./". 1096 // This also applies to a segment with a colon character (e.g., "file:colon") that cannot be used 1097 // as the first segment of a relative-path reference, as it would be mistaken for a scheme name 1098 // (see https://tools.ietf.org/html/rfc3986#section-4.2). 1099 return !isset($path[0]) || '/' === $path[0] 1100 || false !== ($colonPos = strpos($path, ':')) && ($colonPos < ($slashPos = strpos($path, '/')) || false === $slashPos) 1101 ? "./$path" : $path; 1102 } 1103 1104 /** 1105 * Generates the normalized query string for the Request. 1106 * 1107 * It builds a normalized query string, where keys/value pairs are alphabetized 1108 * and have consistent escaping. 1109 * 1110 * @return string|null A normalized query string for the Request 1111 */ 1112 public function getQueryString() 1113 { 1114 $qs = static::normalizeQueryString($this->server->get('QUERY_STRING')); 1115 1116 return '' === $qs ? null : $qs; 1117 } 1118 1119 /** 1120 * Checks whether the request is secure or not. 1121 * 1122 * This method can read the client protocol from the "X-Forwarded-Proto" header 1123 * when trusted proxies were set via "setTrustedProxies()". 1124 * 1125 * The "X-Forwarded-Proto" header must contain the protocol: "https" or "http". 1126 * 1127 * @return bool 1128 */ 1129 public function isSecure() 1130 { 1131 if ($this->isFromTrustedProxy() && $proto = $this->getTrustedValues(self::HEADER_X_FORWARDED_PROTO)) { 1132 return \in_array(strtolower($proto[0]), ['https', 'on', 'ssl', '1'], true); 1133 } 1134 1135 $https = $this->server->get('HTTPS'); 1136 1137 return !empty($https) && 'off' !== strtolower($https); 1138 } 1139 1140 /** 1141 * Returns the host name. 1142 * 1143 * This method can read the client host name from the "X-Forwarded-Host" header 1144 * when trusted proxies were set via "setTrustedProxies()". 1145 * 1146 * The "X-Forwarded-Host" header must contain the client host name. 1147 * 1148 * @return string 1149 * 1150 * @throws SuspiciousOperationException when the host name is invalid or not trusted 1151 */ 1152 public function getHost() 1153 { 1154 if ($this->isFromTrustedProxy() && $host = $this->getTrustedValues(self::HEADER_X_FORWARDED_HOST)) { 1155 $host = $host[0]; 1156 } elseif (!$host = $this->headers->get('HOST')) { 1157 if (!$host = $this->server->get('SERVER_NAME')) { 1158 $host = $this->server->get('SERVER_ADDR', ''); 1159 } 1160 } 1161 1162 // trim and remove port number from host 1163 // host is lowercase as per RFC 952/2181 1164 $host = strtolower(preg_replace('/:\d+$/', '', trim($host))); 1165 1166 // as the host can come from the user (HTTP_HOST and depending on the configuration, SERVER_NAME too can come from the user) 1167 // check that it does not contain forbidden characters (see RFC 952 and RFC 2181) 1168 // use preg_replace() instead of preg_match() to prevent DoS attacks with long host names 1169 if ($host && '' !== preg_replace('/(?:^\[)?[a-zA-Z0-9-:\]_]+\.?/', '', $host)) { 1170 if (!$this->isHostValid) { 1171 return ''; 1172 } 1173 $this->isHostValid = false; 1174 1175 throw new SuspiciousOperationException(sprintf('Invalid Host "%s".', $host)); 1176 } 1177 1178 if (\count(self::$trustedHostPatterns) > 0) { 1179 // to avoid host header injection attacks, you should provide a list of trusted host patterns 1180 1181 if (\in_array($host, self::$trustedHosts)) { 1182 return $host; 1183 } 1184 1185 foreach (self::$trustedHostPatterns as $pattern) { 1186 if (preg_match($pattern, $host)) { 1187 self::$trustedHosts[] = $host; 1188 1189 return $host; 1190 } 1191 } 1192 1193 if (!$this->isHostValid) { 1194 return ''; 1195 } 1196 $this->isHostValid = false; 1197 1198 throw new SuspiciousOperationException(sprintf('Untrusted Host "%s".', $host)); 1199 } 1200 1201 return $host; 1202 } 1203 1204 /** 1205 * Sets the request method. 1206 */ 1207 public function setMethod(string $method) 1208 { 1209 $this->method = null; 1210 $this->server->set('REQUEST_METHOD', $method); 1211 } 1212 1213 /** 1214 * Gets the request "intended" method. 1215 * 1216 * If the X-HTTP-Method-Override header is set, and if the method is a POST, 1217 * then it is used to determine the "real" intended HTTP method. 1218 * 1219 * The _method request parameter can also be used to determine the HTTP method, 1220 * but only if enableHttpMethodParameterOverride() has been called. 1221 * 1222 * The method is always an uppercased string. 1223 * 1224 * @return string The request method 1225 * 1226 * @see getRealMethod() 1227 */ 1228 public function getMethod() 1229 { 1230 if (null !== $this->method) { 1231 return $this->method; 1232 } 1233 1234 $this->method = strtoupper($this->server->get('REQUEST_METHOD', 'GET')); 1235 1236 if ('POST' !== $this->method) { 1237 return $this->method; 1238 } 1239 1240 $method = $this->headers->get('X-HTTP-METHOD-OVERRIDE'); 1241 1242 if (!$method && self::$httpMethodParameterOverride) { 1243 $method = $this->request->get('_method', $this->query->get('_method', 'POST')); 1244 } 1245 1246 if (!\is_string($method)) { 1247 return $this->method; 1248 } 1249 1250 $method = strtoupper($method); 1251 1252 if (\in_array($method, ['GET', 'HEAD', 'POST', 'PUT', 'DELETE', 'CONNECT', 'OPTIONS', 'PATCH', 'PURGE', 'TRACE'], true)) { 1253 return $this->method = $method; 1254 } 1255 1256 if (!preg_match('/^[A-Z]++$/D', $method)) { 1257 throw new SuspiciousOperationException(sprintf('Invalid method override "%s".', $method)); 1258 } 1259 1260 return $this->method = $method; 1261 } 1262 1263 /** 1264 * Gets the "real" request method. 1265 * 1266 * @return string The request method 1267 * 1268 * @see getMethod() 1269 */ 1270 public function getRealMethod() 1271 { 1272 return strtoupper($this->server->get('REQUEST_METHOD', 'GET')); 1273 } 1274 1275 /** 1276 * Gets the mime type associated with the format. 1277 * 1278 * @return string|null The associated mime type (null if not found) 1279 */ 1280 public function getMimeType(string $format) 1281 { 1282 if (null === static::$formats) { 1283 static::initializeFormats(); 1284 } 1285 1286 return isset(static::$formats[$format]) ? static::$formats[$format][0] : null; 1287 } 1288 1289 /** 1290 * Gets the mime types associated with the format. 1291 * 1292 * @return array The associated mime types 1293 */ 1294 public static function getMimeTypes(string $format) 1295 { 1296 if (null === static::$formats) { 1297 static::initializeFormats(); 1298 } 1299 1300 return isset(static::$formats[$format]) ? static::$formats[$format] : []; 1301 } 1302 1303 /** 1304 * Gets the format associated with the mime type. 1305 * 1306 * @return string|null The format (null if not found) 1307 */ 1308 public function getFormat(?string $mimeType) 1309 { 1310 $canonicalMimeType = null; 1311 if (false !== $pos = strpos($mimeType, ';')) { 1312 $canonicalMimeType = trim(substr($mimeType, 0, $pos)); 1313 } 1314 1315 if (null === static::$formats) { 1316 static::initializeFormats(); 1317 } 1318 1319 foreach (static::$formats as $format => $mimeTypes) { 1320 if (\in_array($mimeType, (array) $mimeTypes)) { 1321 return $format; 1322 } 1323 if (null !== $canonicalMimeType && \in_array($canonicalMimeType, (array) $mimeTypes)) { 1324 return $format; 1325 } 1326 } 1327 1328 return null; 1329 } 1330 1331 /** 1332 * Associates a format with mime types. 1333 * 1334 * @param string|array $mimeTypes The associated mime types (the preferred one must be the first as it will be used as the content type) 1335 */ 1336 public function setFormat(?string $format, $mimeTypes) 1337 { 1338 if (null === static::$formats) { 1339 static::initializeFormats(); 1340 } 1341 1342 static::$formats[$format] = \is_array($mimeTypes) ? $mimeTypes : [$mimeTypes]; 1343 } 1344 1345 /** 1346 * Gets the request format. 1347 * 1348 * Here is the process to determine the format: 1349 * 1350 * * format defined by the user (with setRequestFormat()) 1351 * * _format request attribute 1352 * * $default 1353 * 1354 * @see getPreferredFormat 1355 * 1356 * @return string|null The request format 1357 */ 1358 public function getRequestFormat(?string $default = 'html') 1359 { 1360 if (null === $this->format) { 1361 $this->format = $this->attributes->get('_format'); 1362 } 1363 1364 return null === $this->format ? $default : $this->format; 1365 } 1366 1367 /** 1368 * Sets the request format. 1369 */ 1370 public function setRequestFormat(?string $format) 1371 { 1372 $this->format = $format; 1373 } 1374 1375 /** 1376 * Gets the format associated with the request. 1377 * 1378 * @return string|null The format (null if no content type is present) 1379 */ 1380 public function getContentType() 1381 { 1382 return $this->getFormat($this->headers->get('CONTENT_TYPE')); 1383 } 1384 1385 /** 1386 * Sets the default locale. 1387 */ 1388 public function setDefaultLocale(string $locale) 1389 { 1390 $this->defaultLocale = $locale; 1391 1392 if (null === $this->locale) { 1393 $this->setPhpDefaultLocale($locale); 1394 } 1395 } 1396 1397 /** 1398 * Get the default locale. 1399 * 1400 * @return string 1401 */ 1402 public function getDefaultLocale() 1403 { 1404 return $this->defaultLocale; 1405 } 1406 1407 /** 1408 * Sets the locale. 1409 */ 1410 public function setLocale(string $locale) 1411 { 1412 $this->setPhpDefaultLocale($this->locale = $locale); 1413 } 1414 1415 /** 1416 * Get the locale. 1417 * 1418 * @return string 1419 */ 1420 public function getLocale() 1421 { 1422 return null === $this->locale ? $this->defaultLocale : $this->locale; 1423 } 1424 1425 /** 1426 * Checks if the request method is of specified type. 1427 * 1428 * @param string $method Uppercase request method (GET, POST etc) 1429 * 1430 * @return bool 1431 */ 1432 public function isMethod(string $method) 1433 { 1434 return $this->getMethod() === strtoupper($method); 1435 } 1436 1437 /** 1438 * Checks whether or not the method is safe. 1439 * 1440 * @see https://tools.ietf.org/html/rfc7231#section-4.2.1 1441 * 1442 * @return bool 1443 */ 1444 public function isMethodSafe() 1445 { 1446 return \in_array($this->getMethod(), ['GET', 'HEAD', 'OPTIONS', 'TRACE']); 1447 } 1448 1449 /** 1450 * Checks whether or not the method is idempotent. 1451 * 1452 * @return bool 1453 */ 1454 public function isMethodIdempotent() 1455 { 1456 return \in_array($this->getMethod(), ['HEAD', 'GET', 'PUT', 'DELETE', 'TRACE', 'OPTIONS', 'PURGE']); 1457 } 1458 1459 /** 1460 * Checks whether the method is cacheable or not. 1461 * 1462 * @see https://tools.ietf.org/html/rfc7231#section-4.2.3 1463 * 1464 * @return bool True for GET and HEAD, false otherwise 1465 */ 1466 public function isMethodCacheable() 1467 { 1468 return \in_array($this->getMethod(), ['GET', 'HEAD']); 1469 } 1470 1471 /** 1472 * Returns the protocol version. 1473 * 1474 * If the application is behind a proxy, the protocol version used in the 1475 * requests between the client and the proxy and between the proxy and the 1476 * server might be different. This returns the former (from the "Via" header) 1477 * if the proxy is trusted (see "setTrustedProxies()"), otherwise it returns 1478 * the latter (from the "SERVER_PROTOCOL" server parameter). 1479 * 1480 * @return string 1481 */ 1482 public function getProtocolVersion() 1483 { 1484 if ($this->isFromTrustedProxy()) { 1485 preg_match('~^(HTTP/)?([1-9]\.[0-9]) ~', $this->headers->get('Via'), $matches); 1486 1487 if ($matches) { 1488 return 'HTTP/'.$matches[2]; 1489 } 1490 } 1491 1492 return $this->server->get('SERVER_PROTOCOL'); 1493 } 1494 1495 /** 1496 * Returns the request body content. 1497 * 1498 * @param bool $asResource If true, a resource will be returned 1499 * 1500 * @return string|resource The request body content or a resource to read the body stream 1501 * 1502 * @throws \LogicException 1503 */ 1504 public function getContent(bool $asResource = false) 1505 { 1506 $currentContentIsResource = \is_resource($this->content); 1507 1508 if (true === $asResource) { 1509 if ($currentContentIsResource) { 1510 rewind($this->content); 1511 1512 return $this->content; 1513 } 1514 1515 // Content passed in parameter (test) 1516 if (\is_string($this->content)) { 1517 $resource = fopen('php://temp', 'r+'); 1518 fwrite($resource, $this->content); 1519 rewind($resource); 1520 1521 return $resource; 1522 } 1523 1524 $this->content = false; 1525 1526 return fopen('php://input', 'rb'); 1527 } 1528 1529 if ($currentContentIsResource) { 1530 rewind($this->content); 1531 1532 return stream_get_contents($this->content); 1533 } 1534 1535 if (null === $this->content || false === $this->content) { 1536 $this->content = file_get_contents('php://input'); 1537 } 1538 1539 return $this->content; 1540 } 1541 1542 /** 1543 * Gets the Etags. 1544 * 1545 * @return array The entity tags 1546 */ 1547 public function getETags() 1548 { 1549 return preg_split('/\s*,\s*/', $this->headers->get('if_none_match'), null, PREG_SPLIT_NO_EMPTY); 1550 } 1551 1552 /** 1553 * @return bool 1554 */ 1555 public function isNoCache() 1556 { 1557 return $this->headers->hasCacheControlDirective('no-cache') || 'no-cache' == $this->headers->get('Pragma'); 1558 } 1559 1560 /** 1561 * Gets the preferred format for the response by inspecting, in the following order: 1562 * * the request format set using setRequestFormat 1563 * * the values of the Accept HTTP header 1564 * 1565 * Note that if you use this method, you should send the "Vary: Accept" header 1566 * in the response to prevent any issues with intermediary HTTP caches. 1567 */ 1568 public function getPreferredFormat(?string $default = 'html'): ?string 1569 { 1570 if (null !== $this->preferredFormat || null !== $this->preferredFormat = $this->getRequestFormat(null)) { 1571 return $this->preferredFormat; 1572 } 1573 1574 foreach ($this->getAcceptableContentTypes() as $mimeType) { 1575 if ($this->preferredFormat = $this->getFormat($mimeType)) { 1576 return $this->preferredFormat; 1577 } 1578 } 1579 1580 return $default; 1581 } 1582 1583 /** 1584 * Returns the preferred language. 1585 * 1586 * @param string[] $locales An array of ordered available locales 1587 * 1588 * @return string|null The preferred locale 1589 */ 1590 public function getPreferredLanguage(array $locales = null) 1591 { 1592 $preferredLanguages = $this->getLanguages(); 1593 1594 if (empty($locales)) { 1595 return isset($preferredLanguages[0]) ? $preferredLanguages[0] : null; 1596 } 1597 1598 if (!$preferredLanguages) { 1599 return $locales[0]; 1600 } 1601 1602 $extendedPreferredLanguages = []; 1603 foreach ($preferredLanguages as $language) { 1604 $extendedPreferredLanguages[] = $language; 1605 if (false !== $position = strpos($language, '_')) { 1606 $superLanguage = substr($language, 0, $position); 1607 if (!\in_array($superLanguage, $preferredLanguages)) { 1608 $extendedPreferredLanguages[] = $superLanguage; 1609 } 1610 } 1611 } 1612 1613 $preferredLanguages = array_values(array_intersect($extendedPreferredLanguages, $locales)); 1614 1615 return isset($preferredLanguages[0]) ? $preferredLanguages[0] : $locales[0]; 1616 } 1617 1618 /** 1619 * Gets a list of languages acceptable by the client browser. 1620 * 1621 * @return array Languages ordered in the user browser preferences 1622 */ 1623 public function getLanguages() 1624 { 1625 if (null !== $this->languages) { 1626 return $this->languages; 1627 } 1628 1629 $languages = AcceptHeader::fromString($this->headers->get('Accept-Language'))->all(); 1630 $this->languages = []; 1631 foreach ($languages as $lang => $acceptHeaderItem) { 1632 if (false !== strpos($lang, '-')) { 1633 $codes = explode('-', $lang); 1634 if ('i' === $codes[0]) { 1635 // Language not listed in ISO 639 that are not variants 1636 // of any listed language, which can be registered with the 1637 // i-prefix, such as i-cherokee 1638 if (\count($codes) > 1) { 1639 $lang = $codes[1]; 1640 } 1641 } else { 1642 for ($i = 0, $max = \count($codes); $i < $max; ++$i) { 1643 if (0 === $i) { 1644 $lang = strtolower($codes[0]); 1645 } else { 1646 $lang .= '_'.strtoupper($codes[$i]); 1647 } 1648 } 1649 } 1650 } 1651 1652 $this->languages[] = $lang; 1653 } 1654 1655 return $this->languages; 1656 } 1657 1658 /** 1659 * Gets a list of charsets acceptable by the client browser. 1660 * 1661 * @return array List of charsets in preferable order 1662 */ 1663 public function getCharsets() 1664 { 1665 if (null !== $this->charsets) { 1666 return $this->charsets; 1667 } 1668 1669 return $this->charsets = array_keys(AcceptHeader::fromString($this->headers->get('Accept-Charset'))->all()); 1670 } 1671 1672 /** 1673 * Gets a list of encodings acceptable by the client browser. 1674 * 1675 * @return array List of encodings in preferable order 1676 */ 1677 public function getEncodings() 1678 { 1679 if (null !== $this->encodings) { 1680 return $this->encodings; 1681 } 1682 1683 return $this->encodings = array_keys(AcceptHeader::fromString($this->headers->get('Accept-Encoding'))->all()); 1684 } 1685 1686 /** 1687 * Gets a list of content types acceptable by the client browser. 1688 * 1689 * @return array List of content types in preferable order 1690 */ 1691 public function getAcceptableContentTypes() 1692 { 1693 if (null !== $this->acceptableContentTypes) { 1694 return $this->acceptableContentTypes; 1695 } 1696 1697 return $this->acceptableContentTypes = array_keys(AcceptHeader::fromString($this->headers->get('Accept'))->all()); 1698 } 1699 1700 /** 1701 * Returns true if the request is a XMLHttpRequest. 1702 * 1703 * It works if your JavaScript library sets an X-Requested-With HTTP header. 1704 * It is known to work with common JavaScript frameworks: 1705 * 1706 * @see https://wikipedia.org/wiki/List_of_Ajax_frameworks#JavaScript 1707 * 1708 * @return bool true if the request is an XMLHttpRequest, false otherwise 1709 */ 1710 public function isXmlHttpRequest() 1711 { 1712 return 'XMLHttpRequest' == $this->headers->get('X-Requested-With'); 1713 } 1714 1715 /* 1716 * The following methods are derived from code of the Zend Framework (1.10dev - 2010-01-24) 1717 * 1718 * Code subject to the new BSD license (https://framework.zend.com/license). 1719 * 1720 * Copyright (c) 2005-2010 Zend Technologies USA Inc. (https://www.zend.com/) 1721 */ 1722 1723 protected function prepareRequestUri() 1724 { 1725 $requestUri = ''; 1726 1727 if ('1' == $this->server->get('IIS_WasUrlRewritten') && '' != $this->server->get('UNENCODED_URL')) { 1728 // IIS7 with URL Rewrite: make sure we get the unencoded URL (double slash problem) 1729 $requestUri = $this->server->get('UNENCODED_URL'); 1730 $this->server->remove('UNENCODED_URL'); 1731 $this->server->remove('IIS_WasUrlRewritten'); 1732 } elseif ($this->server->has('REQUEST_URI')) { 1733 $requestUri = $this->server->get('REQUEST_URI'); 1734 1735 if ('' !== $requestUri && '/' === $requestUri[0]) { 1736 // To only use path and query remove the fragment. 1737 if (false !== $pos = strpos($requestUri, '#')) { 1738 $requestUri = substr($requestUri, 0, $pos); 1739 } 1740 } else { 1741 // HTTP proxy reqs setup request URI with scheme and host [and port] + the URL path, 1742 // only use URL path. 1743 $uriComponents = parse_url($requestUri); 1744 1745 if (isset($uriComponents['path'])) { 1746 $requestUri = $uriComponents['path']; 1747 } 1748 1749 if (isset($uriComponents['query'])) { 1750 $requestUri .= '?'.$uriComponents['query']; 1751 } 1752 } 1753 } elseif ($this->server->has('ORIG_PATH_INFO')) { 1754 // IIS 5.0, PHP as CGI 1755 $requestUri = $this->server->get('ORIG_PATH_INFO'); 1756 if ('' != $this->server->get('QUERY_STRING')) { 1757 $requestUri .= '?'.$this->server->get('QUERY_STRING'); 1758 } 1759 $this->server->remove('ORIG_PATH_INFO'); 1760 } 1761 1762 // normalize the request URI to ease creating sub-requests from this request 1763 $this->server->set('REQUEST_URI', $requestUri); 1764 1765 return $requestUri; 1766 } 1767 1768 /** 1769 * Prepares the base URL. 1770 * 1771 * @return string 1772 */ 1773 protected function prepareBaseUrl() 1774 { 1775 $filename = basename($this->server->get('SCRIPT_FILENAME')); 1776 1777 if (basename($this->server->get('SCRIPT_NAME')) === $filename) { 1778 $baseUrl = $this->server->get('SCRIPT_NAME'); 1779 } elseif (basename($this->server->get('PHP_SELF')) === $filename) { 1780 $baseUrl = $this->server->get('PHP_SELF'); 1781 } elseif (basename($this->server->get('ORIG_SCRIPT_NAME')) === $filename) { 1782 $baseUrl = $this->server->get('ORIG_SCRIPT_NAME'); // 1and1 shared hosting compatibility 1783 } else { 1784 // Backtrack up the script_filename to find the portion matching 1785 // php_self 1786 $path = $this->server->get('PHP_SELF', ''); 1787 $file = $this->server->get('SCRIPT_FILENAME', ''); 1788 $segs = explode('/', trim($file, '/')); 1789 $segs = array_reverse($segs); 1790 $index = 0; 1791 $last = \count($segs); 1792 $baseUrl = ''; 1793 do { 1794 $seg = $segs[$index]; 1795 $baseUrl = '/'.$seg.$baseUrl; 1796 ++$index; 1797 } while ($last > $index && (false !== $pos = strpos($path, $baseUrl)) && 0 != $pos); 1798 } 1799 1800 // Does the baseUrl have anything in common with the request_uri? 1801 $requestUri = $this->getRequestUri(); 1802 if ('' !== $requestUri && '/' !== $requestUri[0]) { 1803 $requestUri = '/'.$requestUri; 1804 } 1805 1806 if ($baseUrl && null !== $prefix = $this->getUrlencodedPrefix($requestUri, $baseUrl)) { 1807 // full $baseUrl matches 1808 return $prefix; 1809 } 1810 1811 if ($baseUrl && null !== $prefix = $this->getUrlencodedPrefix($requestUri, rtrim(\dirname($baseUrl), '/'.\DIRECTORY_SEPARATOR).'/')) { 1812 // directory portion of $baseUrl matches 1813 return rtrim($prefix, '/'.\DIRECTORY_SEPARATOR); 1814 } 1815 1816 $truncatedRequestUri = $requestUri; 1817 if (false !== $pos = strpos($requestUri, '?')) { 1818 $truncatedRequestUri = substr($requestUri, 0, $pos); 1819 } 1820 1821 $basename = basename($baseUrl); 1822 if (empty($basename) || !strpos(rawurldecode($truncatedRequestUri), $basename)) { 1823 // no match whatsoever; set it blank 1824 return ''; 1825 } 1826 1827 // If using mod_rewrite or ISAPI_Rewrite strip the script filename 1828 // out of baseUrl. $pos !== 0 makes sure it is not matching a value 1829 // from PATH_INFO or QUERY_STRING 1830 if (\strlen($requestUri) >= \strlen($baseUrl) && (false !== $pos = strpos($requestUri, $baseUrl)) && 0 !== $pos) { 1831 $baseUrl = substr($requestUri, 0, $pos + \strlen($baseUrl)); 1832 } 1833 1834 return rtrim($baseUrl, '/'.\DIRECTORY_SEPARATOR); 1835 } 1836 1837 /** 1838 * Prepares the base path. 1839 * 1840 * @return string base path 1841 */ 1842 protected function prepareBasePath() 1843 { 1844 $baseUrl = $this->getBaseUrl(); 1845 if (empty($baseUrl)) { 1846 return ''; 1847 } 1848 1849 $filename = basename($this->server->get('SCRIPT_FILENAME')); 1850 if (basename($baseUrl) === $filename) { 1851 $basePath = \dirname($baseUrl); 1852 } else { 1853 $basePath = $baseUrl; 1854 } 1855 1856 if ('\\' === \DIRECTORY_SEPARATOR) { 1857 $basePath = str_replace('\\', '/', $basePath); 1858 } 1859 1860 return rtrim($basePath, '/'); 1861 } 1862 1863 /** 1864 * Prepares the path info. 1865 * 1866 * @return string path info 1867 */ 1868 protected function preparePathInfo() 1869 { 1870 if (null === ($requestUri = $this->getRequestUri())) { 1871 return '/'; 1872 } 1873 1874 // Remove the query string from REQUEST_URI 1875 if (false !== $pos = strpos($requestUri, '?')) { 1876 $requestUri = substr($requestUri, 0, $pos); 1877 } 1878 if ('' !== $requestUri && '/' !== $requestUri[0]) { 1879 $requestUri = '/'.$requestUri; 1880 } 1881 1882 if (null === ($baseUrl = $this->getBaseUrl())) { 1883 return $requestUri; 1884 } 1885 1886 $pathInfo = substr($requestUri, \strlen($baseUrl)); 1887 if (false === $pathInfo || '' === $pathInfo) { 1888 // If substr() returns false then PATH_INFO is set to an empty string 1889 return '/'; 1890 } 1891 1892 return (string) $pathInfo; 1893 } 1894 1895 /** 1896 * Initializes HTTP request formats. 1897 */ 1898 protected static function initializeFormats() 1899 { 1900 static::$formats = [ 1901 'html' => ['text/html', 'application/xhtml+xml'], 1902 'txt' => ['text/plain'], 1903 'js' => ['application/javascript', 'application/x-javascript', 'text/javascript'], 1904 'css' => ['text/css'], 1905 'json' => ['application/json', 'application/x-json'], 1906 'jsonld' => ['application/ld+json'], 1907 'xml' => ['text/xml', 'application/xml', 'application/x-xml'], 1908 'rdf' => ['application/rdf+xml'], 1909 'atom' => ['application/atom+xml'], 1910 'rss' => ['application/rss+xml'], 1911 'form' => ['application/x-www-form-urlencoded'], 1912 ]; 1913 } 1914 1915 private function setPhpDefaultLocale(string $locale): void 1916 { 1917 // if either the class Locale doesn't exist, or an exception is thrown when 1918 // setting the default locale, the intl module is not installed, and 1919 // the call can be ignored: 1920 try { 1921 if (class_exists('Locale', false)) { 1922 \Locale::setDefault($locale); 1923 } 1924 } catch (\Exception $e) { 1925 } 1926 } 1927 1928 /** 1929 * Returns the prefix as encoded in the string when the string starts with 1930 * the given prefix, null otherwise. 1931 */ 1932 private function getUrlencodedPrefix(string $string, string $prefix): ?string 1933 { 1934 if (0 !== strpos(rawurldecode($string), $prefix)) { 1935 return null; 1936 } 1937 1938 $len = \strlen($prefix); 1939 1940 if (preg_match(sprintf('#^(%%[[:xdigit:]]{2}|.){%d}#', $len), $string, $match)) { 1941 return $match[0]; 1942 } 1943 1944 return null; 1945 } 1946 1947 private static function createRequestFromFactory(array $query = [], array $request = [], array $attributes = [], array $cookies = [], array $files = [], array $server = [], $content = null): self 1948 { 1949 if (self::$requestFactory) { 1950 $request = (self::$requestFactory)($query, $request, $attributes, $cookies, $files, $server, $content); 1951 1952 if (!$request instanceof self) { 1953 throw new \LogicException('The Request factory must return an instance of Symfony\Component\HttpFoundation\Request.'); 1954 } 1955 1956 return $request; 1957 } 1958 1959 return new static($query, $request, $attributes, $cookies, $files, $server, $content); 1960 } 1961 1962 /** 1963 * Indicates whether this request originated from a trusted proxy. 1964 * 1965 * This can be useful to determine whether or not to trust the 1966 * contents of a proxy-specific header. 1967 * 1968 * @return bool true if the request came from a trusted proxy, false otherwise 1969 */ 1970 public function isFromTrustedProxy() 1971 { 1972 return self::$trustedProxies && IpUtils::checkIp($this->server->get('REMOTE_ADDR'), self::$trustedProxies); 1973 } 1974 1975 private function getTrustedValues(int $type, string $ip = null): array 1976 { 1977 $clientValues = []; 1978 $forwardedValues = []; 1979 1980 if ((self::$trustedHeaderSet & $type) && $this->headers->has(self::$trustedHeaders[$type])) { 1981 foreach (explode(',', $this->headers->get(self::$trustedHeaders[$type])) as $v) { 1982 $clientValues[] = (self::HEADER_X_FORWARDED_PORT === $type ? '0.0.0.0:' : '').trim($v); 1983 } 1984 } 1985 1986 if ((self::$trustedHeaderSet & self::HEADER_FORWARDED) && $this->headers->has(self::$trustedHeaders[self::HEADER_FORWARDED])) { 1987 $forwarded = $this->headers->get(self::$trustedHeaders[self::HEADER_FORWARDED]); 1988 $parts = HeaderUtils::split($forwarded, ',;='); 1989 $forwardedValues = []; 1990 $param = self::$forwardedParams[$type]; 1991 foreach ($parts as $subParts) { 1992 if (null === $v = HeaderUtils::combine($subParts)[$param] ?? null) { 1993 continue; 1994 } 1995 if (self::HEADER_X_FORWARDED_PORT === $type) { 1996 if (']' === substr($v, -1) || false === $v = strrchr($v, ':')) { 1997 $v = $this->isSecure() ? ':443' : ':80'; 1998 } 1999 $v = '0.0.0.0'.$v; 2000 } 2001 $forwardedValues[] = $v; 2002 } 2003 } 2004 2005 if (null !== $ip) { 2006 $clientValues = $this->normalizeAndFilterClientIps($clientValues, $ip); 2007 $forwardedValues = $this->normalizeAndFilterClientIps($forwardedValues, $ip); 2008 } 2009 2010 if ($forwardedValues === $clientValues || !$clientValues) { 2011 return $forwardedValues; 2012 } 2013 2014 if (!$forwardedValues) { 2015 return $clientValues; 2016 } 2017 2018 if (!$this->isForwardedValid) { 2019 return null !== $ip ? ['0.0.0.0', $ip] : []; 2020 } 2021 $this->isForwardedValid = false; 2022 2023 throw new ConflictingHeadersException(sprintf('The request has both a trusted "%s" header and a trusted "%s" header, conflicting with each other. You should either configure your proxy to remove one of them, or configure your project to distrust the offending one.', self::$trustedHeaders[self::HEADER_FORWARDED], self::$trustedHeaders[$type])); 2024 } 2025 2026 private function normalizeAndFilterClientIps(array $clientIps, string $ip): array 2027 { 2028 if (!$clientIps) { 2029 return []; 2030 } 2031 $clientIps[] = $ip; // Complete the IP chain with the IP the request actually came from 2032 $firstTrustedIp = null; 2033 2034 foreach ($clientIps as $key => $clientIp) { 2035 if (strpos($clientIp, '.')) { 2036 // Strip :port from IPv4 addresses. This is allowed in Forwarded 2037 // and may occur in X-Forwarded-For. 2038 $i = strpos($clientIp, ':'); 2039 if ($i) { 2040 $clientIps[$key] = $clientIp = substr($clientIp, 0, $i); 2041 } 2042 } elseif (0 === strpos($clientIp, '[')) { 2043 // Strip brackets and :port from IPv6 addresses. 2044 $i = strpos($clientIp, ']', 1); 2045 $clientIps[$key] = $clientIp = substr($clientIp, 1, $i - 1); 2046 } 2047 2048 if (!filter_var($clientIp, FILTER_VALIDATE_IP)) { 2049 unset($clientIps[$key]); 2050 2051 continue; 2052 } 2053 2054 if (IpUtils::checkIp($clientIp, self::$trustedProxies)) { 2055 unset($clientIps[$key]); 2056 2057 // Fallback to this when the client IP falls into the range of trusted proxies 2058 if (null === $firstTrustedIp) { 2059 $firstTrustedIp = $clientIp; 2060 } 2061 } 2062 } 2063 2064 // Now the IP chain contains only untrusted proxies and the client IP 2065 return $clientIps ? array_reverse($clientIps) : [$firstTrustedIp]; 2066 } 2067} 2068