Response.php 36 KB

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