FileCache.php 11 KB

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