Request.php 61 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939
  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) {
  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. continue;
  735. }
  736. if (IpUtils::checkIp($clientIp, self::$trustedProxies)) {
  737. unset($clientIps[$key]);
  738. // Fallback to this when the client IP falls into the range of trusted proxies
  739. if (null === $firstTrustedIp) {
  740. $firstTrustedIp = $clientIp;
  741. }
  742. }
  743. }
  744. // Now the IP chain contains only untrusted proxies and the client IP
  745. return $clientIps ? array_reverse($clientIps) : array($firstTrustedIp);
  746. }
  747. /**
  748. * Returns the client IP address.
  749. *
  750. * This method can read the client IP address from the "X-Forwarded-For" header
  751. * when trusted proxies were set via "setTrustedProxies()". The "X-Forwarded-For"
  752. * header value is a comma+space separated list of IP addresses, the left-most
  753. * being the original client, and each successive proxy that passed the request
  754. * adding the IP address where it received the request from.
  755. *
  756. * If your reverse proxy uses a different header name than "X-Forwarded-For",
  757. * ("Client-Ip" for instance), configure it via "setTrustedHeaderName()" with
  758. * the "client-ip" key.
  759. *
  760. * @return string The client IP address
  761. *
  762. * @see getClientIps()
  763. * @see http://en.wikipedia.org/wiki/X-Forwarded-For
  764. */
  765. public function getClientIp()
  766. {
  767. $ipAddresses = $this->getClientIps();
  768. return $ipAddresses[0];
  769. }
  770. /**
  771. * Returns current script name.
  772. *
  773. * @return string
  774. */
  775. public function getScriptName()
  776. {
  777. return $this->server->get('SCRIPT_NAME', $this->server->get('ORIG_SCRIPT_NAME', ''));
  778. }
  779. /**
  780. * Returns the path being requested relative to the executed script.
  781. *
  782. * The path info always starts with a /.
  783. *
  784. * Suppose this request is instantiated from /mysite on localhost:
  785. *
  786. * * http://localhost/mysite returns an empty string
  787. * * http://localhost/mysite/about returns '/about'
  788. * * http://localhost/mysite/enco%20ded returns '/enco%20ded'
  789. * * http://localhost/mysite/about?var=1 returns '/about'
  790. *
  791. * @return string The raw path (i.e. not urldecoded)
  792. */
  793. public function getPathInfo()
  794. {
  795. if (null === $this->pathInfo) {
  796. $this->pathInfo = $this->preparePathInfo();
  797. }
  798. return $this->pathInfo;
  799. }
  800. /**
  801. * Returns the root path from which this request is executed.
  802. *
  803. * Suppose that an index.php file instantiates this request object:
  804. *
  805. * * http://localhost/index.php returns an empty string
  806. * * http://localhost/index.php/page returns an empty string
  807. * * http://localhost/web/index.php returns '/web'
  808. * * http://localhost/we%20b/index.php returns '/we%20b'
  809. *
  810. * @return string The raw path (i.e. not urldecoded)
  811. */
  812. public function getBasePath()
  813. {
  814. if (null === $this->basePath) {
  815. $this->basePath = $this->prepareBasePath();
  816. }
  817. return $this->basePath;
  818. }
  819. /**
  820. * Returns the root URL from which this request is executed.
  821. *
  822. * The base URL never ends with a /.
  823. *
  824. * This is similar to getBasePath(), except that it also includes the
  825. * script filename (e.g. index.php) if one exists.
  826. *
  827. * @return string The raw URL (i.e. not urldecoded)
  828. */
  829. public function getBaseUrl()
  830. {
  831. if (null === $this->baseUrl) {
  832. $this->baseUrl = $this->prepareBaseUrl();
  833. }
  834. return $this->baseUrl;
  835. }
  836. /**
  837. * Gets the request's scheme.
  838. *
  839. * @return string
  840. */
  841. public function getScheme()
  842. {
  843. return $this->isSecure() ? 'https' : 'http';
  844. }
  845. /**
  846. * Returns the port on which the request is made.
  847. *
  848. * This method can read the client port from the "X-Forwarded-Port" header
  849. * when trusted proxies were set via "setTrustedProxies()".
  850. *
  851. * The "X-Forwarded-Port" header must contain the client port.
  852. *
  853. * If your reverse proxy uses a different header name than "X-Forwarded-Port",
  854. * configure it via "setTrustedHeaderName()" with the "client-port" key.
  855. *
  856. * @return string
  857. */
  858. public function getPort()
  859. {
  860. if ($this->isFromTrustedProxy()) {
  861. if (self::$trustedHeaders[self::HEADER_CLIENT_PORT] && $port = $this->headers->get(self::$trustedHeaders[self::HEADER_CLIENT_PORT])) {
  862. return $port;
  863. }
  864. if (self::$trustedHeaders[self::HEADER_CLIENT_PROTO] && 'https' === $this->headers->get(self::$trustedHeaders[self::HEADER_CLIENT_PROTO], 'http')) {
  865. return 443;
  866. }
  867. }
  868. if ($host = $this->headers->get('HOST')) {
  869. if ($host[0] === '[') {
  870. $pos = strpos($host, ':', strrpos($host, ']'));
  871. } else {
  872. $pos = strrpos($host, ':');
  873. }
  874. if (false !== $pos) {
  875. return (int) substr($host, $pos + 1);
  876. }
  877. return 'https' === $this->getScheme() ? 443 : 80;
  878. }
  879. return $this->server->get('SERVER_PORT');
  880. }
  881. /**
  882. * Returns the user.
  883. *
  884. * @return string|null
  885. */
  886. public function getUser()
  887. {
  888. return $this->headers->get('PHP_AUTH_USER');
  889. }
  890. /**
  891. * Returns the password.
  892. *
  893. * @return string|null
  894. */
  895. public function getPassword()
  896. {
  897. return $this->headers->get('PHP_AUTH_PW');
  898. }
  899. /**
  900. * Gets the user info.
  901. *
  902. * @return string A user name and, optionally, scheme-specific information about how to gain authorization to access the server
  903. */
  904. public function getUserInfo()
  905. {
  906. $userinfo = $this->getUser();
  907. $pass = $this->getPassword();
  908. if ('' != $pass) {
  909. $userinfo .= ":$pass";
  910. }
  911. return $userinfo;
  912. }
  913. /**
  914. * Returns the HTTP host being requested.
  915. *
  916. * The port name will be appended to the host if it's non-standard.
  917. *
  918. * @return string
  919. */
  920. public function getHttpHost()
  921. {
  922. $scheme = $this->getScheme();
  923. $port = $this->getPort();
  924. if (('http' == $scheme && $port == 80) || ('https' == $scheme && $port == 443)) {
  925. return $this->getHost();
  926. }
  927. return $this->getHost().':'.$port;
  928. }
  929. /**
  930. * Returns the requested URI (path and query string).
  931. *
  932. * @return string The raw URI (i.e. not URI decoded)
  933. */
  934. public function getRequestUri()
  935. {
  936. if (null === $this->requestUri) {
  937. $this->requestUri = $this->prepareRequestUri();
  938. }
  939. return $this->requestUri;
  940. }
  941. /**
  942. * Gets the scheme and HTTP host.
  943. *
  944. * If the URL was called with basic authentication, the user
  945. * and the password are not added to the generated string.
  946. *
  947. * @return string The scheme and HTTP host
  948. */
  949. public function getSchemeAndHttpHost()
  950. {
  951. return $this->getScheme().'://'.$this->getHttpHost();
  952. }
  953. /**
  954. * Generates a normalized URI (URL) for the Request.
  955. *
  956. * @return string A normalized URI (URL) for the Request
  957. *
  958. * @see getQueryString()
  959. */
  960. public function getUri()
  961. {
  962. if (null !== $qs = $this->getQueryString()) {
  963. $qs = '?'.$qs;
  964. }
  965. return $this->getSchemeAndHttpHost().$this->getBaseUrl().$this->getPathInfo().$qs;
  966. }
  967. /**
  968. * Generates a normalized URI for the given path.
  969. *
  970. * @param string $path A path to use instead of the current one
  971. *
  972. * @return string The normalized URI for the path
  973. */
  974. public function getUriForPath($path)
  975. {
  976. return $this->getSchemeAndHttpHost().$this->getBaseUrl().$path;
  977. }
  978. /**
  979. * Returns the path as relative reference from the current Request path.
  980. *
  981. * Only the URIs path component (no schema, host etc.) is relevant and must be given.
  982. * Both paths must be absolute and not contain relative parts.
  983. * Relative URLs from one resource to another are useful when generating self-contained downloadable document archives.
  984. * Furthermore, they can be used to reduce the link size in documents.
  985. *
  986. * Example target paths, given a base path of "/a/b/c/d":
  987. * - "/a/b/c/d" -> ""
  988. * - "/a/b/c/" -> "./"
  989. * - "/a/b/" -> "../"
  990. * - "/a/b/c/other" -> "other"
  991. * - "/a/x/y" -> "../../x/y"
  992. *
  993. * @param string $path The target path
  994. *
  995. * @return string The relative target path
  996. */
  997. public function getRelativeUriForPath($path)
  998. {
  999. // be sure that we are dealing with an absolute path
  1000. if (!isset($path[0]) || '/' !== $path[0]) {
  1001. return $path;
  1002. }
  1003. if ($path === $basePath = $this->getPathInfo()) {
  1004. return '';
  1005. }
  1006. $sourceDirs = explode('/', isset($basePath[0]) && '/' === $basePath[0] ? substr($basePath, 1) : $basePath);
  1007. $targetDirs = explode('/', isset($path[0]) && '/' === $path[0] ? substr($path, 1) : $path);
  1008. array_pop($sourceDirs);
  1009. $targetFile = array_pop($targetDirs);
  1010. foreach ($sourceDirs as $i => $dir) {
  1011. if (isset($targetDirs[$i]) && $dir === $targetDirs[$i]) {
  1012. unset($sourceDirs[$i], $targetDirs[$i]);
  1013. } else {
  1014. break;
  1015. }
  1016. }
  1017. $targetDirs[] = $targetFile;
  1018. $path = str_repeat('../', count($sourceDirs)).implode('/', $targetDirs);
  1019. // A reference to the same base directory or an empty subdirectory must be prefixed with "./".
  1020. // This also applies to a segment with a colon character (e.g., "file:colon") that cannot be used
  1021. // as the first segment of a relative-path reference, as it would be mistaken for a scheme name
  1022. // (see http://tools.ietf.org/html/rfc3986#section-4.2).
  1023. return !isset($path[0]) || '/' === $path[0]
  1024. || false !== ($colonPos = strpos($path, ':')) && ($colonPos < ($slashPos = strpos($path, '/')) || false === $slashPos)
  1025. ? "./$path" : $path;
  1026. }
  1027. /**
  1028. * Generates the normalized query string for the Request.
  1029. *
  1030. * It builds a normalized query string, where keys/value pairs are alphabetized
  1031. * and have consistent escaping.
  1032. *
  1033. * @return string|null A normalized query string for the Request
  1034. */
  1035. public function getQueryString()
  1036. {
  1037. $qs = static::normalizeQueryString($this->server->get('QUERY_STRING'));
  1038. return '' === $qs ? null : $qs;
  1039. }
  1040. /**
  1041. * Checks whether the request is secure or not.
  1042. *
  1043. * This method can read the client protocol from the "X-Forwarded-Proto" header
  1044. * when trusted proxies were set via "setTrustedProxies()".
  1045. *
  1046. * The "X-Forwarded-Proto" header must contain the protocol: "https" or "http".
  1047. *
  1048. * If your reverse proxy uses a different header name than "X-Forwarded-Proto"
  1049. * ("SSL_HTTPS" for instance), configure it via "setTrustedHeaderName()" with
  1050. * the "client-proto" key.
  1051. *
  1052. * @return bool
  1053. */
  1054. public function isSecure()
  1055. {
  1056. if ($this->isFromTrustedProxy() && self::$trustedHeaders[self::HEADER_CLIENT_PROTO] && $proto = $this->headers->get(self::$trustedHeaders[self::HEADER_CLIENT_PROTO])) {
  1057. return in_array(strtolower(current(explode(',', $proto))), array('https', 'on', 'ssl', '1'));
  1058. }
  1059. $https = $this->server->get('HTTPS');
  1060. return !empty($https) && 'off' !== strtolower($https);
  1061. }
  1062. /**
  1063. * Returns the host name.
  1064. *
  1065. * This method can read the client host name from the "X-Forwarded-Host" header
  1066. * when trusted proxies were set via "setTrustedProxies()".
  1067. *
  1068. * The "X-Forwarded-Host" header must contain the client host name.
  1069. *
  1070. * If your reverse proxy uses a different header name than "X-Forwarded-Host",
  1071. * configure it via "setTrustedHeaderName()" with the "client-host" key.
  1072. *
  1073. * @return string
  1074. *
  1075. * @throws \UnexpectedValueException when the host name is invalid
  1076. */
  1077. public function getHost()
  1078. {
  1079. if ($this->isFromTrustedProxy() && self::$trustedHeaders[self::HEADER_CLIENT_HOST] && $host = $this->headers->get(self::$trustedHeaders[self::HEADER_CLIENT_HOST])) {
  1080. $elements = explode(',', $host);
  1081. $host = $elements[count($elements) - 1];
  1082. } elseif (!$host = $this->headers->get('HOST')) {
  1083. if (!$host = $this->server->get('SERVER_NAME')) {
  1084. $host = $this->server->get('SERVER_ADDR', '');
  1085. }
  1086. }
  1087. // trim and remove port number from host
  1088. // host is lowercase as per RFC 952/2181
  1089. $host = strtolower(preg_replace('/:\d+$/', '', trim($host)));
  1090. // as the host can come from the user (HTTP_HOST and depending on the configuration, SERVER_NAME too can come from the user)
  1091. // check that it does not contain forbidden characters (see RFC 952 and RFC 2181)
  1092. // use preg_replace() instead of preg_match() to prevent DoS attacks with long host names
  1093. if ($host && '' !== preg_replace('/(?:^\[)?[a-zA-Z0-9-:\]_]+\.?/', '', $host)) {
  1094. throw new \UnexpectedValueException(sprintf('Invalid Host "%s"', $host));
  1095. }
  1096. if (count(self::$trustedHostPatterns) > 0) {
  1097. // to avoid host header injection attacks, you should provide a list of trusted host patterns
  1098. if (in_array($host, self::$trustedHosts)) {
  1099. return $host;
  1100. }
  1101. foreach (self::$trustedHostPatterns as $pattern) {
  1102. if (preg_match($pattern, $host)) {
  1103. self::$trustedHosts[] = $host;
  1104. return $host;
  1105. }
  1106. }
  1107. throw new \UnexpectedValueException(sprintf('Untrusted Host "%s"', $host));
  1108. }
  1109. return $host;
  1110. }
  1111. /**
  1112. * Sets the request method.
  1113. *
  1114. * @param string $method
  1115. */
  1116. public function setMethod($method)
  1117. {
  1118. $this->method = null;
  1119. $this->server->set('REQUEST_METHOD', $method);
  1120. }
  1121. /**
  1122. * Gets the request "intended" method.
  1123. *
  1124. * If the X-HTTP-Method-Override header is set, and if the method is a POST,
  1125. * then it is used to determine the "real" intended HTTP method.
  1126. *
  1127. * The _method request parameter can also be used to determine the HTTP method,
  1128. * but only if enableHttpMethodParameterOverride() has been called.
  1129. *
  1130. * The method is always an uppercased string.
  1131. *
  1132. * @return string The request method
  1133. *
  1134. * @see getRealMethod()
  1135. */
  1136. public function getMethod()
  1137. {
  1138. if (null === $this->method) {
  1139. $this->method = strtoupper($this->server->get('REQUEST_METHOD', 'GET'));
  1140. if ('POST' === $this->method) {
  1141. if ($method = $this->headers->get('X-HTTP-METHOD-OVERRIDE')) {
  1142. $this->method = strtoupper($method);
  1143. } elseif (self::$httpMethodParameterOverride) {
  1144. $this->method = strtoupper($this->request->get('_method', $this->query->get('_method', 'POST')));
  1145. }
  1146. }
  1147. }
  1148. return $this->method;
  1149. }
  1150. /**
  1151. * Gets the "real" request method.
  1152. *
  1153. * @return string The request method
  1154. *
  1155. * @see getMethod()
  1156. */
  1157. public function getRealMethod()
  1158. {
  1159. return strtoupper($this->server->get('REQUEST_METHOD', 'GET'));
  1160. }
  1161. /**
  1162. * Gets the mime type associated with the format.
  1163. *
  1164. * @param string $format The format
  1165. *
  1166. * @return string The associated mime type (null if not found)
  1167. */
  1168. public function getMimeType($format)
  1169. {
  1170. if (null === static::$formats) {
  1171. static::initializeFormats();
  1172. }
  1173. return isset(static::$formats[$format]) ? static::$formats[$format][0] : null;
  1174. }
  1175. /**
  1176. * Gets the format associated with the mime type.
  1177. *
  1178. * @param string $mimeType The associated mime type
  1179. *
  1180. * @return string|null The format (null if not found)
  1181. */
  1182. public function getFormat($mimeType)
  1183. {
  1184. $canonicalMimeType = null;
  1185. if (false !== $pos = strpos($mimeType, ';')) {
  1186. $canonicalMimeType = substr($mimeType, 0, $pos);
  1187. }
  1188. if (null === static::$formats) {
  1189. static::initializeFormats();
  1190. }
  1191. foreach (static::$formats as $format => $mimeTypes) {
  1192. if (in_array($mimeType, (array) $mimeTypes)) {
  1193. return $format;
  1194. }
  1195. if (null !== $canonicalMimeType && in_array($canonicalMimeType, (array) $mimeTypes)) {
  1196. return $format;
  1197. }
  1198. }
  1199. }
  1200. /**
  1201. * Associates a format with mime types.
  1202. *
  1203. * @param string $format The format
  1204. * @param string|array $mimeTypes The associated mime types (the preferred one must be the first as it will be used as the content type)
  1205. */
  1206. public function setFormat($format, $mimeTypes)
  1207. {
  1208. if (null === static::$formats) {
  1209. static::initializeFormats();
  1210. }
  1211. static::$formats[$format] = is_array($mimeTypes) ? $mimeTypes : array($mimeTypes);
  1212. }
  1213. /**
  1214. * Gets the request format.
  1215. *
  1216. * Here is the process to determine the format:
  1217. *
  1218. * * format defined by the user (with setRequestFormat())
  1219. * * _format request parameter
  1220. * * $default
  1221. *
  1222. * @param string $default The default format
  1223. *
  1224. * @return string The request format
  1225. */
  1226. public function getRequestFormat($default = 'html')
  1227. {
  1228. if (null === $this->format) {
  1229. $this->format = $this->get('_format', $default);
  1230. }
  1231. return $this->format;
  1232. }
  1233. /**
  1234. * Sets the request format.
  1235. *
  1236. * @param string $format The request format.
  1237. */
  1238. public function setRequestFormat($format)
  1239. {
  1240. $this->format = $format;
  1241. }
  1242. /**
  1243. * Gets the format associated with the request.
  1244. *
  1245. * @return string|null The format (null if no content type is present)
  1246. */
  1247. public function getContentType()
  1248. {
  1249. return $this->getFormat($this->headers->get('CONTENT_TYPE'));
  1250. }
  1251. /**
  1252. * Sets the default locale.
  1253. *
  1254. * @param string $locale
  1255. */
  1256. public function setDefaultLocale($locale)
  1257. {
  1258. $this->defaultLocale = $locale;
  1259. if (null === $this->locale) {
  1260. $this->setPhpDefaultLocale($locale);
  1261. }
  1262. }
  1263. /**
  1264. * Get the default locale.
  1265. *
  1266. * @return string
  1267. */
  1268. public function getDefaultLocale()
  1269. {
  1270. return $this->defaultLocale;
  1271. }
  1272. /**
  1273. * Sets the locale.
  1274. *
  1275. * @param string $locale
  1276. */
  1277. public function setLocale($locale)
  1278. {
  1279. $this->setPhpDefaultLocale($this->locale = $locale);
  1280. }
  1281. /**
  1282. * Get the locale.
  1283. *
  1284. * @return string
  1285. */
  1286. public function getLocale()
  1287. {
  1288. return null === $this->locale ? $this->defaultLocale : $this->locale;
  1289. }
  1290. /**
  1291. * Checks if the request method is of specified type.
  1292. *
  1293. * @param string $method Uppercase request method (GET, POST etc).
  1294. *
  1295. * @return bool
  1296. */
  1297. public function isMethod($method)
  1298. {
  1299. return $this->getMethod() === strtoupper($method);
  1300. }
  1301. /**
  1302. * Checks whether the method is safe or not.
  1303. *
  1304. * @return bool
  1305. */
  1306. public function isMethodSafe()
  1307. {
  1308. return in_array($this->getMethod(), array('GET', 'HEAD'));
  1309. }
  1310. /**
  1311. * Returns the request body content.
  1312. *
  1313. * @param bool $asResource If true, a resource will be returned
  1314. *
  1315. * @return string|resource The request body content or a resource to read the body stream.
  1316. *
  1317. * @throws \LogicException
  1318. */
  1319. public function getContent($asResource = false)
  1320. {
  1321. $currentContentIsResource = is_resource($this->content);
  1322. if (PHP_VERSION_ID < 50600 && false === $this->content) {
  1323. throw new \LogicException('getContent() can only be called once when using the resource return type and PHP below 5.6.');
  1324. }
  1325. if (true === $asResource) {
  1326. if ($currentContentIsResource) {
  1327. rewind($this->content);
  1328. return $this->content;
  1329. }
  1330. // Content passed in parameter (test)
  1331. if (is_string($this->content)) {
  1332. $resource = fopen('php://temp', 'r+');
  1333. fwrite($resource, $this->content);
  1334. rewind($resource);
  1335. return $resource;
  1336. }
  1337. $this->content = false;
  1338. return fopen('php://input', 'rb');
  1339. }
  1340. if ($currentContentIsResource) {
  1341. rewind($this->content);
  1342. return stream_get_contents($this->content);
  1343. }
  1344. if (null === $this->content) {
  1345. $this->content = file_get_contents('php://input');
  1346. }
  1347. return $this->content;
  1348. }
  1349. /**
  1350. * Gets the Etags.
  1351. *
  1352. * @return array The entity tags
  1353. */
  1354. public function getETags()
  1355. {
  1356. return preg_split('/\s*,\s*/', $this->headers->get('if_none_match'), null, PREG_SPLIT_NO_EMPTY);
  1357. }
  1358. /**
  1359. * @return bool
  1360. */
  1361. public function isNoCache()
  1362. {
  1363. return $this->headers->hasCacheControlDirective('no-cache') || 'no-cache' == $this->headers->get('Pragma');
  1364. }
  1365. /**
  1366. * Returns the preferred language.
  1367. *
  1368. * @param array $locales An array of ordered available locales
  1369. *
  1370. * @return string|null The preferred locale
  1371. */
  1372. public function getPreferredLanguage(array $locales = null)
  1373. {
  1374. $preferredLanguages = $this->getLanguages();
  1375. if (empty($locales)) {
  1376. return isset($preferredLanguages[0]) ? $preferredLanguages[0] : null;
  1377. }
  1378. if (!$preferredLanguages) {
  1379. return $locales[0];
  1380. }
  1381. $extendedPreferredLanguages = array();
  1382. foreach ($preferredLanguages as $language) {
  1383. $extendedPreferredLanguages[] = $language;
  1384. if (false !== $position = strpos($language, '_')) {
  1385. $superLanguage = substr($language, 0, $position);
  1386. if (!in_array($superLanguage, $preferredLanguages)) {
  1387. $extendedPreferredLanguages[] = $superLanguage;
  1388. }
  1389. }
  1390. }
  1391. $preferredLanguages = array_values(array_intersect($extendedPreferredLanguages, $locales));
  1392. return isset($preferredLanguages[0]) ? $preferredLanguages[0] : $locales[0];
  1393. }
  1394. /**
  1395. * Gets a list of languages acceptable by the client browser.
  1396. *
  1397. * @return array Languages ordered in the user browser preferences
  1398. */
  1399. public function getLanguages()
  1400. {
  1401. if (null !== $this->languages) {
  1402. return $this->languages;
  1403. }
  1404. $languages = AcceptHeader::fromString($this->headers->get('Accept-Language'))->all();
  1405. $this->languages = array();
  1406. foreach ($languages as $lang => $acceptHeaderItem) {
  1407. if (false !== strpos($lang, '-')) {
  1408. $codes = explode('-', $lang);
  1409. if ('i' === $codes[0]) {
  1410. // Language not listed in ISO 639 that are not variants
  1411. // of any listed language, which can be registered with the
  1412. // i-prefix, such as i-cherokee
  1413. if (count($codes) > 1) {
  1414. $lang = $codes[1];
  1415. }
  1416. } else {
  1417. for ($i = 0, $max = count($codes); $i < $max; ++$i) {
  1418. if ($i === 0) {
  1419. $lang = strtolower($codes[0]);
  1420. } else {
  1421. $lang .= '_'.strtoupper($codes[$i]);
  1422. }
  1423. }
  1424. }
  1425. }
  1426. $this->languages[] = $lang;
  1427. }
  1428. return $this->languages;
  1429. }
  1430. /**
  1431. * Gets a list of charsets acceptable by the client browser.
  1432. *
  1433. * @return array List of charsets in preferable order
  1434. */
  1435. public function getCharsets()
  1436. {
  1437. if (null !== $this->charsets) {
  1438. return $this->charsets;
  1439. }
  1440. return $this->charsets = array_keys(AcceptHeader::fromString($this->headers->get('Accept-Charset'))->all());
  1441. }
  1442. /**
  1443. * Gets a list of encodings acceptable by the client browser.
  1444. *
  1445. * @return array List of encodings in preferable order
  1446. */
  1447. public function getEncodings()
  1448. {
  1449. if (null !== $this->encodings) {
  1450. return $this->encodings;
  1451. }
  1452. return $this->encodings = array_keys(AcceptHeader::fromString($this->headers->get('Accept-Encoding'))->all());
  1453. }
  1454. /**
  1455. * Gets a list of content types acceptable by the client browser.
  1456. *
  1457. * @return array List of content types in preferable order
  1458. */
  1459. public function getAcceptableContentTypes()
  1460. {
  1461. if (null !== $this->acceptableContentTypes) {
  1462. return $this->acceptableContentTypes;
  1463. }
  1464. return $this->acceptableContentTypes = array_keys(AcceptHeader::fromString($this->headers->get('Accept'))->all());
  1465. }
  1466. /**
  1467. * Returns true if the request is a XMLHttpRequest.
  1468. *
  1469. * It works if your JavaScript library sets an X-Requested-With HTTP header.
  1470. * It is known to work with common JavaScript frameworks:
  1471. *
  1472. * @link http://en.wikipedia.org/wiki/List_of_Ajax_frameworks#JavaScript
  1473. *
  1474. * @return bool true if the request is an XMLHttpRequest, false otherwise
  1475. */
  1476. public function isXmlHttpRequest()
  1477. {
  1478. return 'XMLHttpRequest' == $this->headers->get('X-Requested-With');
  1479. }
  1480. /*
  1481. * The following methods are derived from code of the Zend Framework (1.10dev - 2010-01-24)
  1482. *
  1483. * Code subject to the new BSD license (http://framework.zend.com/license/new-bsd).
  1484. *
  1485. * Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
  1486. */
  1487. protected function prepareRequestUri()
  1488. {
  1489. $requestUri = '';
  1490. if ($this->headers->has('X_ORIGINAL_URL')) {
  1491. // IIS with Microsoft Rewrite Module
  1492. $requestUri = $this->headers->get('X_ORIGINAL_URL');
  1493. $this->headers->remove('X_ORIGINAL_URL');
  1494. $this->server->remove('HTTP_X_ORIGINAL_URL');
  1495. $this->server->remove('UNENCODED_URL');
  1496. $this->server->remove('IIS_WasUrlRewritten');
  1497. } elseif ($this->headers->has('X_REWRITE_URL')) {
  1498. // IIS with ISAPI_Rewrite
  1499. $requestUri = $this->headers->get('X_REWRITE_URL');
  1500. $this->headers->remove('X_REWRITE_URL');
  1501. } elseif ($this->server->get('IIS_WasUrlRewritten') == '1' && $this->server->get('UNENCODED_URL') != '') {
  1502. // IIS7 with URL Rewrite: make sure we get the unencoded URL (double slash problem)
  1503. $requestUri = $this->server->get('UNENCODED_URL');
  1504. $this->server->remove('UNENCODED_URL');
  1505. $this->server->remove('IIS_WasUrlRewritten');
  1506. } elseif ($this->server->has('REQUEST_URI')) {
  1507. $requestUri = $this->server->get('REQUEST_URI');
  1508. // HTTP proxy reqs setup request URI with scheme and host [and port] + the URL path, only use URL path
  1509. $schemeAndHttpHost = $this->getSchemeAndHttpHost();
  1510. if (strpos($requestUri, $schemeAndHttpHost) === 0) {
  1511. $requestUri = substr($requestUri, strlen($schemeAndHttpHost));
  1512. }
  1513. } elseif ($this->server->has('ORIG_PATH_INFO')) {
  1514. // IIS 5.0, PHP as CGI
  1515. $requestUri = $this->server->get('ORIG_PATH_INFO');
  1516. if ('' != $this->server->get('QUERY_STRING')) {
  1517. $requestUri .= '?'.$this->server->get('QUERY_STRING');
  1518. }
  1519. $this->server->remove('ORIG_PATH_INFO');
  1520. }
  1521. // normalize the request URI to ease creating sub-requests from this request
  1522. $this->server->set('REQUEST_URI', $requestUri);
  1523. return $requestUri;
  1524. }
  1525. /**
  1526. * Prepares the base URL.
  1527. *
  1528. * @return string
  1529. */
  1530. protected function prepareBaseUrl()
  1531. {
  1532. $filename = basename($this->server->get('SCRIPT_FILENAME'));
  1533. if (basename($this->server->get('SCRIPT_NAME')) === $filename) {
  1534. $baseUrl = $this->server->get('SCRIPT_NAME');
  1535. } elseif (basename($this->server->get('PHP_SELF')) === $filename) {
  1536. $baseUrl = $this->server->get('PHP_SELF');
  1537. } elseif (basename($this->server->get('ORIG_SCRIPT_NAME')) === $filename) {
  1538. $baseUrl = $this->server->get('ORIG_SCRIPT_NAME'); // 1and1 shared hosting compatibility
  1539. } else {
  1540. // Backtrack up the script_filename to find the portion matching
  1541. // php_self
  1542. $path = $this->server->get('PHP_SELF', '');
  1543. $file = $this->server->get('SCRIPT_FILENAME', '');
  1544. $segs = explode('/', trim($file, '/'));
  1545. $segs = array_reverse($segs);
  1546. $index = 0;
  1547. $last = count($segs);
  1548. $baseUrl = '';
  1549. do {
  1550. $seg = $segs[$index];
  1551. $baseUrl = '/'.$seg.$baseUrl;
  1552. ++$index;
  1553. } while ($last > $index && (false !== $pos = strpos($path, $baseUrl)) && 0 != $pos);
  1554. }
  1555. // Does the baseUrl have anything in common with the request_uri?
  1556. $requestUri = $this->getRequestUri();
  1557. if ($baseUrl && false !== $prefix = $this->getUrlencodedPrefix($requestUri, $baseUrl)) {
  1558. // full $baseUrl matches
  1559. return $prefix;
  1560. }
  1561. if ($baseUrl && false !== $prefix = $this->getUrlencodedPrefix($requestUri, rtrim(dirname($baseUrl), '/'.DIRECTORY_SEPARATOR).'/')) {
  1562. // directory portion of $baseUrl matches
  1563. return rtrim($prefix, '/'.DIRECTORY_SEPARATOR);
  1564. }
  1565. $truncatedRequestUri = $requestUri;
  1566. if (false !== $pos = strpos($requestUri, '?')) {
  1567. $truncatedRequestUri = substr($requestUri, 0, $pos);
  1568. }
  1569. $basename = basename($baseUrl);
  1570. if (empty($basename) || !strpos(rawurldecode($truncatedRequestUri), $basename)) {
  1571. // no match whatsoever; set it blank
  1572. return '';
  1573. }
  1574. // If using mod_rewrite or ISAPI_Rewrite strip the script filename
  1575. // out of baseUrl. $pos !== 0 makes sure it is not matching a value
  1576. // from PATH_INFO or QUERY_STRING
  1577. if (strlen($requestUri) >= strlen($baseUrl) && (false !== $pos = strpos($requestUri, $baseUrl)) && $pos !== 0) {
  1578. $baseUrl = substr($requestUri, 0, $pos + strlen($baseUrl));
  1579. }
  1580. return rtrim($baseUrl, '/'.DIRECTORY_SEPARATOR);
  1581. }
  1582. /**
  1583. * Prepares the base path.
  1584. *
  1585. * @return string base path
  1586. */
  1587. protected function prepareBasePath()
  1588. {
  1589. $filename = basename($this->server->get('SCRIPT_FILENAME'));
  1590. $baseUrl = $this->getBaseUrl();
  1591. if (empty($baseUrl)) {
  1592. return '';
  1593. }
  1594. if (basename($baseUrl) === $filename) {
  1595. $basePath = dirname($baseUrl);
  1596. } else {
  1597. $basePath = $baseUrl;
  1598. }
  1599. if ('\\' === DIRECTORY_SEPARATOR) {
  1600. $basePath = str_replace('\\', '/', $basePath);
  1601. }
  1602. return rtrim($basePath, '/');
  1603. }
  1604. /**
  1605. * Prepares the path info.
  1606. *
  1607. * @return string path info
  1608. */
  1609. protected function preparePathInfo()
  1610. {
  1611. $baseUrl = $this->getBaseUrl();
  1612. if (null === ($requestUri = $this->getRequestUri())) {
  1613. return '/';
  1614. }
  1615. // Remove the query string from REQUEST_URI
  1616. if ($pos = strpos($requestUri, '?')) {
  1617. $requestUri = substr($requestUri, 0, $pos);
  1618. }
  1619. $pathInfo = substr($requestUri, strlen($baseUrl));
  1620. if (null !== $baseUrl && (false === $pathInfo || '' === $pathInfo)) {
  1621. // If substr() returns false then PATH_INFO is set to an empty string
  1622. return '/';
  1623. } elseif (null === $baseUrl) {
  1624. return $requestUri;
  1625. }
  1626. return (string) $pathInfo;
  1627. }
  1628. /**
  1629. * Initializes HTTP request formats.
  1630. */
  1631. protected static function initializeFormats()
  1632. {
  1633. static::$formats = array(
  1634. 'html' => array('text/html', 'application/xhtml+xml'),
  1635. 'txt' => array('text/plain'),
  1636. 'js' => array('application/javascript', 'application/x-javascript', 'text/javascript'),
  1637. 'css' => array('text/css'),
  1638. 'json' => array('application/json', 'application/x-json'),
  1639. 'xml' => array('text/xml', 'application/xml', 'application/x-xml'),
  1640. 'rdf' => array('application/rdf+xml'),
  1641. 'atom' => array('application/atom+xml'),
  1642. 'rss' => array('application/rss+xml'),
  1643. 'form' => array('application/x-www-form-urlencoded'),
  1644. );
  1645. }
  1646. /**
  1647. * Sets the default PHP locale.
  1648. *
  1649. * @param string $locale
  1650. */
  1651. private function setPhpDefaultLocale($locale)
  1652. {
  1653. // if either the class Locale doesn't exist, or an exception is thrown when
  1654. // setting the default locale, the intl module is not installed, and
  1655. // the call can be ignored:
  1656. try {
  1657. if (class_exists('Locale', false)) {
  1658. \Locale::setDefault($locale);
  1659. }
  1660. } catch (\Exception $e) {
  1661. }
  1662. }
  1663. /*
  1664. * Returns the prefix as encoded in the string when the string starts with
  1665. * the given prefix, false otherwise.
  1666. *
  1667. * @param string $string The urlencoded string
  1668. * @param string $prefix The prefix not encoded
  1669. *
  1670. * @return string|false The prefix as it is encoded in $string, or false
  1671. */
  1672. private function getUrlencodedPrefix($string, $prefix)
  1673. {
  1674. if (0 !== strpos(rawurldecode($string), $prefix)) {
  1675. return false;
  1676. }
  1677. $len = strlen($prefix);
  1678. if (preg_match(sprintf('#^(%%[[:xdigit:]]{2}|.){%d}#', $len), $string, $match)) {
  1679. return $match[0];
  1680. }
  1681. return false;
  1682. }
  1683. private static function createRequestFromFactory(array $query = array(), array $request = array(), array $attributes = array(), array $cookies = array(), array $files = array(), array $server = array(), $content = null)
  1684. {
  1685. if (self::$requestFactory) {
  1686. $request = call_user_func(self::$requestFactory, $query, $request, $attributes, $cookies, $files, $server, $content);
  1687. if (!$request instanceof self) {
  1688. throw new \LogicException('The Request factory must return an instance of Symfony\Component\HttpFoundation\Request.');
  1689. }
  1690. return $request;
  1691. }
  1692. return new static($query, $request, $attributes, $cookies, $files, $server, $content);
  1693. }
  1694. private function isFromTrustedProxy()
  1695. {
  1696. return self::$trustedProxies && IpUtils::checkIp($this->server->get('REMOTE_ADDR'), self::$trustedProxies);
  1697. }
  1698. }