Request.php 67 KB

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