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

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