Response.php 35 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234
  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 \Symfony\Component\HttpFoundation\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 http://www.iana.org/assignments/http-status-codes/ 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 = array(
  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 = array())
  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 = array())
  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. } else {
  254. // Content-type based on the Request
  255. if (!$headers->has('Content-Type')) {
  256. $format = $request->getRequestFormat();
  257. if (null !== $format && $mimeType = $request->getMimeType($format)) {
  258. $headers->set('Content-Type', $mimeType);
  259. }
  260. }
  261. // Fix Content-Type
  262. $charset = $this->charset ?: 'UTF-8';
  263. if (!$headers->has('Content-Type')) {
  264. $headers->set('Content-Type', 'text/html; charset='.$charset);
  265. } elseif (0 === stripos($headers->get('Content-Type'), 'text/') && false === stripos($headers->get('Content-Type'), 'charset')) {
  266. // add the charset
  267. $headers->set('Content-Type', $headers->get('Content-Type').'; charset='.$charset);
  268. }
  269. // Fix Content-Length
  270. if ($headers->has('Transfer-Encoding')) {
  271. $headers->remove('Content-Length');
  272. }
  273. if ($request->isMethod('HEAD')) {
  274. // cf. RFC2616 14.13
  275. $length = $headers->get('Content-Length');
  276. $this->setContent(null);
  277. if ($length) {
  278. $headers->set('Content-Length', $length);
  279. }
  280. }
  281. }
  282. // Fix protocol
  283. if ('HTTP/1.0' != $request->server->get('SERVER_PROTOCOL')) {
  284. $this->setProtocolVersion('1.1');
  285. }
  286. // Check if we need to send extra expire info headers
  287. if ('1.0' == $this->getProtocolVersion() && false !== strpos($this->headers->get('Cache-Control'), 'no-cache')) {
  288. $this->headers->set('pragma', 'no-cache');
  289. $this->headers->set('expires', -1);
  290. }
  291. $this->ensureIEOverSSLCompatibility($request);
  292. return $this;
  293. }
  294. /**
  295. * Sends HTTP headers.
  296. *
  297. * @return $this
  298. */
  299. public function sendHeaders()
  300. {
  301. // headers have already been sent by the developer
  302. if (headers_sent()) {
  303. return $this;
  304. }
  305. // headers
  306. foreach ($this->headers->allPreserveCaseWithoutCookies() as $name => $values) {
  307. foreach ($values as $value) {
  308. header($name.': '.$value, false, $this->statusCode);
  309. }
  310. }
  311. // cookies
  312. foreach ($this->headers->getCookies() as $cookie) {
  313. header('Set-Cookie: '.$cookie->getName().strstr($cookie, '='), false, $this->statusCode);
  314. }
  315. // status
  316. header(sprintf('HTTP/%s %s %s', $this->version, $this->statusCode, $this->statusText), true, $this->statusCode);
  317. return $this;
  318. }
  319. /**
  320. * Sends content for the current web response.
  321. *
  322. * @return $this
  323. */
  324. public function sendContent()
  325. {
  326. echo $this->content;
  327. return $this;
  328. }
  329. /**
  330. * Sends HTTP headers and content.
  331. *
  332. * @return $this
  333. */
  334. public function send()
  335. {
  336. $this->sendHeaders();
  337. $this->sendContent();
  338. if (\function_exists('fastcgi_finish_request')) {
  339. fastcgi_finish_request();
  340. } elseif (!\in_array(\PHP_SAPI, array('cli', 'phpdbg'), true)) {
  341. static::closeOutputBuffers(0, true);
  342. }
  343. return $this;
  344. }
  345. /**
  346. * Sets the response content.
  347. *
  348. * Valid types are strings, numbers, null, and objects that implement a __toString() method.
  349. *
  350. * @param mixed $content Content that can be cast to string
  351. *
  352. * @return $this
  353. *
  354. * @throws \UnexpectedValueException
  355. */
  356. public function setContent($content)
  357. {
  358. if (null !== $content && !\is_string($content) && !is_numeric($content) && !\is_callable(array($content, '__toString'))) {
  359. throw new \UnexpectedValueException(sprintf('The Response content must be a string or object implementing __toString(), "%s" given.', \gettype($content)));
  360. }
  361. $this->content = (string) $content;
  362. return $this;
  363. }
  364. /**
  365. * Gets the current response content.
  366. *
  367. * @return string Content
  368. */
  369. public function getContent()
  370. {
  371. return $this->content;
  372. }
  373. /**
  374. * Sets the HTTP protocol version (1.0 or 1.1).
  375. *
  376. * @return $this
  377. *
  378. * @final
  379. */
  380. public function setProtocolVersion(string $version)
  381. {
  382. $this->version = $version;
  383. return $this;
  384. }
  385. /**
  386. * Gets the HTTP protocol version.
  387. *
  388. * @final
  389. */
  390. public function getProtocolVersion(): string
  391. {
  392. return $this->version;
  393. }
  394. /**
  395. * Sets the response status code.
  396. *
  397. * If the status text is null it will be automatically populated for the known
  398. * status codes and left empty otherwise.
  399. *
  400. * @return $this
  401. *
  402. * @throws \InvalidArgumentException When the HTTP status code is not valid
  403. *
  404. * @final
  405. */
  406. public function setStatusCode(int $code, $text = null)
  407. {
  408. $this->statusCode = $code;
  409. if ($this->isInvalid()) {
  410. throw new \InvalidArgumentException(sprintf('The HTTP status code "%s" is not valid.', $code));
  411. }
  412. if (null === $text) {
  413. $this->statusText = isset(self::$statusTexts[$code]) ? self::$statusTexts[$code] : 'unknown status';
  414. return $this;
  415. }
  416. if (false === $text) {
  417. $this->statusText = '';
  418. return $this;
  419. }
  420. $this->statusText = $text;
  421. return $this;
  422. }
  423. /**
  424. * Retrieves the status code for the current web response.
  425. *
  426. * @final
  427. */
  428. public function getStatusCode(): int
  429. {
  430. return $this->statusCode;
  431. }
  432. /**
  433. * Sets the response charset.
  434. *
  435. * @return $this
  436. *
  437. * @final
  438. */
  439. public function setCharset(string $charset)
  440. {
  441. $this->charset = $charset;
  442. return $this;
  443. }
  444. /**
  445. * Retrieves the response charset.
  446. *
  447. * @final
  448. */
  449. public function getCharset(): ?string
  450. {
  451. return $this->charset;
  452. }
  453. /**
  454. * Returns true if the response may safely be kept in a shared (surrogate) cache.
  455. *
  456. * Responses marked "private" with an explicit Cache-Control directive are
  457. * considered uncacheable.
  458. *
  459. * Responses with neither a freshness lifetime (Expires, max-age) nor cache
  460. * validator (Last-Modified, ETag) are considered uncacheable because there is
  461. * no way to tell when or how to remove them from the cache.
  462. *
  463. * Note that RFC 7231 and RFC 7234 possibly allow for a more permissive implementation,
  464. * for example "status codes that are defined as cacheable by default [...]
  465. * can be reused by a cache with heuristic expiration unless otherwise indicated"
  466. * (https://tools.ietf.org/html/rfc7231#section-6.1)
  467. *
  468. * @final
  469. */
  470. public function isCacheable(): bool
  471. {
  472. if (!\in_array($this->statusCode, array(200, 203, 300, 301, 302, 404, 410))) {
  473. return false;
  474. }
  475. if ($this->headers->hasCacheControlDirective('no-store') || $this->headers->getCacheControlDirective('private')) {
  476. return false;
  477. }
  478. return $this->isValidateable() || $this->isFresh();
  479. }
  480. /**
  481. * Returns true if the response is "fresh".
  482. *
  483. * Fresh responses may be served from cache without any interaction with the
  484. * origin. A response is considered fresh when it includes a Cache-Control/max-age
  485. * indicator or Expires header and the calculated age is less than the freshness lifetime.
  486. *
  487. * @final
  488. */
  489. public function isFresh(): bool
  490. {
  491. return $this->getTtl() > 0;
  492. }
  493. /**
  494. * Returns true if the response includes headers that can be used to validate
  495. * the response with the origin server using a conditional GET request.
  496. *
  497. * @final
  498. */
  499. public function isValidateable(): bool
  500. {
  501. return $this->headers->has('Last-Modified') || $this->headers->has('ETag');
  502. }
  503. /**
  504. * Marks the response as "private".
  505. *
  506. * It makes the response ineligible for serving other clients.
  507. *
  508. * @return $this
  509. *
  510. * @final
  511. */
  512. public function setPrivate()
  513. {
  514. $this->headers->removeCacheControlDirective('public');
  515. $this->headers->addCacheControlDirective('private');
  516. return $this;
  517. }
  518. /**
  519. * Marks the response as "public".
  520. *
  521. * It makes the response eligible for serving other clients.
  522. *
  523. * @return $this
  524. *
  525. * @final
  526. */
  527. public function setPublic()
  528. {
  529. $this->headers->addCacheControlDirective('public');
  530. $this->headers->removeCacheControlDirective('private');
  531. return $this;
  532. }
  533. /**
  534. * Marks the response as "immutable".
  535. *
  536. * @return $this
  537. *
  538. * @final
  539. */
  540. public function setImmutable(bool $immutable = true)
  541. {
  542. if ($immutable) {
  543. $this->headers->addCacheControlDirective('immutable');
  544. } else {
  545. $this->headers->removeCacheControlDirective('immutable');
  546. }
  547. return $this;
  548. }
  549. /**
  550. * Returns true if the response is marked as "immutable".
  551. *
  552. * @final
  553. */
  554. public function isImmutable(): bool
  555. {
  556. return $this->headers->hasCacheControlDirective('immutable');
  557. }
  558. /**
  559. * Returns true if the response must be revalidated by caches.
  560. *
  561. * This method indicates that the response must not be served stale by a
  562. * cache in any circumstance without first revalidating with the origin.
  563. * When present, the TTL of the response should not be overridden to be
  564. * greater than the value provided by the origin.
  565. *
  566. * @final
  567. */
  568. public function mustRevalidate(): bool
  569. {
  570. return $this->headers->hasCacheControlDirective('must-revalidate') || $this->headers->hasCacheControlDirective('proxy-revalidate');
  571. }
  572. /**
  573. * Returns the Date header as a DateTime instance.
  574. *
  575. * @throws \RuntimeException When the header is not parseable
  576. *
  577. * @final
  578. */
  579. public function getDate(): ?\DateTimeInterface
  580. {
  581. return $this->headers->getDate('Date');
  582. }
  583. /**
  584. * Sets the Date header.
  585. *
  586. * @return $this
  587. *
  588. * @final
  589. */
  590. public function setDate(\DateTimeInterface $date)
  591. {
  592. if ($date instanceof \DateTime) {
  593. $date = \DateTimeImmutable::createFromMutable($date);
  594. }
  595. $date = $date->setTimezone(new \DateTimeZone('UTC'));
  596. $this->headers->set('Date', $date->format('D, d M Y H:i:s').' GMT');
  597. return $this;
  598. }
  599. /**
  600. * Returns the age of the response in seconds.
  601. *
  602. * @final
  603. */
  604. public function getAge(): int
  605. {
  606. if (null !== $age = $this->headers->get('Age')) {
  607. return (int) $age;
  608. }
  609. return max(time() - $this->getDate()->format('U'), 0);
  610. }
  611. /**
  612. * Marks the response stale by setting the Age header to be equal to the maximum age of the response.
  613. *
  614. * @return $this
  615. */
  616. public function expire()
  617. {
  618. if ($this->isFresh()) {
  619. $this->headers->set('Age', $this->getMaxAge());
  620. $this->headers->remove('Expires');
  621. }
  622. return $this;
  623. }
  624. /**
  625. * Returns the value of the Expires header as a DateTime instance.
  626. *
  627. * @final
  628. */
  629. public function getExpires(): ?\DateTimeInterface
  630. {
  631. try {
  632. return $this->headers->getDate('Expires');
  633. } catch (\RuntimeException $e) {
  634. // according to RFC 2616 invalid date formats (e.g. "0" and "-1") must be treated as in the past
  635. return \DateTime::createFromFormat('U', time() - 172800);
  636. }
  637. }
  638. /**
  639. * Sets the Expires HTTP header with a DateTime instance.
  640. *
  641. * Passing null as value will remove the header.
  642. *
  643. * @return $this
  644. *
  645. * @final
  646. */
  647. public function setExpires(\DateTimeInterface $date = null)
  648. {
  649. if (null === $date) {
  650. $this->headers->remove('Expires');
  651. return $this;
  652. }
  653. if ($date instanceof \DateTime) {
  654. $date = \DateTimeImmutable::createFromMutable($date);
  655. }
  656. $date = $date->setTimezone(new \DateTimeZone('UTC'));
  657. $this->headers->set('Expires', $date->format('D, d M Y H:i:s').' GMT');
  658. return $this;
  659. }
  660. /**
  661. * Returns the number of seconds after the time specified in the response's Date
  662. * header when the response should no longer be considered fresh.
  663. *
  664. * First, it checks for a s-maxage directive, then a max-age directive, and then it falls
  665. * back on an expires header. It returns null when no maximum age can be established.
  666. *
  667. * @final
  668. */
  669. public function getMaxAge(): ?int
  670. {
  671. if ($this->headers->hasCacheControlDirective('s-maxage')) {
  672. return (int) $this->headers->getCacheControlDirective('s-maxage');
  673. }
  674. if ($this->headers->hasCacheControlDirective('max-age')) {
  675. return (int) $this->headers->getCacheControlDirective('max-age');
  676. }
  677. if (null !== $this->getExpires()) {
  678. return (int) ($this->getExpires()->format('U') - $this->getDate()->format('U'));
  679. }
  680. return null;
  681. }
  682. /**
  683. * Sets the number of seconds after which the response should no longer be considered fresh.
  684. *
  685. * This methods sets the Cache-Control max-age directive.
  686. *
  687. * @return $this
  688. *
  689. * @final
  690. */
  691. public function setMaxAge(int $value)
  692. {
  693. $this->headers->addCacheControlDirective('max-age', $value);
  694. return $this;
  695. }
  696. /**
  697. * Sets the number of seconds after which the response should no longer be considered fresh by shared caches.
  698. *
  699. * This methods sets the Cache-Control s-maxage directive.
  700. *
  701. * @return $this
  702. *
  703. * @final
  704. */
  705. public function setSharedMaxAge(int $value)
  706. {
  707. $this->setPublic();
  708. $this->headers->addCacheControlDirective('s-maxage', $value);
  709. return $this;
  710. }
  711. /**
  712. * Returns the response's time-to-live in seconds.
  713. *
  714. * It returns null when no freshness information is present in the response.
  715. *
  716. * When the responses TTL is <= 0, the response may not be served from cache without first
  717. * revalidating with the origin.
  718. *
  719. * @final
  720. */
  721. public function getTtl(): ?int
  722. {
  723. $maxAge = $this->getMaxAge();
  724. return null !== $maxAge ? $maxAge - $this->getAge() : null;
  725. }
  726. /**
  727. * Sets the response's time-to-live for shared caches in seconds.
  728. *
  729. * This method adjusts the Cache-Control/s-maxage directive.
  730. *
  731. * @return $this
  732. *
  733. * @final
  734. */
  735. public function setTtl(int $seconds)
  736. {
  737. $this->setSharedMaxAge($this->getAge() + $seconds);
  738. return $this;
  739. }
  740. /**
  741. * Sets the response's time-to-live for private/client caches in seconds.
  742. *
  743. * This method adjusts the Cache-Control/max-age directive.
  744. *
  745. * @return $this
  746. *
  747. * @final
  748. */
  749. public function setClientTtl(int $seconds)
  750. {
  751. $this->setMaxAge($this->getAge() + $seconds);
  752. return $this;
  753. }
  754. /**
  755. * Returns the Last-Modified HTTP header as a DateTime instance.
  756. *
  757. * @throws \RuntimeException When the HTTP header is not parseable
  758. *
  759. * @final
  760. */
  761. public function getLastModified(): ?\DateTimeInterface
  762. {
  763. return $this->headers->getDate('Last-Modified');
  764. }
  765. /**
  766. * Sets the Last-Modified HTTP header with a DateTime instance.
  767. *
  768. * Passing null as value will remove the header.
  769. *
  770. * @return $this
  771. *
  772. * @final
  773. */
  774. public function setLastModified(\DateTimeInterface $date = null)
  775. {
  776. if (null === $date) {
  777. $this->headers->remove('Last-Modified');
  778. return $this;
  779. }
  780. if ($date instanceof \DateTime) {
  781. $date = \DateTimeImmutable::createFromMutable($date);
  782. }
  783. $date = $date->setTimezone(new \DateTimeZone('UTC'));
  784. $this->headers->set('Last-Modified', $date->format('D, d M Y H:i:s').' GMT');
  785. return $this;
  786. }
  787. /**
  788. * Returns the literal value of the ETag HTTP header.
  789. *
  790. * @final
  791. */
  792. public function getEtag(): ?string
  793. {
  794. return $this->headers->get('ETag');
  795. }
  796. /**
  797. * Sets the ETag value.
  798. *
  799. * @param string|null $etag The ETag unique identifier or null to remove the header
  800. * @param bool $weak Whether you want a weak ETag or not
  801. *
  802. * @return $this
  803. *
  804. * @final
  805. */
  806. public function setEtag(string $etag = null, bool $weak = false)
  807. {
  808. if (null === $etag) {
  809. $this->headers->remove('Etag');
  810. } else {
  811. if (0 !== strpos($etag, '"')) {
  812. $etag = '"'.$etag.'"';
  813. }
  814. $this->headers->set('ETag', (true === $weak ? 'W/' : '').$etag);
  815. }
  816. return $this;
  817. }
  818. /**
  819. * Sets the response's cache headers (validation and/or expiration).
  820. *
  821. * Available options are: etag, last_modified, max_age, s_maxage, private, public and immutable.
  822. *
  823. * @return $this
  824. *
  825. * @throws \InvalidArgumentException
  826. *
  827. * @final
  828. */
  829. public function setCache(array $options)
  830. {
  831. if ($diff = array_diff(array_keys($options), array('etag', 'last_modified', 'max_age', 's_maxage', 'private', 'public', 'immutable'))) {
  832. throw new \InvalidArgumentException(sprintf('Response does not support the following options: "%s".', implode('", "', array_values($diff))));
  833. }
  834. if (isset($options['etag'])) {
  835. $this->setEtag($options['etag']);
  836. }
  837. if (isset($options['last_modified'])) {
  838. $this->setLastModified($options['last_modified']);
  839. }
  840. if (isset($options['max_age'])) {
  841. $this->setMaxAge($options['max_age']);
  842. }
  843. if (isset($options['s_maxage'])) {
  844. $this->setSharedMaxAge($options['s_maxage']);
  845. }
  846. if (isset($options['public'])) {
  847. if ($options['public']) {
  848. $this->setPublic();
  849. } else {
  850. $this->setPrivate();
  851. }
  852. }
  853. if (isset($options['private'])) {
  854. if ($options['private']) {
  855. $this->setPrivate();
  856. } else {
  857. $this->setPublic();
  858. }
  859. }
  860. if (isset($options['immutable'])) {
  861. $this->setImmutable((bool) $options['immutable']);
  862. }
  863. return $this;
  864. }
  865. /**
  866. * Modifies the response so that it conforms to the rules defined for a 304 status code.
  867. *
  868. * This sets the status, removes the body, and discards any headers
  869. * that MUST NOT be included in 304 responses.
  870. *
  871. * @return $this
  872. *
  873. * @see http://tools.ietf.org/html/rfc2616#section-10.3.5
  874. *
  875. * @final
  876. */
  877. public function setNotModified()
  878. {
  879. $this->setStatusCode(304);
  880. $this->setContent(null);
  881. // remove headers that MUST NOT be included with 304 Not Modified responses
  882. foreach (array('Allow', 'Content-Encoding', 'Content-Language', 'Content-Length', 'Content-MD5', 'Content-Type', 'Last-Modified') as $header) {
  883. $this->headers->remove($header);
  884. }
  885. return $this;
  886. }
  887. /**
  888. * Returns true if the response includes a Vary header.
  889. *
  890. * @final
  891. */
  892. public function hasVary(): bool
  893. {
  894. return null !== $this->headers->get('Vary');
  895. }
  896. /**
  897. * Returns an array of header names given in the Vary header.
  898. *
  899. * @final
  900. */
  901. public function getVary(): array
  902. {
  903. if (!$vary = $this->headers->get('Vary', null, false)) {
  904. return array();
  905. }
  906. $ret = array();
  907. foreach ($vary as $item) {
  908. $ret = array_merge($ret, preg_split('/[\s,]+/', $item));
  909. }
  910. return $ret;
  911. }
  912. /**
  913. * Sets the Vary header.
  914. *
  915. * @param string|array $headers
  916. * @param bool $replace Whether to replace the actual value or not (true by default)
  917. *
  918. * @return $this
  919. *
  920. * @final
  921. */
  922. public function setVary($headers, bool $replace = true)
  923. {
  924. $this->headers->set('Vary', $headers, $replace);
  925. return $this;
  926. }
  927. /**
  928. * Determines if the Response validators (ETag, Last-Modified) match
  929. * a conditional value specified in the Request.
  930. *
  931. * If the Response is not modified, it sets the status code to 304 and
  932. * removes the actual content by calling the setNotModified() method.
  933. *
  934. * @return bool true if the Response validators match the Request, false otherwise
  935. *
  936. * @final
  937. */
  938. public function isNotModified(Request $request): bool
  939. {
  940. if (!$request->isMethodCacheable()) {
  941. return false;
  942. }
  943. $notModified = false;
  944. $lastModified = $this->headers->get('Last-Modified');
  945. $modifiedSince = $request->headers->get('If-Modified-Since');
  946. if ($etags = $request->getETags()) {
  947. $notModified = \in_array($this->getEtag(), $etags) || \in_array('*', $etags);
  948. }
  949. if ($modifiedSince && $lastModified) {
  950. $notModified = strtotime($modifiedSince) >= strtotime($lastModified) && (!$etags || $notModified);
  951. }
  952. if ($notModified) {
  953. $this->setNotModified();
  954. }
  955. return $notModified;
  956. }
  957. /**
  958. * Is response invalid?
  959. *
  960. * @see http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
  961. *
  962. * @final
  963. */
  964. public function isInvalid(): bool
  965. {
  966. return $this->statusCode < 100 || $this->statusCode >= 600;
  967. }
  968. /**
  969. * Is response informative?
  970. *
  971. * @final
  972. */
  973. public function isInformational(): bool
  974. {
  975. return $this->statusCode >= 100 && $this->statusCode < 200;
  976. }
  977. /**
  978. * Is response successful?
  979. *
  980. * @final
  981. */
  982. public function isSuccessful(): bool
  983. {
  984. return $this->statusCode >= 200 && $this->statusCode < 300;
  985. }
  986. /**
  987. * Is the response a redirect?
  988. *
  989. * @final
  990. */
  991. public function isRedirection(): bool
  992. {
  993. return $this->statusCode >= 300 && $this->statusCode < 400;
  994. }
  995. /**
  996. * Is there a client error?
  997. *
  998. * @final
  999. */
  1000. public function isClientError(): bool
  1001. {
  1002. return $this->statusCode >= 400 && $this->statusCode < 500;
  1003. }
  1004. /**
  1005. * Was there a server side error?
  1006. *
  1007. * @final
  1008. */
  1009. public function isServerError(): bool
  1010. {
  1011. return $this->statusCode >= 500 && $this->statusCode < 600;
  1012. }
  1013. /**
  1014. * Is the response OK?
  1015. *
  1016. * @final
  1017. */
  1018. public function isOk(): bool
  1019. {
  1020. return 200 === $this->statusCode;
  1021. }
  1022. /**
  1023. * Is the response forbidden?
  1024. *
  1025. * @final
  1026. */
  1027. public function isForbidden(): bool
  1028. {
  1029. return 403 === $this->statusCode;
  1030. }
  1031. /**
  1032. * Is the response a not found error?
  1033. *
  1034. * @final
  1035. */
  1036. public function isNotFound(): bool
  1037. {
  1038. return 404 === $this->statusCode;
  1039. }
  1040. /**
  1041. * Is the response a redirect of some form?
  1042. *
  1043. * @final
  1044. */
  1045. public function isRedirect(string $location = null): bool
  1046. {
  1047. return \in_array($this->statusCode, array(201, 301, 302, 303, 307, 308)) && (null === $location ?: $location == $this->headers->get('Location'));
  1048. }
  1049. /**
  1050. * Is the response empty?
  1051. *
  1052. * @final
  1053. */
  1054. public function isEmpty(): bool
  1055. {
  1056. return \in_array($this->statusCode, array(204, 304));
  1057. }
  1058. /**
  1059. * Cleans or flushes output buffers up to target level.
  1060. *
  1061. * Resulting level can be greater than target level if a non-removable buffer has been encountered.
  1062. *
  1063. * @final
  1064. */
  1065. public static function closeOutputBuffers(int $targetLevel, bool $flush)
  1066. {
  1067. $status = ob_get_status(true);
  1068. $level = \count($status);
  1069. $flags = PHP_OUTPUT_HANDLER_REMOVABLE | ($flush ? PHP_OUTPUT_HANDLER_FLUSHABLE : PHP_OUTPUT_HANDLER_CLEANABLE);
  1070. while ($level-- > $targetLevel && ($s = $status[$level]) && (!isset($s['del']) ? !isset($s['flags']) || ($s['flags'] & $flags) === $flags : $s['del'])) {
  1071. if ($flush) {
  1072. ob_end_flush();
  1073. } else {
  1074. ob_end_clean();
  1075. }
  1076. }
  1077. }
  1078. /**
  1079. * Checks if we need to remove Cache-Control for SSL encrypted downloads when using IE < 9.
  1080. *
  1081. * @see http://support.microsoft.com/kb/323308
  1082. *
  1083. * @final
  1084. */
  1085. protected function ensureIEOverSSLCompatibility(Request $request)
  1086. {
  1087. if (false !== stripos($this->headers->get('Content-Disposition'), 'attachment') && 1 == preg_match('/MSIE (.*?);/i', $request->server->get('HTTP_USER_AGENT'), $match) && true === $request->isSecure()) {
  1088. if ((int) preg_replace('/(MSIE )(.*?);/', '$2', $match[0]) < 9) {
  1089. $this->headers->remove('Cache-Control');
  1090. }
  1091. }
  1092. }
  1093. }