PageRenderTime 41ms CodeModel.GetById 13ms RepoModel.GetById 0ms app.codeStats 0ms

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

https://bitbucket.org/vishallogiciel/admin-bootstrap
PHP | 419 lines | 264 code | 35 blank | 120 comment | 46 complexity | bfdb281edfb0450df7a13e3eb11968ec 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. * 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. return unlink($path);
  188. }
  189. /**
  190. * Delete all values from the cache
  191. *
  192. * @param boolean $check Optional - only delete expired cache items
  193. * @return boolean 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 integer $now The current timestamp
  226. * @param integer $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. $_path = $file->getRealPath();
  256. $file = null;
  257. unlink($_path);
  258. }
  259. }
  260. }
  261. /**
  262. * Not implemented
  263. *
  264. * @param string $key
  265. * @param integer $offset
  266. * @return void
  267. * @throws CacheException
  268. */
  269. public function decrement($key, $offset = 1) {
  270. throw new CacheException(__d('cake_dev', 'Files cannot be atomically decremented.'));
  271. }
  272. /**
  273. * Not implemented
  274. *
  275. * @param string $key
  276. * @param integer $offset
  277. * @return void
  278. * @throws CacheException
  279. */
  280. public function increment($key, $offset = 1) {
  281. throw new CacheException(__d('cake_dev', 'Files cannot be atomically incremented.'));
  282. }
  283. /**
  284. * Sets the current cache key this class is managing, and creates a writable SplFileObject
  285. * for the cache file the key is referring to.
  286. *
  287. * @param string $key The key
  288. * @param boolean $createKey Whether the key should be created if it doesn't exists, or not
  289. * @return boolean true if the cache key could be set, false otherwise
  290. */
  291. protected function _setKey($key, $createKey = false) {
  292. $groups = null;
  293. if (!empty($this->_groupPrefix)) {
  294. $groups = vsprintf($this->_groupPrefix, $this->groups());
  295. }
  296. $dir = $this->settings['path'] . $groups;
  297. if (!is_dir($dir)) {
  298. mkdir($dir, 0775, true);
  299. }
  300. $path = new SplFileInfo($dir . $key);
  301. if (!$createKey && !$path->isFile()) {
  302. return false;
  303. }
  304. if (empty($this->_File) || $this->_File->getBaseName() !== $key) {
  305. $exists = file_exists($path->getPathname());
  306. try {
  307. $this->_File = $path->openFile('c+');
  308. } catch (Exception $e) {
  309. trigger_error($e->getMessage(), E_USER_WARNING);
  310. return false;
  311. }
  312. unset($path);
  313. if (!$exists && !chmod($this->_File->getPathname(), (int)$this->settings['mask'])) {
  314. trigger_error(__d(
  315. 'cake_dev', 'Could not apply permission mask "%s" on cache file "%s"',
  316. array($this->_File->getPathname(), $this->settings['mask'])), E_USER_WARNING);
  317. }
  318. }
  319. return true;
  320. }
  321. /**
  322. * Determine is cache directory is writable
  323. *
  324. * @return boolean
  325. */
  326. protected function _active() {
  327. $dir = new SplFileInfo($this->settings['path']);
  328. if (Configure::read('debug')) {
  329. $path = $dir->getPathname();
  330. if (!is_dir($path)) {
  331. mkdir($path, 0775, true);
  332. }
  333. }
  334. if ($this->_init && !($dir->isDir() && $dir->isWritable())) {
  335. $this->_init = false;
  336. trigger_error(__d('cake_dev', '%s is not writable', $this->settings['path']), E_USER_WARNING);
  337. return false;
  338. }
  339. return true;
  340. }
  341. /**
  342. * Generates a safe key for use with cache engine storage engines.
  343. *
  344. * @param string $key the key passed over
  345. * @return mixed string $key or false
  346. */
  347. public function key($key) {
  348. if (empty($key)) {
  349. return false;
  350. }
  351. $key = Inflector::underscore(str_replace(array(DS, '/', '.', '<', '>', '?', ':', '|', '*', '"'), '_', strval($key)));
  352. return $key;
  353. }
  354. /**
  355. * Recursively deletes all files under any directory named as $group
  356. *
  357. * @return boolean success
  358. */
  359. public function clearGroup($group) {
  360. $this->_File = null;
  361. $directoryIterator = new RecursiveDirectoryIterator($this->settings['path']);
  362. $contents = new RecursiveIteratorIterator($directoryIterator, RecursiveIteratorIterator::CHILD_FIRST);
  363. foreach ($contents as $object) {
  364. $containsGroup = strpos($object->getPathName(), DS . $group . DS) !== false;
  365. $hasPrefix = strpos($object->getBaseName(), $this->settings['prefix']) === 0;
  366. if ($object->isFile() && $containsGroup && $hasPrefix) {
  367. unlink($object->getPathName());
  368. }
  369. }
  370. return true;
  371. }
  372. }