Request.php 70 KB

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