Request.php 64 KB

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