You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

1313 lines
38 KiB

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