FileEngine.php 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370
  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. if (!empty($this->groupPrefix)) {
  80. $this->groupPrefix = str_replace('_', DS, $this->groupPrefix);
  81. }
  82. return $this->_active();
  83. }
  84. /**
  85. * Garbage collection. Permanently remove all expired and deleted data
  86. *
  87. * @return boolean True if garbage collection was successful, false on failure
  88. */
  89. public function gc() {
  90. return $this->clear(true);
  91. }
  92. /**
  93. * Write data for key into cache
  94. *
  95. * @param string $key Identifier for the data
  96. * @param mixed $data Data to be cached
  97. * @param mixed $duration How long to cache the data, in seconds
  98. * @return boolean True if the data was successfully cached, false on failure
  99. */
  100. public function write($key, $data, $duration) {
  101. if ($data === '' || !$this->_init) {
  102. return false;
  103. }
  104. if ($this->_setKey($key, true) === false) {
  105. return false;
  106. }
  107. $lineBreak = "\n";
  108. if ($this->settings['isWindows']) {
  109. $lineBreak = "\r\n";
  110. }
  111. if (!empty($this->settings['serialize'])) {
  112. if ($this->settings['isWindows']) {
  113. $data = str_replace('\\', '\\\\\\\\', serialize($data));
  114. } else {
  115. $data = serialize($data);
  116. }
  117. }
  118. $expires = time() + $duration;
  119. $contents = $expires . $lineBreak . $data . $lineBreak;
  120. if ($this->settings['lock']) {
  121. $this->_File->flock(LOCK_EX);
  122. }
  123. $this->_File->rewind();
  124. $success = $this->_File->ftruncate(0) && $this->_File->fwrite($contents) && $this->_File->fflush();
  125. if ($this->settings['lock']) {
  126. $this->_File->flock(LOCK_UN);
  127. }
  128. return $success;
  129. }
  130. /**
  131. * Read a key from the cache
  132. *
  133. * @param string $key Identifier for the data
  134. * @return mixed The cached data, or false if the data doesn't exist, has expired, or if there was an error fetching it
  135. */
  136. public function read($key) {
  137. if (!$this->_init || $this->_setKey($key) === false) {
  138. return false;
  139. }
  140. if ($this->settings['lock']) {
  141. $this->_File->flock(LOCK_SH);
  142. }
  143. $this->_File->rewind();
  144. $time = time();
  145. $cachetime = intval($this->_File->current());
  146. if ($cachetime !== false && ($cachetime < $time || ($time + $this->settings['duration']) < $cachetime)) {
  147. if ($this->settings['lock']) {
  148. $this->_File->flock(LOCK_UN);
  149. }
  150. return false;
  151. }
  152. $data = '';
  153. $this->_File->next();
  154. while ($this->_File->valid()) {
  155. $data .= $this->_File->current();
  156. $this->_File->next();
  157. }
  158. if ($this->settings['lock']) {
  159. $this->_File->flock(LOCK_UN);
  160. }
  161. $data = trim($data);
  162. if ($data !== '' && !empty($this->settings['serialize'])) {
  163. if ($this->settings['isWindows']) {
  164. $data = str_replace('\\\\\\\\', '\\', $data);
  165. }
  166. $data = unserialize((string)$data);
  167. }
  168. return $data;
  169. }
  170. /**
  171. * Delete a key from the cache
  172. *
  173. * @param string $key Identifier for the data
  174. * @return boolean True if the value was successfully deleted, false if it didn't exist or couldn't be removed
  175. */
  176. public function delete($key) {
  177. if ($this->_setKey($key) === false || !$this->_init) {
  178. return false;
  179. }
  180. $path = $this->_File->getRealPath();
  181. $this->_File = null;
  182. return unlink($path);
  183. }
  184. /**
  185. * Delete all values from the cache
  186. *
  187. * @param boolean $check Optional - only delete expired cache items
  188. * @return boolean True if the cache was successfully cleared, false otherwise
  189. */
  190. public function clear($check) {
  191. if (!$this->_init) {
  192. return false;
  193. }
  194. $dir = dir($this->settings['path']);
  195. if ($check) {
  196. $now = time();
  197. $threshold = $now - $this->settings['duration'];
  198. }
  199. $prefixLength = strlen($this->settings['prefix']);
  200. while (($entry = $dir->read()) !== false) {
  201. if (substr($entry, 0, $prefixLength) !== $this->settings['prefix']) {
  202. continue;
  203. }
  204. if ($this->_setKey($entry) === false) {
  205. continue;
  206. }
  207. if ($check) {
  208. $mtime = $this->_File->getMTime();
  209. if ($mtime > $threshold) {
  210. continue;
  211. }
  212. $expires = (int)$this->_File->current();
  213. if ($expires > $now) {
  214. continue;
  215. }
  216. }
  217. $path = $this->_File->getRealPath();
  218. $this->_File = null;
  219. if (file_exists($path)) {
  220. unlink($path);
  221. }
  222. }
  223. $dir->close();
  224. return true;
  225. }
  226. /**
  227. * Not implemented
  228. *
  229. * @param string $key
  230. * @param integer $offset
  231. * @return void
  232. * @throws CacheException
  233. */
  234. public function decrement($key, $offset = 1) {
  235. throw new CacheException(__d('cake_dev', 'Files cannot be atomically decremented.'));
  236. }
  237. /**
  238. * Not implemented
  239. *
  240. * @param string $key
  241. * @param integer $offset
  242. * @return void
  243. * @throws CacheException
  244. */
  245. public function increment($key, $offset = 1) {
  246. throw new CacheException(__d('cake_dev', 'Files cannot be atomically incremented.'));
  247. }
  248. /**
  249. * Sets the current cache key this class is managing, and creates a writable SplFileObject
  250. * for the cache file the key is referring to.
  251. *
  252. * @param string $key The key
  253. * @param boolean $createKey Whether the key should be created if it doesn't exists, or not
  254. * @return boolean true if the cache key could be set, false otherwise
  255. */
  256. protected function _setKey($key, $createKey = false) {
  257. $groups = null;
  258. if (!empty($this->groupPrefix)) {
  259. $groups = vsprintf($this->groupPrefix, $this->groups());
  260. }
  261. $dir = $this->settings['path'] . $groups;
  262. if (!is_dir($dir)) {
  263. mkdir($dir, 0777, true);
  264. }
  265. $path = new SplFileInfo($dir . $key);
  266. if (!$createKey && !$path->isFile()) {
  267. return false;
  268. }
  269. if (empty($this->_File) || $this->_File->getBaseName() !== $key) {
  270. $exists = file_exists($path->getPathname());
  271. try {
  272. $this->_File = $path->openFile('c+');
  273. } catch (Exception $e) {
  274. trigger_error($e->getMessage(), E_USER_WARNING);
  275. return false;
  276. }
  277. unset($path);
  278. if (!$exists && !chmod($this->_File->getPathname(), (int)$this->settings['mask'])) {
  279. trigger_error(__d(
  280. 'cake_dev', 'Could not apply permission mask "%s" on cache file "%s"',
  281. array($this->_File->getPathname(), $this->settings['mask'])), E_USER_WARNING);
  282. }
  283. }
  284. return true;
  285. }
  286. /**
  287. * Determine is cache directory is writable
  288. *
  289. * @return boolean
  290. */
  291. protected function _active() {
  292. $dir = new SplFileInfo($this->settings['path']);
  293. if ($this->_init && !($dir->isDir() && $dir->isWritable())) {
  294. $this->_init = false;
  295. trigger_error(__d('cake_dev', '%s is not writable', $this->settings['path']), E_USER_WARNING);
  296. return false;
  297. }
  298. return true;
  299. }
  300. /**
  301. * Generates a safe key for use with cache engine storage engines.
  302. *
  303. * @param string $key the key passed over
  304. * @return mixed string $key or false
  305. */
  306. public function key($key) {
  307. if (empty($key)) {
  308. return false;
  309. }
  310. $key = Inflector::underscore(str_replace(array(DS, '/', '.'), '_', strval($key)));
  311. return $key;
  312. }
  313. /**
  314. * Recursively deletes all files under any directory named as $group
  315. *
  316. * @return boolean success
  317. **/
  318. public function clearGroup($group) {
  319. $directoryIterator = new RecursiveDirectoryIterator($this->settings['path']);
  320. $contents = new RecursiveIteratorIterator($directoryIterator, RecursiveIteratorIterator::CHILD_FIRST);
  321. foreach ($contents as $object) {
  322. $containsGroup = strpos($object->getPathName(), DS . $group . DS) !== false;
  323. if ($object->isFile() && $containsGroup) {
  324. unlink($object->getPathName());
  325. }
  326. }
  327. return true;
  328. }
  329. }