FileEngine.php 11 KB

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