Request.php 68 KB

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