Request.php 64 KB

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