Response.php 37 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307
  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. }
  198. /**
  199. * Factory method for chainability.
  200. *
  201. * Example:
  202. *
  203. * return Response::create($body, 200)
  204. * ->setSharedMaxAge(300);
  205. *
  206. * @param mixed $content The response content, see setContent()
  207. * @param int $status The response status code
  208. * @param array $headers An array of response headers
  209. *
  210. * @return static
  211. */
  212. public static function create($content = '', $status = 200, $headers = array())
  213. {
  214. return new static($content, $status, $headers);
  215. }
  216. /**
  217. * Returns the Response as an HTTP string.
  218. *
  219. * The string representation of the Response is the same as the
  220. * one that will be sent to the client only if the prepare() method
  221. * has been called before.
  222. *
  223. * @return string The Response as an HTTP string
  224. *
  225. * @see prepare()
  226. */
  227. public function __toString()
  228. {
  229. return
  230. sprintf('HTTP/%s %s %s', $this->version, $this->statusCode, $this->statusText)."\r\n".
  231. $this->headers."\r\n".
  232. $this->getContent();
  233. }
  234. /**
  235. * Clones the current Response instance.
  236. */
  237. public function __clone()
  238. {
  239. $this->headers = clone $this->headers;
  240. }
  241. /**
  242. * Prepares the Response before it is sent to the client.
  243. *
  244. * This method tweaks the Response to ensure that it is
  245. * compliant with RFC 2616. Most of the changes are based on
  246. * the Request that is "associated" with this Response.
  247. *
  248. * @return $this
  249. */
  250. public function prepare(Request $request)
  251. {
  252. $headers = $this->headers;
  253. if ($this->isInformational() || $this->isEmpty()) {
  254. $this->setContent(null);
  255. $headers->remove('Content-Type');
  256. $headers->remove('Content-Length');
  257. } else {
  258. // Content-type based on the Request
  259. if (!$headers->has('Content-Type')) {
  260. $format = $request->getRequestFormat();
  261. if (null !== $format && $mimeType = $request->getMimeType($format)) {
  262. $headers->set('Content-Type', $mimeType);
  263. }
  264. }
  265. // Fix Content-Type
  266. $charset = $this->charset ?: 'UTF-8';
  267. if (!$headers->has('Content-Type')) {
  268. $headers->set('Content-Type', 'text/html; charset='.$charset);
  269. } elseif (0 === stripos($headers->get('Content-Type'), 'text/') && false === stripos($headers->get('Content-Type'), 'charset')) {
  270. // add the charset
  271. $headers->set('Content-Type', $headers->get('Content-Type').'; charset='.$charset);
  272. }
  273. // Fix Content-Length
  274. if ($headers->has('Transfer-Encoding')) {
  275. $headers->remove('Content-Length');
  276. }
  277. if ($request->isMethod('HEAD')) {
  278. // cf. RFC2616 14.13
  279. $length = $headers->get('Content-Length');
  280. $this->setContent(null);
  281. if ($length) {
  282. $headers->set('Content-Length', $length);
  283. }
  284. }
  285. }
  286. // Fix protocol
  287. if ('HTTP/1.0' != $request->server->get('SERVER_PROTOCOL')) {
  288. $this->setProtocolVersion('1.1');
  289. }
  290. // Check if we need to send extra expire info headers
  291. if ('1.0' == $this->getProtocolVersion() && false !== strpos($this->headers->get('Cache-Control'), 'no-cache')) {
  292. $this->headers->set('pragma', 'no-cache');
  293. $this->headers->set('expires', -1);
  294. }
  295. $this->ensureIEOverSSLCompatibility($request);
  296. return $this;
  297. }
  298. /**
  299. * Sends HTTP headers.
  300. *
  301. * @return $this
  302. */
  303. public function sendHeaders()
  304. {
  305. // headers have already been sent by the developer
  306. if (headers_sent()) {
  307. return $this;
  308. }
  309. // headers
  310. foreach ($this->headers->allPreserveCaseWithoutCookies() as $name => $values) {
  311. foreach ($values as $value) {
  312. header($name.': '.$value, false, $this->statusCode);
  313. }
  314. }
  315. // cookies
  316. foreach ($this->headers->getCookies() as $cookie) {
  317. header('Set-Cookie: '.$cookie->getName().strstr($cookie, '='), false, $this->statusCode);
  318. }
  319. // status
  320. header(sprintf('HTTP/%s %s %s', $this->version, $this->statusCode, $this->statusText), true, $this->statusCode);
  321. return $this;
  322. }
  323. /**
  324. * Sends content for the current web response.
  325. *
  326. * @return $this
  327. */
  328. public function sendContent()
  329. {
  330. echo $this->content;
  331. return $this;
  332. }
  333. /**
  334. * Sends HTTP headers and content.
  335. *
  336. * @return $this
  337. */
  338. public function send()
  339. {
  340. $this->sendHeaders();
  341. $this->sendContent();
  342. if (\function_exists('fastcgi_finish_request')) {
  343. fastcgi_finish_request();
  344. } elseif (!\in_array(\PHP_SAPI, array('cli', 'phpdbg'), true)) {
  345. static::closeOutputBuffers(0, true);
  346. }
  347. return $this;
  348. }
  349. /**
  350. * Sets the response content.
  351. *
  352. * Valid types are strings, numbers, null, and objects that implement a __toString() method.
  353. *
  354. * @param mixed $content Content that can be cast to string
  355. *
  356. * @return $this
  357. *
  358. * @throws \UnexpectedValueException
  359. */
  360. public function setContent($content)
  361. {
  362. if (null !== $content && !\is_string($content) && !is_numeric($content) && !\is_callable(array($content, '__toString'))) {
  363. throw new \UnexpectedValueException(sprintf('The Response content must be a string or object implementing __toString(), "%s" given.', \gettype($content)));
  364. }
  365. $this->content = (string) $content;
  366. return $this;
  367. }
  368. /**
  369. * Gets the current response content.
  370. *
  371. * @return string Content
  372. */
  373. public function getContent()
  374. {
  375. return $this->content;
  376. }
  377. /**
  378. * Sets the HTTP protocol version (1.0 or 1.1).
  379. *
  380. * @param string $version The HTTP protocol version
  381. *
  382. * @return $this
  383. *
  384. * @final since version 3.2
  385. */
  386. public function setProtocolVersion($version)
  387. {
  388. $this->version = $version;
  389. return $this;
  390. }
  391. /**
  392. * Gets the HTTP protocol version.
  393. *
  394. * @return string The HTTP protocol version
  395. *
  396. * @final since version 3.2
  397. */
  398. public function getProtocolVersion()
  399. {
  400. return $this->version;
  401. }
  402. /**
  403. * Sets the response status code.
  404. *
  405. * If the status text is null it will be automatically populated for the known
  406. * status codes and left empty otherwise.
  407. *
  408. * @param int $code HTTP status code
  409. * @param mixed $text HTTP status text
  410. *
  411. * @return $this
  412. *
  413. * @throws \InvalidArgumentException When the HTTP status code is not valid
  414. *
  415. * @final since version 3.2
  416. */
  417. public function setStatusCode($code, $text = null)
  418. {
  419. $this->statusCode = $code = (int) $code;
  420. if ($this->isInvalid()) {
  421. throw new \InvalidArgumentException(sprintf('The HTTP status code "%s" is not valid.', $code));
  422. }
  423. if (null === $text) {
  424. $this->statusText = isset(self::$statusTexts[$code]) ? self::$statusTexts[$code] : 'unknown status';
  425. return $this;
  426. }
  427. if (false === $text) {
  428. $this->statusText = '';
  429. return $this;
  430. }
  431. $this->statusText = $text;
  432. return $this;
  433. }
  434. /**
  435. * Retrieves the status code for the current web response.
  436. *
  437. * @return int Status code
  438. *
  439. * @final since version 3.2
  440. */
  441. public function getStatusCode()
  442. {
  443. return $this->statusCode;
  444. }
  445. /**
  446. * Sets the response charset.
  447. *
  448. * @param string $charset Character set
  449. *
  450. * @return $this
  451. *
  452. * @final since version 3.2
  453. */
  454. public function setCharset($charset)
  455. {
  456. $this->charset = $charset;
  457. return $this;
  458. }
  459. /**
  460. * Retrieves the response charset.
  461. *
  462. * @return string Character set
  463. *
  464. * @final since version 3.2
  465. */
  466. public function getCharset()
  467. {
  468. return $this->charset;
  469. }
  470. /**
  471. * Returns true if the response may safely be kept in a shared (surrogate) cache.
  472. *
  473. * Responses marked "private" with an explicit Cache-Control directive are
  474. * considered uncacheable.
  475. *
  476. * Responses with neither a freshness lifetime (Expires, max-age) nor cache
  477. * validator (Last-Modified, ETag) are considered uncacheable because there is
  478. * no way to tell when or how to remove them from the cache.
  479. *
  480. * Note that RFC 7231 and RFC 7234 possibly allow for a more permissive implementation,
  481. * for example "status codes that are defined as cacheable by default [...]
  482. * can be reused by a cache with heuristic expiration unless otherwise indicated"
  483. * (https://tools.ietf.org/html/rfc7231#section-6.1)
  484. *
  485. * @return bool true if the response is worth caching, false otherwise
  486. *
  487. * @final since version 3.3
  488. */
  489. public function isCacheable()
  490. {
  491. if (!\in_array($this->statusCode, array(200, 203, 300, 301, 302, 404, 410))) {
  492. return false;
  493. }
  494. if ($this->headers->hasCacheControlDirective('no-store') || $this->headers->getCacheControlDirective('private')) {
  495. return false;
  496. }
  497. return $this->isValidateable() || $this->isFresh();
  498. }
  499. /**
  500. * Returns true if the response is "fresh".
  501. *
  502. * Fresh responses may be served from cache without any interaction with the
  503. * origin. A response is considered fresh when it includes a Cache-Control/max-age
  504. * indicator or Expires header and the calculated age is less than the freshness lifetime.
  505. *
  506. * @return bool true if the response is fresh, false otherwise
  507. *
  508. * @final since version 3.3
  509. */
  510. public function isFresh()
  511. {
  512. return $this->getTtl() > 0;
  513. }
  514. /**
  515. * Returns true if the response includes headers that can be used to validate
  516. * the response with the origin server using a conditional GET request.
  517. *
  518. * @return bool true if the response is validateable, false otherwise
  519. *
  520. * @final since version 3.3
  521. */
  522. public function isValidateable()
  523. {
  524. return $this->headers->has('Last-Modified') || $this->headers->has('ETag');
  525. }
  526. /**
  527. * Marks the response as "private".
  528. *
  529. * It makes the response ineligible for serving other clients.
  530. *
  531. * @return $this
  532. *
  533. * @final since version 3.2
  534. */
  535. public function setPrivate()
  536. {
  537. $this->headers->removeCacheControlDirective('public');
  538. $this->headers->addCacheControlDirective('private');
  539. return $this;
  540. }
  541. /**
  542. * Marks the response as "public".
  543. *
  544. * It makes the response eligible for serving other clients.
  545. *
  546. * @return $this
  547. *
  548. * @final since version 3.2
  549. */
  550. public function setPublic()
  551. {
  552. $this->headers->addCacheControlDirective('public');
  553. $this->headers->removeCacheControlDirective('private');
  554. return $this;
  555. }
  556. /**
  557. * Marks the response as "immutable".
  558. *
  559. * @param bool $immutable enables or disables the immutable directive
  560. *
  561. * @return $this
  562. *
  563. * @final
  564. */
  565. public function setImmutable($immutable = true)
  566. {
  567. if ($immutable) {
  568. $this->headers->addCacheControlDirective('immutable');
  569. } else {
  570. $this->headers->removeCacheControlDirective('immutable');
  571. }
  572. return $this;
  573. }
  574. /**
  575. * Returns true if the response is marked as "immutable".
  576. *
  577. * @return bool returns true if the response is marked as "immutable"; otherwise false
  578. *
  579. * @final
  580. */
  581. public function isImmutable()
  582. {
  583. return $this->headers->hasCacheControlDirective('immutable');
  584. }
  585. /**
  586. * Returns true if the response must be revalidated by caches.
  587. *
  588. * This method indicates that the response must not be served stale by a
  589. * cache in any circumstance without first revalidating with the origin.
  590. * When present, the TTL of the response should not be overridden to be
  591. * greater than the value provided by the origin.
  592. *
  593. * @return bool true if the response must be revalidated by a cache, false otherwise
  594. *
  595. * @final since version 3.3
  596. */
  597. public function mustRevalidate()
  598. {
  599. return $this->headers->hasCacheControlDirective('must-revalidate') || $this->headers->hasCacheControlDirective('proxy-revalidate');
  600. }
  601. /**
  602. * Returns the Date header as a DateTime instance.
  603. *
  604. * @return \DateTime A \DateTime instance
  605. *
  606. * @throws \RuntimeException When the header is not parseable
  607. *
  608. * @final since version 3.2
  609. */
  610. public function getDate()
  611. {
  612. return $this->headers->getDate('Date');
  613. }
  614. /**
  615. * Sets the Date header.
  616. *
  617. * @return $this
  618. *
  619. * @final since version 3.2
  620. */
  621. public function setDate(\DateTime $date)
  622. {
  623. $date->setTimezone(new \DateTimeZone('UTC'));
  624. $this->headers->set('Date', $date->format('D, d M Y H:i:s').' GMT');
  625. return $this;
  626. }
  627. /**
  628. * Returns the age of the response.
  629. *
  630. * @return int The age of the response in seconds
  631. *
  632. * @final since version 3.2
  633. */
  634. public function getAge()
  635. {
  636. if (null !== $age = $this->headers->get('Age')) {
  637. return (int) $age;
  638. }
  639. return max(time() - $this->getDate()->format('U'), 0);
  640. }
  641. /**
  642. * Marks the response stale by setting the Age header to be equal to the maximum age of the response.
  643. *
  644. * @return $this
  645. */
  646. public function expire()
  647. {
  648. if ($this->isFresh()) {
  649. $this->headers->set('Age', $this->getMaxAge());
  650. $this->headers->remove('Expires');
  651. }
  652. return $this;
  653. }
  654. /**
  655. * Returns the value of the Expires header as a DateTime instance.
  656. *
  657. * @return \DateTime|null A DateTime instance or null if the header does not exist
  658. *
  659. * @final since version 3.2
  660. */
  661. public function getExpires()
  662. {
  663. try {
  664. return $this->headers->getDate('Expires');
  665. } catch (\RuntimeException $e) {
  666. // according to RFC 2616 invalid date formats (e.g. "0" and "-1") must be treated as in the past
  667. return \DateTime::createFromFormat(DATE_RFC2822, 'Sat, 01 Jan 00 00:00:00 +0000');
  668. }
  669. }
  670. /**
  671. * Sets the Expires HTTP header with a DateTime instance.
  672. *
  673. * Passing null as value will remove the header.
  674. *
  675. * @param \DateTime|null $date A \DateTime instance or null to remove the header
  676. *
  677. * @return $this
  678. *
  679. * @final since version 3.2
  680. */
  681. public function setExpires(\DateTime $date = null)
  682. {
  683. if (null === $date) {
  684. $this->headers->remove('Expires');
  685. } else {
  686. $date = clone $date;
  687. $date->setTimezone(new \DateTimeZone('UTC'));
  688. $this->headers->set('Expires', $date->format('D, d M Y H:i:s').' GMT');
  689. }
  690. return $this;
  691. }
  692. /**
  693. * Returns the number of seconds after the time specified in the response's Date
  694. * header when the response should no longer be considered fresh.
  695. *
  696. * First, it checks for a s-maxage directive, then a max-age directive, and then it falls
  697. * back on an expires header. It returns null when no maximum age can be established.
  698. *
  699. * @return int|null Number of seconds
  700. *
  701. * @final since version 3.2
  702. */
  703. public function getMaxAge()
  704. {
  705. if ($this->headers->hasCacheControlDirective('s-maxage')) {
  706. return (int) $this->headers->getCacheControlDirective('s-maxage');
  707. }
  708. if ($this->headers->hasCacheControlDirective('max-age')) {
  709. return (int) $this->headers->getCacheControlDirective('max-age');
  710. }
  711. if (null !== $this->getExpires()) {
  712. return $this->getExpires()->format('U') - $this->getDate()->format('U');
  713. }
  714. }
  715. /**
  716. * Sets the number of seconds after which the response should no longer be considered fresh.
  717. *
  718. * This methods sets the Cache-Control max-age directive.
  719. *
  720. * @param int $value Number of seconds
  721. *
  722. * @return $this
  723. *
  724. * @final since version 3.2
  725. */
  726. public function setMaxAge($value)
  727. {
  728. $this->headers->addCacheControlDirective('max-age', $value);
  729. return $this;
  730. }
  731. /**
  732. * Sets the number of seconds after which the response should no longer be considered fresh by shared caches.
  733. *
  734. * This methods sets the Cache-Control s-maxage directive.
  735. *
  736. * @param int $value Number of seconds
  737. *
  738. * @return $this
  739. *
  740. * @final since version 3.2
  741. */
  742. public function setSharedMaxAge($value)
  743. {
  744. $this->setPublic();
  745. $this->headers->addCacheControlDirective('s-maxage', $value);
  746. return $this;
  747. }
  748. /**
  749. * Returns the response's time-to-live in seconds.
  750. *
  751. * It returns null when no freshness information is present in the response.
  752. *
  753. * When the responses TTL is <= 0, the response may not be served from cache without first
  754. * revalidating with the origin.
  755. *
  756. * @return int|null The TTL in seconds
  757. *
  758. * @final since version 3.2
  759. */
  760. public function getTtl()
  761. {
  762. if (null !== $maxAge = $this->getMaxAge()) {
  763. return $maxAge - $this->getAge();
  764. }
  765. }
  766. /**
  767. * Sets the response's time-to-live for shared caches.
  768. *
  769. * This method adjusts the Cache-Control/s-maxage directive.
  770. *
  771. * @param int $seconds Number of seconds
  772. *
  773. * @return $this
  774. *
  775. * @final since version 3.2
  776. */
  777. public function setTtl($seconds)
  778. {
  779. $this->setSharedMaxAge($this->getAge() + $seconds);
  780. return $this;
  781. }
  782. /**
  783. * Sets the response's time-to-live for private/client caches.
  784. *
  785. * This method adjusts the Cache-Control/max-age directive.
  786. *
  787. * @param int $seconds Number of seconds
  788. *
  789. * @return $this
  790. *
  791. * @final since version 3.2
  792. */
  793. public function setClientTtl($seconds)
  794. {
  795. $this->setMaxAge($this->getAge() + $seconds);
  796. return $this;
  797. }
  798. /**
  799. * Returns the Last-Modified HTTP header as a DateTime instance.
  800. *
  801. * @return \DateTime|null A DateTime instance or null if the header does not exist
  802. *
  803. * @throws \RuntimeException When the HTTP header is not parseable
  804. *
  805. * @final since version 3.2
  806. */
  807. public function getLastModified()
  808. {
  809. return $this->headers->getDate('Last-Modified');
  810. }
  811. /**
  812. * Sets the Last-Modified HTTP header with a DateTime instance.
  813. *
  814. * Passing null as value will remove the header.
  815. *
  816. * @param \DateTime|null $date A \DateTime instance or null to remove the header
  817. *
  818. * @return $this
  819. *
  820. * @final since version 3.2
  821. */
  822. public function setLastModified(\DateTime $date = null)
  823. {
  824. if (null === $date) {
  825. $this->headers->remove('Last-Modified');
  826. } else {
  827. $date = clone $date;
  828. $date->setTimezone(new \DateTimeZone('UTC'));
  829. $this->headers->set('Last-Modified', $date->format('D, d M Y H:i:s').' GMT');
  830. }
  831. return $this;
  832. }
  833. /**
  834. * Returns the literal value of the ETag HTTP header.
  835. *
  836. * @return string|null The ETag HTTP header or null if it does not exist
  837. *
  838. * @final since version 3.2
  839. */
  840. public function getEtag()
  841. {
  842. return $this->headers->get('ETag');
  843. }
  844. /**
  845. * Sets the ETag value.
  846. *
  847. * @param string|null $etag The ETag unique identifier or null to remove the header
  848. * @param bool $weak Whether you want a weak ETag or not
  849. *
  850. * @return $this
  851. *
  852. * @final since version 3.2
  853. */
  854. public function setEtag($etag = null, $weak = false)
  855. {
  856. if (null === $etag) {
  857. $this->headers->remove('Etag');
  858. } else {
  859. if (0 !== strpos($etag, '"')) {
  860. $etag = '"'.$etag.'"';
  861. }
  862. $this->headers->set('ETag', (true === $weak ? 'W/' : '').$etag);
  863. }
  864. return $this;
  865. }
  866. /**
  867. * Sets the response's cache headers (validation and/or expiration).
  868. *
  869. * Available options are: etag, last_modified, max_age, s_maxage, private, public and immutable.
  870. *
  871. * @param array $options An array of cache options
  872. *
  873. * @return $this
  874. *
  875. * @throws \InvalidArgumentException
  876. *
  877. * @final since version 3.3
  878. */
  879. public function setCache(array $options)
  880. {
  881. if ($diff = array_diff(array_keys($options), array('etag', 'last_modified', 'max_age', 's_maxage', 'private', 'public', 'immutable'))) {
  882. throw new \InvalidArgumentException(sprintf('Response does not support the following options: "%s".', implode('", "', array_values($diff))));
  883. }
  884. if (isset($options['etag'])) {
  885. $this->setEtag($options['etag']);
  886. }
  887. if (isset($options['last_modified'])) {
  888. $this->setLastModified($options['last_modified']);
  889. }
  890. if (isset($options['max_age'])) {
  891. $this->setMaxAge($options['max_age']);
  892. }
  893. if (isset($options['s_maxage'])) {
  894. $this->setSharedMaxAge($options['s_maxage']);
  895. }
  896. if (isset($options['public'])) {
  897. if ($options['public']) {
  898. $this->setPublic();
  899. } else {
  900. $this->setPrivate();
  901. }
  902. }
  903. if (isset($options['private'])) {
  904. if ($options['private']) {
  905. $this->setPrivate();
  906. } else {
  907. $this->setPublic();
  908. }
  909. }
  910. if (isset($options['immutable'])) {
  911. $this->setImmutable((bool) $options['immutable']);
  912. }
  913. return $this;
  914. }
  915. /**
  916. * Modifies the response so that it conforms to the rules defined for a 304 status code.
  917. *
  918. * This sets the status, removes the body, and discards any headers
  919. * that MUST NOT be included in 304 responses.
  920. *
  921. * @return $this
  922. *
  923. * @see http://tools.ietf.org/html/rfc2616#section-10.3.5
  924. *
  925. * @final since version 3.3
  926. */
  927. public function setNotModified()
  928. {
  929. $this->setStatusCode(304);
  930. $this->setContent(null);
  931. // remove headers that MUST NOT be included with 304 Not Modified responses
  932. foreach (array('Allow', 'Content-Encoding', 'Content-Language', 'Content-Length', 'Content-MD5', 'Content-Type', 'Last-Modified') as $header) {
  933. $this->headers->remove($header);
  934. }
  935. return $this;
  936. }
  937. /**
  938. * Returns true if the response includes a Vary header.
  939. *
  940. * @return bool true if the response includes a Vary header, false otherwise
  941. *
  942. * @final since version 3.2
  943. */
  944. public function hasVary()
  945. {
  946. return null !== $this->headers->get('Vary');
  947. }
  948. /**
  949. * Returns an array of header names given in the Vary header.
  950. *
  951. * @return array An array of Vary names
  952. *
  953. * @final since version 3.2
  954. */
  955. public function getVary()
  956. {
  957. if (!$vary = $this->headers->get('Vary', null, false)) {
  958. return array();
  959. }
  960. $ret = array();
  961. foreach ($vary as $item) {
  962. $ret = array_merge($ret, preg_split('/[\s,]+/', $item));
  963. }
  964. return $ret;
  965. }
  966. /**
  967. * Sets the Vary header.
  968. *
  969. * @param string|array $headers
  970. * @param bool $replace Whether to replace the actual value or not (true by default)
  971. *
  972. * @return $this
  973. *
  974. * @final since version 3.2
  975. */
  976. public function setVary($headers, $replace = true)
  977. {
  978. $this->headers->set('Vary', $headers, $replace);
  979. return $this;
  980. }
  981. /**
  982. * Determines if the Response validators (ETag, Last-Modified) match
  983. * a conditional value specified in the Request.
  984. *
  985. * If the Response is not modified, it sets the status code to 304 and
  986. * removes the actual content by calling the setNotModified() method.
  987. *
  988. * @return bool true if the Response validators match the Request, false otherwise
  989. *
  990. * @final since version 3.3
  991. */
  992. public function isNotModified(Request $request)
  993. {
  994. if (!$request->isMethodCacheable()) {
  995. return false;
  996. }
  997. $notModified = false;
  998. $lastModified = $this->headers->get('Last-Modified');
  999. $modifiedSince = $request->headers->get('If-Modified-Since');
  1000. if ($etags = $request->getETags()) {
  1001. $notModified = \in_array($this->getEtag(), $etags) || \in_array('*', $etags);
  1002. }
  1003. if ($modifiedSince && $lastModified) {
  1004. $notModified = strtotime($modifiedSince) >= strtotime($lastModified) && (!$etags || $notModified);
  1005. }
  1006. if ($notModified) {
  1007. $this->setNotModified();
  1008. }
  1009. return $notModified;
  1010. }
  1011. /**
  1012. * Is response invalid?
  1013. *
  1014. * @return bool
  1015. *
  1016. * @see http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
  1017. *
  1018. * @final since version 3.2
  1019. */
  1020. public function isInvalid()
  1021. {
  1022. return $this->statusCode < 100 || $this->statusCode >= 600;
  1023. }
  1024. /**
  1025. * Is response informative?
  1026. *
  1027. * @return bool
  1028. *
  1029. * @final since version 3.3
  1030. */
  1031. public function isInformational()
  1032. {
  1033. return $this->statusCode >= 100 && $this->statusCode < 200;
  1034. }
  1035. /**
  1036. * Is response successful?
  1037. *
  1038. * @return bool
  1039. *
  1040. * @final since version 3.2
  1041. */
  1042. public function isSuccessful()
  1043. {
  1044. return $this->statusCode >= 200 && $this->statusCode < 300;
  1045. }
  1046. /**
  1047. * Is the response a redirect?
  1048. *
  1049. * @return bool
  1050. *
  1051. * @final since version 3.2
  1052. */
  1053. public function isRedirection()
  1054. {
  1055. return $this->statusCode >= 300 && $this->statusCode < 400;
  1056. }
  1057. /**
  1058. * Is there a client error?
  1059. *
  1060. * @return bool
  1061. *
  1062. * @final since version 3.2
  1063. */
  1064. public function isClientError()
  1065. {
  1066. return $this->statusCode >= 400 && $this->statusCode < 500;
  1067. }
  1068. /**
  1069. * Was there a server side error?
  1070. *
  1071. * @return bool
  1072. *
  1073. * @final since version 3.3
  1074. */
  1075. public function isServerError()
  1076. {
  1077. return $this->statusCode >= 500 && $this->statusCode < 600;
  1078. }
  1079. /**
  1080. * Is the response OK?
  1081. *
  1082. * @return bool
  1083. *
  1084. * @final since version 3.2
  1085. */
  1086. public function isOk()
  1087. {
  1088. return 200 === $this->statusCode;
  1089. }
  1090. /**
  1091. * Is the response forbidden?
  1092. *
  1093. * @return bool
  1094. *
  1095. * @final since version 3.2
  1096. */
  1097. public function isForbidden()
  1098. {
  1099. return 403 === $this->statusCode;
  1100. }
  1101. /**
  1102. * Is the response a not found error?
  1103. *
  1104. * @return bool
  1105. *
  1106. * @final since version 3.2
  1107. */
  1108. public function isNotFound()
  1109. {
  1110. return 404 === $this->statusCode;
  1111. }
  1112. /**
  1113. * Is the response a redirect of some form?
  1114. *
  1115. * @param string $location
  1116. *
  1117. * @return bool
  1118. *
  1119. * @final since version 3.2
  1120. */
  1121. public function isRedirect($location = null)
  1122. {
  1123. return \in_array($this->statusCode, array(201, 301, 302, 303, 307, 308)) && (null === $location ?: $location == $this->headers->get('Location'));
  1124. }
  1125. /**
  1126. * Is the response empty?
  1127. *
  1128. * @return bool
  1129. *
  1130. * @final since version 3.2
  1131. */
  1132. public function isEmpty()
  1133. {
  1134. return \in_array($this->statusCode, array(204, 304));
  1135. }
  1136. /**
  1137. * Cleans or flushes output buffers up to target level.
  1138. *
  1139. * Resulting level can be greater than target level if a non-removable buffer has been encountered.
  1140. *
  1141. * @param int $targetLevel The target output buffering level
  1142. * @param bool $flush Whether to flush or clean the buffers
  1143. *
  1144. * @final since version 3.3
  1145. */
  1146. public static function closeOutputBuffers($targetLevel, $flush)
  1147. {
  1148. $status = ob_get_status(true);
  1149. $level = \count($status);
  1150. // PHP_OUTPUT_HANDLER_* are not defined on HHVM 3.3
  1151. $flags = \defined('PHP_OUTPUT_HANDLER_REMOVABLE') ? PHP_OUTPUT_HANDLER_REMOVABLE | ($flush ? PHP_OUTPUT_HANDLER_FLUSHABLE : PHP_OUTPUT_HANDLER_CLEANABLE) : -1;
  1152. while ($level-- > $targetLevel && ($s = $status[$level]) && (!isset($s['del']) ? !isset($s['flags']) || ($s['flags'] & $flags) === $flags : $s['del'])) {
  1153. if ($flush) {
  1154. ob_end_flush();
  1155. } else {
  1156. ob_end_clean();
  1157. }
  1158. }
  1159. }
  1160. /**
  1161. * Checks if we need to remove Cache-Control for SSL encrypted downloads when using IE < 9.
  1162. *
  1163. * @see http://support.microsoft.com/kb/323308
  1164. *
  1165. * @final since version 3.3
  1166. */
  1167. protected function ensureIEOverSSLCompatibility(Request $request)
  1168. {
  1169. if (false !== stripos($this->headers->get('Content-Disposition'), 'attachment') && 1 == preg_match('/MSIE (.*?);/i', $request->server->get('HTTP_USER_AGENT'), $match) && true === $request->isSecure()) {
  1170. if ((int) preg_replace('/(MSIE )(.*?);/', '$2', $match[0]) < 9) {
  1171. $this->headers->remove('Cache-Control');
  1172. }
  1173. }
  1174. }
  1175. }