FileEngine.php 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  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-2011, 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-2011, 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
  24. *
  25. * @package Cake.Cache.Engine
  26. */
  27. class FileEngine extends CacheEngine {
  28. /**
  29. * Instance of SplFileObject class
  30. *
  31. * @var File
  32. */
  33. protected $_File = null;
  34. /**
  35. * Settings
  36. *
  37. * - path = absolute path to cache directory, default => CACHE
  38. * - prefix = string prefix for filename, default => cake_
  39. * - lock = enable file locking on write, default => false
  40. * - serialize = serialize the data, default => true
  41. *
  42. * @var array
  43. * @see CacheEngine::__defaults
  44. */
  45. public $settings = array();
  46. /**
  47. * True unless FileEngine::__active(); fails
  48. *
  49. * @var boolean
  50. */
  51. protected $_init = true;
  52. /**
  53. * Initialize the Cache Engine
  54. *
  55. * Called automatically by the cache frontend
  56. * To reinitialize the settings call Cache::engine('EngineName', [optional] settings = array());
  57. *
  58. * @param array $settings array of setting for the engine
  59. * @return boolean True if the engine has been successfully initialized, false if not
  60. */
  61. public function init($settings = array()) {
  62. parent::init(array_merge(
  63. array(
  64. 'engine' => 'File', 'path' => CACHE, 'prefix'=> 'cake_', 'lock'=> true,
  65. 'serialize'=> true, 'isWindows' => false
  66. ),
  67. $settings
  68. ));
  69. if (DS === '\\') {
  70. $this->settings['isWindows'] = true;
  71. }
  72. if (substr($this->settings['path'], -1) !== DS) {
  73. $this->settings['path'] .= DS;
  74. }
  75. return $this->_active();
  76. }
  77. /**
  78. * Garbage collection. Permanently remove all expired and deleted data
  79. *
  80. * @return boolean True if garbage collection was succesful, false on failure
  81. */
  82. public function gc() {
  83. return $this->clear(true);
  84. }
  85. /**
  86. * Write data for key into cache
  87. *
  88. * @param string $key Identifier for the data
  89. * @param mixed $data Data to be cached
  90. * @param mixed $duration How long to cache the data, in seconds
  91. * @return boolean True if the data was successfully cached, false on failure
  92. */
  93. public function write($key, $data, $duration) {
  94. if ($data === '' || !$this->_init) {
  95. return false;
  96. }
  97. if ($this->_setKey($key, true) === false) {
  98. return false;
  99. }
  100. $lineBreak = "\n";
  101. if ($this->settings['isWindows']) {
  102. $lineBreak = "\r\n";
  103. }
  104. if (!empty($this->settings['serialize'])) {
  105. if ($this->settings['isWindows']) {
  106. $data = str_replace('\\', '\\\\\\\\', serialize($data));
  107. } else {
  108. $data = serialize($data);
  109. }
  110. }
  111. $expires = time() + $duration;
  112. $contents = $expires . $lineBreak . $data . $lineBreak;
  113. if (!$handle = fopen($this->_File->getPathName(), 'c')) {
  114. return false;
  115. }
  116. if ($this->settings['lock']) {
  117. flock($handle, LOCK_EX);
  118. }
  119. $success = ftruncate($handle, 0) && fwrite($handle, $contents) && fflush($handle);
  120. if ($this->settings['lock']) {
  121. flock($handle, LOCK_UN);
  122. }
  123. fclose($handle);
  124. return $success;
  125. }
  126. /**
  127. * Read a key from the cache
  128. *
  129. * @param string $key Identifier for the data
  130. * @return mixed The cached data, or false if the data doesn't exist, has expired, or if there was an error fetching it
  131. */
  132. public function read($key) {
  133. if (!$this->_init || $this->_setKey($key) === false) {
  134. return false;
  135. }
  136. if ($this->settings['lock']) {
  137. $this->_File->flock(LOCK_SH);
  138. }
  139. $this->_File->rewind();
  140. $time = time();
  141. $cachetime = intval($this->_File->current());
  142. if ($cachetime !== false && ($cachetime < $time || ($time + $this->settings['duration']) < $cachetime)) {
  143. if ($this->settings['lock']) {
  144. $this->_File->flock(LOCK_UN);
  145. }
  146. return false;
  147. }
  148. $data = '';
  149. $this->_File->next();
  150. while ($this->_File->valid()) {
  151. $data .= $this->_File->current();
  152. $this->_File->next();
  153. }
  154. if ($this->settings['lock']) {
  155. $this->_File->flock(LOCK_UN);
  156. }
  157. $data = trim($data);
  158. if ($data !== '' && !empty($this->settings['serialize'])) {
  159. if ($this->settings['isWindows']) {
  160. $data = str_replace('\\\\\\\\', '\\', $data);
  161. }
  162. $data = unserialize((string)$data);
  163. }
  164. return $data;
  165. }
  166. /**
  167. * Delete a key from the cache
  168. *
  169. * @param string $key Identifier for the data
  170. * @return boolean True if the value was successfully deleted, false if it didn't exist or couldn't be removed
  171. */
  172. public function delete($key) {
  173. if ($this->_setKey($key) === false || !$this->_init) {
  174. return false;
  175. }
  176. $path = $this->_File->getRealPath();
  177. $this->_File = null;
  178. return unlink($path);
  179. }
  180. /**
  181. * Delete all values from the cache
  182. *
  183. * @param boolean $check Optional - only delete expired cache items
  184. * @return boolean True if the cache was successfully cleared, false otherwise
  185. */
  186. public function clear($check) {
  187. if (!$this->_init) {
  188. return false;
  189. }
  190. $dir = dir($this->settings['path']);
  191. if ($check) {
  192. $now = time();
  193. $threshold = $now - $this->settings['duration'];
  194. }
  195. $prefixLength = strlen($this->settings['prefix']);
  196. while (($entry = $dir->read()) !== false) {
  197. if (substr($entry, 0, $prefixLength) !== $this->settings['prefix']) {
  198. continue;
  199. }
  200. if ($this->_setKey($entry) === false) {
  201. continue;
  202. }
  203. if ($check) {
  204. $mtime = $this->_File->getMTime();
  205. if ($mtime > $threshold) {
  206. continue;
  207. }
  208. $expires = (int)$this->_File->current();
  209. if ($expires > $now) {
  210. continue;
  211. }
  212. }
  213. $path = $this->_File->getRealPath();
  214. $this->_File = null;
  215. if (file_exists($path)) {
  216. unlink($path);
  217. }
  218. }
  219. $dir->close();
  220. return true;
  221. }
  222. /**
  223. * Not implemented
  224. *
  225. * @param string $key
  226. * @param integer $offset
  227. * @return void
  228. * @throws CacheException
  229. */
  230. public function decrement($key, $offset = 1) {
  231. throw new CacheException(__d('cake_dev', 'Files cannot be atomically decremented.'));
  232. }
  233. /**
  234. * Not implemented
  235. *
  236. * @param string $key
  237. * @param integer $offset
  238. * @return void
  239. * @throws CacheException
  240. */
  241. public function increment($key, $offset = 1) {
  242. throw new CacheException(__d('cake_dev', 'Files cannot be atomically incremented.'));
  243. }
  244. /**
  245. * Sets the current cache key this class is managing
  246. *
  247. * @param string $key The key
  248. * @param boolean $createKey Whether the key should be created if it doesn't exists, or not
  249. * @return boolean true if the cache key could be set, false otherwise
  250. */
  251. protected function _setKey($key, $createKey = false) {
  252. $path = new SplFileInfo($this->settings['path'] . $key);
  253. if (!$createKey && !$path->isFile()) {
  254. return false;
  255. }
  256. $old = umask(0);
  257. if (empty($this->_File) || $this->_File->getBaseName() !== $key) {
  258. $this->_File = $path->openFile('a+');
  259. }
  260. umask($old);
  261. return true;
  262. }
  263. /**
  264. * Determine is cache directory is writable
  265. *
  266. * @return boolean
  267. */
  268. protected function _active() {
  269. $dir = new SplFileInfo($this->settings['path']);
  270. if ($this->_init && !($dir->isDir() && $dir->isWritable())) {
  271. $this->_init = false;
  272. trigger_error(__d('cake_dev', '%s is not writable', $this->settings['path']), E_USER_WARNING);
  273. return false;
  274. }
  275. return true;
  276. }
  277. }