FileEngine.php 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382
  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 (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  13. *
  14. * Licensed under The MIT License
  15. * For full copyright and license information, please see the LICENSE.txt
  16. * Redistributions of files must retain the above copyright notice.
  17. *
  18. * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  19. * @link http://cakephp.org CakePHP(tm) Project
  20. * @since CakePHP(tm) v 1.2.0.4933
  21. * @license http://www.opensource.org/licenses/mit-license.php MIT License
  22. */
  23. /**
  24. * File Storage engine for cache. Filestorage is the slowest cache storage
  25. * to read and write. However, it is good for servers that don't have other storage
  26. * engine available, or have content which is not performance sensitive.
  27. *
  28. * You can configure a FileEngine cache, using Cache::config()
  29. *
  30. * @package Cake.Cache.Engine
  31. */
  32. class FileEngine extends CacheEngine {
  33. /**
  34. * Instance of SplFileObject class
  35. *
  36. * @var File
  37. */
  38. protected $_File = null;
  39. /**
  40. * Settings
  41. *
  42. * - path = absolute path to cache directory, default => CACHE
  43. * - prefix = string prefix for filename, default => cake_
  44. * - lock = enable file locking on write, default => false
  45. * - serialize = serialize the data, default => true
  46. *
  47. * @var array
  48. * @see CacheEngine::__defaults
  49. */
  50. public $settings = array();
  51. /**
  52. * True unless FileEngine::__active(); fails
  53. *
  54. * @var boolean
  55. */
  56. protected $_init = true;
  57. /**
  58. * Initialize the Cache Engine
  59. *
  60. * Called automatically by the cache frontend
  61. * To reinitialize the settings call Cache::engine('EngineName', [optional] settings = array());
  62. *
  63. * @param array $settings array of setting for the engine
  64. * @return boolean True if the engine has been successfully initialized, false if not
  65. */
  66. public function init($settings = array()) {
  67. $settings += array(
  68. 'engine' => 'File',
  69. 'path' => CACHE,
  70. 'prefix' => 'cake_',
  71. 'lock' => true,
  72. 'serialize' => true,
  73. 'isWindows' => false,
  74. 'mask' => 0664
  75. );
  76. parent::init($settings);
  77. if (DS === '\\') {
  78. $this->settings['isWindows'] = true;
  79. }
  80. if (substr($this->settings['path'], -1) !== DS) {
  81. $this->settings['path'] .= DS;
  82. }
  83. if (!empty($this->_groupPrefix)) {
  84. $this->_groupPrefix = str_replace('_', DS, $this->_groupPrefix);
  85. }
  86. return $this->_active();
  87. }
  88. /**
  89. * Garbage collection. Permanently remove all expired and deleted data
  90. *
  91. * @param integer $expires [optional] An expires timestamp, invalidating all data before.
  92. * @return boolean True if garbage collection was successful, false on failure
  93. */
  94. public function gc($expires = null) {
  95. return $this->clear(true);
  96. }
  97. /**
  98. * Write data for key into cache
  99. *
  100. * @param string $key Identifier for the data
  101. * @param mixed $data Data to be cached
  102. * @param integer $duration How long to cache the data, in seconds
  103. * @return boolean True if the data was successfully cached, false on failure
  104. */
  105. public function write($key, $data, $duration) {
  106. if ($data === '' || !$this->_init) {
  107. return false;
  108. }
  109. if ($this->_setKey($key, true) === false) {
  110. return false;
  111. }
  112. $lineBreak = "\n";
  113. if ($this->settings['isWindows']) {
  114. $lineBreak = "\r\n";
  115. }
  116. if (!empty($this->settings['serialize'])) {
  117. if ($this->settings['isWindows']) {
  118. $data = str_replace('\\', '\\\\\\\\', serialize($data));
  119. } else {
  120. $data = serialize($data);
  121. }
  122. }
  123. $expires = time() + $duration;
  124. $contents = $expires . $lineBreak . $data . $lineBreak;
  125. if ($this->settings['lock']) {
  126. $this->_File->flock(LOCK_EX);
  127. }
  128. $this->_File->rewind();
  129. $success = $this->_File->ftruncate(0) && $this->_File->fwrite($contents) && $this->_File->fflush();
  130. if ($this->settings['lock']) {
  131. $this->_File->flock(LOCK_UN);
  132. }
  133. return $success;
  134. }
  135. /**
  136. * Read a key from the cache
  137. *
  138. * @param string $key Identifier for the data
  139. * @return mixed The cached data, or false if the data doesn't exist, has expired, or if there was an error fetching it
  140. */
  141. public function read($key) {
  142. if (!$this->_init || $this->_setKey($key) === false) {
  143. return false;
  144. }
  145. if ($this->settings['lock']) {
  146. $this->_File->flock(LOCK_SH);
  147. }
  148. $this->_File->rewind();
  149. $time = time();
  150. $cachetime = intval($this->_File->current());
  151. if ($cachetime !== false && ($cachetime < $time || ($time + $this->settings['duration']) < $cachetime)) {
  152. if ($this->settings['lock']) {
  153. $this->_File->flock(LOCK_UN);
  154. }
  155. return false;
  156. }
  157. $data = '';
  158. $this->_File->next();
  159. while ($this->_File->valid()) {
  160. $data .= $this->_File->current();
  161. $this->_File->next();
  162. }
  163. if ($this->settings['lock']) {
  164. $this->_File->flock(LOCK_UN);
  165. }
  166. $data = trim($data);
  167. if ($data !== '' && !empty($this->settings['serialize'])) {
  168. if ($this->settings['isWindows']) {
  169. $data = str_replace('\\\\\\\\', '\\', $data);
  170. }
  171. $data = unserialize((string)$data);
  172. }
  173. return $data;
  174. }
  175. /**
  176. * Delete a key from the cache
  177. *
  178. * @param string $key Identifier for the data
  179. * @return boolean True if the value was successfully deleted, false if it didn't exist or couldn't be removed
  180. */
  181. public function delete($key) {
  182. if ($this->_setKey($key) === false || !$this->_init) {
  183. return false;
  184. }
  185. $path = $this->_File->getRealPath();
  186. $this->_File = null;
  187. return unlink($path);
  188. }
  189. /**
  190. * Delete all values from the cache
  191. *
  192. * @param boolean $check Optional - only delete expired cache items
  193. * @return boolean True if the cache was successfully cleared, false otherwise
  194. */
  195. public function clear($check) {
  196. if (!$this->_init) {
  197. return false;
  198. }
  199. $dir = dir($this->settings['path']);
  200. if ($check) {
  201. $now = time();
  202. $threshold = $now - $this->settings['duration'];
  203. }
  204. $prefixLength = strlen($this->settings['prefix']);
  205. while (($entry = $dir->read()) !== false) {
  206. if (substr($entry, 0, $prefixLength) !== $this->settings['prefix']) {
  207. continue;
  208. }
  209. if ($this->_setKey($entry) === false) {
  210. continue;
  211. }
  212. if ($check) {
  213. $mtime = $this->_File->getMTime();
  214. if ($mtime > $threshold) {
  215. continue;
  216. }
  217. $expires = (int)$this->_File->current();
  218. if ($expires > $now) {
  219. continue;
  220. }
  221. }
  222. $path = $this->_File->getRealPath();
  223. $this->_File = null;
  224. if (file_exists($path)) {
  225. unlink($path);
  226. }
  227. }
  228. $dir->close();
  229. return true;
  230. }
  231. /**
  232. * Not implemented
  233. *
  234. * @param string $key
  235. * @param integer $offset
  236. * @return void
  237. * @throws CacheException
  238. */
  239. public function decrement($key, $offset = 1) {
  240. throw new CacheException(__d('cake_dev', 'Files cannot be atomically decremented.'));
  241. }
  242. /**
  243. * Not implemented
  244. *
  245. * @param string $key
  246. * @param integer $offset
  247. * @return void
  248. * @throws CacheException
  249. */
  250. public function increment($key, $offset = 1) {
  251. throw new CacheException(__d('cake_dev', 'Files cannot be atomically incremented.'));
  252. }
  253. /**
  254. * Sets the current cache key this class is managing, and creates a writable SplFileObject
  255. * for the cache file the key is referring to.
  256. *
  257. * @param string $key The key
  258. * @param boolean $createKey Whether the key should be created if it doesn't exists, or not
  259. * @return boolean true if the cache key could be set, false otherwise
  260. */
  261. protected function _setKey($key, $createKey = false) {
  262. $groups = null;
  263. if (!empty($this->_groupPrefix)) {
  264. $groups = vsprintf($this->_groupPrefix, $this->groups());
  265. }
  266. $dir = $this->settings['path'] . $groups;
  267. if (!is_dir($dir)) {
  268. mkdir($dir, 0775, true);
  269. }
  270. $path = new SplFileInfo($dir . $key);
  271. if (!$createKey && !$path->isFile()) {
  272. return false;
  273. }
  274. if (empty($this->_File) || $this->_File->getBaseName() !== $key) {
  275. $exists = file_exists($path->getPathname());
  276. try {
  277. $this->_File = $path->openFile('c+');
  278. } catch (Exception $e) {
  279. trigger_error($e->getMessage(), E_USER_WARNING);
  280. return false;
  281. }
  282. unset($path);
  283. if (!$exists && !chmod($this->_File->getPathname(), (int)$this->settings['mask'])) {
  284. trigger_error(__d(
  285. 'cake_dev', 'Could not apply permission mask "%s" on cache file "%s"',
  286. array($this->_File->getPathname(), $this->settings['mask'])), E_USER_WARNING);
  287. }
  288. }
  289. return true;
  290. }
  291. /**
  292. * Determine is cache directory is writable
  293. *
  294. * @return boolean
  295. */
  296. protected function _active() {
  297. $dir = new SplFileInfo($this->settings['path']);
  298. if (Configure::read('debug')) {
  299. $path = $dir->getPathname();
  300. if (!is_dir($path)) {
  301. mkdir($path, 0775, true);
  302. }
  303. }
  304. if ($this->_init && !($dir->isDir() && $dir->isWritable())) {
  305. $this->_init = false;
  306. trigger_error(__d('cake_dev', '%s is not writable', $this->settings['path']), E_USER_WARNING);
  307. return false;
  308. }
  309. return true;
  310. }
  311. /**
  312. * Generates a safe key for use with cache engine storage engines.
  313. *
  314. * @param string $key the key passed over
  315. * @return mixed string $key or false
  316. */
  317. public function key($key) {
  318. if (empty($key)) {
  319. return false;
  320. }
  321. $key = Inflector::underscore(str_replace(array(DS, '/', '.'), '_', strval($key)));
  322. return $key;
  323. }
  324. /**
  325. * Recursively deletes all files under any directory named as $group
  326. *
  327. * @return boolean success
  328. */
  329. public function clearGroup($group) {
  330. $directoryIterator = new RecursiveDirectoryIterator($this->settings['path']);
  331. $contents = new RecursiveIteratorIterator($directoryIterator, RecursiveIteratorIterator::CHILD_FIRST);
  332. foreach ($contents as $object) {
  333. $containsGroup = strpos($object->getPathName(), DS . $group . DS) !== false;
  334. $hasPrefix = strpos($object->getBaseName(), $this->settings['prefix']) === 0;
  335. if ($object->isFile() && $containsGroup && $hasPrefix) {
  336. unlink($object->getPathName());
  337. }
  338. }
  339. $this->_File = null;
  340. return true;
  341. }
  342. }