Request.php 64 KB

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