HttpCache.php 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160
  1. <?php
  2. /**
  3. * @link http://www.yiiframework.com/
  4. * @copyright Copyright (c) 2008 Yii Software LLC
  5. * @license http://www.yiiframework.com/license/
  6. */
  7. namespace yii\web;
  8. use Yii;
  9. use yii\base\ActionFilter;
  10. use yii\base\Action;
  11. /**
  12. * The HttpCache provides functionality for caching via HTTP Last-Modified and Etag headers.
  13. *
  14. * It is an action filter that can be added to a controller and handles the `beforeAction` event.
  15. *
  16. * To use AccessControl, declare it in the `behaviors()` method of your controller class.
  17. * In the following example the filter will be applied to the `list`-action and
  18. * the Last-Modified header will contain the date of the last update to the user table in the database.
  19. *
  20. * ~~~
  21. * public function behaviors()
  22. * {
  23. * return [
  24. * 'httpCache' => [
  25. * 'class' => \yii\web\HttpCache::className(),
  26. * 'only' => ['list'],
  27. * 'lastModified' => function ($action, $params) {
  28. * $q = new Query();
  29. * return strtotime($q->from('users')->max('updated_timestamp'));
  30. * },
  31. * // 'etagSeed' => function ($action, $params) {
  32. * // return // generate etag seed here
  33. * // }
  34. * ],
  35. * ];
  36. * }
  37. * ~~~
  38. *
  39. * @author Da:Sourcerer <[email protected]>
  40. * @author Qiang Xue <[email protected]>
  41. * @since 2.0
  42. */
  43. class HttpCache extends ActionFilter
  44. {
  45. /**
  46. * @var callback a PHP callback that returns the UNIX timestamp of the last modification time.
  47. * The callback's signature should be:
  48. *
  49. * ~~~
  50. * function ($action, $params)
  51. * ~~~
  52. *
  53. * where `$action` is the [[Action]] object that this filter is currently handling;
  54. * `$params` takes the value of [[params]]. The callback should return a UNIX timestamp.
  55. */
  56. public $lastModified;
  57. /**
  58. * @var callback a PHP callback that generates the Etag seed string.
  59. * The callback's signature should be:
  60. *
  61. * ~~~
  62. * function ($action, $params)
  63. * ~~~
  64. *
  65. * where `$action` is the [[Action]] object that this filter is currently handling;
  66. * `$params` takes the value of [[params]]. The callback should return a string serving
  67. * as the seed for generating an Etag.
  68. */
  69. public $etagSeed;
  70. /**
  71. * @var mixed additional parameters that should be passed to the [[lastModified]] and [[etagSeed]] callbacks.
  72. */
  73. public $params;
  74. /**
  75. * @var string HTTP cache control header. If null, the header will not be sent.
  76. */
  77. public $cacheControlHeader = 'max-age=3600, public';
  78. /**
  79. * This method is invoked right before an action is to be executed (after all possible filters.)
  80. * You may override this method to do last-minute preparation for the action.
  81. * @param Action $action the action to be executed.
  82. * @return boolean whether the action should continue to be executed.
  83. */
  84. public function beforeAction($action)
  85. {
  86. $verb = Yii::$app->getRequest()->getMethod();
  87. if ($verb !== 'GET' && $verb !== 'HEAD' || $this->lastModified === null && $this->etagSeed === null) {
  88. return true;
  89. }
  90. $lastModified = $etag = null;
  91. if ($this->lastModified !== null) {
  92. $lastModified = call_user_func($this->lastModified, $action, $this->params);
  93. }
  94. if ($this->etagSeed !== null) {
  95. $seed = call_user_func($this->etagSeed, $action, $this->params);
  96. $etag = $this->generateEtag($seed);
  97. }
  98. $this->sendCacheControlHeader();
  99. $response = Yii::$app->getResponse();
  100. if ($etag !== null) {
  101. $response->getHeaders()->set('Etag', $etag);
  102. }
  103. if ($this->validateCache($lastModified, $etag)) {
  104. $response->setStatusCode(304);
  105. return false;
  106. }
  107. if ($lastModified !== null) {
  108. $response->getHeaders()->set('Last-Modified', gmdate('D, d M Y H:i:s', $lastModified) . ' GMT');
  109. }
  110. return true;
  111. }
  112. /**
  113. * Validates if the HTTP cache contains valid content.
  114. * @param integer $lastModified the calculated Last-Modified value in terms of a UNIX timestamp.
  115. * If null, the Last-Modified header will not be validated.
  116. * @param string $etag the calculated ETag value. If null, the ETag header will not be validated.
  117. * @return boolean whether the HTTP cache is still valid.
  118. */
  119. protected function validateCache($lastModified, $etag)
  120. {
  121. if ($lastModified !== null && (!isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) || @strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']) < $lastModified)) {
  122. return false;
  123. } else {
  124. return $etag === null || isset($_SERVER['HTTP_IF_NONE_MATCH']) && $_SERVER['HTTP_IF_NONE_MATCH'] === $etag;
  125. }
  126. }
  127. /**
  128. * Sends the cache control header to the client
  129. * @see cacheControl
  130. */
  131. protected function sendCacheControlHeader()
  132. {
  133. session_cache_limiter('public');
  134. $headers = Yii::$app->getResponse()->getHeaders();
  135. $headers->set('Pragma');
  136. if ($this->cacheControlHeader !== null) {
  137. $headers->set('Cache-Control', $this->cacheControlHeader);
  138. }
  139. }
  140. /**
  141. * Generates an Etag from the given seed string.
  142. * @param string $seed Seed for the ETag
  143. * @return string the generated Etag
  144. */
  145. protected function generateEtag($seed)
  146. {
  147. return '"' . base64_encode(sha1($seed, true)) . '"';
  148. }
  149. }