Request.php 63 KB

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