FileEngine.php 11 KB

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