Response.php 40 KB

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