FileEngine.php 7.3 KB

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