FileEngine.php 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  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. * @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. $expires = time() + $duration;
  115. $contents = $expires . $lineBreak . $data . $lineBreak;
  116. if (!$handle = fopen($this->_File->getPathName(), 'c')) {
  117. return false;
  118. }
  119. if ($this->settings['lock']) {
  120. flock($handle, LOCK_EX);
  121. }
  122. $success = ftruncate($handle, 0) && fwrite($handle, $contents) && fflush($handle);
  123. if ($this->settings['lock']) {
  124. flock($handle, LOCK_UN);
  125. }
  126. fclose($handle);
  127. return $success;
  128. }
  129. /**
  130. * Read a key from the cache
  131. *
  132. * @param string $key Identifier for the data
  133. * @return mixed The cached data, or false if the data doesn't exist, has expired, or if there was an error fetching it
  134. */
  135. public function read($key) {
  136. if (!$this->_init || $this->_setKey($key) === false) {
  137. return false;
  138. }
  139. if ($this->settings['lock']) {
  140. $this->_File->flock(LOCK_SH);
  141. }
  142. $this->_File->rewind();
  143. $time = time();
  144. $cachetime = intval($this->_File->current());
  145. if ($cachetime !== false && ($cachetime < $time || ($time + $this->settings['duration']) < $cachetime)) {
  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. unlink($path);
  216. }
  217. $dir->close();
  218. return true;
  219. }
  220. /**
  221. * Not implemented
  222. *
  223. * @return void
  224. * @throws CacheException
  225. */
  226. public function decrement($key, $offset = 1) {
  227. throw new CacheException(__d('cake_dev', 'Files cannot be atomically decremented.'));
  228. }
  229. /**
  230. * Not implemented
  231. *
  232. * @return void
  233. * @throws CacheException
  234. */
  235. public function increment($key, $offset = 1) {
  236. throw new CacheException(__d('cake_dev', 'Files cannot be atomically incremented.'));
  237. }
  238. /**
  239. * Sets the current cache key this class is managing
  240. *
  241. * @param string $key The key
  242. * @param boolean $createKey Whether the key should be created if it doesn't exists, or not
  243. * @return boolean true if the cache key could be set, false otherwise
  244. * @access protected
  245. */
  246. protected function _setKey($key, $createKey = false) {
  247. $path = new SplFileInfo($this->settings['path'] . $key);
  248. if (!$createKey && !$path->isFile()) {
  249. return false;
  250. }
  251. $old = umask(0);
  252. if (empty($this->_File) || $this->_File->getBaseName() !== $key) {
  253. $this->_File = $path->openFile('a+');
  254. }
  255. umask($old);
  256. return true;
  257. }
  258. /**
  259. * Determine is cache directory is writable
  260. *
  261. * @return boolean
  262. * @access protected
  263. */
  264. protected function _active() {
  265. $dir = new SplFileInfo($this->settings['path']);
  266. if ($this->_init && !($dir->isDir() && $dir->isWritable())) {
  267. $this->_init = false;
  268. trigger_error(__d('cake_dev', '%s is not writable', $this->settings['path']), E_USER_WARNING);
  269. return false;
  270. }
  271. return true;
  272. }
  273. }