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

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