Response.php 40 KB

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