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