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