FileEngine.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409
  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. $threshold = $now = false;
  200. if ($check) {
  201. $now = time();
  202. $threshold = $now - $this->settings['duration'];
  203. }
  204. $this->_clearDirectory($this->settings['path'], $now, $threshold);
  205. $directory = new RecursiveDirectoryIterator($this->settings['path']);
  206. $contents = new RecursiveIteratorIterator($directory, RecursiveIteratorIterator::SELF_FIRST);
  207. foreach ($contents as $path) {
  208. if ($path->isFile()) {
  209. continue;
  210. }
  211. $this->_clearDirectory($path->getRealPath() . DS, $now, $threshold);
  212. }
  213. return true;
  214. }
  215. /**
  216. * Used to clear a directory of matching files.
  217. *
  218. * @param string $path The path to search.
  219. * @param integer $now The current timestamp
  220. * @param integer $threshold Any file not modified after this value will be deleted.
  221. * @return void
  222. */
  223. protected function _clearDirectory($path, $now, $threshold) {
  224. $prefixLength = strlen($this->settings['prefix']);
  225. if (!is_dir($path)) {
  226. return;
  227. }
  228. $dir = dir($path);
  229. while (($entry = $dir->read()) !== false) {
  230. if (substr($entry, 0, $prefixLength) !== $this->settings['prefix']) {
  231. continue;
  232. }
  233. $filePath = $path . $entry;
  234. if (is_dir($filePath)) {
  235. continue;
  236. }
  237. $file = new SplFileObject($path . $entry, 'r');
  238. if ($threshold) {
  239. $mtime = $file->getMTime();
  240. if ($mtime > $threshold) {
  241. continue;
  242. }
  243. $expires = (int)$file->current();
  244. if ($expires > $now) {
  245. continue;
  246. }
  247. }
  248. if ($file->isFile()) {
  249. unlink($file->getRealPath());
  250. }
  251. }
  252. }
  253. /**
  254. * Not implemented
  255. *
  256. * @param string $key
  257. * @param integer $offset
  258. * @return void
  259. * @throws CacheException
  260. */
  261. public function decrement($key, $offset = 1) {
  262. throw new CacheException(__d('cake_dev', 'Files cannot be atomically decremented.'));
  263. }
  264. /**
  265. * Not implemented
  266. *
  267. * @param string $key
  268. * @param integer $offset
  269. * @return void
  270. * @throws CacheException
  271. */
  272. public function increment($key, $offset = 1) {
  273. throw new CacheException(__d('cake_dev', 'Files cannot be atomically incremented.'));
  274. }
  275. /**
  276. * Sets the current cache key this class is managing, and creates a writable SplFileObject
  277. * for the cache file the key is referring to.
  278. *
  279. * @param string $key The key
  280. * @param boolean $createKey Whether the key should be created if it doesn't exists, or not
  281. * @return boolean true if the cache key could be set, false otherwise
  282. */
  283. protected function _setKey($key, $createKey = false) {
  284. $groups = null;
  285. if (!empty($this->_groupPrefix)) {
  286. $groups = vsprintf($this->_groupPrefix, $this->groups());
  287. }
  288. $dir = $this->settings['path'] . $groups;
  289. if (!is_dir($dir)) {
  290. mkdir($dir, 0775, true);
  291. }
  292. $path = new SplFileInfo($dir . $key);
  293. if (!$createKey && !$path->isFile()) {
  294. return false;
  295. }
  296. if (empty($this->_File) || $this->_File->getBaseName() !== $key) {
  297. $exists = file_exists($path->getPathname());
  298. try {
  299. $this->_File = $path->openFile('c+');
  300. } catch (Exception $e) {
  301. trigger_error($e->getMessage(), E_USER_WARNING);
  302. return false;
  303. }
  304. unset($path);
  305. if (!$exists && !chmod($this->_File->getPathname(), (int)$this->settings['mask'])) {
  306. trigger_error(__d(
  307. 'cake_dev', 'Could not apply permission mask "%s" on cache file "%s"',
  308. array($this->_File->getPathname(), $this->settings['mask'])), E_USER_WARNING);
  309. }
  310. }
  311. return true;
  312. }
  313. /**
  314. * Determine is cache directory is writable
  315. *
  316. * @return boolean
  317. */
  318. protected function _active() {
  319. $dir = new SplFileInfo($this->settings['path']);
  320. if (Configure::read('debug')) {
  321. $path = $dir->getPathname();
  322. if (!is_dir($path)) {
  323. mkdir($path, 0775, true);
  324. }
  325. }
  326. if ($this->_init && !($dir->isDir() && $dir->isWritable())) {
  327. $this->_init = false;
  328. trigger_error(__d('cake_dev', '%s is not writable', $this->settings['path']), E_USER_WARNING);
  329. return false;
  330. }
  331. return true;
  332. }
  333. /**
  334. * Generates a safe key for use with cache engine storage engines.
  335. *
  336. * @param string $key the key passed over
  337. * @return mixed string $key or false
  338. */
  339. public function key($key) {
  340. if (empty($key)) {
  341. return false;
  342. }
  343. $key = Inflector::underscore(str_replace(array(DS, '/', '.'), '_', strval($key)));
  344. return $key;
  345. }
  346. /**
  347. * Recursively deletes all files under any directory named as $group
  348. *
  349. * @return boolean success
  350. */
  351. public function clearGroup($group) {
  352. $directoryIterator = new RecursiveDirectoryIterator($this->settings['path']);
  353. $contents = new RecursiveIteratorIterator($directoryIterator, RecursiveIteratorIterator::CHILD_FIRST);
  354. foreach ($contents as $object) {
  355. $containsGroup = strpos($object->getPathName(), DS . $group . DS) !== false;
  356. $hasPrefix = strpos($object->getBaseName(), $this->settings['prefix']) === 0;
  357. if ($object->isFile() && $containsGroup && $hasPrefix) {
  358. unlink($object->getPathName());
  359. }
  360. }
  361. $this->_File = null;
  362. return true;
  363. }
  364. }