Request.php 64 KB

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