菜谱项目

Request.php 68KB

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