[ Index ]

PHP Cross Reference of phpBB-3.2.8-deutsch

title

Body

[close]

/vendor/symfony/http-foundation/ -> Request.php (source)

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


Generated: Tue Apr 7 19:42:26 2020 Cross-referenced by PHPXref 0.7.1