Request.php 68 KB

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