Response.php 32 KB

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