Du kannst nicht mehr als 25 Themen auswählen Themen müssen entweder mit einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  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\caching;
  8. use Yii;
  9. use yii\helpers\FileHelper;
  10. /**
  11. * FileCache implements a cache component using files.
  12. *
  13. * For each data value being cached, FileCache will store it in a separate file.
  14. * The cache files are placed under [[cachePath]]. FileCache will perform garbage collection
  15. * automatically to remove expired cache files.
  16. *
  17. * Please refer to [[Cache]] for common cache operations that are supported by FileCache.
  18. *
  19. * @author Qiang Xue <qiang.xue@gmail.com>
  20. * @since 2.0
  21. */
  22. class FileCache extends Cache
  23. {
  24. /**
  25. * @var string a string prefixed to every cache key. This is needed when you store
  26. * cache data under the same [[cachePath]] for different applications to avoid
  27. * conflict.
  28. *
  29. * To ensure interoperability, only alphanumeric characters should be used.
  30. */
  31. public $keyPrefix = '';
  32. /**
  33. * @var string the directory to store cache files. You may use path alias here.
  34. * If not set, it will use the "cache" subdirectory under the application runtime path.
  35. */
  36. public $cachePath = '@runtime/cache';
  37. /**
  38. * @var string cache file suffix. Defaults to '.bin'.
  39. */
  40. public $cacheFileSuffix = '.bin';
  41. /**
  42. * @var integer the level of sub-directories to store cache files. Defaults to 1.
  43. * If the system has huge number of cache files (e.g. one million), you may use a bigger value
  44. * (usually no bigger than 3). Using sub-directories is mainly to ensure the file system
  45. * is not over burdened with a single directory having too many files.
  46. */
  47. public $directoryLevel = 1;
  48. /**
  49. * @var integer the probability (parts per million) that garbage collection (GC) should be performed
  50. * when storing a piece of data in the cache. Defaults to 10, meaning 0.001% chance.
  51. * This number should be between 0 and 1000000. A value 0 means no GC will be performed at all.
  52. */
  53. public $gcProbability = 10;
  54. /**
  55. * @var integer the permission to be set for newly created cache files.
  56. * This value will be used by PHP chmod() function. No umask will be applied.
  57. * If not set, the permission will be determined by the current environment.
  58. */
  59. public $fileMode;
  60. /**
  61. * @var integer the permission to be set for newly created directories.
  62. * This value will be used by PHP chmod() function. No umask will be applied.
  63. * Defaults to 0775, meaning the directory is read-writable by owner and group,
  64. * but read-only for other users.
  65. */
  66. public $dirMode = 0775;
  67. /**
  68. * Initializes this component by ensuring the existence of the cache path.
  69. */
  70. public function init()
  71. {
  72. parent::init();
  73. $this->cachePath = Yii::getAlias($this->cachePath);
  74. if (!is_dir($this->cachePath)) {
  75. FileHelper::createDirectory($this->cachePath, $this->dirMode, true);
  76. }
  77. }
  78. /**
  79. * Checks whether a specified key exists in the cache.
  80. * This can be faster than getting the value from the cache if the data is big.
  81. * Note that this method does not check whether the dependency associated
  82. * with the cached data, if there is any, has changed. So a call to [[get]]
  83. * may return false while exists returns true.
  84. * @param mixed $key a key identifying the cached value. This can be a simple string or
  85. * a complex data structure consisting of factors representing the key.
  86. * @return boolean true if a value exists in cache, false if the value is not in the cache or expired.
  87. */
  88. public function exists($key)
  89. {
  90. $cacheFile = $this->getCacheFile($this->buildKey($key));
  91. return @filemtime($cacheFile) > time();
  92. }
  93. /**
  94. * Retrieves a value from cache with a specified key.
  95. * This is the implementation of the method declared in the parent class.
  96. * @param string $key a unique key identifying the cached value
  97. * @return string|false the value stored in cache, false if the value is not in the cache or expired.
  98. */
  99. protected function getValue($key)
  100. {
  101. $cacheFile = $this->getCacheFile($key);
  102. if (@filemtime($cacheFile) > time()) {
  103. $fp = @fopen($cacheFile, 'r');
  104. if ($fp !== false) {
  105. @flock($fp, LOCK_SH);
  106. $cacheValue = @stream_get_contents($fp);
  107. @flock($fp, LOCK_UN);
  108. @fclose($fp);
  109. return $cacheValue;
  110. }
  111. }
  112. return false;
  113. }
  114. /**
  115. * Stores a value identified by a key in cache.
  116. * This is the implementation of the method declared in the parent class.
  117. *
  118. * @param string $key the key identifying the value to be cached
  119. * @param string $value the value to be cached. Other types (If you have disabled [[serializer]]) unable to get is
  120. * correct in [[getValue()]].
  121. * @param integer $duration the number of seconds in which the cached value will expire. 0 means never expire.
  122. * @return boolean true if the value is successfully stored into cache, false otherwise
  123. */
  124. protected function setValue($key, $value, $duration)
  125. {
  126. $this->gc();
  127. $cacheFile = $this->getCacheFile($key);
  128. if ($this->directoryLevel > 0) {
  129. @FileHelper::createDirectory(dirname($cacheFile), $this->dirMode, true);
  130. }
  131. if (@file_put_contents($cacheFile, $value, LOCK_EX) !== false) {
  132. if ($this->fileMode !== null) {
  133. @chmod($cacheFile, $this->fileMode);
  134. }
  135. if ($duration <= 0) {
  136. $duration = 31536000; // 1 year
  137. }
  138. return @touch($cacheFile, $duration + time());
  139. } else {
  140. $error = error_get_last();
  141. Yii::warning("Unable to write cache file '{$cacheFile}': {$error['message']}", __METHOD__);
  142. return false;
  143. }
  144. }
  145. /**
  146. * Stores a value identified by a key into cache if the cache does not contain this key.
  147. * This is the implementation of the method declared in the parent class.
  148. *
  149. * @param string $key the key identifying the value to be cached
  150. * @param string $value the value to be cached. Other types (if you have disabled [[serializer]]) unable to get is
  151. * correct in [[getValue()]].
  152. * @param integer $duration the number of seconds in which the cached value will expire. 0 means never expire.
  153. * @return boolean true if the value is successfully stored into cache, false otherwise
  154. */
  155. protected function addValue($key, $value, $duration)
  156. {
  157. $cacheFile = $this->getCacheFile($key);
  158. if (@filemtime($cacheFile) > time()) {
  159. return false;
  160. }
  161. return $this->setValue($key, $value, $duration);
  162. }
  163. /**
  164. * Deletes a value with the specified key from cache
  165. * This is the implementation of the method declared in the parent class.
  166. * @param string $key the key of the value to be deleted
  167. * @return boolean if no error happens during deletion
  168. */
  169. protected function deleteValue($key)
  170. {
  171. $cacheFile = $this->getCacheFile($key);
  172. return @unlink($cacheFile);
  173. }
  174. /**
  175. * Returns the cache file path given the cache key.
  176. * @param string $key cache key
  177. * @return string the cache file path
  178. */
  179. protected function getCacheFile($key)
  180. {
  181. if ($this->directoryLevel > 0) {
  182. $base = $this->cachePath;
  183. for ($i = 0; $i < $this->directoryLevel; ++$i) {
  184. if (($prefix = substr($key, $i + $i, 2)) !== false) {
  185. $base .= DIRECTORY_SEPARATOR . $prefix;
  186. }
  187. }
  188. return $base . DIRECTORY_SEPARATOR . $key . $this->cacheFileSuffix;
  189. } else {
  190. return $this->cachePath . DIRECTORY_SEPARATOR . $key . $this->cacheFileSuffix;
  191. }
  192. }
  193. /**
  194. * Deletes all values from cache.
  195. * This is the implementation of the method declared in the parent class.
  196. * @return boolean whether the flush operation was successful.
  197. */
  198. protected function flushValues()
  199. {
  200. $this->gc(true, false);
  201. return true;
  202. }
  203. /**
  204. * Removes expired cache files.
  205. * @param boolean $force whether to enforce the garbage collection regardless of [[gcProbability]].
  206. * Defaults to false, meaning the actual deletion happens with the probability as specified by [[gcProbability]].
  207. * @param boolean $expiredOnly whether to removed expired cache files only.
  208. * If false, all cache files under [[cachePath]] will be removed.
  209. */
  210. public function gc($force = false, $expiredOnly = true)
  211. {
  212. if ($force || mt_rand(0, 1000000) < $this->gcProbability) {
  213. $this->gcRecursive($this->cachePath, $expiredOnly);
  214. }
  215. }
  216. /**
  217. * Recursively removing expired cache files under a directory.
  218. * This method is mainly used by [[gc()]].
  219. * @param string $path the directory under which expired cache files are removed.
  220. * @param boolean $expiredOnly whether to only remove expired cache files. If false, all files
  221. * under `$path` will be removed.
  222. */
  223. protected function gcRecursive($path, $expiredOnly)
  224. {
  225. if (($handle = opendir($path)) !== false) {
  226. while (($file = readdir($handle)) !== false) {
  227. if ($file[0] === '.') {
  228. continue;
  229. }
  230. $fullPath = $path . DIRECTORY_SEPARATOR . $file;
  231. if (is_dir($fullPath)) {
  232. $this->gcRecursive($fullPath, $expiredOnly);
  233. if (!$expiredOnly) {
  234. if (!@rmdir($fullPath)) {
  235. $error = error_get_last();
  236. Yii::warning("Unable to remove directory '{$fullPath}': {$error['message']}", __METHOD__);
  237. }
  238. }
  239. } elseif (!$expiredOnly || $expiredOnly && @filemtime($fullPath) < time()) {
  240. if (!@unlink($fullPath)) {
  241. $error = error_get_last();
  242. Yii::warning("Unable to remove file '{$fullPath}': {$error['message']}", __METHOD__);
  243. }
  244. }
  245. }
  246. closedir($handle);
  247. }
  248. }
  249. }