Ampache PHP Cross Reference Groupware Applications

Source: /modules/Symfony/Component/HttpFoundation/Response.php - 1257 lines - 35706 bytes - Summary - Text - Print

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

title

Description

title

Description

title

Description

title

title

Body