Request.php 52 KB

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