Response.php 39 KB

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