Request.php 58 KB

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