vendor/symfony/http-foundation/Request.php line 700

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