Request.php 68 KB

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