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