No Description

Response.php 35KB

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