Response.php 34KB

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