Chris@0: Chris@0: * Chris@0: * For the full copyright and license information, please view the LICENSE Chris@0: * file that was distributed with this source code. Chris@0: */ Chris@0: Chris@0: namespace Symfony\Component\HttpFoundation; Chris@0: Chris@0: use Symfony\Component\HttpFoundation\Exception\ConflictingHeadersException; Chris@14: use Symfony\Component\HttpFoundation\Exception\SuspiciousOperationException; Chris@0: use Symfony\Component\HttpFoundation\Session\SessionInterface; Chris@0: Chris@0: /** Chris@0: * Request represents an HTTP request. Chris@0: * Chris@0: * The methods dealing with URL accept / return a raw path (% encoded): Chris@0: * * getBasePath Chris@0: * * getBaseUrl Chris@0: * * getPathInfo Chris@0: * * getRequestUri Chris@0: * * getUri Chris@0: * * getUriForPath Chris@0: * Chris@0: * @author Fabien Potencier Chris@0: */ Chris@0: class Request Chris@0: { Chris@14: const HEADER_FORWARDED = 0b00001; // When using RFC 7239 Chris@14: const HEADER_X_FORWARDED_FOR = 0b00010; Chris@14: const HEADER_X_FORWARDED_HOST = 0b00100; Chris@14: const HEADER_X_FORWARDED_PROTO = 0b01000; Chris@14: const HEADER_X_FORWARDED_PORT = 0b10000; Chris@14: const HEADER_X_FORWARDED_ALL = 0b11110; // All "X-Forwarded-*" headers Chris@14: const HEADER_X_FORWARDED_AWS_ELB = 0b11010; // AWS ELB doesn't send X-Forwarded-Host Chris@14: Chris@14: /** @deprecated since version 3.3, to be removed in 4.0 */ Chris@14: const HEADER_CLIENT_IP = self::HEADER_X_FORWARDED_FOR; Chris@14: /** @deprecated since version 3.3, to be removed in 4.0 */ Chris@14: const HEADER_CLIENT_HOST = self::HEADER_X_FORWARDED_HOST; Chris@14: /** @deprecated since version 3.3, to be removed in 4.0 */ Chris@14: const HEADER_CLIENT_PROTO = self::HEADER_X_FORWARDED_PROTO; Chris@14: /** @deprecated since version 3.3, to be removed in 4.0 */ Chris@14: const HEADER_CLIENT_PORT = self::HEADER_X_FORWARDED_PORT; Chris@0: Chris@0: const METHOD_HEAD = 'HEAD'; Chris@0: const METHOD_GET = 'GET'; Chris@0: const METHOD_POST = 'POST'; Chris@0: const METHOD_PUT = 'PUT'; Chris@0: const METHOD_PATCH = 'PATCH'; Chris@0: const METHOD_DELETE = 'DELETE'; Chris@0: const METHOD_PURGE = 'PURGE'; Chris@0: const METHOD_OPTIONS = 'OPTIONS'; Chris@0: const METHOD_TRACE = 'TRACE'; Chris@0: const METHOD_CONNECT = 'CONNECT'; Chris@0: Chris@0: /** Chris@0: * @var string[] Chris@0: */ Chris@17: protected static $trustedProxies = []; Chris@0: Chris@0: /** Chris@0: * @var string[] Chris@0: */ Chris@17: protected static $trustedHostPatterns = []; Chris@0: Chris@0: /** Chris@0: * @var string[] Chris@0: */ Chris@17: protected static $trustedHosts = []; Chris@0: Chris@0: /** Chris@0: * Names for headers that can be trusted when Chris@0: * using trusted proxies. Chris@0: * Chris@0: * The FORWARDED header is the standard as of rfc7239. Chris@0: * Chris@0: * The other headers are non-standard, but widely used Chris@0: * by popular reverse proxies (like Apache mod_proxy or Amazon EC2). Chris@14: * Chris@14: * @deprecated since version 3.3, to be removed in 4.0 Chris@0: */ Chris@17: protected static $trustedHeaders = [ Chris@0: self::HEADER_FORWARDED => 'FORWARDED', Chris@0: self::HEADER_CLIENT_IP => 'X_FORWARDED_FOR', Chris@0: self::HEADER_CLIENT_HOST => 'X_FORWARDED_HOST', Chris@0: self::HEADER_CLIENT_PROTO => 'X_FORWARDED_PROTO', Chris@0: self::HEADER_CLIENT_PORT => 'X_FORWARDED_PORT', Chris@17: ]; Chris@0: Chris@0: protected static $httpMethodParameterOverride = false; Chris@0: Chris@0: /** Chris@0: * Custom parameters. Chris@0: * Chris@0: * @var \Symfony\Component\HttpFoundation\ParameterBag Chris@0: */ Chris@0: public $attributes; Chris@0: Chris@0: /** Chris@0: * Request body parameters ($_POST). Chris@0: * Chris@0: * @var \Symfony\Component\HttpFoundation\ParameterBag Chris@0: */ Chris@0: public $request; Chris@0: Chris@0: /** Chris@0: * Query string parameters ($_GET). Chris@0: * Chris@0: * @var \Symfony\Component\HttpFoundation\ParameterBag Chris@0: */ Chris@0: public $query; Chris@0: Chris@0: /** Chris@0: * Server and execution environment parameters ($_SERVER). Chris@0: * Chris@0: * @var \Symfony\Component\HttpFoundation\ServerBag Chris@0: */ Chris@0: public $server; Chris@0: Chris@0: /** Chris@0: * Uploaded files ($_FILES). Chris@0: * Chris@0: * @var \Symfony\Component\HttpFoundation\FileBag Chris@0: */ Chris@0: public $files; Chris@0: Chris@0: /** Chris@0: * Cookies ($_COOKIE). Chris@0: * Chris@0: * @var \Symfony\Component\HttpFoundation\ParameterBag Chris@0: */ Chris@0: public $cookies; Chris@0: Chris@0: /** Chris@0: * Headers (taken from the $_SERVER). Chris@0: * Chris@0: * @var \Symfony\Component\HttpFoundation\HeaderBag Chris@0: */ Chris@0: public $headers; Chris@0: Chris@0: /** Chris@14: * @var string|resource|false|null Chris@0: */ Chris@0: protected $content; Chris@0: Chris@0: /** Chris@0: * @var array Chris@0: */ Chris@0: protected $languages; Chris@0: Chris@0: /** Chris@0: * @var array Chris@0: */ Chris@0: protected $charsets; Chris@0: Chris@0: /** Chris@0: * @var array Chris@0: */ Chris@0: protected $encodings; Chris@0: Chris@0: /** Chris@0: * @var array Chris@0: */ Chris@0: protected $acceptableContentTypes; Chris@0: Chris@0: /** Chris@0: * @var string Chris@0: */ Chris@0: protected $pathInfo; Chris@0: Chris@0: /** Chris@0: * @var string Chris@0: */ Chris@0: protected $requestUri; Chris@0: Chris@0: /** Chris@0: * @var string Chris@0: */ Chris@0: protected $baseUrl; Chris@0: Chris@0: /** Chris@0: * @var string Chris@0: */ Chris@0: protected $basePath; Chris@0: Chris@0: /** Chris@0: * @var string Chris@0: */ Chris@0: protected $method; Chris@0: Chris@0: /** Chris@0: * @var string Chris@0: */ Chris@0: protected $format; Chris@0: Chris@0: /** Chris@0: * @var \Symfony\Component\HttpFoundation\Session\SessionInterface Chris@0: */ Chris@0: protected $session; Chris@0: Chris@0: /** Chris@0: * @var string Chris@0: */ Chris@0: protected $locale; Chris@0: Chris@0: /** Chris@0: * @var string Chris@0: */ Chris@0: protected $defaultLocale = 'en'; Chris@0: Chris@0: /** Chris@0: * @var array Chris@0: */ Chris@0: protected static $formats; Chris@0: Chris@0: protected static $requestFactory; Chris@0: Chris@14: private $isHostValid = true; Chris@0: private $isForwardedValid = true; Chris@0: Chris@14: private static $trustedHeaderSet = -1; Chris@14: Chris@14: /** @deprecated since version 3.3, to be removed in 4.0 */ Chris@17: private static $trustedHeaderNames = [ Chris@14: self::HEADER_FORWARDED => 'FORWARDED', Chris@14: self::HEADER_CLIENT_IP => 'X_FORWARDED_FOR', Chris@14: self::HEADER_CLIENT_HOST => 'X_FORWARDED_HOST', Chris@14: self::HEADER_CLIENT_PROTO => 'X_FORWARDED_PROTO', Chris@14: self::HEADER_CLIENT_PORT => 'X_FORWARDED_PORT', Chris@17: ]; Chris@14: Chris@17: private static $forwardedParams = [ Chris@14: self::HEADER_X_FORWARDED_FOR => 'for', Chris@14: self::HEADER_X_FORWARDED_HOST => 'host', Chris@14: self::HEADER_X_FORWARDED_PROTO => 'proto', Chris@14: self::HEADER_X_FORWARDED_PORT => 'host', Chris@17: ]; Chris@0: Chris@0: /** Chris@14: * @param array $query The GET parameters Chris@14: * @param array $request The POST parameters Chris@14: * @param array $attributes The request attributes (parameters parsed from the PATH_INFO, ...) Chris@14: * @param array $cookies The COOKIE parameters Chris@14: * @param array $files The FILES parameters Chris@14: * @param array $server The SERVER parameters Chris@14: * @param string|resource|null $content The raw body data Chris@0: */ Chris@17: public function __construct(array $query = [], array $request = [], array $attributes = [], array $cookies = [], array $files = [], array $server = [], $content = null) Chris@0: { Chris@0: $this->initialize($query, $request, $attributes, $cookies, $files, $server, $content); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Sets the parameters for this request. Chris@0: * Chris@0: * This method also re-initializes all properties. Chris@0: * Chris@14: * @param array $query The GET parameters Chris@14: * @param array $request The POST parameters Chris@14: * @param array $attributes The request attributes (parameters parsed from the PATH_INFO, ...) Chris@14: * @param array $cookies The COOKIE parameters Chris@14: * @param array $files The FILES parameters Chris@14: * @param array $server The SERVER parameters Chris@14: * @param string|resource|null $content The raw body data Chris@0: */ Chris@17: public function initialize(array $query = [], array $request = [], array $attributes = [], array $cookies = [], array $files = [], array $server = [], $content = null) Chris@0: { Chris@0: $this->request = new ParameterBag($request); Chris@0: $this->query = new ParameterBag($query); Chris@0: $this->attributes = new ParameterBag($attributes); Chris@0: $this->cookies = new ParameterBag($cookies); Chris@0: $this->files = new FileBag($files); Chris@0: $this->server = new ServerBag($server); Chris@0: $this->headers = new HeaderBag($this->server->getHeaders()); Chris@0: Chris@0: $this->content = $content; Chris@0: $this->languages = null; Chris@0: $this->charsets = null; Chris@0: $this->encodings = null; Chris@0: $this->acceptableContentTypes = null; Chris@0: $this->pathInfo = null; Chris@0: $this->requestUri = null; Chris@0: $this->baseUrl = null; Chris@0: $this->basePath = null; Chris@0: $this->method = null; Chris@0: $this->format = null; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Creates a new request with values from PHP's super globals. Chris@0: * Chris@0: * @return static Chris@0: */ Chris@0: public static function createFromGlobals() Chris@0: { Chris@0: // With the php's bug #66606, the php's built-in web server Chris@0: // stores the Content-Type and Content-Length header values in Chris@0: // HTTP_CONTENT_TYPE and HTTP_CONTENT_LENGTH fields. Chris@0: $server = $_SERVER; Chris@17: if ('cli-server' === \PHP_SAPI) { Chris@18: if (\array_key_exists('HTTP_CONTENT_LENGTH', $_SERVER)) { Chris@0: $server['CONTENT_LENGTH'] = $_SERVER['HTTP_CONTENT_LENGTH']; Chris@0: } Chris@18: if (\array_key_exists('HTTP_CONTENT_TYPE', $_SERVER)) { Chris@0: $server['CONTENT_TYPE'] = $_SERVER['HTTP_CONTENT_TYPE']; Chris@0: } Chris@0: } Chris@0: Chris@17: $request = self::createRequestFromFactory($_GET, $_POST, [], $_COOKIE, $_FILES, $server); Chris@0: Chris@0: if (0 === strpos($request->headers->get('CONTENT_TYPE'), 'application/x-www-form-urlencoded') Chris@17: && \in_array(strtoupper($request->server->get('REQUEST_METHOD', 'GET')), ['PUT', 'DELETE', 'PATCH']) Chris@0: ) { Chris@0: parse_str($request->getContent(), $data); Chris@0: $request->request = new ParameterBag($data); Chris@0: } Chris@0: Chris@0: return $request; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Creates a Request based on a given URI and configuration. Chris@0: * Chris@0: * The information contained in the URI always take precedence Chris@0: * over the other information (server and parameters). Chris@0: * Chris@14: * @param string $uri The URI Chris@14: * @param string $method The HTTP method Chris@14: * @param array $parameters The query (GET) or request (POST) parameters Chris@14: * @param array $cookies The request cookies ($_COOKIE) Chris@14: * @param array $files The request files ($_FILES) Chris@14: * @param array $server The server parameters ($_SERVER) Chris@14: * @param string|resource|null $content The raw body data Chris@0: * Chris@0: * @return static Chris@0: */ Chris@17: public static function create($uri, $method = 'GET', $parameters = [], $cookies = [], $files = [], $server = [], $content = null) Chris@0: { Chris@17: $server = array_replace([ Chris@0: 'SERVER_NAME' => 'localhost', Chris@0: 'SERVER_PORT' => 80, Chris@0: 'HTTP_HOST' => 'localhost', Chris@0: 'HTTP_USER_AGENT' => 'Symfony/3.X', Chris@0: 'HTTP_ACCEPT' => 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', Chris@0: 'HTTP_ACCEPT_LANGUAGE' => 'en-us,en;q=0.5', Chris@0: 'HTTP_ACCEPT_CHARSET' => 'ISO-8859-1,utf-8;q=0.7,*;q=0.7', Chris@0: 'REMOTE_ADDR' => '127.0.0.1', Chris@0: 'SCRIPT_NAME' => '', Chris@0: 'SCRIPT_FILENAME' => '', Chris@0: 'SERVER_PROTOCOL' => 'HTTP/1.1', Chris@0: 'REQUEST_TIME' => time(), Chris@17: ], $server); Chris@0: Chris@0: $server['PATH_INFO'] = ''; Chris@0: $server['REQUEST_METHOD'] = strtoupper($method); Chris@0: Chris@0: $components = parse_url($uri); Chris@0: if (isset($components['host'])) { Chris@0: $server['SERVER_NAME'] = $components['host']; Chris@0: $server['HTTP_HOST'] = $components['host']; Chris@0: } Chris@0: Chris@0: if (isset($components['scheme'])) { Chris@0: if ('https' === $components['scheme']) { Chris@0: $server['HTTPS'] = 'on'; Chris@0: $server['SERVER_PORT'] = 443; Chris@0: } else { Chris@0: unset($server['HTTPS']); Chris@0: $server['SERVER_PORT'] = 80; Chris@0: } Chris@0: } Chris@0: Chris@0: if (isset($components['port'])) { Chris@0: $server['SERVER_PORT'] = $components['port']; Chris@17: $server['HTTP_HOST'] .= ':'.$components['port']; Chris@0: } Chris@0: Chris@0: if (isset($components['user'])) { Chris@0: $server['PHP_AUTH_USER'] = $components['user']; Chris@0: } Chris@0: Chris@0: if (isset($components['pass'])) { Chris@0: $server['PHP_AUTH_PW'] = $components['pass']; Chris@0: } Chris@0: Chris@0: if (!isset($components['path'])) { Chris@0: $components['path'] = '/'; Chris@0: } Chris@0: Chris@0: switch (strtoupper($method)) { Chris@0: case 'POST': Chris@0: case 'PUT': Chris@0: case 'DELETE': Chris@0: if (!isset($server['CONTENT_TYPE'])) { Chris@0: $server['CONTENT_TYPE'] = 'application/x-www-form-urlencoded'; Chris@0: } Chris@0: // no break Chris@0: case 'PATCH': Chris@0: $request = $parameters; Chris@17: $query = []; Chris@0: break; Chris@0: default: Chris@17: $request = []; Chris@0: $query = $parameters; Chris@0: break; Chris@0: } Chris@0: Chris@0: $queryString = ''; Chris@0: if (isset($components['query'])) { Chris@0: parse_str(html_entity_decode($components['query']), $qs); Chris@0: Chris@0: if ($query) { Chris@0: $query = array_replace($qs, $query); Chris@0: $queryString = http_build_query($query, '', '&'); Chris@0: } else { Chris@0: $query = $qs; Chris@0: $queryString = $components['query']; Chris@0: } Chris@0: } elseif ($query) { Chris@0: $queryString = http_build_query($query, '', '&'); Chris@0: } Chris@0: Chris@0: $server['REQUEST_URI'] = $components['path'].('' !== $queryString ? '?'.$queryString : ''); Chris@0: $server['QUERY_STRING'] = $queryString; Chris@0: Chris@17: return self::createRequestFromFactory($query, $request, [], $cookies, $files, $server, $content); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Sets a callable able to create a Request instance. Chris@0: * Chris@0: * This is mainly useful when you need to override the Request class Chris@0: * to keep BC with an existing system. It should not be used for any Chris@0: * other purpose. Chris@0: * Chris@0: * @param callable|null $callable A PHP callable Chris@0: */ Chris@0: public static function setFactory($callable) Chris@0: { Chris@0: self::$requestFactory = $callable; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Clones a request and overrides some of its parameters. Chris@0: * Chris@0: * @param array $query The GET parameters Chris@0: * @param array $request The POST parameters Chris@0: * @param array $attributes The request attributes (parameters parsed from the PATH_INFO, ...) Chris@0: * @param array $cookies The COOKIE parameters Chris@0: * @param array $files The FILES parameters Chris@0: * @param array $server The SERVER parameters Chris@0: * Chris@0: * @return static Chris@0: */ Chris@0: public function duplicate(array $query = null, array $request = null, array $attributes = null, array $cookies = null, array $files = null, array $server = null) Chris@0: { Chris@0: $dup = clone $this; Chris@14: if (null !== $query) { Chris@0: $dup->query = new ParameterBag($query); Chris@0: } Chris@14: if (null !== $request) { Chris@0: $dup->request = new ParameterBag($request); Chris@0: } Chris@14: if (null !== $attributes) { Chris@0: $dup->attributes = new ParameterBag($attributes); Chris@0: } Chris@14: if (null !== $cookies) { Chris@0: $dup->cookies = new ParameterBag($cookies); Chris@0: } Chris@14: if (null !== $files) { Chris@0: $dup->files = new FileBag($files); Chris@0: } Chris@14: if (null !== $server) { Chris@0: $dup->server = new ServerBag($server); Chris@0: $dup->headers = new HeaderBag($dup->server->getHeaders()); Chris@0: } Chris@0: $dup->languages = null; Chris@0: $dup->charsets = null; Chris@0: $dup->encodings = null; Chris@0: $dup->acceptableContentTypes = null; Chris@0: $dup->pathInfo = null; Chris@0: $dup->requestUri = null; Chris@0: $dup->baseUrl = null; Chris@0: $dup->basePath = null; Chris@0: $dup->method = null; Chris@0: $dup->format = null; Chris@0: Chris@0: if (!$dup->get('_format') && $this->get('_format')) { Chris@0: $dup->attributes->set('_format', $this->get('_format')); Chris@0: } Chris@0: Chris@0: if (!$dup->getRequestFormat(null)) { Chris@0: $dup->setRequestFormat($this->getRequestFormat(null)); Chris@0: } Chris@0: Chris@0: return $dup; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Clones the current request. Chris@0: * Chris@0: * Note that the session is not cloned as duplicated requests Chris@0: * are most of the time sub-requests of the main one. Chris@0: */ Chris@0: public function __clone() Chris@0: { Chris@0: $this->query = clone $this->query; Chris@0: $this->request = clone $this->request; Chris@0: $this->attributes = clone $this->attributes; Chris@0: $this->cookies = clone $this->cookies; Chris@0: $this->files = clone $this->files; Chris@0: $this->server = clone $this->server; Chris@0: $this->headers = clone $this->headers; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Returns the request as a string. Chris@0: * Chris@0: * @return string The request Chris@0: */ Chris@0: public function __toString() Chris@0: { Chris@0: try { Chris@0: $content = $this->getContent(); Chris@0: } catch (\LogicException $e) { Chris@0: return trigger_error($e, E_USER_ERROR); Chris@0: } Chris@0: Chris@14: $cookieHeader = ''; Chris@17: $cookies = []; Chris@14: Chris@14: foreach ($this->cookies as $k => $v) { Chris@14: $cookies[] = $k.'='.$v; Chris@14: } Chris@14: Chris@14: if (!empty($cookies)) { Chris@14: $cookieHeader = 'Cookie: '.implode('; ', $cookies)."\r\n"; Chris@14: } Chris@14: Chris@0: return Chris@0: sprintf('%s %s %s', $this->getMethod(), $this->getRequestUri(), $this->server->get('SERVER_PROTOCOL'))."\r\n". Chris@14: $this->headers. Chris@14: $cookieHeader."\r\n". Chris@0: $content; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Overrides the PHP global variables according to this request instance. Chris@0: * Chris@0: * It overrides $_GET, $_POST, $_REQUEST, $_SERVER, $_COOKIE. Chris@0: * $_FILES is never overridden, see rfc1867 Chris@0: */ Chris@0: public function overrideGlobals() Chris@0: { Chris@14: $this->server->set('QUERY_STRING', static::normalizeQueryString(http_build_query($this->query->all(), '', '&'))); Chris@0: Chris@0: $_GET = $this->query->all(); Chris@0: $_POST = $this->request->all(); Chris@0: $_SERVER = $this->server->all(); Chris@0: $_COOKIE = $this->cookies->all(); Chris@0: Chris@0: foreach ($this->headers->all() as $key => $value) { Chris@0: $key = strtoupper(str_replace('-', '_', $key)); Chris@17: if (\in_array($key, ['CONTENT_TYPE', 'CONTENT_LENGTH'])) { Chris@0: $_SERVER[$key] = implode(', ', $value); Chris@0: } else { Chris@0: $_SERVER['HTTP_'.$key] = implode(', ', $value); Chris@0: } Chris@0: } Chris@0: Chris@17: $request = ['g' => $_GET, 'p' => $_POST, 'c' => $_COOKIE]; Chris@0: Chris@0: $requestOrder = ini_get('request_order') ?: ini_get('variables_order'); Chris@0: $requestOrder = preg_replace('#[^cgp]#', '', strtolower($requestOrder)) ?: 'gp'; Chris@0: Chris@17: $_REQUEST = []; Chris@0: foreach (str_split($requestOrder) as $order) { Chris@0: $_REQUEST = array_merge($_REQUEST, $request[$order]); Chris@0: } Chris@0: } Chris@0: Chris@0: /** Chris@0: * Sets a list of trusted proxies. Chris@0: * Chris@0: * You should only list the reverse proxies that you manage directly. Chris@0: * Chris@14: * @param array $proxies A list of trusted proxies Chris@14: * @param int $trustedHeaderSet A bit field of Request::HEADER_*, to set which headers to trust from your proxies Chris@14: * Chris@14: * @throws \InvalidArgumentException When $trustedHeaderSet is invalid Chris@0: */ Chris@14: public static function setTrustedProxies(array $proxies/*, int $trustedHeaderSet*/) Chris@0: { Chris@0: self::$trustedProxies = $proxies; Chris@14: Chris@17: if (2 > \func_num_args()) { Chris@14: @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); Chris@14: Chris@14: return; Chris@14: } Chris@14: $trustedHeaderSet = (int) func_get_arg(1); Chris@14: Chris@14: foreach (self::$trustedHeaderNames as $header => $name) { Chris@14: self::$trustedHeaders[$header] = $header & $trustedHeaderSet ? $name : null; Chris@14: } Chris@14: self::$trustedHeaderSet = $trustedHeaderSet; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Gets the list of trusted proxies. Chris@0: * Chris@0: * @return array An array of trusted proxies Chris@0: */ Chris@0: public static function getTrustedProxies() Chris@0: { Chris@0: return self::$trustedProxies; Chris@0: } Chris@0: Chris@0: /** Chris@14: * Gets the set of trusted headers from trusted proxies. Chris@14: * Chris@14: * @return int A bit field of Request::HEADER_* that defines which headers are trusted from your proxies Chris@14: */ Chris@14: public static function getTrustedHeaderSet() Chris@14: { Chris@14: return self::$trustedHeaderSet; Chris@14: } Chris@14: Chris@14: /** Chris@0: * Sets a list of trusted host patterns. Chris@0: * Chris@0: * You should only list the hosts you manage using regexs. Chris@0: * Chris@0: * @param array $hostPatterns A list of trusted host patterns Chris@0: */ Chris@0: public static function setTrustedHosts(array $hostPatterns) Chris@0: { Chris@0: self::$trustedHostPatterns = array_map(function ($hostPattern) { Chris@16: return sprintf('{%s}i', $hostPattern); Chris@0: }, $hostPatterns); Chris@0: // we need to reset trusted hosts on trusted host patterns change Chris@17: self::$trustedHosts = []; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Gets the list of trusted host patterns. Chris@0: * Chris@0: * @return array An array of trusted host patterns Chris@0: */ Chris@0: public static function getTrustedHosts() Chris@0: { Chris@0: return self::$trustedHostPatterns; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Sets the name for trusted headers. Chris@0: * Chris@0: * The following header keys are supported: Chris@0: * Chris@0: * * Request::HEADER_CLIENT_IP: defaults to X-Forwarded-For (see getClientIp()) Chris@0: * * Request::HEADER_CLIENT_HOST: defaults to X-Forwarded-Host (see getHost()) Chris@0: * * Request::HEADER_CLIENT_PORT: defaults to X-Forwarded-Port (see getPort()) Chris@0: * * Request::HEADER_CLIENT_PROTO: defaults to X-Forwarded-Proto (see getScheme() and isSecure()) Chris@0: * * Request::HEADER_FORWARDED: defaults to Forwarded (see RFC 7239) Chris@0: * Chris@0: * Setting an empty value allows to disable the trusted header for the given key. Chris@0: * Chris@0: * @param string $key The header key Chris@0: * @param string $value The header name Chris@0: * Chris@0: * @throws \InvalidArgumentException Chris@14: * Chris@14: * @deprecated since version 3.3, to be removed in 4.0. Use the $trustedHeaderSet argument of the Request::setTrustedProxies() method instead. Chris@0: */ Chris@0: public static function setTrustedHeaderName($key, $value) Chris@0: { Chris@14: @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); Chris@14: Chris@14: if ('forwarded' === $key) { Chris@14: $key = self::HEADER_FORWARDED; Chris@14: } elseif ('client_ip' === $key) { Chris@14: $key = self::HEADER_CLIENT_IP; Chris@14: } elseif ('client_host' === $key) { Chris@14: $key = self::HEADER_CLIENT_HOST; Chris@14: } elseif ('client_proto' === $key) { Chris@14: $key = self::HEADER_CLIENT_PROTO; Chris@14: } elseif ('client_port' === $key) { Chris@14: $key = self::HEADER_CLIENT_PORT; Chris@18: } elseif (!\array_key_exists($key, self::$trustedHeaders)) { Chris@0: throw new \InvalidArgumentException(sprintf('Unable to set the trusted header name for key "%s".', $key)); Chris@0: } Chris@0: Chris@0: self::$trustedHeaders[$key] = $value; Chris@14: Chris@14: if (null !== $value) { Chris@14: self::$trustedHeaderNames[$key] = $value; Chris@14: self::$trustedHeaderSet |= $key; Chris@14: } else { Chris@14: self::$trustedHeaderSet &= ~$key; Chris@14: } Chris@0: } Chris@0: Chris@0: /** Chris@0: * Gets the trusted proxy header name. Chris@0: * Chris@0: * @param string $key The header key Chris@0: * Chris@0: * @return string The header name Chris@0: * Chris@0: * @throws \InvalidArgumentException Chris@14: * Chris@14: * @deprecated since version 3.3, to be removed in 4.0. Use the Request::getTrustedHeaderSet() method instead. Chris@0: */ Chris@0: public static function getTrustedHeaderName($key) Chris@0: { Chris@17: if (2 > \func_num_args() || func_get_arg(1)) { Chris@14: @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); Chris@14: } Chris@14: Chris@18: if (!\array_key_exists($key, self::$trustedHeaders)) { Chris@0: throw new \InvalidArgumentException(sprintf('Unable to get the trusted header name for key "%s".', $key)); Chris@0: } Chris@0: Chris@0: return self::$trustedHeaders[$key]; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Normalizes a query string. Chris@0: * Chris@0: * It builds a normalized query string, where keys/value pairs are alphabetized, Chris@0: * have consistent escaping and unneeded delimiters are removed. Chris@0: * Chris@0: * @param string $qs Query string Chris@0: * Chris@0: * @return string A normalized query string for the Request Chris@0: */ Chris@0: public static function normalizeQueryString($qs) Chris@0: { Chris@0: if ('' == $qs) { Chris@0: return ''; Chris@0: } Chris@0: Chris@17: $parts = []; Chris@17: $order = []; Chris@0: Chris@0: foreach (explode('&', $qs) as $param) { Chris@0: if ('' === $param || '=' === $param[0]) { Chris@0: // Ignore useless delimiters, e.g. "x=y&". Chris@0: // Also ignore pairs with empty key, even if there was a value, e.g. "=value", as such nameless values cannot be retrieved anyway. Chris@0: // PHP also does not include them when building _GET. Chris@0: continue; Chris@0: } Chris@0: Chris@0: $keyValuePair = explode('=', $param, 2); Chris@0: Chris@0: // GET parameters, that are submitted from a HTML form, encode spaces as "+" by default (as defined in enctype application/x-www-form-urlencoded). Chris@0: // 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 Chris@0: // RFC 3986 with rawurlencode. Chris@0: $parts[] = isset($keyValuePair[1]) ? Chris@0: rawurlencode(urldecode($keyValuePair[0])).'='.rawurlencode(urldecode($keyValuePair[1])) : Chris@0: rawurlencode(urldecode($keyValuePair[0])); Chris@0: $order[] = urldecode($keyValuePair[0]); Chris@0: } Chris@0: Chris@0: array_multisort($order, SORT_ASC, $parts); Chris@0: Chris@0: return implode('&', $parts); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Enables support for the _method request parameter to determine the intended HTTP method. Chris@0: * Chris@0: * Be warned that enabling this feature might lead to CSRF issues in your code. Chris@0: * Check that you are using CSRF tokens when required. Chris@0: * If the HTTP method parameter override is enabled, an html-form with method "POST" can be altered Chris@0: * and used to send a "PUT" or "DELETE" request via the _method request parameter. Chris@0: * If these methods are not protected against CSRF, this presents a possible vulnerability. Chris@0: * Chris@0: * The HTTP method can only be overridden when the real HTTP method is POST. Chris@0: */ Chris@0: public static function enableHttpMethodParameterOverride() Chris@0: { Chris@0: self::$httpMethodParameterOverride = true; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Checks whether support for the _method request parameter is enabled. Chris@0: * Chris@0: * @return bool True when the _method request parameter is enabled, false otherwise Chris@0: */ Chris@0: public static function getHttpMethodParameterOverride() Chris@0: { Chris@0: return self::$httpMethodParameterOverride; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Gets a "parameter" value from any bag. Chris@0: * Chris@0: * This method is mainly useful for libraries that want to provide some flexibility. If you don't need the Chris@0: * flexibility in controllers, it is better to explicitly get request parameters from the appropriate Chris@0: * public property instead (attributes, query, request). Chris@0: * Chris@0: * Order of precedence: PATH (routing placeholders or custom attributes), GET, BODY Chris@0: * Chris@14: * @param string $key The key Chris@14: * @param mixed $default The default value if the parameter key does not exist Chris@0: * Chris@0: * @return mixed Chris@0: */ Chris@0: public function get($key, $default = null) Chris@0: { Chris@0: if ($this !== $result = $this->attributes->get($key, $this)) { Chris@0: return $result; Chris@0: } Chris@0: Chris@0: if ($this !== $result = $this->query->get($key, $this)) { Chris@0: return $result; Chris@0: } Chris@0: Chris@0: if ($this !== $result = $this->request->get($key, $this)) { Chris@0: return $result; Chris@0: } Chris@0: Chris@0: return $default; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Gets the Session. Chris@0: * Chris@0: * @return SessionInterface|null The session Chris@0: */ Chris@0: public function getSession() Chris@0: { Chris@0: return $this->session; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Whether the request contains a Session which was started in one of the Chris@0: * previous requests. Chris@0: * Chris@0: * @return bool Chris@0: */ Chris@0: public function hasPreviousSession() Chris@0: { Chris@0: // the check for $this->session avoids malicious users trying to fake a session cookie with proper name Chris@0: return $this->hasSession() && $this->cookies->has($this->session->getName()); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Whether the request contains a Session object. Chris@0: * Chris@0: * This method does not give any information about the state of the session object, Chris@0: * like whether the session is started or not. It is just a way to check if this Request Chris@0: * is associated with a Session instance. Chris@0: * Chris@0: * @return bool true when the Request contains a Session object, false otherwise Chris@0: */ Chris@0: public function hasSession() Chris@0: { Chris@0: return null !== $this->session; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Sets the Session. Chris@0: * Chris@0: * @param SessionInterface $session The Session Chris@0: */ Chris@0: public function setSession(SessionInterface $session) Chris@0: { Chris@0: $this->session = $session; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Returns the client IP addresses. Chris@0: * Chris@0: * In the returned array the most trusted IP address is first, and the Chris@0: * least trusted one last. The "real" client IP address is the last one, Chris@0: * but this is also the least trusted one. Trusted proxies are stripped. Chris@0: * Chris@0: * Use this method carefully; you should use getClientIp() instead. Chris@0: * Chris@0: * @return array The client IP addresses Chris@0: * Chris@0: * @see getClientIp() Chris@0: */ Chris@0: public function getClientIps() Chris@0: { Chris@0: $ip = $this->server->get('REMOTE_ADDR'); Chris@0: Chris@0: if (!$this->isFromTrustedProxy()) { Chris@17: return [$ip]; Chris@0: } Chris@0: Chris@17: return $this->getTrustedValues(self::HEADER_CLIENT_IP, $ip) ?: [$ip]; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Returns the client IP address. Chris@0: * Chris@0: * This method can read the client IP address from the "X-Forwarded-For" header Chris@0: * when trusted proxies were set via "setTrustedProxies()". The "X-Forwarded-For" Chris@0: * header value is a comma+space separated list of IP addresses, the left-most Chris@0: * being the original client, and each successive proxy that passed the request Chris@0: * adding the IP address where it received the request from. Chris@0: * Chris@0: * If your reverse proxy uses a different header name than "X-Forwarded-For", Chris@14: * ("Client-Ip" for instance), configure it via the $trustedHeaderSet Chris@14: * argument of the Request::setTrustedProxies() method instead. Chris@0: * Chris@0: * @return string|null The client IP address Chris@0: * Chris@0: * @see getClientIps() Chris@0: * @see http://en.wikipedia.org/wiki/X-Forwarded-For Chris@0: */ Chris@0: public function getClientIp() Chris@0: { Chris@0: $ipAddresses = $this->getClientIps(); Chris@0: Chris@0: return $ipAddresses[0]; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Returns current script name. Chris@0: * Chris@0: * @return string Chris@0: */ Chris@0: public function getScriptName() Chris@0: { Chris@0: return $this->server->get('SCRIPT_NAME', $this->server->get('ORIG_SCRIPT_NAME', '')); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Returns the path being requested relative to the executed script. Chris@0: * Chris@0: * The path info always starts with a /. Chris@0: * Chris@0: * Suppose this request is instantiated from /mysite on localhost: Chris@0: * Chris@0: * * http://localhost/mysite returns an empty string Chris@0: * * http://localhost/mysite/about returns '/about' Chris@0: * * http://localhost/mysite/enco%20ded returns '/enco%20ded' Chris@0: * * http://localhost/mysite/about?var=1 returns '/about' Chris@0: * Chris@0: * @return string The raw path (i.e. not urldecoded) Chris@0: */ Chris@0: public function getPathInfo() Chris@0: { Chris@0: if (null === $this->pathInfo) { Chris@0: $this->pathInfo = $this->preparePathInfo(); Chris@0: } Chris@0: Chris@0: return $this->pathInfo; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Returns the root path from which this request is executed. Chris@0: * Chris@0: * Suppose that an index.php file instantiates this request object: Chris@0: * Chris@0: * * http://localhost/index.php returns an empty string Chris@0: * * http://localhost/index.php/page returns an empty string Chris@0: * * http://localhost/web/index.php returns '/web' Chris@0: * * http://localhost/we%20b/index.php returns '/we%20b' Chris@0: * Chris@0: * @return string The raw path (i.e. not urldecoded) Chris@0: */ Chris@0: public function getBasePath() Chris@0: { Chris@0: if (null === $this->basePath) { Chris@0: $this->basePath = $this->prepareBasePath(); Chris@0: } Chris@0: Chris@0: return $this->basePath; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Returns the root URL from which this request is executed. Chris@0: * Chris@0: * The base URL never ends with a /. Chris@0: * Chris@0: * This is similar to getBasePath(), except that it also includes the Chris@0: * script filename (e.g. index.php) if one exists. Chris@0: * Chris@0: * @return string The raw URL (i.e. not urldecoded) Chris@0: */ Chris@0: public function getBaseUrl() Chris@0: { Chris@0: if (null === $this->baseUrl) { Chris@0: $this->baseUrl = $this->prepareBaseUrl(); Chris@0: } Chris@0: Chris@0: return $this->baseUrl; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Gets the request's scheme. Chris@0: * Chris@0: * @return string Chris@0: */ Chris@0: public function getScheme() Chris@0: { Chris@0: return $this->isSecure() ? 'https' : 'http'; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Returns the port on which the request is made. Chris@0: * Chris@0: * This method can read the client port from the "X-Forwarded-Port" header Chris@0: * when trusted proxies were set via "setTrustedProxies()". Chris@0: * Chris@0: * The "X-Forwarded-Port" header must contain the client port. Chris@0: * Chris@0: * If your reverse proxy uses a different header name than "X-Forwarded-Port", Chris@14: * configure it via via the $trustedHeaderSet argument of the Chris@14: * Request::setTrustedProxies() method instead. Chris@0: * Chris@0: * @return int|string can be a string if fetched from the server bag Chris@0: */ Chris@0: public function getPort() Chris@0: { Chris@0: if ($this->isFromTrustedProxy() && $host = $this->getTrustedValues(self::HEADER_CLIENT_PORT)) { Chris@0: $host = $host[0]; Chris@0: } elseif ($this->isFromTrustedProxy() && $host = $this->getTrustedValues(self::HEADER_CLIENT_HOST)) { Chris@0: $host = $host[0]; Chris@0: } elseif (!$host = $this->headers->get('HOST')) { Chris@0: return $this->server->get('SERVER_PORT'); Chris@0: } Chris@0: Chris@14: if ('[' === $host[0]) { Chris@0: $pos = strpos($host, ':', strrpos($host, ']')); Chris@0: } else { Chris@0: $pos = strrpos($host, ':'); Chris@0: } Chris@0: Chris@0: if (false !== $pos) { Chris@0: return (int) substr($host, $pos + 1); Chris@0: } Chris@0: Chris@0: return 'https' === $this->getScheme() ? 443 : 80; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Returns the user. Chris@0: * Chris@0: * @return string|null Chris@0: */ Chris@0: public function getUser() Chris@0: { Chris@0: return $this->headers->get('PHP_AUTH_USER'); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Returns the password. Chris@0: * Chris@0: * @return string|null Chris@0: */ Chris@0: public function getPassword() Chris@0: { Chris@0: return $this->headers->get('PHP_AUTH_PW'); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Gets the user info. Chris@0: * Chris@0: * @return string A user name and, optionally, scheme-specific information about how to gain authorization to access the server Chris@0: */ Chris@0: public function getUserInfo() Chris@0: { Chris@0: $userinfo = $this->getUser(); Chris@0: Chris@0: $pass = $this->getPassword(); Chris@0: if ('' != $pass) { Chris@0: $userinfo .= ":$pass"; Chris@0: } Chris@0: Chris@0: return $userinfo; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Returns the HTTP host being requested. Chris@0: * Chris@0: * The port name will be appended to the host if it's non-standard. Chris@0: * Chris@0: * @return string Chris@0: */ Chris@0: public function getHttpHost() Chris@0: { Chris@0: $scheme = $this->getScheme(); Chris@0: $port = $this->getPort(); Chris@0: Chris@14: if (('http' == $scheme && 80 == $port) || ('https' == $scheme && 443 == $port)) { Chris@0: return $this->getHost(); Chris@0: } Chris@0: Chris@0: return $this->getHost().':'.$port; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Returns the requested URI (path and query string). Chris@0: * Chris@0: * @return string The raw URI (i.e. not URI decoded) Chris@0: */ Chris@0: public function getRequestUri() Chris@0: { Chris@0: if (null === $this->requestUri) { Chris@0: $this->requestUri = $this->prepareRequestUri(); Chris@0: } Chris@0: Chris@0: return $this->requestUri; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Gets the scheme and HTTP host. Chris@0: * Chris@0: * If the URL was called with basic authentication, the user Chris@0: * and the password are not added to the generated string. Chris@0: * Chris@0: * @return string The scheme and HTTP host Chris@0: */ Chris@0: public function getSchemeAndHttpHost() Chris@0: { Chris@0: return $this->getScheme().'://'.$this->getHttpHost(); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Generates a normalized URI (URL) for the Request. Chris@0: * Chris@0: * @return string A normalized URI (URL) for the Request Chris@0: * Chris@0: * @see getQueryString() Chris@0: */ Chris@0: public function getUri() Chris@0: { Chris@0: if (null !== $qs = $this->getQueryString()) { Chris@0: $qs = '?'.$qs; Chris@0: } Chris@0: Chris@0: return $this->getSchemeAndHttpHost().$this->getBaseUrl().$this->getPathInfo().$qs; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Generates a normalized URI for the given path. Chris@0: * Chris@0: * @param string $path A path to use instead of the current one Chris@0: * Chris@0: * @return string The normalized URI for the path Chris@0: */ Chris@0: public function getUriForPath($path) Chris@0: { Chris@0: return $this->getSchemeAndHttpHost().$this->getBaseUrl().$path; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Returns the path as relative reference from the current Request path. Chris@0: * Chris@0: * Only the URIs path component (no schema, host etc.) is relevant and must be given. Chris@0: * Both paths must be absolute and not contain relative parts. Chris@0: * Relative URLs from one resource to another are useful when generating self-contained downloadable document archives. Chris@0: * Furthermore, they can be used to reduce the link size in documents. Chris@0: * Chris@0: * Example target paths, given a base path of "/a/b/c/d": Chris@0: * - "/a/b/c/d" -> "" Chris@0: * - "/a/b/c/" -> "./" Chris@0: * - "/a/b/" -> "../" Chris@0: * - "/a/b/c/other" -> "other" Chris@0: * - "/a/x/y" -> "../../x/y" Chris@0: * Chris@0: * @param string $path The target path Chris@0: * Chris@0: * @return string The relative target path Chris@0: */ Chris@0: public function getRelativeUriForPath($path) Chris@0: { Chris@0: // be sure that we are dealing with an absolute path Chris@0: if (!isset($path[0]) || '/' !== $path[0]) { Chris@0: return $path; Chris@0: } Chris@0: Chris@0: if ($path === $basePath = $this->getPathInfo()) { Chris@0: return ''; Chris@0: } Chris@0: Chris@0: $sourceDirs = explode('/', isset($basePath[0]) && '/' === $basePath[0] ? substr($basePath, 1) : $basePath); Chris@17: $targetDirs = explode('/', substr($path, 1)); Chris@0: array_pop($sourceDirs); Chris@0: $targetFile = array_pop($targetDirs); Chris@0: Chris@0: foreach ($sourceDirs as $i => $dir) { Chris@0: if (isset($targetDirs[$i]) && $dir === $targetDirs[$i]) { Chris@0: unset($sourceDirs[$i], $targetDirs[$i]); Chris@0: } else { Chris@0: break; Chris@0: } Chris@0: } Chris@0: Chris@0: $targetDirs[] = $targetFile; Chris@17: $path = str_repeat('../', \count($sourceDirs)).implode('/', $targetDirs); Chris@0: Chris@0: // A reference to the same base directory or an empty subdirectory must be prefixed with "./". Chris@0: // This also applies to a segment with a colon character (e.g., "file:colon") that cannot be used Chris@0: // as the first segment of a relative-path reference, as it would be mistaken for a scheme name Chris@0: // (see http://tools.ietf.org/html/rfc3986#section-4.2). Chris@0: return !isset($path[0]) || '/' === $path[0] Chris@0: || false !== ($colonPos = strpos($path, ':')) && ($colonPos < ($slashPos = strpos($path, '/')) || false === $slashPos) Chris@0: ? "./$path" : $path; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Generates the normalized query string for the Request. Chris@0: * Chris@0: * It builds a normalized query string, where keys/value pairs are alphabetized Chris@0: * and have consistent escaping. Chris@0: * Chris@0: * @return string|null A normalized query string for the Request Chris@0: */ Chris@0: public function getQueryString() Chris@0: { Chris@0: $qs = static::normalizeQueryString($this->server->get('QUERY_STRING')); Chris@0: Chris@0: return '' === $qs ? null : $qs; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Checks whether the request is secure or not. Chris@0: * Chris@0: * This method can read the client protocol from the "X-Forwarded-Proto" header Chris@0: * when trusted proxies were set via "setTrustedProxies()". Chris@0: * Chris@0: * The "X-Forwarded-Proto" header must contain the protocol: "https" or "http". Chris@0: * Chris@0: * If your reverse proxy uses a different header name than "X-Forwarded-Proto" Chris@14: * ("SSL_HTTPS" for instance), configure it via the $trustedHeaderSet Chris@14: * argument of the Request::setTrustedProxies() method instead. Chris@0: * Chris@0: * @return bool Chris@0: */ Chris@0: public function isSecure() Chris@0: { Chris@0: if ($this->isFromTrustedProxy() && $proto = $this->getTrustedValues(self::HEADER_CLIENT_PROTO)) { Chris@17: return \in_array(strtolower($proto[0]), ['https', 'on', 'ssl', '1'], true); Chris@0: } Chris@0: Chris@0: $https = $this->server->get('HTTPS'); Chris@0: Chris@0: return !empty($https) && 'off' !== strtolower($https); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Returns the host name. Chris@0: * Chris@0: * This method can read the client host name from the "X-Forwarded-Host" header Chris@0: * when trusted proxies were set via "setTrustedProxies()". Chris@0: * Chris@0: * The "X-Forwarded-Host" header must contain the client host name. Chris@0: * Chris@0: * If your reverse proxy uses a different header name than "X-Forwarded-Host", Chris@14: * configure it via the $trustedHeaderSet argument of the Chris@14: * Request::setTrustedProxies() method instead. Chris@0: * Chris@0: * @return string Chris@0: * Chris@14: * @throws SuspiciousOperationException when the host name is invalid or not trusted Chris@0: */ Chris@0: public function getHost() Chris@0: { Chris@0: if ($this->isFromTrustedProxy() && $host = $this->getTrustedValues(self::HEADER_CLIENT_HOST)) { Chris@0: $host = $host[0]; Chris@0: } elseif (!$host = $this->headers->get('HOST')) { Chris@0: if (!$host = $this->server->get('SERVER_NAME')) { Chris@0: $host = $this->server->get('SERVER_ADDR', ''); Chris@0: } Chris@0: } Chris@0: Chris@0: // trim and remove port number from host Chris@0: // host is lowercase as per RFC 952/2181 Chris@0: $host = strtolower(preg_replace('/:\d+$/', '', trim($host))); Chris@0: Chris@0: // as the host can come from the user (HTTP_HOST and depending on the configuration, SERVER_NAME too can come from the user) Chris@0: // check that it does not contain forbidden characters (see RFC 952 and RFC 2181) Chris@0: // use preg_replace() instead of preg_match() to prevent DoS attacks with long host names Chris@0: if ($host && '' !== preg_replace('/(?:^\[)?[a-zA-Z0-9-:\]_]+\.?/', '', $host)) { Chris@14: if (!$this->isHostValid) { Chris@14: return ''; Chris@14: } Chris@14: $this->isHostValid = false; Chris@14: Chris@14: throw new SuspiciousOperationException(sprintf('Invalid Host "%s".', $host)); Chris@0: } Chris@0: Chris@17: if (\count(self::$trustedHostPatterns) > 0) { Chris@0: // to avoid host header injection attacks, you should provide a list of trusted host patterns Chris@0: Chris@17: if (\in_array($host, self::$trustedHosts)) { Chris@0: return $host; Chris@0: } Chris@0: Chris@0: foreach (self::$trustedHostPatterns as $pattern) { Chris@0: if (preg_match($pattern, $host)) { Chris@0: self::$trustedHosts[] = $host; Chris@0: Chris@0: return $host; Chris@0: } Chris@0: } Chris@0: Chris@14: if (!$this->isHostValid) { Chris@14: return ''; Chris@14: } Chris@14: $this->isHostValid = false; Chris@14: Chris@14: throw new SuspiciousOperationException(sprintf('Untrusted Host "%s".', $host)); Chris@0: } Chris@0: Chris@0: return $host; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Sets the request method. Chris@0: * Chris@0: * @param string $method Chris@0: */ Chris@0: public function setMethod($method) Chris@0: { Chris@0: $this->method = null; Chris@0: $this->server->set('REQUEST_METHOD', $method); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Gets the request "intended" method. Chris@0: * Chris@0: * If the X-HTTP-Method-Override header is set, and if the method is a POST, Chris@0: * then it is used to determine the "real" intended HTTP method. Chris@0: * Chris@0: * The _method request parameter can also be used to determine the HTTP method, Chris@0: * but only if enableHttpMethodParameterOverride() has been called. Chris@0: * Chris@0: * The method is always an uppercased string. Chris@0: * Chris@0: * @return string The request method Chris@0: * Chris@0: * @see getRealMethod() Chris@0: */ Chris@0: public function getMethod() Chris@0: { Chris@18: if (null !== $this->method) { Chris@18: return $this->method; Chris@0: } Chris@0: Chris@18: $this->method = strtoupper($this->server->get('REQUEST_METHOD', 'GET')); Chris@18: Chris@18: if ('POST' !== $this->method) { Chris@18: return $this->method; Chris@18: } Chris@18: Chris@18: $method = $this->headers->get('X-HTTP-METHOD-OVERRIDE'); Chris@18: Chris@18: if (!$method && self::$httpMethodParameterOverride) { Chris@18: $method = $this->request->get('_method', $this->query->get('_method', 'POST')); Chris@18: } Chris@18: Chris@18: if (!\is_string($method)) { Chris@18: return $this->method; Chris@18: } Chris@18: Chris@18: $method = strtoupper($method); Chris@18: Chris@18: if (\in_array($method, ['GET', 'HEAD', 'POST', 'PUT', 'DELETE', 'CONNECT', 'OPTIONS', 'PATCH', 'PURGE', 'TRACE'], true)) { Chris@18: return $this->method = $method; Chris@18: } Chris@18: Chris@18: if (!preg_match('/^[A-Z]++$/D', $method)) { Chris@18: throw new SuspiciousOperationException(sprintf('Invalid method override "%s".', $method)); Chris@18: } Chris@18: Chris@18: return $this->method = $method; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Gets the "real" request method. Chris@0: * Chris@0: * @return string The request method Chris@0: * Chris@0: * @see getMethod() Chris@0: */ Chris@0: public function getRealMethod() Chris@0: { Chris@0: return strtoupper($this->server->get('REQUEST_METHOD', 'GET')); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Gets the mime type associated with the format. Chris@0: * Chris@0: * @param string $format The format Chris@0: * Chris@16: * @return string|null The associated mime type (null if not found) Chris@0: */ Chris@0: public function getMimeType($format) Chris@0: { Chris@0: if (null === static::$formats) { Chris@0: static::initializeFormats(); Chris@0: } Chris@0: Chris@0: return isset(static::$formats[$format]) ? static::$formats[$format][0] : null; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Gets the mime types associated with the format. Chris@0: * Chris@0: * @param string $format The format Chris@0: * Chris@0: * @return array The associated mime types Chris@0: */ Chris@0: public static function getMimeTypes($format) Chris@0: { Chris@0: if (null === static::$formats) { Chris@0: static::initializeFormats(); Chris@0: } Chris@0: Chris@17: return isset(static::$formats[$format]) ? static::$formats[$format] : []; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Gets the format associated with the mime type. Chris@0: * Chris@0: * @param string $mimeType The associated mime type Chris@0: * Chris@0: * @return string|null The format (null if not found) Chris@0: */ Chris@0: public function getFormat($mimeType) Chris@0: { Chris@0: $canonicalMimeType = null; Chris@0: if (false !== $pos = strpos($mimeType, ';')) { Chris@17: $canonicalMimeType = trim(substr($mimeType, 0, $pos)); Chris@0: } Chris@0: Chris@0: if (null === static::$formats) { Chris@0: static::initializeFormats(); Chris@0: } Chris@0: Chris@0: foreach (static::$formats as $format => $mimeTypes) { Chris@17: if (\in_array($mimeType, (array) $mimeTypes)) { Chris@0: return $format; Chris@0: } Chris@17: if (null !== $canonicalMimeType && \in_array($canonicalMimeType, (array) $mimeTypes)) { Chris@0: return $format; Chris@0: } Chris@0: } Chris@0: } Chris@0: Chris@0: /** Chris@0: * Associates a format with mime types. Chris@0: * Chris@0: * @param string $format The format Chris@0: * @param string|array $mimeTypes The associated mime types (the preferred one must be the first as it will be used as the content type) Chris@0: */ Chris@0: public function setFormat($format, $mimeTypes) Chris@0: { Chris@0: if (null === static::$formats) { Chris@0: static::initializeFormats(); Chris@0: } Chris@0: Chris@17: static::$formats[$format] = \is_array($mimeTypes) ? $mimeTypes : [$mimeTypes]; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Gets the request format. Chris@0: * Chris@0: * Here is the process to determine the format: Chris@0: * Chris@0: * * format defined by the user (with setRequestFormat()) Chris@0: * * _format request attribute Chris@0: * * $default Chris@0: * Chris@17: * @param string|null $default The default format Chris@0: * Chris@18: * @return string|null The request format Chris@0: */ Chris@0: public function getRequestFormat($default = 'html') Chris@0: { Chris@0: if (null === $this->format) { Chris@0: $this->format = $this->attributes->get('_format'); Chris@0: } Chris@0: Chris@0: return null === $this->format ? $default : $this->format; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Sets the request format. Chris@0: * Chris@0: * @param string $format The request format Chris@0: */ Chris@0: public function setRequestFormat($format) Chris@0: { Chris@0: $this->format = $format; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Gets the format associated with the request. Chris@0: * Chris@0: * @return string|null The format (null if no content type is present) Chris@0: */ Chris@0: public function getContentType() Chris@0: { Chris@0: return $this->getFormat($this->headers->get('CONTENT_TYPE')); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Sets the default locale. Chris@0: * Chris@0: * @param string $locale Chris@0: */ Chris@0: public function setDefaultLocale($locale) Chris@0: { Chris@0: $this->defaultLocale = $locale; Chris@0: Chris@0: if (null === $this->locale) { Chris@0: $this->setPhpDefaultLocale($locale); Chris@0: } Chris@0: } Chris@0: Chris@0: /** Chris@0: * Get the default locale. Chris@0: * Chris@0: * @return string Chris@0: */ Chris@0: public function getDefaultLocale() Chris@0: { Chris@0: return $this->defaultLocale; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Sets the locale. Chris@0: * Chris@0: * @param string $locale Chris@0: */ Chris@0: public function setLocale($locale) Chris@0: { Chris@0: $this->setPhpDefaultLocale($this->locale = $locale); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Get the locale. Chris@0: * Chris@0: * @return string Chris@0: */ Chris@0: public function getLocale() Chris@0: { Chris@0: return null === $this->locale ? $this->defaultLocale : $this->locale; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Checks if the request method is of specified type. Chris@0: * Chris@0: * @param string $method Uppercase request method (GET, POST etc) Chris@0: * Chris@0: * @return bool Chris@0: */ Chris@0: public function isMethod($method) Chris@0: { Chris@0: return $this->getMethod() === strtoupper($method); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Checks whether or not the method is safe. Chris@0: * Chris@0: * @see https://tools.ietf.org/html/rfc7231#section-4.2.1 Chris@0: * Chris@0: * @param bool $andCacheable Adds the additional condition that the method should be cacheable. True by default. Chris@0: * Chris@0: * @return bool Chris@0: */ Chris@0: public function isMethodSafe(/* $andCacheable = true */) Chris@0: { Chris@17: if (!\func_num_args() || func_get_arg(0)) { Chris@0: // This deprecation should be turned into a BadMethodCallException in 4.0 (without adding the argument in the signature) Chris@0: // then setting $andCacheable to false should be deprecated in 4.1 Chris@14: @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); Chris@0: Chris@17: return \in_array($this->getMethod(), ['GET', 'HEAD']); Chris@0: } Chris@0: Chris@17: return \in_array($this->getMethod(), ['GET', 'HEAD', 'OPTIONS', 'TRACE']); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Checks whether or not the method is idempotent. Chris@0: * Chris@0: * @return bool Chris@0: */ Chris@0: public function isMethodIdempotent() Chris@0: { Chris@17: return \in_array($this->getMethod(), ['HEAD', 'GET', 'PUT', 'DELETE', 'TRACE', 'OPTIONS', 'PURGE']); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Checks whether the method is cacheable or not. Chris@0: * Chris@0: * @see https://tools.ietf.org/html/rfc7231#section-4.2.3 Chris@0: * Chris@17: * @return bool True for GET and HEAD, false otherwise Chris@0: */ Chris@0: public function isMethodCacheable() Chris@0: { Chris@17: return \in_array($this->getMethod(), ['GET', 'HEAD']); Chris@0: } Chris@0: Chris@0: /** Chris@14: * Returns the protocol version. Chris@14: * Chris@14: * If the application is behind a proxy, the protocol version used in the Chris@14: * requests between the client and the proxy and between the proxy and the Chris@14: * server might be different. This returns the former (from the "Via" header) Chris@14: * if the proxy is trusted (see "setTrustedProxies()"), otherwise it returns Chris@14: * the latter (from the "SERVER_PROTOCOL" server parameter). Chris@14: * Chris@14: * @return string Chris@14: */ Chris@14: public function getProtocolVersion() Chris@14: { Chris@14: if ($this->isFromTrustedProxy()) { Chris@14: preg_match('~^(HTTP/)?([1-9]\.[0-9]) ~', $this->headers->get('Via'), $matches); Chris@14: Chris@14: if ($matches) { Chris@14: return 'HTTP/'.$matches[2]; Chris@14: } Chris@14: } Chris@14: Chris@14: return $this->server->get('SERVER_PROTOCOL'); Chris@14: } Chris@14: Chris@14: /** Chris@0: * Returns the request body content. Chris@0: * Chris@0: * @param bool $asResource If true, a resource will be returned Chris@0: * Chris@0: * @return string|resource The request body content or a resource to read the body stream Chris@0: * Chris@0: * @throws \LogicException Chris@0: */ Chris@0: public function getContent($asResource = false) Chris@0: { Chris@17: $currentContentIsResource = \is_resource($this->content); Chris@12: if (\PHP_VERSION_ID < 50600 && false === $this->content) { Chris@0: throw new \LogicException('getContent() can only be called once when using the resource return type and PHP below 5.6.'); Chris@0: } Chris@0: Chris@0: if (true === $asResource) { Chris@0: if ($currentContentIsResource) { Chris@0: rewind($this->content); Chris@0: Chris@0: return $this->content; Chris@0: } Chris@0: Chris@0: // Content passed in parameter (test) Chris@17: if (\is_string($this->content)) { Chris@0: $resource = fopen('php://temp', 'r+'); Chris@0: fwrite($resource, $this->content); Chris@0: rewind($resource); Chris@0: Chris@0: return $resource; Chris@0: } Chris@0: Chris@0: $this->content = false; Chris@0: Chris@0: return fopen('php://input', 'rb'); Chris@0: } Chris@0: Chris@0: if ($currentContentIsResource) { Chris@0: rewind($this->content); Chris@0: Chris@0: return stream_get_contents($this->content); Chris@0: } Chris@0: Chris@0: if (null === $this->content || false === $this->content) { Chris@0: $this->content = file_get_contents('php://input'); Chris@0: } Chris@0: Chris@0: return $this->content; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Gets the Etags. Chris@0: * Chris@0: * @return array The entity tags Chris@0: */ Chris@0: public function getETags() Chris@0: { Chris@0: return preg_split('/\s*,\s*/', $this->headers->get('if_none_match'), null, PREG_SPLIT_NO_EMPTY); Chris@0: } Chris@0: Chris@0: /** Chris@0: * @return bool Chris@0: */ Chris@0: public function isNoCache() Chris@0: { Chris@0: return $this->headers->hasCacheControlDirective('no-cache') || 'no-cache' == $this->headers->get('Pragma'); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Returns the preferred language. Chris@0: * Chris@0: * @param array $locales An array of ordered available locales Chris@0: * Chris@0: * @return string|null The preferred locale Chris@0: */ Chris@0: public function getPreferredLanguage(array $locales = null) Chris@0: { Chris@0: $preferredLanguages = $this->getLanguages(); Chris@0: Chris@0: if (empty($locales)) { Chris@0: return isset($preferredLanguages[0]) ? $preferredLanguages[0] : null; Chris@0: } Chris@0: Chris@0: if (!$preferredLanguages) { Chris@0: return $locales[0]; Chris@0: } Chris@0: Chris@17: $extendedPreferredLanguages = []; Chris@0: foreach ($preferredLanguages as $language) { Chris@0: $extendedPreferredLanguages[] = $language; Chris@0: if (false !== $position = strpos($language, '_')) { Chris@0: $superLanguage = substr($language, 0, $position); Chris@17: if (!\in_array($superLanguage, $preferredLanguages)) { Chris@0: $extendedPreferredLanguages[] = $superLanguage; Chris@0: } Chris@0: } Chris@0: } Chris@0: Chris@0: $preferredLanguages = array_values(array_intersect($extendedPreferredLanguages, $locales)); Chris@0: Chris@0: return isset($preferredLanguages[0]) ? $preferredLanguages[0] : $locales[0]; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Gets a list of languages acceptable by the client browser. Chris@0: * Chris@0: * @return array Languages ordered in the user browser preferences Chris@0: */ Chris@0: public function getLanguages() Chris@0: { Chris@0: if (null !== $this->languages) { Chris@0: return $this->languages; Chris@0: } Chris@0: Chris@0: $languages = AcceptHeader::fromString($this->headers->get('Accept-Language'))->all(); Chris@17: $this->languages = []; Chris@0: foreach ($languages as $lang => $acceptHeaderItem) { Chris@0: if (false !== strpos($lang, '-')) { Chris@0: $codes = explode('-', $lang); Chris@0: if ('i' === $codes[0]) { Chris@0: // Language not listed in ISO 639 that are not variants Chris@0: // of any listed language, which can be registered with the Chris@0: // i-prefix, such as i-cherokee Chris@17: if (\count($codes) > 1) { Chris@0: $lang = $codes[1]; Chris@0: } Chris@0: } else { Chris@17: for ($i = 0, $max = \count($codes); $i < $max; ++$i) { Chris@14: if (0 === $i) { Chris@0: $lang = strtolower($codes[0]); Chris@0: } else { Chris@0: $lang .= '_'.strtoupper($codes[$i]); Chris@0: } Chris@0: } Chris@0: } Chris@0: } Chris@0: Chris@0: $this->languages[] = $lang; Chris@0: } Chris@0: Chris@0: return $this->languages; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Gets a list of charsets acceptable by the client browser. Chris@0: * Chris@0: * @return array List of charsets in preferable order Chris@0: */ Chris@0: public function getCharsets() Chris@0: { Chris@0: if (null !== $this->charsets) { Chris@0: return $this->charsets; Chris@0: } Chris@0: Chris@0: return $this->charsets = array_keys(AcceptHeader::fromString($this->headers->get('Accept-Charset'))->all()); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Gets a list of encodings acceptable by the client browser. Chris@0: * Chris@0: * @return array List of encodings in preferable order Chris@0: */ Chris@0: public function getEncodings() Chris@0: { Chris@0: if (null !== $this->encodings) { Chris@0: return $this->encodings; Chris@0: } Chris@0: Chris@0: return $this->encodings = array_keys(AcceptHeader::fromString($this->headers->get('Accept-Encoding'))->all()); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Gets a list of content types acceptable by the client browser. Chris@0: * Chris@0: * @return array List of content types in preferable order Chris@0: */ Chris@0: public function getAcceptableContentTypes() Chris@0: { Chris@0: if (null !== $this->acceptableContentTypes) { Chris@0: return $this->acceptableContentTypes; Chris@0: } Chris@0: Chris@0: return $this->acceptableContentTypes = array_keys(AcceptHeader::fromString($this->headers->get('Accept'))->all()); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Returns true if the request is a XMLHttpRequest. Chris@0: * Chris@0: * It works if your JavaScript library sets an X-Requested-With HTTP header. Chris@0: * It is known to work with common JavaScript frameworks: Chris@0: * Chris@0: * @see http://en.wikipedia.org/wiki/List_of_Ajax_frameworks#JavaScript Chris@0: * Chris@0: * @return bool true if the request is an XMLHttpRequest, false otherwise Chris@0: */ Chris@0: public function isXmlHttpRequest() Chris@0: { Chris@0: return 'XMLHttpRequest' == $this->headers->get('X-Requested-With'); Chris@0: } Chris@0: Chris@0: /* Chris@0: * The following methods are derived from code of the Zend Framework (1.10dev - 2010-01-24) Chris@0: * Chris@0: * Code subject to the new BSD license (http://framework.zend.com/license/new-bsd). Chris@0: * Chris@0: * Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) Chris@0: */ Chris@0: Chris@0: protected function prepareRequestUri() Chris@0: { Chris@0: $requestUri = ''; Chris@0: Chris@17: if ('1' == $this->server->get('IIS_WasUrlRewritten') && '' != $this->server->get('UNENCODED_URL')) { Chris@0: // IIS7 with URL Rewrite: make sure we get the unencoded URL (double slash problem) Chris@0: $requestUri = $this->server->get('UNENCODED_URL'); Chris@0: $this->server->remove('UNENCODED_URL'); Chris@0: $this->server->remove('IIS_WasUrlRewritten'); Chris@0: } elseif ($this->server->has('REQUEST_URI')) { Chris@0: $requestUri = $this->server->get('REQUEST_URI'); Chris@17: Chris@17: if ('' !== $requestUri && '/' === $requestUri[0]) { Chris@17: // To only use path and query remove the fragment. Chris@17: if (false !== $pos = strpos($requestUri, '#')) { Chris@17: $requestUri = substr($requestUri, 0, $pos); Chris@17: } Chris@17: } else { Chris@17: // HTTP proxy reqs setup request URI with scheme and host [and port] + the URL path, Chris@17: // only use URL path. Chris@17: $uriComponents = parse_url($requestUri); Chris@17: Chris@17: if (isset($uriComponents['path'])) { Chris@17: $requestUri = $uriComponents['path']; Chris@17: } Chris@17: Chris@17: if (isset($uriComponents['query'])) { Chris@17: $requestUri .= '?'.$uriComponents['query']; Chris@17: } Chris@0: } Chris@0: } elseif ($this->server->has('ORIG_PATH_INFO')) { Chris@0: // IIS 5.0, PHP as CGI Chris@0: $requestUri = $this->server->get('ORIG_PATH_INFO'); Chris@0: if ('' != $this->server->get('QUERY_STRING')) { Chris@0: $requestUri .= '?'.$this->server->get('QUERY_STRING'); Chris@0: } Chris@0: $this->server->remove('ORIG_PATH_INFO'); Chris@0: } Chris@0: Chris@0: // normalize the request URI to ease creating sub-requests from this request Chris@0: $this->server->set('REQUEST_URI', $requestUri); Chris@0: Chris@0: return $requestUri; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Prepares the base URL. Chris@0: * Chris@0: * @return string Chris@0: */ Chris@0: protected function prepareBaseUrl() Chris@0: { Chris@0: $filename = basename($this->server->get('SCRIPT_FILENAME')); Chris@0: Chris@0: if (basename($this->server->get('SCRIPT_NAME')) === $filename) { Chris@0: $baseUrl = $this->server->get('SCRIPT_NAME'); Chris@0: } elseif (basename($this->server->get('PHP_SELF')) === $filename) { Chris@0: $baseUrl = $this->server->get('PHP_SELF'); Chris@0: } elseif (basename($this->server->get('ORIG_SCRIPT_NAME')) === $filename) { Chris@0: $baseUrl = $this->server->get('ORIG_SCRIPT_NAME'); // 1and1 shared hosting compatibility Chris@0: } else { Chris@0: // Backtrack up the script_filename to find the portion matching Chris@0: // php_self Chris@0: $path = $this->server->get('PHP_SELF', ''); Chris@0: $file = $this->server->get('SCRIPT_FILENAME', ''); Chris@0: $segs = explode('/', trim($file, '/')); Chris@0: $segs = array_reverse($segs); Chris@0: $index = 0; Chris@17: $last = \count($segs); Chris@0: $baseUrl = ''; Chris@0: do { Chris@0: $seg = $segs[$index]; Chris@0: $baseUrl = '/'.$seg.$baseUrl; Chris@0: ++$index; Chris@0: } while ($last > $index && (false !== $pos = strpos($path, $baseUrl)) && 0 != $pos); Chris@0: } Chris@0: Chris@0: // Does the baseUrl have anything in common with the request_uri? Chris@0: $requestUri = $this->getRequestUri(); Chris@14: if ('' !== $requestUri && '/' !== $requestUri[0]) { Chris@0: $requestUri = '/'.$requestUri; Chris@0: } Chris@0: Chris@0: if ($baseUrl && false !== $prefix = $this->getUrlencodedPrefix($requestUri, $baseUrl)) { Chris@0: // full $baseUrl matches Chris@0: return $prefix; Chris@0: } Chris@0: Chris@17: if ($baseUrl && false !== $prefix = $this->getUrlencodedPrefix($requestUri, rtrim(\dirname($baseUrl), '/'.\DIRECTORY_SEPARATOR).'/')) { Chris@0: // directory portion of $baseUrl matches Chris@17: return rtrim($prefix, '/'.\DIRECTORY_SEPARATOR); Chris@0: } Chris@0: Chris@0: $truncatedRequestUri = $requestUri; Chris@0: if (false !== $pos = strpos($requestUri, '?')) { Chris@0: $truncatedRequestUri = substr($requestUri, 0, $pos); Chris@0: } Chris@0: Chris@0: $basename = basename($baseUrl); Chris@0: if (empty($basename) || !strpos(rawurldecode($truncatedRequestUri), $basename)) { Chris@0: // no match whatsoever; set it blank Chris@0: return ''; Chris@0: } Chris@0: Chris@0: // If using mod_rewrite or ISAPI_Rewrite strip the script filename Chris@0: // out of baseUrl. $pos !== 0 makes sure it is not matching a value Chris@0: // from PATH_INFO or QUERY_STRING Chris@17: if (\strlen($requestUri) >= \strlen($baseUrl) && (false !== $pos = strpos($requestUri, $baseUrl)) && 0 !== $pos) { Chris@17: $baseUrl = substr($requestUri, 0, $pos + \strlen($baseUrl)); Chris@0: } Chris@0: Chris@17: return rtrim($baseUrl, '/'.\DIRECTORY_SEPARATOR); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Prepares the base path. Chris@0: * Chris@0: * @return string base path Chris@0: */ Chris@0: protected function prepareBasePath() Chris@0: { Chris@0: $baseUrl = $this->getBaseUrl(); Chris@0: if (empty($baseUrl)) { Chris@0: return ''; Chris@0: } Chris@0: Chris@14: $filename = basename($this->server->get('SCRIPT_FILENAME')); Chris@0: if (basename($baseUrl) === $filename) { Chris@17: $basePath = \dirname($baseUrl); Chris@0: } else { Chris@0: $basePath = $baseUrl; Chris@0: } Chris@0: Chris@17: if ('\\' === \DIRECTORY_SEPARATOR) { Chris@0: $basePath = str_replace('\\', '/', $basePath); Chris@0: } Chris@0: Chris@0: return rtrim($basePath, '/'); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Prepares the path info. Chris@0: * Chris@0: * @return string path info Chris@0: */ Chris@0: protected function preparePathInfo() Chris@0: { Chris@0: if (null === ($requestUri = $this->getRequestUri())) { Chris@0: return '/'; Chris@0: } Chris@0: Chris@0: // Remove the query string from REQUEST_URI Chris@0: if (false !== $pos = strpos($requestUri, '?')) { Chris@0: $requestUri = substr($requestUri, 0, $pos); Chris@0: } Chris@14: if ('' !== $requestUri && '/' !== $requestUri[0]) { Chris@0: $requestUri = '/'.$requestUri; Chris@0: } Chris@0: Chris@14: if (null === ($baseUrl = $this->getBaseUrl())) { Chris@14: return $requestUri; Chris@14: } Chris@14: Chris@17: $pathInfo = substr($requestUri, \strlen($baseUrl)); Chris@14: if (false === $pathInfo || '' === $pathInfo) { Chris@0: // If substr() returns false then PATH_INFO is set to an empty string Chris@0: return '/'; Chris@0: } Chris@0: Chris@0: return (string) $pathInfo; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Initializes HTTP request formats. Chris@0: */ Chris@0: protected static function initializeFormats() Chris@0: { Chris@17: static::$formats = [ Chris@17: 'html' => ['text/html', 'application/xhtml+xml'], Chris@17: 'txt' => ['text/plain'], Chris@17: 'js' => ['application/javascript', 'application/x-javascript', 'text/javascript'], Chris@17: 'css' => ['text/css'], Chris@17: 'json' => ['application/json', 'application/x-json'], Chris@17: 'jsonld' => ['application/ld+json'], Chris@17: 'xml' => ['text/xml', 'application/xml', 'application/x-xml'], Chris@17: 'rdf' => ['application/rdf+xml'], Chris@17: 'atom' => ['application/atom+xml'], Chris@17: 'rss' => ['application/rss+xml'], Chris@17: 'form' => ['application/x-www-form-urlencoded'], Chris@17: ]; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Sets the default PHP locale. Chris@0: * Chris@0: * @param string $locale Chris@0: */ Chris@0: private function setPhpDefaultLocale($locale) Chris@0: { Chris@0: // if either the class Locale doesn't exist, or an exception is thrown when Chris@0: // setting the default locale, the intl module is not installed, and Chris@0: // the call can be ignored: Chris@0: try { Chris@0: if (class_exists('Locale', false)) { Chris@0: \Locale::setDefault($locale); Chris@0: } Chris@0: } catch (\Exception $e) { Chris@0: } Chris@0: } Chris@0: Chris@0: /* Chris@0: * Returns the prefix as encoded in the string when the string starts with Chris@0: * the given prefix, false otherwise. Chris@0: * Chris@0: * @param string $string The urlencoded string Chris@0: * @param string $prefix The prefix not encoded Chris@0: * Chris@0: * @return string|false The prefix as it is encoded in $string, or false Chris@0: */ Chris@0: private function getUrlencodedPrefix($string, $prefix) Chris@0: { Chris@0: if (0 !== strpos(rawurldecode($string), $prefix)) { Chris@0: return false; Chris@0: } Chris@0: Chris@17: $len = \strlen($prefix); Chris@0: Chris@0: if (preg_match(sprintf('#^(%%[[:xdigit:]]{2}|.){%d}#', $len), $string, $match)) { Chris@0: return $match[0]; Chris@0: } Chris@0: Chris@0: return false; Chris@0: } Chris@0: Chris@17: private static function createRequestFromFactory(array $query = [], array $request = [], array $attributes = [], array $cookies = [], array $files = [], array $server = [], $content = null) Chris@0: { Chris@0: if (self::$requestFactory) { Chris@17: $request = \call_user_func(self::$requestFactory, $query, $request, $attributes, $cookies, $files, $server, $content); Chris@0: Chris@0: if (!$request instanceof self) { Chris@0: throw new \LogicException('The Request factory must return an instance of Symfony\Component\HttpFoundation\Request.'); Chris@0: } Chris@0: Chris@0: return $request; Chris@0: } Chris@0: Chris@0: return new static($query, $request, $attributes, $cookies, $files, $server, $content); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Indicates whether this request originated from a trusted proxy. Chris@0: * Chris@0: * This can be useful to determine whether or not to trust the Chris@0: * contents of a proxy-specific header. Chris@0: * Chris@0: * @return bool true if the request came from a trusted proxy, false otherwise Chris@0: */ Chris@0: public function isFromTrustedProxy() Chris@0: { Chris@0: return self::$trustedProxies && IpUtils::checkIp($this->server->get('REMOTE_ADDR'), self::$trustedProxies); Chris@0: } Chris@0: Chris@0: private function getTrustedValues($type, $ip = null) Chris@0: { Chris@17: $clientValues = []; Chris@17: $forwardedValues = []; Chris@0: Chris@0: if (self::$trustedHeaders[$type] && $this->headers->has(self::$trustedHeaders[$type])) { Chris@0: foreach (explode(',', $this->headers->get(self::$trustedHeaders[$type])) as $v) { Chris@0: $clientValues[] = (self::HEADER_CLIENT_PORT === $type ? '0.0.0.0:' : '').trim($v); Chris@0: } Chris@0: } Chris@0: Chris@0: if (self::$trustedHeaders[self::HEADER_FORWARDED] && $this->headers->has(self::$trustedHeaders[self::HEADER_FORWARDED])) { Chris@0: $forwardedValues = $this->headers->get(self::$trustedHeaders[self::HEADER_FORWARDED]); Chris@17: $forwardedValues = preg_match_all(sprintf('{(?:%s)="?([a-zA-Z0-9\.:_\-/\[\]]*+)}', self::$forwardedParams[$type]), $forwardedValues, $matches) ? $matches[1] : []; Chris@17: if (self::HEADER_CLIENT_PORT === $type) { Chris@17: foreach ($forwardedValues as $k => $v) { Chris@17: if (']' === substr($v, -1) || false === $v = strrchr($v, ':')) { Chris@17: $v = $this->isSecure() ? ':443' : ':80'; Chris@17: } Chris@17: $forwardedValues[$k] = '0.0.0.0'.$v; Chris@17: } Chris@17: } Chris@0: } Chris@0: Chris@0: if (null !== $ip) { Chris@0: $clientValues = $this->normalizeAndFilterClientIps($clientValues, $ip); Chris@0: $forwardedValues = $this->normalizeAndFilterClientIps($forwardedValues, $ip); Chris@0: } Chris@0: Chris@0: if ($forwardedValues === $clientValues || !$clientValues) { Chris@0: return $forwardedValues; Chris@0: } Chris@0: Chris@0: if (!$forwardedValues) { Chris@0: return $clientValues; Chris@0: } Chris@0: Chris@0: if (!$this->isForwardedValid) { Chris@17: return null !== $ip ? ['0.0.0.0', $ip] : []; Chris@0: } Chris@0: $this->isForwardedValid = false; Chris@0: Chris@0: 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])); Chris@0: } Chris@0: Chris@0: private function normalizeAndFilterClientIps(array $clientIps, $ip) Chris@0: { Chris@0: if (!$clientIps) { Chris@17: return []; Chris@0: } Chris@0: $clientIps[] = $ip; // Complete the IP chain with the IP the request actually came from Chris@0: $firstTrustedIp = null; Chris@0: Chris@0: foreach ($clientIps as $key => $clientIp) { Chris@17: if (strpos($clientIp, '.')) { Chris@17: // Strip :port from IPv4 addresses. This is allowed in Forwarded Chris@17: // and may occur in X-Forwarded-For. Chris@17: $i = strpos($clientIp, ':'); Chris@17: if ($i) { Chris@17: $clientIps[$key] = $clientIp = substr($clientIp, 0, $i); Chris@17: } Chris@17: } elseif (0 === strpos($clientIp, '[')) { Chris@17: // Strip brackets and :port from IPv6 addresses. Chris@17: $i = strpos($clientIp, ']', 1); Chris@17: $clientIps[$key] = $clientIp = substr($clientIp, 1, $i - 1); Chris@0: } Chris@0: Chris@0: if (!filter_var($clientIp, FILTER_VALIDATE_IP)) { Chris@0: unset($clientIps[$key]); Chris@0: Chris@0: continue; Chris@0: } Chris@0: Chris@0: if (IpUtils::checkIp($clientIp, self::$trustedProxies)) { Chris@0: unset($clientIps[$key]); Chris@0: Chris@0: // Fallback to this when the client IP falls into the range of trusted proxies Chris@0: if (null === $firstTrustedIp) { Chris@0: $firstTrustedIp = $clientIp; Chris@0: } Chris@0: } Chris@0: } Chris@0: Chris@0: // Now the IP chain contains only untrusted proxies and the client IP Chris@17: return $clientIps ? array_reverse($clientIps) : [$firstTrustedIp]; Chris@0: } Chris@0: }