Response.php 35 KB

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