Request.php 69 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154
  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 = array();
  58. /**
  59. * @var string[]
  60. */
  61. protected static $trustedHostPatterns = array();
  62. /**
  63. * @var string[]
  64. */
  65. protected static $trustedHosts = array();
  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 = array(
  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 = array(
  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 = array(
  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(), array $request = array(), array $attributes = array(), array $cookies = array(), array $files = array(), array $server = array(), $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(), array $request = array(), array $attributes = array(), array $cookies = array(), array $files = array(), array $server = array(), $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, array(), $_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')), array('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 = array(), $cookies = array(), $files = array(), $server = array(), $content = null)
  297. {
  298. $server = array_replace(array(
  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'] = $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 = array();
  352. break;
  353. default:
  354. $request = array();
  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, array(), $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 = array();
  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, array('CONTENT_TYPE', 'CONTENT_LENGTH'))) {
  498. $_SERVER[$key] = implode(', ', $value);
  499. } else {
  500. $_SERVER['HTTP_'.$key] = implode(', ', $value);
  501. }
  502. }
  503. $request = array('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 = array();
  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 = array();
  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 = array();
  657. $order = array();
  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 array($ip);
  788. }
  789. return $this->getTrustedValues(self::HEADER_CLIENT_IP, $ip) ?: array($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('/', isset($path[0]) && '/' === $path[0] ? substr($path, 1) : $path);
  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]), array('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. $this->method = strtoupper($this->server->get('REQUEST_METHOD', 'GET'));
  1189. if ('POST' === $this->method) {
  1190. if ($method = $this->headers->get('X-HTTP-METHOD-OVERRIDE')) {
  1191. $this->method = strtoupper($method);
  1192. } elseif (self::$httpMethodParameterOverride) {
  1193. $this->method = strtoupper($this->request->get('_method', $this->query->get('_method', 'POST')));
  1194. }
  1195. }
  1196. }
  1197. return $this->method;
  1198. }
  1199. /**
  1200. * Gets the "real" request method.
  1201. *
  1202. * @return string The request method
  1203. *
  1204. * @see getMethod()
  1205. */
  1206. public function getRealMethod()
  1207. {
  1208. return strtoupper($this->server->get('REQUEST_METHOD', 'GET'));
  1209. }
  1210. /**
  1211. * Gets the mime type associated with the format.
  1212. *
  1213. * @param string $format The format
  1214. *
  1215. * @return string The associated mime type (null if not found)
  1216. */
  1217. public function getMimeType($format)
  1218. {
  1219. if (null === static::$formats) {
  1220. static::initializeFormats();
  1221. }
  1222. return isset(static::$formats[$format]) ? static::$formats[$format][0] : null;
  1223. }
  1224. /**
  1225. * Gets the mime types associated with the format.
  1226. *
  1227. * @param string $format The format
  1228. *
  1229. * @return array The associated mime types
  1230. */
  1231. public static function getMimeTypes($format)
  1232. {
  1233. if (null === static::$formats) {
  1234. static::initializeFormats();
  1235. }
  1236. return isset(static::$formats[$format]) ? static::$formats[$format] : array();
  1237. }
  1238. /**
  1239. * Gets the format associated with the mime type.
  1240. *
  1241. * @param string $mimeType The associated mime type
  1242. *
  1243. * @return string|null The format (null if not found)
  1244. */
  1245. public function getFormat($mimeType)
  1246. {
  1247. $canonicalMimeType = null;
  1248. if (false !== $pos = strpos($mimeType, ';')) {
  1249. $canonicalMimeType = substr($mimeType, 0, $pos);
  1250. }
  1251. if (null === static::$formats) {
  1252. static::initializeFormats();
  1253. }
  1254. foreach (static::$formats as $format => $mimeTypes) {
  1255. if (in_array($mimeType, (array) $mimeTypes)) {
  1256. return $format;
  1257. }
  1258. if (null !== $canonicalMimeType && in_array($canonicalMimeType, (array) $mimeTypes)) {
  1259. return $format;
  1260. }
  1261. }
  1262. }
  1263. /**
  1264. * Associates a format with mime types.
  1265. *
  1266. * @param string $format The format
  1267. * @param string|array $mimeTypes The associated mime types (the preferred one must be the first as it will be used as the content type)
  1268. */
  1269. public function setFormat($format, $mimeTypes)
  1270. {
  1271. if (null === static::$formats) {
  1272. static::initializeFormats();
  1273. }
  1274. static::$formats[$format] = is_array($mimeTypes) ? $mimeTypes : array($mimeTypes);
  1275. }
  1276. /**
  1277. * Gets the request format.
  1278. *
  1279. * Here is the process to determine the format:
  1280. *
  1281. * * format defined by the user (with setRequestFormat())
  1282. * * _format request attribute
  1283. * * $default
  1284. *
  1285. * @param string $default The default format
  1286. *
  1287. * @return string The request format
  1288. */
  1289. public function getRequestFormat($default = 'html')
  1290. {
  1291. if (null === $this->format) {
  1292. $this->format = $this->attributes->get('_format');
  1293. }
  1294. return null === $this->format ? $default : $this->format;
  1295. }
  1296. /**
  1297. * Sets the request format.
  1298. *
  1299. * @param string $format The request format
  1300. */
  1301. public function setRequestFormat($format)
  1302. {
  1303. $this->format = $format;
  1304. }
  1305. /**
  1306. * Gets the format associated with the request.
  1307. *
  1308. * @return string|null The format (null if no content type is present)
  1309. */
  1310. public function getContentType()
  1311. {
  1312. return $this->getFormat($this->headers->get('CONTENT_TYPE'));
  1313. }
  1314. /**
  1315. * Sets the default locale.
  1316. *
  1317. * @param string $locale
  1318. */
  1319. public function setDefaultLocale($locale)
  1320. {
  1321. $this->defaultLocale = $locale;
  1322. if (null === $this->locale) {
  1323. $this->setPhpDefaultLocale($locale);
  1324. }
  1325. }
  1326. /**
  1327. * Get the default locale.
  1328. *
  1329. * @return string
  1330. */
  1331. public function getDefaultLocale()
  1332. {
  1333. return $this->defaultLocale;
  1334. }
  1335. /**
  1336. * Sets the locale.
  1337. *
  1338. * @param string $locale
  1339. */
  1340. public function setLocale($locale)
  1341. {
  1342. $this->setPhpDefaultLocale($this->locale = $locale);
  1343. }
  1344. /**
  1345. * Get the locale.
  1346. *
  1347. * @return string
  1348. */
  1349. public function getLocale()
  1350. {
  1351. return null === $this->locale ? $this->defaultLocale : $this->locale;
  1352. }
  1353. /**
  1354. * Checks if the request method is of specified type.
  1355. *
  1356. * @param string $method Uppercase request method (GET, POST etc)
  1357. *
  1358. * @return bool
  1359. */
  1360. public function isMethod($method)
  1361. {
  1362. return $this->getMethod() === strtoupper($method);
  1363. }
  1364. /**
  1365. * Checks whether or not the method is safe.
  1366. *
  1367. * @see https://tools.ietf.org/html/rfc7231#section-4.2.1
  1368. *
  1369. * @param bool $andCacheable Adds the additional condition that the method should be cacheable. True by default.
  1370. *
  1371. * @return bool
  1372. */
  1373. public function isMethodSafe(/* $andCacheable = true */)
  1374. {
  1375. if (!func_num_args() || func_get_arg(0)) {
  1376. // This deprecation should be turned into a BadMethodCallException in 4.0 (without adding the argument in the signature)
  1377. // then setting $andCacheable to false should be deprecated in 4.1
  1378. @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);
  1379. return in_array($this->getMethod(), array('GET', 'HEAD'));
  1380. }
  1381. return in_array($this->getMethod(), array('GET', 'HEAD', 'OPTIONS', 'TRACE'));
  1382. }
  1383. /**
  1384. * Checks whether or not the method is idempotent.
  1385. *
  1386. * @return bool
  1387. */
  1388. public function isMethodIdempotent()
  1389. {
  1390. return in_array($this->getMethod(), array('HEAD', 'GET', 'PUT', 'DELETE', 'TRACE', 'OPTIONS', 'PURGE'));
  1391. }
  1392. /**
  1393. * Checks whether the method is cacheable or not.
  1394. *
  1395. * @see https://tools.ietf.org/html/rfc7231#section-4.2.3
  1396. *
  1397. * @return bool
  1398. */
  1399. public function isMethodCacheable()
  1400. {
  1401. return in_array($this->getMethod(), array('GET', 'HEAD'));
  1402. }
  1403. /**
  1404. * Returns the protocol version.
  1405. *
  1406. * If the application is behind a proxy, the protocol version used in the
  1407. * requests between the client and the proxy and between the proxy and the
  1408. * server might be different. This returns the former (from the "Via" header)
  1409. * if the proxy is trusted (see "setTrustedProxies()"), otherwise it returns
  1410. * the latter (from the "SERVER_PROTOCOL" server parameter).
  1411. *
  1412. * @return string
  1413. */
  1414. public function getProtocolVersion()
  1415. {
  1416. if ($this->isFromTrustedProxy()) {
  1417. preg_match('~^(HTTP/)?([1-9]\.[0-9]) ~', $this->headers->get('Via'), $matches);
  1418. if ($matches) {
  1419. return 'HTTP/'.$matches[2];
  1420. }
  1421. }
  1422. return $this->server->get('SERVER_PROTOCOL');
  1423. }
  1424. /**
  1425. * Returns the request body content.
  1426. *
  1427. * @param bool $asResource If true, a resource will be returned
  1428. *
  1429. * @return string|resource The request body content or a resource to read the body stream
  1430. *
  1431. * @throws \LogicException
  1432. */
  1433. public function getContent($asResource = false)
  1434. {
  1435. $currentContentIsResource = is_resource($this->content);
  1436. if (\PHP_VERSION_ID < 50600 && false === $this->content) {
  1437. throw new \LogicException('getContent() can only be called once when using the resource return type and PHP below 5.6.');
  1438. }
  1439. if (true === $asResource) {
  1440. if ($currentContentIsResource) {
  1441. rewind($this->content);
  1442. return $this->content;
  1443. }
  1444. // Content passed in parameter (test)
  1445. if (is_string($this->content)) {
  1446. $resource = fopen('php://temp', 'r+');
  1447. fwrite($resource, $this->content);
  1448. rewind($resource);
  1449. return $resource;
  1450. }
  1451. $this->content = false;
  1452. return fopen('php://input', 'rb');
  1453. }
  1454. if ($currentContentIsResource) {
  1455. rewind($this->content);
  1456. return stream_get_contents($this->content);
  1457. }
  1458. if (null === $this->content || false === $this->content) {
  1459. $this->content = file_get_contents('php://input');
  1460. }
  1461. return $this->content;
  1462. }
  1463. /**
  1464. * Gets the Etags.
  1465. *
  1466. * @return array The entity tags
  1467. */
  1468. public function getETags()
  1469. {
  1470. return preg_split('/\s*,\s*/', $this->headers->get('if_none_match'), null, PREG_SPLIT_NO_EMPTY);
  1471. }
  1472. /**
  1473. * @return bool
  1474. */
  1475. public function isNoCache()
  1476. {
  1477. return $this->headers->hasCacheControlDirective('no-cache') || 'no-cache' == $this->headers->get('Pragma');
  1478. }
  1479. /**
  1480. * Returns the preferred language.
  1481. *
  1482. * @param array $locales An array of ordered available locales
  1483. *
  1484. * @return string|null The preferred locale
  1485. */
  1486. public function getPreferredLanguage(array $locales = null)
  1487. {
  1488. $preferredLanguages = $this->getLanguages();
  1489. if (empty($locales)) {
  1490. return isset($preferredLanguages[0]) ? $preferredLanguages[0] : null;
  1491. }
  1492. if (!$preferredLanguages) {
  1493. return $locales[0];
  1494. }
  1495. $extendedPreferredLanguages = array();
  1496. foreach ($preferredLanguages as $language) {
  1497. $extendedPreferredLanguages[] = $language;
  1498. if (false !== $position = strpos($language, '_')) {
  1499. $superLanguage = substr($language, 0, $position);
  1500. if (!in_array($superLanguage, $preferredLanguages)) {
  1501. $extendedPreferredLanguages[] = $superLanguage;
  1502. }
  1503. }
  1504. }
  1505. $preferredLanguages = array_values(array_intersect($extendedPreferredLanguages, $locales));
  1506. return isset($preferredLanguages[0]) ? $preferredLanguages[0] : $locales[0];
  1507. }
  1508. /**
  1509. * Gets a list of languages acceptable by the client browser.
  1510. *
  1511. * @return array Languages ordered in the user browser preferences
  1512. */
  1513. public function getLanguages()
  1514. {
  1515. if (null !== $this->languages) {
  1516. return $this->languages;
  1517. }
  1518. $languages = AcceptHeader::fromString($this->headers->get('Accept-Language'))->all();
  1519. $this->languages = array();
  1520. foreach ($languages as $lang => $acceptHeaderItem) {
  1521. if (false !== strpos($lang, '-')) {
  1522. $codes = explode('-', $lang);
  1523. if ('i' === $codes[0]) {
  1524. // Language not listed in ISO 639 that are not variants
  1525. // of any listed language, which can be registered with the
  1526. // i-prefix, such as i-cherokee
  1527. if (count($codes) > 1) {
  1528. $lang = $codes[1];
  1529. }
  1530. } else {
  1531. for ($i = 0, $max = count($codes); $i < $max; ++$i) {
  1532. if (0 === $i) {
  1533. $lang = strtolower($codes[0]);
  1534. } else {
  1535. $lang .= '_'.strtoupper($codes[$i]);
  1536. }
  1537. }
  1538. }
  1539. }
  1540. $this->languages[] = $lang;
  1541. }
  1542. return $this->languages;
  1543. }
  1544. /**
  1545. * Gets a list of charsets acceptable by the client browser.
  1546. *
  1547. * @return array List of charsets in preferable order
  1548. */
  1549. public function getCharsets()
  1550. {
  1551. if (null !== $this->charsets) {
  1552. return $this->charsets;
  1553. }
  1554. return $this->charsets = array_keys(AcceptHeader::fromString($this->headers->get('Accept-Charset'))->all());
  1555. }
  1556. /**
  1557. * Gets a list of encodings acceptable by the client browser.
  1558. *
  1559. * @return array List of encodings in preferable order
  1560. */
  1561. public function getEncodings()
  1562. {
  1563. if (null !== $this->encodings) {
  1564. return $this->encodings;
  1565. }
  1566. return $this->encodings = array_keys(AcceptHeader::fromString($this->headers->get('Accept-Encoding'))->all());
  1567. }
  1568. /**
  1569. * Gets a list of content types acceptable by the client browser.
  1570. *
  1571. * @return array List of content types in preferable order
  1572. */
  1573. public function getAcceptableContentTypes()
  1574. {
  1575. if (null !== $this->acceptableContentTypes) {
  1576. return $this->acceptableContentTypes;
  1577. }
  1578. return $this->acceptableContentTypes = array_keys(AcceptHeader::fromString($this->headers->get('Accept'))->all());
  1579. }
  1580. /**
  1581. * Returns true if the request is a XMLHttpRequest.
  1582. *
  1583. * It works if your JavaScript library sets an X-Requested-With HTTP header.
  1584. * It is known to work with common JavaScript frameworks:
  1585. *
  1586. * @see http://en.wikipedia.org/wiki/List_of_Ajax_frameworks#JavaScript
  1587. *
  1588. * @return bool true if the request is an XMLHttpRequest, false otherwise
  1589. */
  1590. public function isXmlHttpRequest()
  1591. {
  1592. return 'XMLHttpRequest' == $this->headers->get('X-Requested-With');
  1593. }
  1594. /*
  1595. * The following methods are derived from code of the Zend Framework (1.10dev - 2010-01-24)
  1596. *
  1597. * Code subject to the new BSD license (http://framework.zend.com/license/new-bsd).
  1598. *
  1599. * Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
  1600. */
  1601. protected function prepareRequestUri()
  1602. {
  1603. $requestUri = '';
  1604. if ($this->headers->has('X_ORIGINAL_URL')) {
  1605. // IIS with Microsoft Rewrite Module
  1606. $requestUri = $this->headers->get('X_ORIGINAL_URL');
  1607. $this->headers->remove('X_ORIGINAL_URL');
  1608. $this->server->remove('HTTP_X_ORIGINAL_URL');
  1609. $this->server->remove('UNENCODED_URL');
  1610. $this->server->remove('IIS_WasUrlRewritten');
  1611. } elseif ($this->headers->has('X_REWRITE_URL')) {
  1612. // IIS with ISAPI_Rewrite
  1613. $requestUri = $this->headers->get('X_REWRITE_URL');
  1614. $this->headers->remove('X_REWRITE_URL');
  1615. } elseif ('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. // HTTP proxy reqs setup request URI with scheme and host [and port] + the URL path, only use URL path
  1623. $schemeAndHttpHost = $this->getSchemeAndHttpHost();
  1624. if (0 === strpos($requestUri, $schemeAndHttpHost)) {
  1625. $requestUri = substr($requestUri, strlen($schemeAndHttpHost));
  1626. }
  1627. } elseif ($this->server->has('ORIG_PATH_INFO')) {
  1628. // IIS 5.0, PHP as CGI
  1629. $requestUri = $this->server->get('ORIG_PATH_INFO');
  1630. if ('' != $this->server->get('QUERY_STRING')) {
  1631. $requestUri .= '?'.$this->server->get('QUERY_STRING');
  1632. }
  1633. $this->server->remove('ORIG_PATH_INFO');
  1634. }
  1635. // normalize the request URI to ease creating sub-requests from this request
  1636. $this->server->set('REQUEST_URI', $requestUri);
  1637. return $requestUri;
  1638. }
  1639. /**
  1640. * Prepares the base URL.
  1641. *
  1642. * @return string
  1643. */
  1644. protected function prepareBaseUrl()
  1645. {
  1646. $filename = basename($this->server->get('SCRIPT_FILENAME'));
  1647. if (basename($this->server->get('SCRIPT_NAME')) === $filename) {
  1648. $baseUrl = $this->server->get('SCRIPT_NAME');
  1649. } elseif (basename($this->server->get('PHP_SELF')) === $filename) {
  1650. $baseUrl = $this->server->get('PHP_SELF');
  1651. } elseif (basename($this->server->get('ORIG_SCRIPT_NAME')) === $filename) {
  1652. $baseUrl = $this->server->get('ORIG_SCRIPT_NAME'); // 1and1 shared hosting compatibility
  1653. } else {
  1654. // Backtrack up the script_filename to find the portion matching
  1655. // php_self
  1656. $path = $this->server->get('PHP_SELF', '');
  1657. $file = $this->server->get('SCRIPT_FILENAME', '');
  1658. $segs = explode('/', trim($file, '/'));
  1659. $segs = array_reverse($segs);
  1660. $index = 0;
  1661. $last = count($segs);
  1662. $baseUrl = '';
  1663. do {
  1664. $seg = $segs[$index];
  1665. $baseUrl = '/'.$seg.$baseUrl;
  1666. ++$index;
  1667. } while ($last > $index && (false !== $pos = strpos($path, $baseUrl)) && 0 != $pos);
  1668. }
  1669. // Does the baseUrl have anything in common with the request_uri?
  1670. $requestUri = $this->getRequestUri();
  1671. if ('' !== $requestUri && '/' !== $requestUri[0]) {
  1672. $requestUri = '/'.$requestUri;
  1673. }
  1674. if ($baseUrl && false !== $prefix = $this->getUrlencodedPrefix($requestUri, $baseUrl)) {
  1675. // full $baseUrl matches
  1676. return $prefix;
  1677. }
  1678. if ($baseUrl && false !== $prefix = $this->getUrlencodedPrefix($requestUri, rtrim(dirname($baseUrl), '/'.DIRECTORY_SEPARATOR).'/')) {
  1679. // directory portion of $baseUrl matches
  1680. return rtrim($prefix, '/'.DIRECTORY_SEPARATOR);
  1681. }
  1682. $truncatedRequestUri = $requestUri;
  1683. if (false !== $pos = strpos($requestUri, '?')) {
  1684. $truncatedRequestUri = substr($requestUri, 0, $pos);
  1685. }
  1686. $basename = basename($baseUrl);
  1687. if (empty($basename) || !strpos(rawurldecode($truncatedRequestUri), $basename)) {
  1688. // no match whatsoever; set it blank
  1689. return '';
  1690. }
  1691. // If using mod_rewrite or ISAPI_Rewrite strip the script filename
  1692. // out of baseUrl. $pos !== 0 makes sure it is not matching a value
  1693. // from PATH_INFO or QUERY_STRING
  1694. if (strlen($requestUri) >= strlen($baseUrl) && (false !== $pos = strpos($requestUri, $baseUrl)) && 0 !== $pos) {
  1695. $baseUrl = substr($requestUri, 0, $pos + strlen($baseUrl));
  1696. }
  1697. return rtrim($baseUrl, '/'.DIRECTORY_SEPARATOR);
  1698. }
  1699. /**
  1700. * Prepares the base path.
  1701. *
  1702. * @return string base path
  1703. */
  1704. protected function prepareBasePath()
  1705. {
  1706. $baseUrl = $this->getBaseUrl();
  1707. if (empty($baseUrl)) {
  1708. return '';
  1709. }
  1710. $filename = basename($this->server->get('SCRIPT_FILENAME'));
  1711. if (basename($baseUrl) === $filename) {
  1712. $basePath = dirname($baseUrl);
  1713. } else {
  1714. $basePath = $baseUrl;
  1715. }
  1716. if ('\\' === DIRECTORY_SEPARATOR) {
  1717. $basePath = str_replace('\\', '/', $basePath);
  1718. }
  1719. return rtrim($basePath, '/');
  1720. }
  1721. /**
  1722. * Prepares the path info.
  1723. *
  1724. * @return string path info
  1725. */
  1726. protected function preparePathInfo()
  1727. {
  1728. if (null === ($requestUri = $this->getRequestUri())) {
  1729. return '/';
  1730. }
  1731. // Remove the query string from REQUEST_URI
  1732. if (false !== $pos = strpos($requestUri, '?')) {
  1733. $requestUri = substr($requestUri, 0, $pos);
  1734. }
  1735. if ('' !== $requestUri && '/' !== $requestUri[0]) {
  1736. $requestUri = '/'.$requestUri;
  1737. }
  1738. if (null === ($baseUrl = $this->getBaseUrl())) {
  1739. return $requestUri;
  1740. }
  1741. $pathInfo = substr($requestUri, strlen($baseUrl));
  1742. if (false === $pathInfo || '' === $pathInfo) {
  1743. // If substr() returns false then PATH_INFO is set to an empty string
  1744. return '/';
  1745. }
  1746. return (string) $pathInfo;
  1747. }
  1748. /**
  1749. * Initializes HTTP request formats.
  1750. */
  1751. protected static function initializeFormats()
  1752. {
  1753. static::$formats = array(
  1754. 'html' => array('text/html', 'application/xhtml+xml'),
  1755. 'txt' => array('text/plain'),
  1756. 'js' => array('application/javascript', 'application/x-javascript', 'text/javascript'),
  1757. 'css' => array('text/css'),
  1758. 'json' => array('application/json', 'application/x-json'),
  1759. 'jsonld' => array('application/ld+json'),
  1760. 'xml' => array('text/xml', 'application/xml', 'application/x-xml'),
  1761. 'rdf' => array('application/rdf+xml'),
  1762. 'atom' => array('application/atom+xml'),
  1763. 'rss' => array('application/rss+xml'),
  1764. 'form' => array('application/x-www-form-urlencoded'),
  1765. );
  1766. }
  1767. /**
  1768. * Sets the default PHP locale.
  1769. *
  1770. * @param string $locale
  1771. */
  1772. private function setPhpDefaultLocale($locale)
  1773. {
  1774. // if either the class Locale doesn't exist, or an exception is thrown when
  1775. // setting the default locale, the intl module is not installed, and
  1776. // the call can be ignored:
  1777. try {
  1778. if (class_exists('Locale', false)) {
  1779. \Locale::setDefault($locale);
  1780. }
  1781. } catch (\Exception $e) {
  1782. }
  1783. }
  1784. /*
  1785. * Returns the prefix as encoded in the string when the string starts with
  1786. * the given prefix, false otherwise.
  1787. *
  1788. * @param string $string The urlencoded string
  1789. * @param string $prefix The prefix not encoded
  1790. *
  1791. * @return string|false The prefix as it is encoded in $string, or false
  1792. */
  1793. private function getUrlencodedPrefix($string, $prefix)
  1794. {
  1795. if (0 !== strpos(rawurldecode($string), $prefix)) {
  1796. return false;
  1797. }
  1798. $len = strlen($prefix);
  1799. if (preg_match(sprintf('#^(%%[[:xdigit:]]{2}|.){%d}#', $len), $string, $match)) {
  1800. return $match[0];
  1801. }
  1802. return false;
  1803. }
  1804. private static function createRequestFromFactory(array $query = array(), array $request = array(), array $attributes = array(), array $cookies = array(), array $files = array(), array $server = array(), $content = null)
  1805. {
  1806. if (self::$requestFactory) {
  1807. $request = call_user_func(self::$requestFactory, $query, $request, $attributes, $cookies, $files, $server, $content);
  1808. if (!$request instanceof self) {
  1809. throw new \LogicException('The Request factory must return an instance of Symfony\Component\HttpFoundation\Request.');
  1810. }
  1811. return $request;
  1812. }
  1813. return new static($query, $request, $attributes, $cookies, $files, $server, $content);
  1814. }
  1815. /**
  1816. * Indicates whether this request originated from a trusted proxy.
  1817. *
  1818. * This can be useful to determine whether or not to trust the
  1819. * contents of a proxy-specific header.
  1820. *
  1821. * @return bool true if the request came from a trusted proxy, false otherwise
  1822. */
  1823. public function isFromTrustedProxy()
  1824. {
  1825. return self::$trustedProxies && IpUtils::checkIp($this->server->get('REMOTE_ADDR'), self::$trustedProxies);
  1826. }
  1827. private function getTrustedValues($type, $ip = null)
  1828. {
  1829. $clientValues = array();
  1830. $forwardedValues = array();
  1831. if (self::$trustedHeaders[$type] && $this->headers->has(self::$trustedHeaders[$type])) {
  1832. foreach (explode(',', $this->headers->get(self::$trustedHeaders[$type])) as $v) {
  1833. $clientValues[] = (self::HEADER_CLIENT_PORT === $type ? '0.0.0.0:' : '').trim($v);
  1834. }
  1835. }
  1836. if (self::$trustedHeaders[self::HEADER_FORWARDED] && $this->headers->has(self::$trustedHeaders[self::HEADER_FORWARDED])) {
  1837. $forwardedValues = $this->headers->get(self::$trustedHeaders[self::HEADER_FORWARDED]);
  1838. $forwardedValues = preg_match_all(sprintf('{(?:%s)=(?:"?\[?)([a-zA-Z0-9\.:_\-/]*+)}', self::$forwardedParams[$type]), $forwardedValues, $matches) ? $matches[1] : array();
  1839. }
  1840. if (null !== $ip) {
  1841. $clientValues = $this->normalizeAndFilterClientIps($clientValues, $ip);
  1842. $forwardedValues = $this->normalizeAndFilterClientIps($forwardedValues, $ip);
  1843. }
  1844. if ($forwardedValues === $clientValues || !$clientValues) {
  1845. return $forwardedValues;
  1846. }
  1847. if (!$forwardedValues) {
  1848. return $clientValues;
  1849. }
  1850. if (!$this->isForwardedValid) {
  1851. return null !== $ip ? array('0.0.0.0', $ip) : array();
  1852. }
  1853. $this->isForwardedValid = false;
  1854. 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]));
  1855. }
  1856. private function normalizeAndFilterClientIps(array $clientIps, $ip)
  1857. {
  1858. if (!$clientIps) {
  1859. return array();
  1860. }
  1861. $clientIps[] = $ip; // Complete the IP chain with the IP the request actually came from
  1862. $firstTrustedIp = null;
  1863. foreach ($clientIps as $key => $clientIp) {
  1864. // Remove port (unfortunately, it does happen)
  1865. if (preg_match('{((?:\d+\.){3}\d+)\:\d+}', $clientIp, $match)) {
  1866. $clientIps[$key] = $clientIp = $match[1];
  1867. }
  1868. if (!filter_var($clientIp, FILTER_VALIDATE_IP)) {
  1869. unset($clientIps[$key]);
  1870. continue;
  1871. }
  1872. if (IpUtils::checkIp($clientIp, self::$trustedProxies)) {
  1873. unset($clientIps[$key]);
  1874. // Fallback to this when the client IP falls into the range of trusted proxies
  1875. if (null === $firstTrustedIp) {
  1876. $firstTrustedIp = $clientIp;
  1877. }
  1878. }
  1879. }
  1880. // Now the IP chain contains only untrusted proxies and the client IP
  1881. return $clientIps ? array_reverse($clientIps) : array($firstTrustedIp);
  1882. }
  1883. }