Response.php 36 KB

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