Request.php 63 KB

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