Request.php 70 KB

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