Drupal investigation

Request.php 63KB

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