PageRenderTime 42ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 0ms

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

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