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

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