Request.php 61 KB

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