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

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