composer package updates
[openemr.git] / vendor / symfony / http-foundation / Response.php
blob9b4bb4cc53807582efe3268117a87492a45ddd37
1 <?php
3 /*
4 * This file is part of the Symfony package.
6 * (c) Fabien Potencier <fabien@symfony.com>
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
12 namespace Symfony\Component\HttpFoundation;
14 /**
15 * Response represents an HTTP response.
17 * @author Fabien Potencier <fabien@symfony.com>
19 class Response
21 const HTTP_CONTINUE = 100;
22 const HTTP_SWITCHING_PROTOCOLS = 101;
23 const HTTP_PROCESSING = 102; // RFC2518
24 const HTTP_EARLY_HINTS = 103; // RFC8297
25 const HTTP_OK = 200;
26 const HTTP_CREATED = 201;
27 const HTTP_ACCEPTED = 202;
28 const HTTP_NON_AUTHORITATIVE_INFORMATION = 203;
29 const HTTP_NO_CONTENT = 204;
30 const HTTP_RESET_CONTENT = 205;
31 const HTTP_PARTIAL_CONTENT = 206;
32 const HTTP_MULTI_STATUS = 207; // RFC4918
33 const HTTP_ALREADY_REPORTED = 208; // RFC5842
34 const HTTP_IM_USED = 226; // RFC3229
35 const HTTP_MULTIPLE_CHOICES = 300;
36 const HTTP_MOVED_PERMANENTLY = 301;
37 const HTTP_FOUND = 302;
38 const HTTP_SEE_OTHER = 303;
39 const HTTP_NOT_MODIFIED = 304;
40 const HTTP_USE_PROXY = 305;
41 const HTTP_RESERVED = 306;
42 const HTTP_TEMPORARY_REDIRECT = 307;
43 const HTTP_PERMANENTLY_REDIRECT = 308; // RFC7238
44 const HTTP_BAD_REQUEST = 400;
45 const HTTP_UNAUTHORIZED = 401;
46 const HTTP_PAYMENT_REQUIRED = 402;
47 const HTTP_FORBIDDEN = 403;
48 const HTTP_NOT_FOUND = 404;
49 const HTTP_METHOD_NOT_ALLOWED = 405;
50 const HTTP_NOT_ACCEPTABLE = 406;
51 const HTTP_PROXY_AUTHENTICATION_REQUIRED = 407;
52 const HTTP_REQUEST_TIMEOUT = 408;
53 const HTTP_CONFLICT = 409;
54 const HTTP_GONE = 410;
55 const HTTP_LENGTH_REQUIRED = 411;
56 const HTTP_PRECONDITION_FAILED = 412;
57 const HTTP_REQUEST_ENTITY_TOO_LARGE = 413;
58 const HTTP_REQUEST_URI_TOO_LONG = 414;
59 const HTTP_UNSUPPORTED_MEDIA_TYPE = 415;
60 const HTTP_REQUESTED_RANGE_NOT_SATISFIABLE = 416;
61 const HTTP_EXPECTATION_FAILED = 417;
62 const HTTP_I_AM_A_TEAPOT = 418; // RFC2324
63 const HTTP_MISDIRECTED_REQUEST = 421; // RFC7540
64 const HTTP_UNPROCESSABLE_ENTITY = 422; // RFC4918
65 const HTTP_LOCKED = 423; // RFC4918
66 const HTTP_FAILED_DEPENDENCY = 424; // RFC4918
67 const HTTP_RESERVED_FOR_WEBDAV_ADVANCED_COLLECTIONS_EXPIRED_PROPOSAL = 425; // RFC2817
68 const HTTP_UPGRADE_REQUIRED = 426; // RFC2817
69 const HTTP_PRECONDITION_REQUIRED = 428; // RFC6585
70 const HTTP_TOO_MANY_REQUESTS = 429; // RFC6585
71 const HTTP_REQUEST_HEADER_FIELDS_TOO_LARGE = 431; // RFC6585
72 const HTTP_UNAVAILABLE_FOR_LEGAL_REASONS = 451;
73 const HTTP_INTERNAL_SERVER_ERROR = 500;
74 const HTTP_NOT_IMPLEMENTED = 501;
75 const HTTP_BAD_GATEWAY = 502;
76 const HTTP_SERVICE_UNAVAILABLE = 503;
77 const HTTP_GATEWAY_TIMEOUT = 504;
78 const HTTP_VERSION_NOT_SUPPORTED = 505;
79 const HTTP_VARIANT_ALSO_NEGOTIATES_EXPERIMENTAL = 506; // RFC2295
80 const HTTP_INSUFFICIENT_STORAGE = 507; // RFC4918
81 const HTTP_LOOP_DETECTED = 508; // RFC5842
82 const HTTP_NOT_EXTENDED = 510; // RFC2774
83 const HTTP_NETWORK_AUTHENTICATION_REQUIRED = 511; // RFC6585
85 /**
86 * @var \Symfony\Component\HttpFoundation\ResponseHeaderBag
88 public $headers;
90 /**
91 * @var string
93 protected $content;
95 /**
96 * @var string
98 protected $version;
101 * @var int
103 protected $statusCode;
106 * @var string
108 protected $statusText;
111 * @var string
113 protected $charset;
116 * Status codes translation table.
118 * The list of codes is complete according to the
119 * {@link http://www.iana.org/assignments/http-status-codes/ Hypertext Transfer Protocol (HTTP) Status Code Registry}
120 * (last updated 2016-03-01).
122 * Unless otherwise noted, the status code is defined in RFC2616.
124 * @var array
126 public static $statusTexts = array(
127 100 => 'Continue',
128 101 => 'Switching Protocols',
129 102 => 'Processing', // RFC2518
130 103 => 'Early Hints',
131 200 => 'OK',
132 201 => 'Created',
133 202 => 'Accepted',
134 203 => 'Non-Authoritative Information',
135 204 => 'No Content',
136 205 => 'Reset Content',
137 206 => 'Partial Content',
138 207 => 'Multi-Status', // RFC4918
139 208 => 'Already Reported', // RFC5842
140 226 => 'IM Used', // RFC3229
141 300 => 'Multiple Choices',
142 301 => 'Moved Permanently',
143 302 => 'Found',
144 303 => 'See Other',
145 304 => 'Not Modified',
146 305 => 'Use Proxy',
147 307 => 'Temporary Redirect',
148 308 => 'Permanent Redirect', // RFC7238
149 400 => 'Bad Request',
150 401 => 'Unauthorized',
151 402 => 'Payment Required',
152 403 => 'Forbidden',
153 404 => 'Not Found',
154 405 => 'Method Not Allowed',
155 406 => 'Not Acceptable',
156 407 => 'Proxy Authentication Required',
157 408 => 'Request Timeout',
158 409 => 'Conflict',
159 410 => 'Gone',
160 411 => 'Length Required',
161 412 => 'Precondition Failed',
162 413 => 'Payload Too Large',
163 414 => 'URI Too Long',
164 415 => 'Unsupported Media Type',
165 416 => 'Range Not Satisfiable',
166 417 => 'Expectation Failed',
167 418 => 'I\'m a teapot', // RFC2324
168 421 => 'Misdirected Request', // RFC7540
169 422 => 'Unprocessable Entity', // RFC4918
170 423 => 'Locked', // RFC4918
171 424 => 'Failed Dependency', // RFC4918
172 425 => 'Reserved for WebDAV advanced collections expired proposal', // RFC2817
173 426 => 'Upgrade Required', // RFC2817
174 428 => 'Precondition Required', // RFC6585
175 429 => 'Too Many Requests', // RFC6585
176 431 => 'Request Header Fields Too Large', // RFC6585
177 451 => 'Unavailable For Legal Reasons', // RFC7725
178 500 => 'Internal Server Error',
179 501 => 'Not Implemented',
180 502 => 'Bad Gateway',
181 503 => 'Service Unavailable',
182 504 => 'Gateway Timeout',
183 505 => 'HTTP Version Not Supported',
184 506 => 'Variant Also Negotiates', // RFC2295
185 507 => 'Insufficient Storage', // RFC4918
186 508 => 'Loop Detected', // RFC5842
187 510 => 'Not Extended', // RFC2774
188 511 => 'Network Authentication Required', // RFC6585
192 * @param mixed $content The response content, see setContent()
193 * @param int $status The response status code
194 * @param array $headers An array of response headers
196 * @throws \InvalidArgumentException When the HTTP status code is not valid
198 public function __construct($content = '', $status = 200, $headers = array())
200 $this->headers = new ResponseHeaderBag($headers);
201 $this->setContent($content);
202 $this->setStatusCode($status);
203 $this->setProtocolVersion('1.0');
205 /* RFC2616 - 14.18 says all Responses need to have a Date */
206 if (!$this->headers->has('Date')) {
207 $this->setDate(\DateTime::createFromFormat('U', time()));
212 * Factory method for chainability.
214 * Example:
216 * return Response::create($body, 200)
217 * ->setSharedMaxAge(300);
219 * @param mixed $content The response content, see setContent()
220 * @param int $status The response status code
221 * @param array $headers An array of response headers
223 * @return static
225 public static function create($content = '', $status = 200, $headers = array())
227 return new static($content, $status, $headers);
231 * Returns the Response as an HTTP string.
233 * The string representation of the Response is the same as the
234 * one that will be sent to the client only if the prepare() method
235 * has been called before.
237 * @return string The Response as an HTTP string
239 * @see prepare()
241 public function __toString()
243 return
244 sprintf('HTTP/%s %s %s', $this->version, $this->statusCode, $this->statusText)."\r\n".
245 $this->headers."\r\n".
246 $this->getContent();
250 * Clones the current Response instance.
252 public function __clone()
254 $this->headers = clone $this->headers;
258 * Prepares the Response before it is sent to the client.
260 * This method tweaks the Response to ensure that it is
261 * compliant with RFC 2616. Most of the changes are based on
262 * the Request that is "associated" with this Response.
264 * @return $this
266 public function prepare(Request $request)
268 $headers = $this->headers;
270 if ($this->isInformational() || $this->isEmpty()) {
271 $this->setContent(null);
272 $headers->remove('Content-Type');
273 $headers->remove('Content-Length');
274 } else {
275 // Content-type based on the Request
276 if (!$headers->has('Content-Type')) {
277 $format = $request->getRequestFormat();
278 if (null !== $format && $mimeType = $request->getMimeType($format)) {
279 $headers->set('Content-Type', $mimeType);
283 // Fix Content-Type
284 $charset = $this->charset ?: 'UTF-8';
285 if (!$headers->has('Content-Type')) {
286 $headers->set('Content-Type', 'text/html; charset='.$charset);
287 } elseif (0 === stripos($headers->get('Content-Type'), 'text/') && false === stripos($headers->get('Content-Type'), 'charset')) {
288 // add the charset
289 $headers->set('Content-Type', $headers->get('Content-Type').'; charset='.$charset);
292 // Fix Content-Length
293 if ($headers->has('Transfer-Encoding')) {
294 $headers->remove('Content-Length');
297 if ($request->isMethod('HEAD')) {
298 // cf. RFC2616 14.13
299 $length = $headers->get('Content-Length');
300 $this->setContent(null);
301 if ($length) {
302 $headers->set('Content-Length', $length);
307 // Fix protocol
308 if ('HTTP/1.0' != $request->server->get('SERVER_PROTOCOL')) {
309 $this->setProtocolVersion('1.1');
312 // Check if we need to send extra expire info headers
313 if ('1.0' == $this->getProtocolVersion() && 'no-cache' == $this->headers->get('Cache-Control')) {
314 $this->headers->set('pragma', 'no-cache');
315 $this->headers->set('expires', -1);
318 $this->ensureIEOverSSLCompatibility($request);
320 return $this;
324 * Sends HTTP headers.
326 * @return $this
328 public function sendHeaders()
330 // headers have already been sent by the developer
331 if (headers_sent()) {
332 return $this;
335 /* RFC2616 - 14.18 says all Responses need to have a Date */
336 if (!$this->headers->has('Date')) {
337 $this->setDate(\DateTime::createFromFormat('U', time()));
340 // headers
341 foreach ($this->headers->allPreserveCase() as $name => $values) {
342 foreach ($values as $value) {
343 header($name.': '.$value, false, $this->statusCode);
347 // status
348 header(sprintf('HTTP/%s %s %s', $this->version, $this->statusCode, $this->statusText), true, $this->statusCode);
350 // cookies
351 foreach ($this->headers->getCookies() as $cookie) {
352 setcookie($cookie->getName(), $cookie->getValue(), $cookie->getExpiresTime(), $cookie->getPath(), $cookie->getDomain(), $cookie->isSecure(), $cookie->isHttpOnly());
355 return $this;
359 * Sends content for the current web response.
361 * @return $this
363 public function sendContent()
365 echo $this->content;
367 return $this;
371 * Sends HTTP headers and content.
373 * @return $this
375 public function send()
377 $this->sendHeaders();
378 $this->sendContent();
380 if (function_exists('fastcgi_finish_request')) {
381 fastcgi_finish_request();
382 } elseif (!\in_array(PHP_SAPI, array('cli', 'phpdbg'), true)) {
383 static::closeOutputBuffers(0, true);
386 return $this;
390 * Sets the response content.
392 * Valid types are strings, numbers, null, and objects that implement a __toString() method.
394 * @param mixed $content Content that can be cast to string
396 * @return $this
398 * @throws \UnexpectedValueException
400 public function setContent($content)
402 if (null !== $content && !is_string($content) && !is_numeric($content) && !is_callable(array($content, '__toString'))) {
403 throw new \UnexpectedValueException(sprintf('The Response content must be a string or object implementing __toString(), "%s" given.', gettype($content)));
406 $this->content = (string) $content;
408 return $this;
412 * Gets the current response content.
414 * @return string Content
416 public function getContent()
418 return $this->content;
422 * Sets the HTTP protocol version (1.0 or 1.1).
424 * @param string $version The HTTP protocol version
426 * @return $this
428 public function setProtocolVersion($version)
430 $this->version = $version;
432 return $this;
436 * Gets the HTTP protocol version.
438 * @return string The HTTP protocol version
440 public function getProtocolVersion()
442 return $this->version;
446 * Sets the response status code.
448 * If the status text is null it will be automatically populated for the known
449 * status codes and left empty otherwise.
451 * @param int $code HTTP status code
452 * @param mixed $text HTTP status text
454 * @return $this
456 * @throws \InvalidArgumentException When the HTTP status code is not valid
458 public function setStatusCode($code, $text = null)
460 $this->statusCode = $code = (int) $code;
461 if ($this->isInvalid()) {
462 throw new \InvalidArgumentException(sprintf('The HTTP status code "%s" is not valid.', $code));
465 if (null === $text) {
466 $this->statusText = isset(self::$statusTexts[$code]) ? self::$statusTexts[$code] : 'unknown status';
468 return $this;
471 if (false === $text) {
472 $this->statusText = '';
474 return $this;
477 $this->statusText = $text;
479 return $this;
483 * Retrieves the status code for the current web response.
485 * @return int Status code
487 public function getStatusCode()
489 return $this->statusCode;
493 * Sets the response charset.
495 * @param string $charset Character set
497 * @return $this
499 public function setCharset($charset)
501 $this->charset = $charset;
503 return $this;
507 * Retrieves the response charset.
509 * @return string Character set
511 public function getCharset()
513 return $this->charset;
517 * Returns true if the response may safely be kept in a shared (surrogate) cache.
519 * Responses marked "private" with an explicit Cache-Control directive are
520 * considered uncacheable.
522 * Responses with neither a freshness lifetime (Expires, max-age) nor cache
523 * validator (Last-Modified, ETag) are considered uncacheable because there is
524 * no way to tell when or how to remove them from the cache.
526 * Note that RFC 7231 and RFC 7234 possibly allow for a more permissive implementation,
527 * for example "status codes that are defined as cacheable by default [...]
528 * can be reused by a cache with heuristic expiration unless otherwise indicated"
529 * (https://tools.ietf.org/html/rfc7231#section-6.1)
531 * @return bool true if the response is worth caching, false otherwise
533 public function isCacheable()
535 if (!in_array($this->statusCode, array(200, 203, 300, 301, 302, 404, 410))) {
536 return false;
539 if ($this->headers->hasCacheControlDirective('no-store') || $this->headers->getCacheControlDirective('private')) {
540 return false;
543 return $this->isValidateable() || $this->isFresh();
547 * Returns true if the response is "fresh".
549 * Fresh responses may be served from cache without any interaction with the
550 * origin. A response is considered fresh when it includes a Cache-Control/max-age
551 * indicator or Expires header and the calculated age is less than the freshness lifetime.
553 * @return bool true if the response is fresh, false otherwise
555 public function isFresh()
557 return $this->getTtl() > 0;
561 * Returns true if the response includes headers that can be used to validate
562 * the response with the origin server using a conditional GET request.
564 * @return bool true if the response is validateable, false otherwise
566 public function isValidateable()
568 return $this->headers->has('Last-Modified') || $this->headers->has('ETag');
572 * Marks the response as "private".
574 * It makes the response ineligible for serving other clients.
576 * @return $this
578 public function setPrivate()
580 $this->headers->removeCacheControlDirective('public');
581 $this->headers->addCacheControlDirective('private');
583 return $this;
587 * Marks the response as "public".
589 * It makes the response eligible for serving other clients.
591 * @return $this
593 public function setPublic()
595 $this->headers->addCacheControlDirective('public');
596 $this->headers->removeCacheControlDirective('private');
598 return $this;
602 * Returns true if the response must be revalidated by caches.
604 * This method indicates that the response must not be served stale by a
605 * cache in any circumstance without first revalidating with the origin.
606 * When present, the TTL of the response should not be overridden to be
607 * greater than the value provided by the origin.
609 * @return bool true if the response must be revalidated by a cache, false otherwise
611 public function mustRevalidate()
613 return $this->headers->hasCacheControlDirective('must-revalidate') || $this->headers->hasCacheControlDirective('proxy-revalidate');
617 * Returns the Date header as a DateTime instance.
619 * @return \DateTime A \DateTime instance
621 * @throws \RuntimeException When the header is not parseable
623 public function getDate()
626 RFC2616 - 14.18 says all Responses need to have a Date.
627 Make sure we provide one even if it the header
628 has been removed in the meantime.
630 if (!$this->headers->has('Date')) {
631 $this->setDate(\DateTime::createFromFormat('U', time()));
634 return $this->headers->getDate('Date');
638 * Sets the Date header.
640 * @return $this
642 public function setDate(\DateTime $date)
644 $date->setTimezone(new \DateTimeZone('UTC'));
645 $this->headers->set('Date', $date->format('D, d M Y H:i:s').' GMT');
647 return $this;
651 * Returns the age of the response.
653 * @return int The age of the response in seconds
655 public function getAge()
657 if (null !== $age = $this->headers->get('Age')) {
658 return (int) $age;
661 return max(time() - $this->getDate()->format('U'), 0);
665 * Marks the response stale by setting the Age header to be equal to the maximum age of the response.
667 * @return $this
669 public function expire()
671 if ($this->isFresh()) {
672 $this->headers->set('Age', $this->getMaxAge());
675 return $this;
679 * Returns the value of the Expires header as a DateTime instance.
681 * @return \DateTime|null A DateTime instance or null if the header does not exist
683 public function getExpires()
685 try {
686 return $this->headers->getDate('Expires');
687 } catch (\RuntimeException $e) {
688 // according to RFC 2616 invalid date formats (e.g. "0" and "-1") must be treated as in the past
689 return \DateTime::createFromFormat(DATE_RFC2822, 'Sat, 01 Jan 00 00:00:00 +0000');
694 * Sets the Expires HTTP header with a DateTime instance.
696 * Passing null as value will remove the header.
698 * @param \DateTime|null $date A \DateTime instance or null to remove the header
700 * @return $this
702 public function setExpires(\DateTime $date = null)
704 if (null === $date) {
705 $this->headers->remove('Expires');
706 } else {
707 $date = clone $date;
708 $date->setTimezone(new \DateTimeZone('UTC'));
709 $this->headers->set('Expires', $date->format('D, d M Y H:i:s').' GMT');
712 return $this;
716 * Returns the number of seconds after the time specified in the response's Date
717 * header when the response should no longer be considered fresh.
719 * First, it checks for a s-maxage directive, then a max-age directive, and then it falls
720 * back on an expires header. It returns null when no maximum age can be established.
722 * @return int|null Number of seconds
724 public function getMaxAge()
726 if ($this->headers->hasCacheControlDirective('s-maxage')) {
727 return (int) $this->headers->getCacheControlDirective('s-maxage');
730 if ($this->headers->hasCacheControlDirective('max-age')) {
731 return (int) $this->headers->getCacheControlDirective('max-age');
734 if (null !== $this->getExpires()) {
735 return $this->getExpires()->format('U') - $this->getDate()->format('U');
740 * Sets the number of seconds after which the response should no longer be considered fresh.
742 * This methods sets the Cache-Control max-age directive.
744 * @param int $value Number of seconds
746 * @return $this
748 public function setMaxAge($value)
750 $this->headers->addCacheControlDirective('max-age', $value);
752 return $this;
756 * Sets the number of seconds after which the response should no longer be considered fresh by shared caches.
758 * This methods sets the Cache-Control s-maxage directive.
760 * @param int $value Number of seconds
762 * @return $this
764 public function setSharedMaxAge($value)
766 $this->setPublic();
767 $this->headers->addCacheControlDirective('s-maxage', $value);
769 return $this;
773 * Returns the response's time-to-live in seconds.
775 * It returns null when no freshness information is present in the response.
777 * When the responses TTL is <= 0, the response may not be served from cache without first
778 * revalidating with the origin.
780 * @return int|null The TTL in seconds
782 public function getTtl()
784 if (null !== $maxAge = $this->getMaxAge()) {
785 return $maxAge - $this->getAge();
790 * Sets the response's time-to-live for shared caches.
792 * This method adjusts the Cache-Control/s-maxage directive.
794 * @param int $seconds Number of seconds
796 * @return $this
798 public function setTtl($seconds)
800 $this->setSharedMaxAge($this->getAge() + $seconds);
802 return $this;
806 * Sets the response's time-to-live for private/client caches.
808 * This method adjusts the Cache-Control/max-age directive.
810 * @param int $seconds Number of seconds
812 * @return $this
814 public function setClientTtl($seconds)
816 $this->setMaxAge($this->getAge() + $seconds);
818 return $this;
822 * Returns the Last-Modified HTTP header as a DateTime instance.
824 * @return \DateTime|null A DateTime instance or null if the header does not exist
826 * @throws \RuntimeException When the HTTP header is not parseable
828 public function getLastModified()
830 return $this->headers->getDate('Last-Modified');
834 * Sets the Last-Modified HTTP header with a DateTime instance.
836 * Passing null as value will remove the header.
838 * @param \DateTime|null $date A \DateTime instance or null to remove the header
840 * @return $this
842 public function setLastModified(\DateTime $date = null)
844 if (null === $date) {
845 $this->headers->remove('Last-Modified');
846 } else {
847 $date = clone $date;
848 $date->setTimezone(new \DateTimeZone('UTC'));
849 $this->headers->set('Last-Modified', $date->format('D, d M Y H:i:s').' GMT');
852 return $this;
856 * Returns the literal value of the ETag HTTP header.
858 * @return string|null The ETag HTTP header or null if it does not exist
860 public function getEtag()
862 return $this->headers->get('ETag');
866 * Sets the ETag value.
868 * @param string|null $etag The ETag unique identifier or null to remove the header
869 * @param bool $weak Whether you want a weak ETag or not
871 * @return $this
873 public function setEtag($etag = null, $weak = false)
875 if (null === $etag) {
876 $this->headers->remove('Etag');
877 } else {
878 if (0 !== strpos($etag, '"')) {
879 $etag = '"'.$etag.'"';
882 $this->headers->set('ETag', (true === $weak ? 'W/' : '').$etag);
885 return $this;
889 * Sets the response's cache headers (validation and/or expiration).
891 * Available options are: etag, last_modified, max_age, s_maxage, private, and public.
893 * @param array $options An array of cache options
895 * @return $this
897 * @throws \InvalidArgumentException
899 public function setCache(array $options)
901 if ($diff = array_diff(array_keys($options), array('etag', 'last_modified', 'max_age', 's_maxage', 'private', 'public'))) {
902 throw new \InvalidArgumentException(sprintf('Response does not support the following options: "%s".', implode('", "', array_values($diff))));
905 if (isset($options['etag'])) {
906 $this->setEtag($options['etag']);
909 if (isset($options['last_modified'])) {
910 $this->setLastModified($options['last_modified']);
913 if (isset($options['max_age'])) {
914 $this->setMaxAge($options['max_age']);
917 if (isset($options['s_maxage'])) {
918 $this->setSharedMaxAge($options['s_maxage']);
921 if (isset($options['public'])) {
922 if ($options['public']) {
923 $this->setPublic();
924 } else {
925 $this->setPrivate();
929 if (isset($options['private'])) {
930 if ($options['private']) {
931 $this->setPrivate();
932 } else {
933 $this->setPublic();
937 return $this;
941 * Modifies the response so that it conforms to the rules defined for a 304 status code.
943 * This sets the status, removes the body, and discards any headers
944 * that MUST NOT be included in 304 responses.
946 * @return $this
948 * @see http://tools.ietf.org/html/rfc2616#section-10.3.5
950 public function setNotModified()
952 $this->setStatusCode(304);
953 $this->setContent(null);
955 // remove headers that MUST NOT be included with 304 Not Modified responses
956 foreach (array('Allow', 'Content-Encoding', 'Content-Language', 'Content-Length', 'Content-MD5', 'Content-Type', 'Last-Modified') as $header) {
957 $this->headers->remove($header);
960 return $this;
964 * Returns true if the response includes a Vary header.
966 * @return bool true if the response includes a Vary header, false otherwise
968 public function hasVary()
970 return null !== $this->headers->get('Vary');
974 * Returns an array of header names given in the Vary header.
976 * @return array An array of Vary names
978 public function getVary()
980 if (!$vary = $this->headers->get('Vary', null, false)) {
981 return array();
984 $ret = array();
985 foreach ($vary as $item) {
986 $ret = array_merge($ret, preg_split('/[\s,]+/', $item));
989 return $ret;
993 * Sets the Vary header.
995 * @param string|array $headers
996 * @param bool $replace Whether to replace the actual value or not (true by default)
998 * @return $this
1000 public function setVary($headers, $replace = true)
1002 $this->headers->set('Vary', $headers, $replace);
1004 return $this;
1008 * Determines if the Response validators (ETag, Last-Modified) match
1009 * a conditional value specified in the Request.
1011 * If the Response is not modified, it sets the status code to 304 and
1012 * removes the actual content by calling the setNotModified() method.
1014 * @return bool true if the Response validators match the Request, false otherwise
1016 public function isNotModified(Request $request)
1018 if (!$request->isMethodCacheable()) {
1019 return false;
1022 $notModified = false;
1023 $lastModified = $this->headers->get('Last-Modified');
1024 $modifiedSince = $request->headers->get('If-Modified-Since');
1026 if ($etags = $request->getETags()) {
1027 $notModified = in_array($this->getEtag(), $etags) || in_array('*', $etags);
1030 if ($modifiedSince && $lastModified) {
1031 $notModified = strtotime($modifiedSince) >= strtotime($lastModified) && (!$etags || $notModified);
1034 if ($notModified) {
1035 $this->setNotModified();
1038 return $notModified;
1042 * Is response invalid?
1044 * @return bool
1046 * @see http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
1048 public function isInvalid()
1050 return $this->statusCode < 100 || $this->statusCode >= 600;
1054 * Is response informative?
1056 * @return bool
1058 public function isInformational()
1060 return $this->statusCode >= 100 && $this->statusCode < 200;
1064 * Is response successful?
1066 * @return bool
1068 public function isSuccessful()
1070 return $this->statusCode >= 200 && $this->statusCode < 300;
1074 * Is the response a redirect?
1076 * @return bool
1078 public function isRedirection()
1080 return $this->statusCode >= 300 && $this->statusCode < 400;
1084 * Is there a client error?
1086 * @return bool
1088 public function isClientError()
1090 return $this->statusCode >= 400 && $this->statusCode < 500;
1094 * Was there a server side error?
1096 * @return bool
1098 public function isServerError()
1100 return $this->statusCode >= 500 && $this->statusCode < 600;
1104 * Is the response OK?
1106 * @return bool
1108 public function isOk()
1110 return 200 === $this->statusCode;
1114 * Is the response forbidden?
1116 * @return bool
1118 public function isForbidden()
1120 return 403 === $this->statusCode;
1124 * Is the response a not found error?
1126 * @return bool
1128 public function isNotFound()
1130 return 404 === $this->statusCode;
1134 * Is the response a redirect of some form?
1136 * @param string $location
1138 * @return bool
1140 public function isRedirect($location = null)
1142 return in_array($this->statusCode, array(201, 301, 302, 303, 307, 308)) && (null === $location ?: $location == $this->headers->get('Location'));
1146 * Is the response empty?
1148 * @return bool
1150 public function isEmpty()
1152 return in_array($this->statusCode, array(204, 304));
1156 * Cleans or flushes output buffers up to target level.
1158 * Resulting level can be greater than target level if a non-removable buffer has been encountered.
1160 * @param int $targetLevel The target output buffering level
1161 * @param bool $flush Whether to flush or clean the buffers
1163 public static function closeOutputBuffers($targetLevel, $flush)
1165 $status = ob_get_status(true);
1166 $level = count($status);
1167 $flags = defined('PHP_OUTPUT_HANDLER_REMOVABLE') ? PHP_OUTPUT_HANDLER_REMOVABLE | ($flush ? PHP_OUTPUT_HANDLER_FLUSHABLE : PHP_OUTPUT_HANDLER_CLEANABLE) : -1;
1169 while ($level-- > $targetLevel && ($s = $status[$level]) && (!isset($s['del']) ? !isset($s['flags']) || ($s['flags'] & $flags) === $flags : $s['del'])) {
1170 if ($flush) {
1171 ob_end_flush();
1172 } else {
1173 ob_end_clean();
1179 * Checks if we need to remove Cache-Control for SSL encrypted downloads when using IE < 9.
1181 * @see http://support.microsoft.com/kb/323308
1183 protected function ensureIEOverSSLCompatibility(Request $request)
1185 if (false !== stripos($this->headers->get('Content-Disposition'), 'attachment') && 1 == preg_match('/MSIE (.*?);/i', $request->server->get('HTTP_USER_AGENT'), $match) && true === $request->isSecure()) {
1186 if ((int) preg_replace('/(MSIE )(.*?);/', '$2', $match[0]) < 9) {
1187 $this->headers->remove('Cache-Control');