No Description

Request.php 57KB

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