Request.php 67 KB

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