Request.php 67 KB

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