Request.php 66 KB

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