Request.php 63 KB

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