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

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