Response.php 37 KB

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