PageRenderTime 42ms CodeModel.GetById 12ms RepoModel.GetById 0ms app.codeStats 1ms

/lib/Cake/Cache/Engine/FileEngine.php

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