Response.php 36 KB

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