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

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