Response.php 34 KB

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