FileEngine.php 7.2 KB

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