Response.php 35 KB

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