Request.php 63KB

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