Response.php 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315
  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. // Help opcache.preload discover always-needed symbols
  12. class_exists(ResponseHeaderBag::class);
  13. /**
  14. * Response represents an HTTP response.
  15. *
  16. * @author Fabien Potencier <fabien@symfony.com>
  17. */
  18. class Response
  19. {
  20. public const HTTP_CONTINUE = 100;
  21. public const HTTP_SWITCHING_PROTOCOLS = 101;
  22. public const HTTP_PROCESSING = 102; // RFC2518
  23. public const HTTP_EARLY_HINTS = 103; // RFC8297
  24. public const HTTP_OK = 200;
  25. public const HTTP_CREATED = 201;
  26. public const HTTP_ACCEPTED = 202;
  27. public const HTTP_NON_AUTHORITATIVE_INFORMATION = 203;
  28. public const HTTP_NO_CONTENT = 204;
  29. public const HTTP_RESET_CONTENT = 205;
  30. public const HTTP_PARTIAL_CONTENT = 206;
  31. public const HTTP_MULTI_STATUS = 207; // RFC4918
  32. public const HTTP_ALREADY_REPORTED = 208; // RFC5842
  33. public const HTTP_IM_USED = 226; // RFC3229
  34. public const HTTP_MULTIPLE_CHOICES = 300;
  35. public const HTTP_MOVED_PERMANENTLY = 301;
  36. public const HTTP_FOUND = 302;
  37. public const HTTP_SEE_OTHER = 303;
  38. public const HTTP_NOT_MODIFIED = 304;
  39. public const HTTP_USE_PROXY = 305;
  40. public const HTTP_RESERVED = 306;
  41. public const HTTP_TEMPORARY_REDIRECT = 307;
  42. public const HTTP_PERMANENTLY_REDIRECT = 308; // RFC7238
  43. public const HTTP_BAD_REQUEST = 400;
  44. public const HTTP_UNAUTHORIZED = 401;
  45. public const HTTP_PAYMENT_REQUIRED = 402;
  46. public const HTTP_FORBIDDEN = 403;
  47. public const HTTP_NOT_FOUND = 404;
  48. public const HTTP_METHOD_NOT_ALLOWED = 405;
  49. public const HTTP_NOT_ACCEPTABLE = 406;
  50. public const HTTP_PROXY_AUTHENTICATION_REQUIRED = 407;
  51. public const HTTP_REQUEST_TIMEOUT = 408;
  52. public const HTTP_CONFLICT = 409;
  53. public const HTTP_GONE = 410;
  54. public const HTTP_LENGTH_REQUIRED = 411;
  55. public const HTTP_PRECONDITION_FAILED = 412;
  56. public const HTTP_REQUEST_ENTITY_TOO_LARGE = 413;
  57. public const HTTP_REQUEST_URI_TOO_LONG = 414;
  58. public const HTTP_UNSUPPORTED_MEDIA_TYPE = 415;
  59. public const HTTP_REQUESTED_RANGE_NOT_SATISFIABLE = 416;
  60. public const HTTP_EXPECTATION_FAILED = 417;
  61. public const HTTP_I_AM_A_TEAPOT = 418; // RFC2324
  62. public const HTTP_MISDIRECTED_REQUEST = 421; // RFC7540
  63. public const HTTP_UNPROCESSABLE_ENTITY = 422; // RFC4918
  64. public const HTTP_LOCKED = 423; // RFC4918
  65. public const HTTP_FAILED_DEPENDENCY = 424; // RFC4918
  66. public const HTTP_TOO_EARLY = 425; // RFC-ietf-httpbis-replay-04
  67. public const HTTP_UPGRADE_REQUIRED = 426; // RFC2817
  68. public const HTTP_PRECONDITION_REQUIRED = 428; // RFC6585
  69. public const HTTP_TOO_MANY_REQUESTS = 429; // RFC6585
  70. public const HTTP_REQUEST_HEADER_FIELDS_TOO_LARGE = 431; // RFC6585
  71. public const HTTP_UNAVAILABLE_FOR_LEGAL_REASONS = 451; // RFC7725
  72. public const HTTP_INTERNAL_SERVER_ERROR = 500;
  73. public const HTTP_NOT_IMPLEMENTED = 501;
  74. public const HTTP_BAD_GATEWAY = 502;
  75. public const HTTP_SERVICE_UNAVAILABLE = 503;
  76. public const HTTP_GATEWAY_TIMEOUT = 504;
  77. public const HTTP_VERSION_NOT_SUPPORTED = 505;
  78. public const HTTP_VARIANT_ALSO_NEGOTIATES_EXPERIMENTAL = 506; // RFC2295
  79. public const HTTP_INSUFFICIENT_STORAGE = 507; // RFC4918
  80. public const HTTP_LOOP_DETECTED = 508; // RFC5842
  81. public const HTTP_NOT_EXTENDED = 510; // RFC2774
  82. public const HTTP_NETWORK_AUTHENTICATION_REQUIRED = 511; // RFC6585
  83. /**
  84. * @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control
  85. */
  86. private const HTTP_RESPONSE_CACHE_CONTROL_DIRECTIVES = [
  87. 'must_revalidate' => false,
  88. 'no_cache' => false,
  89. 'no_store' => false,
  90. 'no_transform' => false,
  91. 'public' => false,
  92. 'private' => false,
  93. 'proxy_revalidate' => false,
  94. 'max_age' => true,
  95. 's_maxage' => true,
  96. 'stale_if_error' => true, // RFC5861
  97. 'stale_while_revalidate' => true, // RFC5861
  98. 'immutable' => false,
  99. 'last_modified' => true,
  100. 'etag' => true,
  101. ];
  102. public ResponseHeaderBag $headers;
  103. protected string $content;
  104. protected string $version;
  105. protected int $statusCode;
  106. protected string $statusText;
  107. protected ?string $charset = null;
  108. /**
  109. * Status codes translation table.
  110. *
  111. * The list of codes is complete according to the
  112. * {@link https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml Hypertext Transfer Protocol (HTTP) Status Code Registry}
  113. * (last updated 2021-10-01).
  114. *
  115. * Unless otherwise noted, the status code is defined in RFC2616.
  116. */
  117. public static array $statusTexts = [
  118. 100 => 'Continue',
  119. 101 => 'Switching Protocols',
  120. 102 => 'Processing', // RFC2518
  121. 103 => 'Early Hints',
  122. 200 => 'OK',
  123. 201 => 'Created',
  124. 202 => 'Accepted',
  125. 203 => 'Non-Authoritative Information',
  126. 204 => 'No Content',
  127. 205 => 'Reset Content',
  128. 206 => 'Partial Content',
  129. 207 => 'Multi-Status', // RFC4918
  130. 208 => 'Already Reported', // RFC5842
  131. 226 => 'IM Used', // RFC3229
  132. 300 => 'Multiple Choices',
  133. 301 => 'Moved Permanently',
  134. 302 => 'Found',
  135. 303 => 'See Other',
  136. 304 => 'Not Modified',
  137. 305 => 'Use Proxy',
  138. 307 => 'Temporary Redirect',
  139. 308 => 'Permanent Redirect', // RFC7238
  140. 400 => 'Bad Request',
  141. 401 => 'Unauthorized',
  142. 402 => 'Payment Required',
  143. 403 => 'Forbidden',
  144. 404 => 'Not Found',
  145. 405 => 'Method Not Allowed',
  146. 406 => 'Not Acceptable',
  147. 407 => 'Proxy Authentication Required',
  148. 408 => 'Request Timeout',
  149. 409 => 'Conflict',
  150. 410 => 'Gone',
  151. 411 => 'Length Required',
  152. 412 => 'Precondition Failed',
  153. 413 => 'Content Too Large', // RFC-ietf-httpbis-semantics
  154. 414 => 'URI Too Long',
  155. 415 => 'Unsupported Media Type',
  156. 416 => 'Range Not Satisfiable',
  157. 417 => 'Expectation Failed',
  158. 418 => 'I\'m a teapot', // RFC2324
  159. 421 => 'Misdirected Request', // RFC7540
  160. 422 => 'Unprocessable Content', // RFC-ietf-httpbis-semantics
  161. 423 => 'Locked', // RFC4918
  162. 424 => 'Failed Dependency', // RFC4918
  163. 425 => 'Too Early', // RFC-ietf-httpbis-replay-04
  164. 426 => 'Upgrade Required', // RFC2817
  165. 428 => 'Precondition Required', // RFC6585
  166. 429 => 'Too Many Requests', // RFC6585
  167. 431 => 'Request Header Fields Too Large', // RFC6585
  168. 451 => 'Unavailable For Legal Reasons', // RFC7725
  169. 500 => 'Internal Server Error',
  170. 501 => 'Not Implemented',
  171. 502 => 'Bad Gateway',
  172. 503 => 'Service Unavailable',
  173. 504 => 'Gateway Timeout',
  174. 505 => 'HTTP Version Not Supported',
  175. 506 => 'Variant Also Negotiates', // RFC2295
  176. 507 => 'Insufficient Storage', // RFC4918
  177. 508 => 'Loop Detected', // RFC5842
  178. 510 => 'Not Extended', // RFC2774
  179. 511 => 'Network Authentication Required', // RFC6585
  180. ];
  181. /**
  182. * Tracks headers already sent in informational responses.
  183. */
  184. private array $sentHeaders;
  185. /**
  186. * @param int $status The HTTP status code (200 "OK" by default)
  187. *
  188. * @throws \InvalidArgumentException When the HTTP status code is not valid
  189. */
  190. public function __construct(?string $content = '', int $status = 200, array $headers = [])
  191. {
  192. $this->headers = new ResponseHeaderBag($headers);
  193. $this->setContent($content);
  194. $this->setStatusCode($status);
  195. $this->setProtocolVersion('1.0');
  196. }
  197. /**
  198. * Returns the Response as an HTTP string.
  199. *
  200. * The string representation of the Response is the same as the
  201. * one that will be sent to the client only if the prepare() method
  202. * has been called before.
  203. *
  204. * @see prepare()
  205. */
  206. public function __toString(): string
  207. {
  208. return
  209. \sprintf('HTTP/%s %s %s', $this->version, $this->statusCode, $this->statusText)."\r\n".
  210. $this->headers."\r\n".
  211. $this->getContent();
  212. }
  213. /**
  214. * Clones the current Response instance.
  215. */
  216. public function __clone()
  217. {
  218. $this->headers = clone $this->headers;
  219. }
  220. /**
  221. * Prepares the Response before it is sent to the client.
  222. *
  223. * This method tweaks the Response to ensure that it is
  224. * compliant with RFC 2616. Most of the changes are based on
  225. * the Request that is "associated" with this Response.
  226. *
  227. * @return $this
  228. */
  229. public function prepare(Request $request): static
  230. {
  231. $headers = $this->headers;
  232. if ($this->isInformational() || $this->isEmpty()) {
  233. $this->setContent(null);
  234. $headers->remove('Content-Type');
  235. $headers->remove('Content-Length');
  236. // prevent PHP from sending the Content-Type header based on default_mimetype
  237. ini_set('default_mimetype', '');
  238. } else {
  239. // Content-type based on the Request
  240. if (!$headers->has('Content-Type')) {
  241. $format = $request->getRequestFormat(null);
  242. if (null !== $format && $mimeType = $request->getMimeType($format)) {
  243. $headers->set('Content-Type', $mimeType);
  244. }
  245. }
  246. // Fix Content-Type
  247. $charset = $this->charset ?: 'UTF-8';
  248. if (!$headers->has('Content-Type')) {
  249. $headers->set('Content-Type', 'text/html; charset='.$charset);
  250. } elseif (0 === stripos($headers->get('Content-Type') ?? '', 'text/') && false === stripos($headers->get('Content-Type') ?? '', 'charset')) {
  251. // add the charset
  252. $headers->set('Content-Type', $headers->get('Content-Type').'; charset='.$charset);
  253. }
  254. // Fix Content-Length
  255. if ($headers->has('Transfer-Encoding')) {
  256. $headers->remove('Content-Length');
  257. }
  258. if ($request->isMethod('HEAD')) {
  259. // cf. RFC2616 14.13
  260. $length = $headers->get('Content-Length');
  261. $this->setContent(null);
  262. if ($length) {
  263. $headers->set('Content-Length', $length);
  264. }
  265. }
  266. }
  267. // Fix protocol
  268. if ('HTTP/1.0' != $request->server->get('SERVER_PROTOCOL')) {
  269. $this->setProtocolVersion('1.1');
  270. }
  271. // Check if we need to send extra expire info headers
  272. if ('1.0' == $this->getProtocolVersion() && str_contains($headers->get('Cache-Control', ''), 'no-cache')) {
  273. $headers->set('pragma', 'no-cache');
  274. $headers->set('expires', -1);
  275. }
  276. $this->ensureIEOverSSLCompatibility($request);
  277. if ($request->isSecure()) {
  278. foreach ($headers->getCookies() as $cookie) {
  279. $cookie->setSecureDefault(true);
  280. }
  281. }
  282. return $this;
  283. }
  284. /**
  285. * Sends HTTP headers.
  286. *
  287. * @param positive-int|null $statusCode The status code to use, override the statusCode property if set and not null
  288. *
  289. * @return $this
  290. */
  291. public function sendHeaders(?int $statusCode = null): static
  292. {
  293. // headers have already been sent by the developer
  294. if (headers_sent()) {
  295. return $this;
  296. }
  297. $informationalResponse = $statusCode >= 100 && $statusCode < 200;
  298. if ($informationalResponse && !\function_exists('headers_send')) {
  299. // skip informational responses if not supported by the SAPI
  300. return $this;
  301. }
  302. // headers
  303. foreach ($this->headers->allPreserveCaseWithoutCookies() as $name => $values) {
  304. // As recommended by RFC 8297, PHP automatically copies headers from previous 103 responses, we need to deal with that if headers changed
  305. $previousValues = $this->sentHeaders[$name] ?? null;
  306. if ($previousValues === $values) {
  307. // Header already sent in a previous response, it will be automatically copied in this response by PHP
  308. continue;
  309. }
  310. $replace = 0 === strcasecmp($name, 'Content-Type');
  311. if (null !== $previousValues && array_diff($previousValues, $values)) {
  312. header_remove($name);
  313. $previousValues = null;
  314. }
  315. $newValues = null === $previousValues ? $values : array_diff($values, $previousValues);
  316. foreach ($newValues as $value) {
  317. header($name.': '.$value, $replace, $this->statusCode);
  318. }
  319. if ($informationalResponse) {
  320. $this->sentHeaders[$name] = $values;
  321. }
  322. }
  323. // cookies
  324. foreach ($this->headers->getCookies() as $cookie) {
  325. header('Set-Cookie: '.$cookie, false, $this->statusCode);
  326. }
  327. if ($informationalResponse) {
  328. headers_send($statusCode);
  329. return $this;
  330. }
  331. $statusCode ??= $this->statusCode;
  332. // status
  333. header(\sprintf('HTTP/%s %s %s', $this->version, $statusCode, $this->statusText), true, $statusCode);
  334. return $this;
  335. }
  336. /**
  337. * Sends content for the current web response.
  338. *
  339. * @return $this
  340. */
  341. public function sendContent(): static
  342. {
  343. echo $this->content;
  344. return $this;
  345. }
  346. /**
  347. * Sends HTTP headers and content.
  348. *
  349. * @param bool $flush Whether output buffers should be flushed
  350. *
  351. * @return $this
  352. */
  353. public function send(bool $flush = true): static
  354. {
  355. $this->sendHeaders();
  356. $this->sendContent();
  357. if (!$flush) {
  358. return $this;
  359. }
  360. if (\function_exists('fastcgi_finish_request')) {
  361. fastcgi_finish_request();
  362. } elseif (\function_exists('litespeed_finish_request')) {
  363. litespeed_finish_request();
  364. } elseif (!\in_array(\PHP_SAPI, ['cli', 'phpdbg', 'embed'], true)) {
  365. static::closeOutputBuffers(0, true);
  366. flush();
  367. }
  368. return $this;
  369. }
  370. /**
  371. * Sets the response content.
  372. *
  373. * @return $this
  374. */
  375. public function setContent(?string $content): static
  376. {
  377. $this->content = $content ?? '';
  378. return $this;
  379. }
  380. /**
  381. * Gets the current response content.
  382. */
  383. public function getContent(): string|false
  384. {
  385. return $this->content;
  386. }
  387. /**
  388. * Sets the HTTP protocol version (1.0 or 1.1).
  389. *
  390. * @return $this
  391. *
  392. * @final
  393. */
  394. public function setProtocolVersion(string $version): static
  395. {
  396. $this->version = $version;
  397. return $this;
  398. }
  399. /**
  400. * Gets the HTTP protocol version.
  401. *
  402. * @final
  403. */
  404. public function getProtocolVersion(): string
  405. {
  406. return $this->version;
  407. }
  408. /**
  409. * Sets the response status code.
  410. *
  411. * If the status text is null it will be automatically populated for the known
  412. * status codes and left empty otherwise.
  413. *
  414. * @return $this
  415. *
  416. * @throws \InvalidArgumentException When the HTTP status code is not valid
  417. *
  418. * @final
  419. */
  420. public function setStatusCode(int $code, ?string $text = null): static
  421. {
  422. $this->statusCode = $code;
  423. if ($this->isInvalid()) {
  424. throw new \InvalidArgumentException(\sprintf('The HTTP status code "%s" is not valid.', $code));
  425. }
  426. if (null === $text) {
  427. $this->statusText = self::$statusTexts[$code] ?? 'unknown status';
  428. return $this;
  429. }
  430. $this->statusText = $text;
  431. return $this;
  432. }
  433. /**
  434. * Retrieves the status code for the current web response.
  435. *
  436. * @final
  437. */
  438. public function getStatusCode(): int
  439. {
  440. return $this->statusCode;
  441. }
  442. /**
  443. * Sets the response charset.
  444. *
  445. * @return $this
  446. *
  447. * @final
  448. */
  449. public function setCharset(string $charset): static
  450. {
  451. $this->charset = $charset;
  452. return $this;
  453. }
  454. /**
  455. * Retrieves the response charset.
  456. *
  457. * @final
  458. */
  459. public function getCharset(): ?string
  460. {
  461. return $this->charset;
  462. }
  463. /**
  464. * Returns true if the response may safely be kept in a shared (surrogate) cache.
  465. *
  466. * Responses marked "private" with an explicit Cache-Control directive are
  467. * considered uncacheable.
  468. *
  469. * Responses with neither a freshness lifetime (Expires, max-age) nor cache
  470. * validator (Last-Modified, ETag) are considered uncacheable because there is
  471. * no way to tell when or how to remove them from the cache.
  472. *
  473. * Note that RFC 7231 and RFC 7234 possibly allow for a more permissive implementation,
  474. * for example "status codes that are defined as cacheable by default [...]
  475. * can be reused by a cache with heuristic expiration unless otherwise indicated"
  476. * (https://tools.ietf.org/html/rfc7231#section-6.1)
  477. *
  478. * @final
  479. */
  480. public function isCacheable(): bool
  481. {
  482. if (!\in_array($this->statusCode, [200, 203, 300, 301, 302, 404, 410])) {
  483. return false;
  484. }
  485. if ($this->headers->hasCacheControlDirective('no-store') || $this->headers->getCacheControlDirective('private')) {
  486. return false;
  487. }
  488. return $this->isValidateable() || $this->isFresh();
  489. }
  490. /**
  491. * Returns true if the response is "fresh".
  492. *
  493. * Fresh responses may be served from cache without any interaction with the
  494. * origin. A response is considered fresh when it includes a Cache-Control/max-age
  495. * indicator or Expires header and the calculated age is less than the freshness lifetime.
  496. *
  497. * @final
  498. */
  499. public function isFresh(): bool
  500. {
  501. return $this->getTtl() > 0;
  502. }
  503. /**
  504. * Returns true if the response includes headers that can be used to validate
  505. * the response with the origin server using a conditional GET request.
  506. *
  507. * @final
  508. */
  509. public function isValidateable(): bool
  510. {
  511. return $this->headers->has('Last-Modified') || $this->headers->has('ETag');
  512. }
  513. /**
  514. * Marks the response as "private".
  515. *
  516. * It makes the response ineligible for serving other clients.
  517. *
  518. * @return $this
  519. *
  520. * @final
  521. */
  522. public function setPrivate(): static
  523. {
  524. $this->headers->removeCacheControlDirective('public');
  525. $this->headers->addCacheControlDirective('private');
  526. return $this;
  527. }
  528. /**
  529. * Marks the response as "public".
  530. *
  531. * It makes the response eligible for serving other clients.
  532. *
  533. * @return $this
  534. *
  535. * @final
  536. */
  537. public function setPublic(): static
  538. {
  539. $this->headers->addCacheControlDirective('public');
  540. $this->headers->removeCacheControlDirective('private');
  541. return $this;
  542. }
  543. /**
  544. * Marks the response as "immutable".
  545. *
  546. * @return $this
  547. *
  548. * @final
  549. */
  550. public function setImmutable(bool $immutable = true): static
  551. {
  552. if ($immutable) {
  553. $this->headers->addCacheControlDirective('immutable');
  554. } else {
  555. $this->headers->removeCacheControlDirective('immutable');
  556. }
  557. return $this;
  558. }
  559. /**
  560. * Returns true if the response is marked as "immutable".
  561. *
  562. * @final
  563. */
  564. public function isImmutable(): bool
  565. {
  566. return $this->headers->hasCacheControlDirective('immutable');
  567. }
  568. /**
  569. * Returns true if the response must be revalidated by shared caches once it has become stale.
  570. *
  571. * This method indicates that the response must not be served stale by a
  572. * cache in any circumstance without first revalidating with the origin.
  573. * When present, the TTL of the response should not be overridden to be
  574. * greater than the value provided by the origin.
  575. *
  576. * @final
  577. */
  578. public function mustRevalidate(): bool
  579. {
  580. return $this->headers->hasCacheControlDirective('must-revalidate') || $this->headers->hasCacheControlDirective('proxy-revalidate');
  581. }
  582. /**
  583. * Returns the Date header as a DateTime instance.
  584. *
  585. * @throws \RuntimeException When the header is not parseable
  586. *
  587. * @final
  588. */
  589. public function getDate(): ?\DateTimeImmutable
  590. {
  591. return $this->headers->getDate('Date');
  592. }
  593. /**
  594. * Sets the Date header.
  595. *
  596. * @return $this
  597. *
  598. * @final
  599. */
  600. public function setDate(\DateTimeInterface $date): static
  601. {
  602. $date = \DateTimeImmutable::createFromInterface($date);
  603. $date = $date->setTimezone(new \DateTimeZone('UTC'));
  604. $this->headers->set('Date', $date->format('D, d M Y H:i:s').' GMT');
  605. return $this;
  606. }
  607. /**
  608. * Returns the age of the response in seconds.
  609. *
  610. * @final
  611. */
  612. public function getAge(): int
  613. {
  614. if (null !== $age = $this->headers->get('Age')) {
  615. return (int) $age;
  616. }
  617. return max(time() - (int) $this->getDate()->format('U'), 0);
  618. }
  619. /**
  620. * Marks the response stale by setting the Age header to be equal to the maximum age of the response.
  621. *
  622. * @return $this
  623. */
  624. public function expire(): static
  625. {
  626. if ($this->isFresh()) {
  627. $this->headers->set('Age', $this->getMaxAge());
  628. $this->headers->remove('Expires');
  629. }
  630. return $this;
  631. }
  632. /**
  633. * Returns the value of the Expires header as a DateTime instance.
  634. *
  635. * @final
  636. */
  637. public function getExpires(): ?\DateTimeImmutable
  638. {
  639. try {
  640. return $this->headers->getDate('Expires');
  641. } catch (\RuntimeException) {
  642. // according to RFC 2616 invalid date formats (e.g. "0" and "-1") must be treated as in the past
  643. return \DateTimeImmutable::createFromFormat('U', time() - 172800);
  644. }
  645. }
  646. /**
  647. * Sets the Expires HTTP header with a DateTime instance.
  648. *
  649. * Passing null as value will remove the header.
  650. *
  651. * @return $this
  652. *
  653. * @final
  654. */
  655. public function setExpires(?\DateTimeInterface $date): static
  656. {
  657. if (null === $date) {
  658. $this->headers->remove('Expires');
  659. return $this;
  660. }
  661. $date = \DateTimeImmutable::createFromInterface($date);
  662. $date = $date->setTimezone(new \DateTimeZone('UTC'));
  663. $this->headers->set('Expires', $date->format('D, d M Y H:i:s').' GMT');
  664. return $this;
  665. }
  666. /**
  667. * Returns the number of seconds after the time specified in the response's Date
  668. * header when the response should no longer be considered fresh.
  669. *
  670. * First, it checks for a s-maxage directive, then a max-age directive, and then it falls
  671. * back on an expires header. It returns null when no maximum age can be established.
  672. *
  673. * @final
  674. */
  675. public function getMaxAge(): ?int
  676. {
  677. if ($this->headers->hasCacheControlDirective('s-maxage')) {
  678. return (int) $this->headers->getCacheControlDirective('s-maxage');
  679. }
  680. if ($this->headers->hasCacheControlDirective('max-age')) {
  681. return (int) $this->headers->getCacheControlDirective('max-age');
  682. }
  683. if (null !== $expires = $this->getExpires()) {
  684. $maxAge = (int) $expires->format('U') - (int) $this->getDate()->format('U');
  685. return max($maxAge, 0);
  686. }
  687. return null;
  688. }
  689. /**
  690. * Sets the number of seconds after which the response should no longer be considered fresh.
  691. *
  692. * This method sets the Cache-Control max-age directive.
  693. *
  694. * @return $this
  695. *
  696. * @final
  697. */
  698. public function setMaxAge(int $value): static
  699. {
  700. $this->headers->addCacheControlDirective('max-age', $value);
  701. return $this;
  702. }
  703. /**
  704. * Sets the number of seconds after which the response should no longer be returned by shared caches when backend is down.
  705. *
  706. * This method sets the Cache-Control stale-if-error directive.
  707. *
  708. * @return $this
  709. *
  710. * @final
  711. */
  712. public function setStaleIfError(int $value): static
  713. {
  714. $this->headers->addCacheControlDirective('stale-if-error', $value);
  715. return $this;
  716. }
  717. /**
  718. * Sets the number of seconds after which the response should no longer return stale content by shared caches.
  719. *
  720. * This method sets the Cache-Control stale-while-revalidate directive.
  721. *
  722. * @return $this
  723. *
  724. * @final
  725. */
  726. public function setStaleWhileRevalidate(int $value): static
  727. {
  728. $this->headers->addCacheControlDirective('stale-while-revalidate', $value);
  729. return $this;
  730. }
  731. /**
  732. * Sets the number of seconds after which the response should no longer be considered fresh by shared caches.
  733. *
  734. * This method sets the Cache-Control s-maxage directive.
  735. *
  736. * @return $this
  737. *
  738. * @final
  739. */
  740. public function setSharedMaxAge(int $value): static
  741. {
  742. $this->setPublic();
  743. $this->headers->addCacheControlDirective('s-maxage', $value);
  744. return $this;
  745. }
  746. /**
  747. * Returns the response's time-to-live in seconds.
  748. *
  749. * It returns null when no freshness information is present in the response.
  750. *
  751. * When the response's TTL is 0, the response may not be served from cache without first
  752. * revalidating with the origin.
  753. *
  754. * @final
  755. */
  756. public function getTtl(): ?int
  757. {
  758. $maxAge = $this->getMaxAge();
  759. return null !== $maxAge ? max($maxAge - $this->getAge(), 0) : null;
  760. }
  761. /**
  762. * Sets the response's time-to-live for shared caches in seconds.
  763. *
  764. * This method adjusts the Cache-Control/s-maxage directive.
  765. *
  766. * @return $this
  767. *
  768. * @final
  769. */
  770. public function setTtl(int $seconds): static
  771. {
  772. $this->setSharedMaxAge($this->getAge() + $seconds);
  773. return $this;
  774. }
  775. /**
  776. * Sets the response's time-to-live for private/client caches in seconds.
  777. *
  778. * This method adjusts the Cache-Control/max-age directive.
  779. *
  780. * @return $this
  781. *
  782. * @final
  783. */
  784. public function setClientTtl(int $seconds): static
  785. {
  786. $this->setMaxAge($this->getAge() + $seconds);
  787. return $this;
  788. }
  789. /**
  790. * Returns the Last-Modified HTTP header as a DateTime instance.
  791. *
  792. * @throws \RuntimeException When the HTTP header is not parseable
  793. *
  794. * @final
  795. */
  796. public function getLastModified(): ?\DateTimeImmutable
  797. {
  798. return $this->headers->getDate('Last-Modified');
  799. }
  800. /**
  801. * Sets the Last-Modified HTTP header with a DateTime instance.
  802. *
  803. * Passing null as value will remove the header.
  804. *
  805. * @return $this
  806. *
  807. * @final
  808. */
  809. public function setLastModified(?\DateTimeInterface $date): static
  810. {
  811. if (null === $date) {
  812. $this->headers->remove('Last-Modified');
  813. return $this;
  814. }
  815. $date = \DateTimeImmutable::createFromInterface($date);
  816. $date = $date->setTimezone(new \DateTimeZone('UTC'));
  817. $this->headers->set('Last-Modified', $date->format('D, d M Y H:i:s').' GMT');
  818. return $this;
  819. }
  820. /**
  821. * Returns the literal value of the ETag HTTP header.
  822. *
  823. * @final
  824. */
  825. public function getEtag(): ?string
  826. {
  827. return $this->headers->get('ETag');
  828. }
  829. /**
  830. * Sets the ETag value.
  831. *
  832. * @param string|null $etag The ETag unique identifier or null to remove the header
  833. * @param bool $weak Whether you want a weak ETag or not
  834. *
  835. * @return $this
  836. *
  837. * @final
  838. */
  839. public function setEtag(?string $etag, bool $weak = false): static
  840. {
  841. if (null === $etag) {
  842. $this->headers->remove('Etag');
  843. } else {
  844. if (!str_starts_with($etag, '"')) {
  845. $etag = '"'.$etag.'"';
  846. }
  847. $this->headers->set('ETag', (true === $weak ? 'W/' : '').$etag);
  848. }
  849. return $this;
  850. }
  851. /**
  852. * Sets the response's cache headers (validation and/or expiration).
  853. *
  854. * Available options are: must_revalidate, no_cache, no_store, no_transform, public, private, proxy_revalidate, max_age, s_maxage, immutable, last_modified and etag.
  855. *
  856. * @return $this
  857. *
  858. * @throws \InvalidArgumentException
  859. *
  860. * @final
  861. */
  862. public function setCache(array $options): static
  863. {
  864. if ($diff = array_diff(array_keys($options), array_keys(self::HTTP_RESPONSE_CACHE_CONTROL_DIRECTIVES))) {
  865. throw new \InvalidArgumentException(\sprintf('Response does not support the following options: "%s".', implode('", "', $diff)));
  866. }
  867. if (isset($options['etag'])) {
  868. $this->setEtag($options['etag']);
  869. }
  870. if (isset($options['last_modified'])) {
  871. $this->setLastModified($options['last_modified']);
  872. }
  873. if (isset($options['max_age'])) {
  874. $this->setMaxAge($options['max_age']);
  875. }
  876. if (isset($options['s_maxage'])) {
  877. $this->setSharedMaxAge($options['s_maxage']);
  878. }
  879. if (isset($options['stale_while_revalidate'])) {
  880. $this->setStaleWhileRevalidate($options['stale_while_revalidate']);
  881. }
  882. if (isset($options['stale_if_error'])) {
  883. $this->setStaleIfError($options['stale_if_error']);
  884. }
  885. foreach (self::HTTP_RESPONSE_CACHE_CONTROL_DIRECTIVES as $directive => $hasValue) {
  886. if (!$hasValue && isset($options[$directive])) {
  887. if ($options[$directive]) {
  888. $this->headers->addCacheControlDirective(str_replace('_', '-', $directive));
  889. } else {
  890. $this->headers->removeCacheControlDirective(str_replace('_', '-', $directive));
  891. }
  892. }
  893. }
  894. if (isset($options['public'])) {
  895. if ($options['public']) {
  896. $this->setPublic();
  897. } else {
  898. $this->setPrivate();
  899. }
  900. }
  901. if (isset($options['private'])) {
  902. if ($options['private']) {
  903. $this->setPrivate();
  904. } else {
  905. $this->setPublic();
  906. }
  907. }
  908. return $this;
  909. }
  910. /**
  911. * Modifies the response so that it conforms to the rules defined for a 304 status code.
  912. *
  913. * This sets the status, removes the body, and discards any headers
  914. * that MUST NOT be included in 304 responses.
  915. *
  916. * @return $this
  917. *
  918. * @see https://tools.ietf.org/html/rfc2616#section-10.3.5
  919. *
  920. * @final
  921. */
  922. public function setNotModified(): static
  923. {
  924. $this->setStatusCode(304);
  925. $this->setContent(null);
  926. // remove headers that MUST NOT be included with 304 Not Modified responses
  927. foreach (['Allow', 'Content-Encoding', 'Content-Language', 'Content-Length', 'Content-MD5', 'Content-Type', 'Last-Modified'] as $header) {
  928. $this->headers->remove($header);
  929. }
  930. return $this;
  931. }
  932. /**
  933. * Returns true if the response includes a Vary header.
  934. *
  935. * @final
  936. */
  937. public function hasVary(): bool
  938. {
  939. return null !== $this->headers->get('Vary');
  940. }
  941. /**
  942. * Returns an array of header names given in the Vary header.
  943. *
  944. * @final
  945. */
  946. public function getVary(): array
  947. {
  948. if (!$vary = $this->headers->all('Vary')) {
  949. return [];
  950. }
  951. $ret = [];
  952. foreach ($vary as $item) {
  953. $ret[] = preg_split('/[\s,]+/', $item);
  954. }
  955. return array_merge([], ...$ret);
  956. }
  957. /**
  958. * Sets the Vary header.
  959. *
  960. * @param bool $replace Whether to replace the actual value or not (true by default)
  961. *
  962. * @return $this
  963. *
  964. * @final
  965. */
  966. public function setVary(string|array $headers, bool $replace = true): static
  967. {
  968. $this->headers->set('Vary', $headers, $replace);
  969. return $this;
  970. }
  971. /**
  972. * Determines if the Response validators (ETag, Last-Modified) match
  973. * a conditional value specified in the Request.
  974. *
  975. * If the Response is not modified, it sets the status code to 304 and
  976. * removes the actual content by calling the setNotModified() method.
  977. *
  978. * @final
  979. */
  980. public function isNotModified(Request $request): bool
  981. {
  982. if (!$request->isMethodCacheable()) {
  983. return false;
  984. }
  985. $notModified = false;
  986. $lastModified = $this->headers->get('Last-Modified');
  987. $modifiedSince = $request->headers->get('If-Modified-Since');
  988. if (($ifNoneMatchEtags = $request->getETags()) && (null !== $etag = $this->getEtag())) {
  989. if (0 == strncmp($etag, 'W/', 2)) {
  990. $etag = substr($etag, 2);
  991. }
  992. // Use weak comparison as per https://tools.ietf.org/html/rfc7232#section-3.2.
  993. foreach ($ifNoneMatchEtags as $ifNoneMatchEtag) {
  994. if (0 == strncmp($ifNoneMatchEtag, 'W/', 2)) {
  995. $ifNoneMatchEtag = substr($ifNoneMatchEtag, 2);
  996. }
  997. if ($ifNoneMatchEtag === $etag || '*' === $ifNoneMatchEtag) {
  998. $notModified = true;
  999. break;
  1000. }
  1001. }
  1002. }
  1003. // Only do If-Modified-Since date comparison when If-None-Match is not present as per https://tools.ietf.org/html/rfc7232#section-3.3.
  1004. elseif ($modifiedSince && $lastModified) {
  1005. $notModified = strtotime($modifiedSince) >= strtotime($lastModified);
  1006. }
  1007. if ($notModified) {
  1008. $this->setNotModified();
  1009. }
  1010. return $notModified;
  1011. }
  1012. /**
  1013. * Is response invalid?
  1014. *
  1015. * @see https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
  1016. *
  1017. * @final
  1018. */
  1019. public function isInvalid(): bool
  1020. {
  1021. return $this->statusCode < 100 || $this->statusCode >= 600;
  1022. }
  1023. /**
  1024. * Is response informative?
  1025. *
  1026. * @final
  1027. */
  1028. public function isInformational(): bool
  1029. {
  1030. return $this->statusCode >= 100 && $this->statusCode < 200;
  1031. }
  1032. /**
  1033. * Is response successful?
  1034. *
  1035. * @final
  1036. */
  1037. public function isSuccessful(): bool
  1038. {
  1039. return $this->statusCode >= 200 && $this->statusCode < 300;
  1040. }
  1041. /**
  1042. * Is the response a redirect?
  1043. *
  1044. * @final
  1045. */
  1046. public function isRedirection(): bool
  1047. {
  1048. return $this->statusCode >= 300 && $this->statusCode < 400;
  1049. }
  1050. /**
  1051. * Is there a client error?
  1052. *
  1053. * @final
  1054. */
  1055. public function isClientError(): bool
  1056. {
  1057. return $this->statusCode >= 400 && $this->statusCode < 500;
  1058. }
  1059. /**
  1060. * Was there a server side error?
  1061. *
  1062. * @final
  1063. */
  1064. public function isServerError(): bool
  1065. {
  1066. return $this->statusCode >= 500 && $this->statusCode < 600;
  1067. }
  1068. /**
  1069. * Is the response OK?
  1070. *
  1071. * @final
  1072. */
  1073. public function isOk(): bool
  1074. {
  1075. return 200 === $this->statusCode;
  1076. }
  1077. /**
  1078. * Is the response forbidden?
  1079. *
  1080. * @final
  1081. */
  1082. public function isForbidden(): bool
  1083. {
  1084. return 403 === $this->statusCode;
  1085. }
  1086. /**
  1087. * Is the response a not found error?
  1088. *
  1089. * @final
  1090. */
  1091. public function isNotFound(): bool
  1092. {
  1093. return 404 === $this->statusCode;
  1094. }
  1095. /**
  1096. * Is the response a redirect of some form?
  1097. *
  1098. * @final
  1099. */
  1100. public function isRedirect(?string $location = null): bool
  1101. {
  1102. return \in_array($this->statusCode, [201, 301, 302, 303, 307, 308]) && (null === $location ?: $location == $this->headers->get('Location'));
  1103. }
  1104. /**
  1105. * Is the response empty?
  1106. *
  1107. * @final
  1108. */
  1109. public function isEmpty(): bool
  1110. {
  1111. return \in_array($this->statusCode, [204, 304]);
  1112. }
  1113. /**
  1114. * Cleans or flushes output buffers up to target level.
  1115. *
  1116. * Resulting level can be greater than target level if a non-removable buffer has been encountered.
  1117. *
  1118. * @final
  1119. */
  1120. public static function closeOutputBuffers(int $targetLevel, bool $flush): void
  1121. {
  1122. $status = ob_get_status(true);
  1123. $level = \count($status);
  1124. $flags = \PHP_OUTPUT_HANDLER_REMOVABLE | ($flush ? \PHP_OUTPUT_HANDLER_FLUSHABLE : \PHP_OUTPUT_HANDLER_CLEANABLE);
  1125. while ($level-- > $targetLevel && ($s = $status[$level]) && (!isset($s['del']) ? !isset($s['flags']) || ($s['flags'] & $flags) === $flags : $s['del'])) {
  1126. if ($flush) {
  1127. ob_end_flush();
  1128. } else {
  1129. ob_end_clean();
  1130. }
  1131. }
  1132. }
  1133. /**
  1134. * Marks a response as safe according to RFC8674.
  1135. *
  1136. * @see https://tools.ietf.org/html/rfc8674
  1137. */
  1138. public function setContentSafe(bool $safe = true): void
  1139. {
  1140. if ($safe) {
  1141. $this->headers->set('Preference-Applied', 'safe');
  1142. } elseif ('safe' === $this->headers->get('Preference-Applied')) {
  1143. $this->headers->remove('Preference-Applied');
  1144. }
  1145. $this->setVary('Prefer', false);
  1146. }
  1147. /**
  1148. * Checks if we need to remove Cache-Control for SSL encrypted downloads when using IE < 9.
  1149. *
  1150. * @see http://support.microsoft.com/kb/323308
  1151. *
  1152. * @final
  1153. */
  1154. protected function ensureIEOverSSLCompatibility(Request $request): void
  1155. {
  1156. if (false !== stripos($this->headers->get('Content-Disposition') ?? '', 'attachment') && 1 == preg_match('/MSIE (.*?);/i', $request->server->get('HTTP_USER_AGENT') ?? '', $match) && true === $request->isSecure()) {
  1157. if ((int) preg_replace('/(MSIE )(.*?);/', '$2', $match[0]) < 9) {
  1158. $this->headers->remove('Cache-Control');
  1159. }
  1160. }
  1161. }
  1162. }