FileEngine.php 15 KB

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