vendor/symfony/http-foundation/Request.php line 42

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