FileEngine.php 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  1. <?php
  2. /**
  3. * File Storage engine for cache. Filestorage is the slowest cache storage
  4. * to read and write. However, it is good for servers that don't have other storage
  5. * engine available, or have content which is not performance sensitive.
  6. *
  7. * You can configure a FileEngine cache, using Cache::config()
  8. *
  9. * PHP 5
  10. *
  11. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  12. * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
  13. *
  14. * Licensed under The MIT License
  15. * Redistributions of files must retain the above copyright notice.
  16. *
  17. * @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
  18. * @link http://cakephp.org CakePHP(tm) Project
  19. * @since CakePHP(tm) v 1.2.0.4933
  20. * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
  21. */
  22. /**
  23. * File Storage engine for cache. Filestorage is the slowest cache storage
  24. * to read and write. However, it is good for servers that don't have other storage
  25. * engine available, or have content which is not performance sensitive.
  26. *
  27. * You can configure a FileEngine cache, using Cache::config()
  28. *
  29. * @package Cake.Cache.Engine
  30. */
  31. class FileEngine extends CacheEngine {
  32. /**
  33. * Instance of SplFileObject class
  34. *
  35. * @var File
  36. */
  37. protected $_File = null;
  38. /**
  39. * Settings
  40. *
  41. * - path = absolute path to cache directory, default => CACHE
  42. * - prefix = string prefix for filename, default => cake_
  43. * - lock = enable file locking on write, default => false
  44. * - serialize = serialize the data, default => true
  45. *
  46. * @var array
  47. * @see CacheEngine::__defaults
  48. */
  49. public $settings = array();
  50. /**
  51. * True unless FileEngine::__active(); fails
  52. *
  53. * @var boolean
  54. */
  55. protected $_init = true;
  56. /**
  57. * Initialize the Cache Engine
  58. *
  59. * Called automatically by the cache frontend
  60. * To reinitialize the settings call Cache::engine('EngineName', [optional] settings = array());
  61. *
  62. * @param array $settings array of setting for the engine
  63. * @return boolean True if the engine has been successfully initialized, false if not
  64. */
  65. public function init($settings = array()) {
  66. parent::init(array_merge(
  67. array(
  68. 'engine' => 'File', 'path' => CACHE, 'prefix' => 'cake_', 'lock' => true,
  69. 'serialize' => true, 'isWindows' => false, 'mask' => 0664
  70. ),
  71. $settings
  72. ));
  73. if (DS === '\\') {
  74. $this->settings['isWindows'] = true;
  75. }
  76. if (substr($this->settings['path'], -1) !== DS) {
  77. $this->settings['path'] .= DS;
  78. }
  79. return $this->_active();
  80. }
  81. /**
  82. * Garbage collection. Permanently remove all expired and deleted data
  83. *
  84. * @param integer $expires [optional] An expires timestamp, invalidataing all data before.
  85. * @return boolean True if garbage collection was successful, false on failure
  86. */
  87. public function gc($expires = null) {
  88. return $this->clear(true);
  89. }
  90. /**
  91. * Write data for key into cache
  92. *
  93. * @param string $key Identifier for the data
  94. * @param mixed $data Data to be cached
  95. * @param mixed $duration How long to cache the data, in seconds
  96. * @return boolean True if the data was successfully cached, false on failure
  97. */
  98. public function write($key, $data, $duration) {
  99. if ($data === '' || !$this->_init) {
  100. return false;
  101. }
  102. if ($this->_setKey($key, true) === false) {
  103. return false;
  104. }
  105. $lineBreak = "\n";
  106. if ($this->settings['isWindows']) {
  107. $lineBreak = "\r\n";
  108. }
  109. if (!empty($this->settings['serialize'])) {
  110. if ($this->settings['isWindows']) {
  111. $data = str_replace('\\', '\\\\\\\\', serialize($data));
  112. } else {
  113. $data = serialize($data);
  114. }
  115. }
  116. $expires = time() + $duration;
  117. $contents = $expires . $lineBreak . $data . $lineBreak;
  118. if ($this->settings['lock']) {
  119. $this->_File->flock(LOCK_EX);
  120. }
  121. $this->_File->rewind();
  122. $success = $this->_File->ftruncate(0) && $this->_File->fwrite($contents) && $this->_File->fflush();
  123. if ($this->settings['lock']) {
  124. $this->_File->flock(LOCK_UN);
  125. }
  126. return $success;
  127. }
  128. /**
  129. * Read a key from the cache
  130. *
  131. * @param string $key Identifier for the data
  132. * @return mixed The cached data, or false if the data doesn't exist, has expired, or if there was an error fetching it
  133. */
  134. public function read($key) {
  135. if (!$this->_init || $this->_setKey($key) === false) {
  136. return false;
  137. }
  138. if ($this->settings['lock']) {
  139. $this->_File->flock(LOCK_SH);
  140. }
  141. $this->_File->rewind();
  142. $time = time();
  143. $cachetime = intval($this->_File->current());
  144. if ($cachetime !== false && ($cachetime < $time || ($time + $this->settings['duration']) < $cachetime)) {
  145. if ($this->settings['lock']) {
  146. $this->_File->flock(LOCK_UN);
  147. }
  148. return false;
  149. }
  150. $data = '';
  151. $this->_File->next();
  152. while ($this->_File->valid()) {
  153. $data .= $this->_File->current();
  154. $this->_File->next();
  155. }
  156. if ($this->settings['lock']) {
  157. $this->_File->flock(LOCK_UN);
  158. }
  159. $data = trim($data);
  160. if ($data !== '' && !empty($this->settings['serialize'])) {
  161. if ($this->settings['isWindows']) {
  162. $data = str_replace('\\\\\\\\', '\\', $data);
  163. }
  164. $data = unserialize((string)$data);
  165. }
  166. return $data;
  167. }
  168. /**
  169. * Delete a key from the cache
  170. *
  171. * @param string $key Identifier for the data
  172. * @return boolean True if the value was successfully deleted, false if it didn't exist or couldn't be removed
  173. */
  174. public function delete($key) {
  175. if ($this->_setKey($key) === false || !$this->_init) {
  176. return false;
  177. }
  178. $path = $this->_File->getRealPath();
  179. $this->_File = null;
  180. return unlink($path);
  181. }
  182. /**
  183. * Delete all values from the cache
  184. *
  185. * @param boolean $check Optional - only delete expired cache items
  186. * @return boolean True if the cache was successfully cleared, false otherwise
  187. */
  188. public function clear($check) {
  189. if (!$this->_init) {
  190. return false;
  191. }
  192. $dir = dir($this->settings['path']);
  193. if ($check) {
  194. $now = time();
  195. $threshold = $now - $this->settings['duration'];
  196. }
  197. $prefixLength = strlen($this->settings['prefix']);
  198. while (($entry = $dir->read()) !== false) {
  199. if (substr($entry, 0, $prefixLength) !== $this->settings['prefix']) {
  200. continue;
  201. }
  202. if ($this->_setKey($entry) === false) {
  203. continue;
  204. }
  205. if ($check) {
  206. $mtime = $this->_File->getMTime();
  207. if ($mtime > $threshold) {
  208. continue;
  209. }
  210. $expires = (int)$this->_File->current();
  211. if ($expires > $now) {
  212. continue;
  213. }
  214. }
  215. $path = $this->_File->getRealPath();
  216. $this->_File = null;
  217. if (file_exists($path)) {
  218. unlink($path);
  219. }
  220. }
  221. $dir->close();
  222. return true;
  223. }
  224. /**
  225. * Not implemented
  226. *
  227. * @param string $key
  228. * @param integer $offset
  229. * @return void
  230. * @throws CacheException
  231. */
  232. public function decrement($key, $offset = 1) {
  233. throw new CacheException(__d('cake_dev', 'Files cannot be atomically decremented.'));
  234. }
  235. /**
  236. * Not implemented
  237. *
  238. * @param string $key
  239. * @param integer $offset
  240. * @return void
  241. * @throws CacheException
  242. */
  243. public function increment($key, $offset = 1) {
  244. throw new CacheException(__d('cake_dev', 'Files cannot be atomically incremented.'));
  245. }
  246. /**
  247. * Sets the current cache key this class is managing, and creates a writable SplFileObject
  248. * for the cache file the key is referring to.
  249. *
  250. * @param string $key The key
  251. * @param boolean $createKey Whether the key should be created if it doesn't exists, or not
  252. * @return boolean true if the cache key could be set, false otherwise
  253. */
  254. protected function _setKey($key, $createKey = false) {
  255. $path = new SplFileInfo($this->settings['path'] . $key);
  256. if (!$createKey && !$path->isFile()) {
  257. return false;
  258. }
  259. if (empty($this->_File) || $this->_File->getBaseName() !== $key) {
  260. $exists = file_exists($path->getPathname());
  261. try {
  262. $this->_File = $path->openFile('c+');
  263. } catch (Exception $e) {
  264. trigger_error($e->getMessage(), E_USER_WARNING);
  265. return false;
  266. }
  267. unset($path);
  268. if (!$exists && !chmod($this->_File->getPathname(), (int)$this->settings['mask'])) {
  269. trigger_error(__d(
  270. 'cake_dev', 'Could not apply permission mask "%s" on cache file "%s"',
  271. array($this->_File->getPathname(), $this->settings['mask'])), E_USER_WARNING);
  272. }
  273. }
  274. return true;
  275. }
  276. /**
  277. * Determine is cache directory is writable
  278. *
  279. * @return boolean
  280. */
  281. protected function _active() {
  282. $dir = new SplFileInfo($this->settings['path']);
  283. if ($this->_init && !($dir->isDir() && $dir->isWritable())) {
  284. $this->_init = false;
  285. trigger_error(__d('cake_dev', '%s is not writable', $this->settings['path']), E_USER_WARNING);
  286. return false;
  287. }
  288. return true;
  289. }
  290. }