You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2143 lines
67 KiB

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