Debian Codegraph @

lib/3rdParty/composer/symfony/http-foundation/Request.php

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