Response.php 37 KB

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