Request.php 60 KB

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