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