Response.php 37 KB

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