FileEngine.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495
  1. <?php
  2. /**
  3. * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
  4. * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  5. *
  6. * Licensed under The MIT License
  7. * For full copyright and license information, please see the LICENSE.txt
  8. * Redistributions of files must retain the above copyright notice.
  9. *
  10. * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  11. * @link https://cakephp.org CakePHP(tm) Project
  12. * @since 1.2.0
  13. * @license https://opensource.org/licenses/mit-license.php MIT License
  14. */
  15. namespace Cake\Cache\Engine;
  16. use Cake\Cache\CacheEngine;
  17. use Cake\Utility\Inflector;
  18. use Exception;
  19. use LogicException;
  20. use RecursiveDirectoryIterator;
  21. use RecursiveIteratorIterator;
  22. use SplFileInfo;
  23. use SplFileObject;
  24. /**
  25. * File Storage engine for cache. Filestorage is the slowest cache storage
  26. * to read and write. However, it is good for servers that don't have other storage
  27. * engine available, or have content which is not performance sensitive.
  28. *
  29. * You can configure a FileEngine cache, using Cache::config()
  30. */
  31. class FileEngine extends CacheEngine
  32. {
  33. /**
  34. * Instance of SplFileObject class
  35. *
  36. * @var \SplFileObject|null
  37. */
  38. protected $_File;
  39. /**
  40. * The default config used unless overridden by runtime configuration
  41. *
  42. * - `duration` Specify how long items in this cache configuration last.
  43. * - `groups` List of groups or 'tags' associated to every key stored in this config.
  44. * handy for deleting a complete group from cache.
  45. * - `isWindows` Automatically populated with whether the host is windows or not
  46. * - `lock` Used by FileCache. Should files be locked before writing to them?
  47. * - `mask` The mask used for created files
  48. * - `path` Path to where cachefiles should be saved. Defaults to system's temp dir.
  49. * - `prefix` Prepended to all entries. Good for when you need to share a keyspace
  50. * with either another cache config or another application.
  51. * - `probability` Probability of hitting a cache gc cleanup. Setting to 0 will disable
  52. * cache::gc from ever being called automatically.
  53. * - `serialize` Should cache objects be serialized first.
  54. *
  55. * @var array
  56. */
  57. protected $_defaultConfig = [
  58. 'duration' => 3600,
  59. 'groups' => [],
  60. 'isWindows' => false,
  61. 'lock' => true,
  62. 'mask' => 0664,
  63. 'path' => null,
  64. 'prefix' => 'cake_',
  65. 'probability' => 100,
  66. 'serialize' => true
  67. ];
  68. /**
  69. * True unless FileEngine::__active(); fails
  70. *
  71. * @var bool
  72. */
  73. protected $_init = true;
  74. /**
  75. * Initialize File Cache Engine
  76. *
  77. * Called automatically by the cache frontend.
  78. *
  79. * @param array $config array of setting for the engine
  80. * @return bool True if the engine has been successfully initialized, false if not
  81. */
  82. public function init(array $config = [])
  83. {
  84. parent::init($config);
  85. if ($this->_config['path'] === null) {
  86. $this->_config['path'] = sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'cake_cache' . DIRECTORY_SEPARATOR;
  87. }
  88. if (DIRECTORY_SEPARATOR === '\\') {
  89. $this->_config['isWindows'] = true;
  90. }
  91. if (substr($this->_config['path'], -1) !== DIRECTORY_SEPARATOR) {
  92. $this->_config['path'] .= DIRECTORY_SEPARATOR;
  93. }
  94. if ($this->_groupPrefix) {
  95. $this->_groupPrefix = str_replace('_', DIRECTORY_SEPARATOR, $this->_groupPrefix);
  96. }
  97. return $this->_active();
  98. }
  99. /**
  100. * Garbage collection. Permanently remove all expired and deleted data
  101. *
  102. * @param int|null $expires [optional] An expires timestamp, invalidating all data before.
  103. * @return bool True if garbage collection was successful, false on failure
  104. */
  105. public function gc($expires = null)
  106. {
  107. return $this->clear(true);
  108. }
  109. /**
  110. * Write data for key into cache
  111. *
  112. * @param string $key Identifier for the data
  113. * @param mixed $data Data to be cached
  114. * @return bool True if the data was successfully cached, false on failure
  115. */
  116. public function write($key, $data)
  117. {
  118. if ($data === '' || !$this->_init) {
  119. return false;
  120. }
  121. $key = $this->_key($key);
  122. if ($this->_setKey($key, true) === false) {
  123. return false;
  124. }
  125. $lineBreak = "\n";
  126. if ($this->_config['isWindows']) {
  127. $lineBreak = "\r\n";
  128. }
  129. if (!empty($this->_config['serialize'])) {
  130. if ($this->_config['isWindows']) {
  131. $data = str_replace('\\', '\\\\\\\\', serialize($data));
  132. } else {
  133. $data = serialize($data);
  134. }
  135. }
  136. $duration = $this->_config['duration'];
  137. $expires = time() + $duration;
  138. $contents = implode([$expires, $lineBreak, $data, $lineBreak]);
  139. if ($this->_config['lock']) {
  140. $this->_File->flock(LOCK_EX);
  141. }
  142. $this->_File->rewind();
  143. $success = $this->_File->ftruncate(0) &&
  144. $this->_File->fwrite($contents) &&
  145. $this->_File->fflush();
  146. if ($this->_config['lock']) {
  147. $this->_File->flock(LOCK_UN);
  148. }
  149. $this->_File = null;
  150. return $success;
  151. }
  152. /**
  153. * Read a key from the cache
  154. *
  155. * @param string $key Identifier for the data
  156. * @return mixed The cached data, or false if the data doesn't exist, has
  157. * expired, or if there was an error fetching it
  158. */
  159. public function read($key)
  160. {
  161. $key = $this->_key($key);
  162. if (!$this->_init || $this->_setKey($key) === false) {
  163. return false;
  164. }
  165. if ($this->_config['lock']) {
  166. $this->_File->flock(LOCK_SH);
  167. }
  168. $this->_File->rewind();
  169. $time = time();
  170. $cachetime = (int)$this->_File->current();
  171. if ($cachetime < $time || ($time + $this->_config['duration']) < $cachetime) {
  172. if ($this->_config['lock']) {
  173. $this->_File->flock(LOCK_UN);
  174. }
  175. return false;
  176. }
  177. $data = '';
  178. $this->_File->next();
  179. while ($this->_File->valid()) {
  180. $data .= $this->_File->current();
  181. $this->_File->next();
  182. }
  183. if ($this->_config['lock']) {
  184. $this->_File->flock(LOCK_UN);
  185. }
  186. $data = trim($data);
  187. if ($data !== '' && !empty($this->_config['serialize'])) {
  188. if ($this->_config['isWindows']) {
  189. $data = str_replace('\\\\\\\\', '\\', $data);
  190. }
  191. $data = unserialize((string)$data);
  192. }
  193. return $data;
  194. }
  195. /**
  196. * Delete a key from the cache
  197. *
  198. * @param string $key Identifier for the data
  199. * @return bool True if the value was successfully deleted, false if it didn't
  200. * exist or couldn't be removed
  201. */
  202. public function delete($key)
  203. {
  204. $key = $this->_key($key);
  205. if ($this->_setKey($key) === false || !$this->_init) {
  206. return false;
  207. }
  208. $path = $this->_File->getRealPath();
  209. $this->_File = null;
  210. //@codingStandardsIgnoreStart
  211. return @unlink($path);
  212. //@codingStandardsIgnoreEnd
  213. }
  214. /**
  215. * Delete all values from the cache
  216. *
  217. * @param bool $check Optional - only delete expired cache items
  218. * @return bool True if the cache was successfully cleared, false otherwise
  219. */
  220. public function clear($check)
  221. {
  222. if (!$this->_init) {
  223. return false;
  224. }
  225. $this->_File = null;
  226. $threshold = $now = false;
  227. if ($check) {
  228. $now = time();
  229. $threshold = $now - $this->_config['duration'];
  230. }
  231. $this->_clearDirectory($this->_config['path'], $now, $threshold);
  232. $directory = new RecursiveDirectoryIterator($this->_config['path']);
  233. $contents = new RecursiveIteratorIterator(
  234. $directory,
  235. RecursiveIteratorIterator::SELF_FIRST
  236. );
  237. $cleared = [];
  238. foreach ($contents as $path) {
  239. if ($path->isFile()) {
  240. continue;
  241. }
  242. $path = $path->getRealPath() . DIRECTORY_SEPARATOR;
  243. if (!in_array($path, $cleared)) {
  244. $this->_clearDirectory($path, $now, $threshold);
  245. $cleared[] = $path;
  246. }
  247. }
  248. return true;
  249. }
  250. /**
  251. * Used to clear a directory of matching files.
  252. *
  253. * @param string $path The path to search.
  254. * @param int $now The current timestamp
  255. * @param int $threshold Any file not modified after this value will be deleted.
  256. * @return void
  257. */
  258. protected function _clearDirectory($path, $now, $threshold)
  259. {
  260. if (!is_dir($path)) {
  261. return;
  262. }
  263. $prefixLength = strlen($this->_config['prefix']);
  264. $dir = dir($path);
  265. while (($entry = $dir->read()) !== false) {
  266. if (substr($entry, 0, $prefixLength) !== $this->_config['prefix']) {
  267. continue;
  268. }
  269. try {
  270. $file = new SplFileObject($path . $entry, 'r');
  271. } catch (Exception $e) {
  272. continue;
  273. }
  274. if ($threshold) {
  275. $mtime = $file->getMTime();
  276. if ($mtime > $threshold) {
  277. continue;
  278. }
  279. $expires = (int)$file->current();
  280. if ($expires > $now) {
  281. continue;
  282. }
  283. }
  284. if ($file->isFile()) {
  285. $filePath = $file->getRealPath();
  286. $file = null;
  287. //@codingStandardsIgnoreStart
  288. @unlink($filePath);
  289. //@codingStandardsIgnoreEnd
  290. }
  291. }
  292. }
  293. /**
  294. * Not implemented
  295. *
  296. * @param string $key The key to decrement
  297. * @param int $offset The number to offset
  298. * @return void
  299. * @throws \LogicException
  300. */
  301. public function decrement($key, $offset = 1)
  302. {
  303. throw new LogicException('Files cannot be atomically decremented.');
  304. }
  305. /**
  306. * Not implemented
  307. *
  308. * @param string $key The key to increment
  309. * @param int $offset The number to offset
  310. * @return void
  311. * @throws \LogicException
  312. */
  313. public function increment($key, $offset = 1)
  314. {
  315. throw new LogicException('Files cannot be atomically incremented.');
  316. }
  317. /**
  318. * Sets the current cache key this class is managing, and creates a writable SplFileObject
  319. * for the cache file the key is referring to.
  320. *
  321. * @param string $key The key
  322. * @param bool $createKey Whether the key should be created if it doesn't exists, or not
  323. * @return bool true if the cache key could be set, false otherwise
  324. */
  325. protected function _setKey($key, $createKey = false)
  326. {
  327. $groups = null;
  328. if ($this->_groupPrefix) {
  329. $groups = vsprintf($this->_groupPrefix, $this->groups());
  330. }
  331. $dir = $this->_config['path'] . $groups;
  332. if (!is_dir($dir)) {
  333. mkdir($dir, 0775, true);
  334. }
  335. $path = new SplFileInfo($dir . $key);
  336. if (!$createKey && !$path->isFile()) {
  337. return false;
  338. }
  339. if (empty($this->_File) || $this->_File->getBasename() !== $key) {
  340. $exists = file_exists($path->getPathname());
  341. try {
  342. $this->_File = $path->openFile('c+');
  343. } catch (Exception $e) {
  344. trigger_error($e->getMessage(), E_USER_WARNING);
  345. return false;
  346. }
  347. unset($path);
  348. if (!$exists && !chmod($this->_File->getPathname(), (int)$this->_config['mask'])) {
  349. trigger_error(sprintf(
  350. 'Could not apply permission mask "%s" on cache file "%s"',
  351. $this->_File->getPathname(),
  352. $this->_config['mask']
  353. ), E_USER_WARNING);
  354. }
  355. }
  356. return true;
  357. }
  358. /**
  359. * Determine if cache directory is writable
  360. *
  361. * @return bool
  362. */
  363. protected function _active()
  364. {
  365. $dir = new SplFileInfo($this->_config['path']);
  366. $path = $dir->getPathname();
  367. $success = true;
  368. if (!is_dir($path)) {
  369. //@codingStandardsIgnoreStart
  370. $success = @mkdir($path, 0775, true);
  371. //@codingStandardsIgnoreEnd
  372. }
  373. $isWritableDir = ($dir->isDir() && $dir->isWritable());
  374. if (!$success || ($this->_init && !$isWritableDir)) {
  375. $this->_init = false;
  376. trigger_error(sprintf(
  377. '%s is not writable',
  378. $this->_config['path']
  379. ), E_USER_WARNING);
  380. }
  381. return $success;
  382. }
  383. /**
  384. * Generates a safe key for use with cache engine storage engines.
  385. *
  386. * @param string $key the key passed over
  387. * @return mixed string $key or false
  388. */
  389. public function key($key)
  390. {
  391. if (empty($key)) {
  392. return false;
  393. }
  394. $key = Inflector::underscore(str_replace(
  395. [DIRECTORY_SEPARATOR, '/', '.', '<', '>', '?', ':', '|', '*', '"'],
  396. '_',
  397. (string)$key
  398. ));
  399. return $key;
  400. }
  401. /**
  402. * Recursively deletes all files under any directory named as $group
  403. *
  404. * @param string $group The group to clear.
  405. * @return bool success
  406. */
  407. public function clearGroup($group)
  408. {
  409. $this->_File = null;
  410. $directoryIterator = new RecursiveDirectoryIterator($this->_config['path']);
  411. $contents = new RecursiveIteratorIterator(
  412. $directoryIterator,
  413. RecursiveIteratorIterator::CHILD_FIRST
  414. );
  415. foreach ($contents as $object) {
  416. $containsGroup = strpos($object->getPathname(), DIRECTORY_SEPARATOR . $group . DIRECTORY_SEPARATOR) !== false;
  417. $hasPrefix = true;
  418. if (strlen($this->_config['prefix']) !== 0) {
  419. $hasPrefix = strpos($object->getBasename(), $this->_config['prefix']) === 0;
  420. }
  421. if ($object->isFile() && $containsGroup && $hasPrefix) {
  422. $path = $object->getPathname();
  423. $object = null;
  424. //@codingStandardsIgnoreStart
  425. @unlink($path);
  426. //@codingStandardsIgnoreEnd
  427. }
  428. }
  429. return true;
  430. }
  431. }