file.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388
  1. <?php
  2. // +----------------------------------------------------------------------+
  3. // | PEAR :: Cache |
  4. // +----------------------------------------------------------------------+
  5. // | Copyright (c) 1997-2003 The PHP Group |
  6. // +----------------------------------------------------------------------+
  7. // | This source file is subject to version 2.0 of the PHP license, |
  8. // | that is bundled with this package in the file LICENSE, and is |
  9. // | available at through the world-wide-web at |
  10. // | http://www.php.net/license/2_02.txt. |
  11. // | If you did not receive a copy of the PHP license and are unable to |
  12. // | obtain it through the world-wide-web, please send a note to |
  13. // | license@php.net so we can mail you a copy immediately. |
  14. // +----------------------------------------------------------------------+
  15. // | Authors: Ulf Wendel <ulf.wendel@phpdoc.de> |
  16. // | Sebastian Bergmann <sb@sebastian-bergmann.de> |
  17. // +----------------------------------------------------------------------+
  18. //
  19. // $Id: file.php,v 1.12 2003/02/19 09:57:11 chregu Exp $
  20. require_once 'Cache/Container.php';
  21. /**
  22. * Stores cache contents in a file.
  23. *
  24. * @author Ulf Wendel <ulf.wendel@phpdoc.de>
  25. * @version $Id: file.php,v 1.12 2003/02/19 09:57:11 chregu Exp $
  26. */
  27. class Cache_Container_file extends Cache_Container {
  28. /**
  29. * File locking
  30. *
  31. * With file container, it's possible, that you get corrupted
  32. * data-entries under bad circumstances. The file locking must
  33. * improve this problem but it's experimental stuff. So the
  34. * default value is false. But it seems to give good results
  35. *
  36. * @var boolean
  37. */
  38. var $fileLocking = false;
  39. /**
  40. * Directory where to put the cache files.
  41. *
  42. * @var string Make sure to add a trailing slash
  43. */
  44. var $cache_dir = '';
  45. /**
  46. * Filename prefix for cache files.
  47. *
  48. * You can use the filename prefix to implement a "domain" based cache or just
  49. * to give the files a more descriptive name. The word "domain" is borroed from
  50. * a user authentification system. One user id (cached dataset with the ID x)
  51. * may exists in different domains (different filename prefix). You might want
  52. * to use this to have different cache values for a production, development and
  53. * quality assurance system. If you want the production cache not to be influenced
  54. * by the quality assurance activities, use different filename prefixes for them.
  55. *
  56. * I personally don't think that you'll never need this, but 640kb happend to be
  57. * not enough, so... you know what I mean. If you find a useful application of the
  58. * feature please update this inline doc.
  59. *
  60. * @var string
  61. */
  62. var $filename_prefix = '';
  63. /**
  64. * List of cache entries, used within a gc run
  65. *
  66. * @var array
  67. */
  68. var $entries;
  69. /**
  70. * Total number of bytes required by all cache entries, used within a gc run.
  71. *
  72. * @var int
  73. */
  74. var $total_size = 0;
  75. /**
  76. * Max Line Length of userdata
  77. *
  78. * If set to 0, it will take the default
  79. * ( 1024 in php 4.2, unlimited in php 4.3)
  80. * see http://ch.php.net/manual/en/function.fgets.php
  81. * for details
  82. *
  83. * @var int
  84. */
  85. var $max_userdata_linelength = 257;
  86. /**
  87. * Creates the cache directory if neccessary
  88. *
  89. * @param array Config options: ["cache_dir" => ..., "filename_prefix" => ...]
  90. */
  91. function Cache_Container_file($options = '') {
  92. if (is_array($options))
  93. $this->setOptions($options, array_merge($this->allowed_options, array('cache_dir', 'filename_prefix', 'max_userdata_linelength')));
  94. clearstatcache();
  95. if ($this->cache_dir)
  96. {
  97. // make relative paths absolute for use in deconstructor.
  98. // it looks like the deconstructor has problems with relative paths
  99. if (OS_UNIX && '/' != $this->cache_dir{0} )
  100. $this->cache_dir = realpath( getcwd() . '/' . $this->cache_dir) . '/';
  101. // check if a trailing slash is in cache_dir
  102. if ($this->cache_dir{strlen($this->cache_dir)-1} != DIRECTORY_SEPARATOR)
  103. $this->cache_dir .= '/';
  104. if (!file_exists($this->cache_dir) || !is_dir($this->cache_dir))
  105. mkdir($this->cache_dir, 0755);
  106. }
  107. $this->entries = array();
  108. $this->group_dirs = array();
  109. } // end func contructor
  110. function fetch($id, $group) {
  111. $file = $this->getFilename($id, $group);
  112. if (!file_exists($file))
  113. return array(NULL, NULL, NULL);
  114. // retrive the content
  115. if (!($fh = @fopen($file, 'rb')))
  116. return new Cache_Error("Can't access cache file '$file'. Check access rights and path.", __FILE__, __LINE__);
  117. // File locking (shared lock)
  118. if ($this->fileLocking)
  119. flock($fh, LOCK_SH);
  120. // file format:
  121. // 1st line: expiration date
  122. // 2nd line: user data
  123. // 3rd+ lines: cache data
  124. $expire = trim(fgets($fh, 12));
  125. if ($this->max_userdata_linelength == 0 ) {
  126. $userdata = trim(fgets($fh));
  127. } else {
  128. $userdata = trim(fgets($fh, $this->max_userdata_linelength));
  129. }
  130. $cachedata = $this->decode(fread($fh, filesize($file)));
  131. // Unlocking
  132. if ($this->fileLocking)
  133. flock($fh, LOCK_UN);
  134. fclose($fh);
  135. // last usage date used by the gc - maxlifetime
  136. // touch without second param produced stupid entries...
  137. touch($file,time());
  138. clearstatcache();
  139. return array($expire, $cachedata, $userdata);
  140. } // end func fetch
  141. /**
  142. * Stores a dataset.
  143. *
  144. * WARNING: If you supply userdata it must not contain any linebreaks,
  145. * otherwise it will break the filestructure.
  146. */
  147. function save($id, $cachedata, $expires, $group, $userdata) {
  148. $this->flushPreload($id, $group);
  149. $file = $this->getFilename($id, $group);
  150. if (!($fh = @fopen($file, 'wb')))
  151. return new Cache_Error("Can't access '$file' to store cache data. Check access rights and path.", __FILE__, __LINE__);
  152. // File locking (exclusive lock)
  153. if ($this->fileLocking)
  154. flock($fh, LOCK_EX);
  155. // file format:
  156. // 1st line: expiration date
  157. // 2nd line: user data
  158. // 3rd+ lines: cache data
  159. $expires = $this->getExpiresAbsolute($expires);
  160. fwrite($fh, $expires . "\n");
  161. fwrite($fh, $userdata . "\n");
  162. fwrite($fh, $this->encode($cachedata));
  163. // File unlocking
  164. if ($this->fileLocking)
  165. flock($fh, LOCK_UN);
  166. fclose($fh);
  167. // I'm not sure if we need this
  168. // i don't think we need this (chregu)
  169. // touch($file);
  170. return true;
  171. } // end func save
  172. function remove($id, $group) {
  173. $this->flushPreload($id, $group);
  174. $file = $this->getFilename($id, $group);
  175. if (file_exists($file)) {
  176. $ok = unlink($file);
  177. clearstatcache();
  178. return $ok;
  179. }
  180. return false;
  181. } // end func remove
  182. function flush($group) {
  183. $this->flushPreload();
  184. $dir = ($group) ? $this->cache_dir . $group . '/' : $this->cache_dir;
  185. $num_removed = $this->deleteDir($dir);
  186. unset($this->group_dirs[$group]);
  187. clearstatcache();
  188. return $num_removed;
  189. } // end func flush
  190. function idExists($id, $group) {
  191. return file_exists($this->getFilename($id, $group));
  192. } // end func idExists
  193. /**
  194. * Deletes all expired files.
  195. *
  196. * Garbage collection for files is a rather "expensive", "long time"
  197. * operation. All files in the cache directory have to be examined which
  198. * means that they must be opened for reading, the expiration date has to be
  199. * read from them and if neccessary they have to be unlinked (removed).
  200. * If you have a user comment for a good default gc probability please add it to
  201. * to the inline docs.
  202. *
  203. * @param integer Maximum lifetime in seconds of an no longer used/touched entry
  204. * @throws Cache_Error
  205. */
  206. function garbageCollection($maxlifetime) {
  207. $this->flushPreload();
  208. clearstatcache();
  209. $ok = $this->doGarbageCollection($maxlifetime, $this->cache_dir);
  210. // check the space used by the cache entries
  211. if ($this->total_size > $this->highwater) {
  212. krsort($this->entries);
  213. reset($this->entries);
  214. while ($this->total_size > $this->lowwater && list($lastmod, $entry) = each($this->entries)) {
  215. if (@unlink($entry['file']))
  216. $this->total_size -= $entry['size'];
  217. else
  218. new CacheError("Can't delete {$entry["file"]}. Check the permissions.");
  219. }
  220. }
  221. $this->entries = array();
  222. $this->total_size = 0;
  223. return $ok;
  224. } // end func garbageCollection
  225. /**
  226. * Does the recursive gc procedure, protected.
  227. *
  228. * @param integer Maximum lifetime in seconds of an no longer used/touched entry
  229. * @param string directory to examine - don't sets this parameter, it's used for a
  230. * recursive function call!
  231. * @throws Cache_Error
  232. */
  233. function doGarbageCollection($maxlifetime, $dir) {
  234. if (!($dh = opendir($dir)))
  235. return new Cache_Error("Can't access cache directory '$dir'. Check permissions and path.", __FILE__, __LINE__);
  236. while ($file = readdir($dh)) {
  237. if ('.' == $file || '..' == $file)
  238. continue;
  239. $file = $dir . $file;
  240. if (is_dir($file)) {
  241. $this->doGarbageCollection($maxlifetime,$file . '/');
  242. continue;
  243. }
  244. // skip trouble makers but inform the user
  245. if (!($fh = @fopen($file, 'rb'))) {
  246. new Cache_Error("Can't access cache file '$file', skipping it. Check permissions and path.", __FILE__, __LINE__);
  247. continue;
  248. }
  249. $expire = fgets($fh, 11);
  250. fclose($fh);
  251. $lastused = filemtime($file);
  252. $this->entries[$lastused] = array('file' => $file, 'size' => filesize($file));
  253. $this->total_size += filesize($file);
  254. // remove if expired
  255. if (( ($expire && $expire <= time()) || ($lastused <= (time() - $maxlifetime)) ) && !unlink($file))
  256. new Cache_Error("Can't unlink cache file '$file', skipping. Check permissions and path.", __FILE__, __LINE__);
  257. }
  258. closedir($dh);
  259. // flush the disk state cache
  260. clearstatcache();
  261. } // end func doGarbageCollection
  262. /**
  263. * Returns the filename for the specified id.
  264. *
  265. * @param string dataset ID
  266. * @param string cache group
  267. * @return string full filename with the path
  268. * @access public
  269. */
  270. function getFilename($id, $group) {
  271. if (isset($this->group_dirs[$group]))
  272. return $this->group_dirs[$group] . $this->filename_prefix . $id;
  273. $dir = $this->cache_dir . $group . '/';
  274. if (!file_exists($dir)) {
  275. mkdir($dir, 0755);
  276. clearstatcache();
  277. }
  278. $this->group_dirs[$group] = $dir;
  279. return $dir . $this->filename_prefix . $id;
  280. } // end func getFilename
  281. /**
  282. * Deletes a directory and all files in it.
  283. *
  284. * @param string directory
  285. * @return integer number of removed files
  286. * @throws Cache_Error
  287. */
  288. function deleteDir($dir) {
  289. if (!($dh = opendir($dir)))
  290. return new Cache_Error("Can't remove directory '$dir'. Check permissions and path.", __FILE__, __LINE__);
  291. $num_removed = 0;
  292. while ($file = readdir($dh)) {
  293. if ('.' == $file || '..' == $file)
  294. continue;
  295. $file = $dir . $file;
  296. if (is_dir($file)) {
  297. $file .= '/';
  298. $num = $this->deleteDir($file . '/');
  299. if (is_int($num))
  300. $num_removed += $num;
  301. } else {
  302. if (unlink($file))
  303. $num_removed++;
  304. }
  305. }
  306. // according to php-manual the following is needed for windows installations.
  307. closedir($dh);
  308. unset( $dh);
  309. if ($dir != $this->cache_dir) { //delete the sub-dir entries itself also, but not the cache-dir.
  310. rmDir($dir);
  311. $num_removed++;
  312. }
  313. return $num_removed;
  314. } // end func deleteDir
  315. } // end class file
  316. ?>