Request.php 76 KB

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