Request.php 76 KB

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