Request.php 52 KB

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