2 // +----------------------------------------------------------------------+
4 // +----------------------------------------------------------------------+
5 // | Copyright (c) 1997, 1998, 1999, 2000, 2001 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 // +----------------------------------------------------------------------+
19 // $Id: file.php,v 1.2 2004-03-14 16:24:36 rurban Exp $
21 require_once('lib/pear/Cache/Container.php');
24 * Stores cache contents in a file.
26 * @author Ulf Wendel <ulf.wendel@phpdoc.de>
27 * @version $Id: file.php,v 1.2 2004-03-14 16:24:36 rurban Exp $
29 class Cache_Container_file extends Cache_Container {
32 * Directory where to put the cache files.
34 * @var string Make sure to add a trailing slash
39 * Filename prefix for cache files.
41 * You can use the filename prefix to implement a "domain" based cache or just
42 * to give the files a more descriptive name. The word "domain" is borroed from
43 * a user authentication system. One user id (cached dataset with the ID x)
44 * may exists in different domains (different filename prefix). You might want
45 * to use this to have different cache values for a production, development and
46 * quality assurance system. If you want the production cache not to be influenced
47 * by the quality assurance activities, use different filename prefixes for them.
49 * I personally don't think that you'll never need this, but 640kb happend to be
50 * not enough, so... you know what I mean. If you find a useful application of the
51 * feature please update this inline doc.
55 var $filename_prefix = '';
59 * List of cache entries, used within a gc run
66 * Total number of bytes required by all cache entries, used within a gc run.
73 * Creates the cache directory if neccessary
75 * @param array Config options: ["cache_dir" => ..., "filename_prefix" => ...]
77 function Cache_Container_file($options = '') {
78 if (is_array($options))
79 $this->setOptions($options, array_merge($this->allowed_options, array('cache_dir', 'filename_prefix')));
84 // make relative paths absolute for use in deconstructor.
85 // it looks like the deconstructor has problems with relative paths
86 if (OS_UNIX && '/' != $this->cache_dir{0} )
87 $this->cache_dir = realpath( getcwd() . '/' . $this->cache_dir) . '/';
89 // check if a trailing slash is in cache_dir
90 if (!substr($this->cache_dir,-1) )
91 $this->cache_dir .= '/';
93 if (!file_exists($this->cache_dir) || !is_dir($this->cache_dir))
94 mkdir($this->cache_dir, 0755);
96 $this->entries = array();
97 $this->group_dirs = array();
99 } // end func contructor
101 function fetch($id, $group) {
102 $file = $this->getFilename($id, $group);
103 if (!file_exists($file))
104 return array(NULL, NULL, NULL);
106 // retrive the content
107 if (!($fh = @fopen($file, 'rb')))
108 return new Cache_Error("Can't access cache file '$file'. Check access rights and path.", __FILE__, __LINE__);
111 // 1st line: expiration date
112 // 2nd line: user data
113 // 3rd+ lines: cache data
114 $expire = trim(fgets($fh, 12));
115 $userdata = trim(fgets($fh, 257));
116 $cachedata = $this->decode(fread($fh, filesize($file)));
119 // last usage date used by the gc - maxlifetime
120 // touch without second param produced stupid entries...
124 return array($expire, $cachedata, $userdata);
130 * WARNING: If you supply userdata it must not contain any linebreaks,
131 * otherwise it will break the filestructure.
133 function save($id, $cachedata, $expires, $group, $userdata) {
134 $this->flushPreload($id, $group);
136 $file = $this->getFilename($id, $group);
137 if (!($fh = @fopen($file, 'wb')))
138 return new Cache_Error("Can't access '$file' to store cache data. Check access rights and path.", __FILE__, __LINE__);
141 // 1st line: expiration date
142 // 2nd line: user data
143 // 3rd+ lines: cache data
144 $expires = $this->getExpiresAbsolute($expires);
145 fwrite($fh, $expires . "\n");
146 fwrite($fh, $userdata . "\n");
147 fwrite($fh, $this->encode($cachedata));
151 // I'm not sure if we need this
152 // i don't think we need this (chregu)
158 function remove($id, $group) {
159 $this->flushPreload($id, $group);
161 $file = $this->getFilename($id, $group);
162 if (file_exists($file)) {
173 function flush($group) {
174 $this->flushPreload();
175 $dir = ($group) ? $this->cache_dir . $group . '/' : $this->cache_dir;
177 $num_removed = $this->deleteDir($dir);
178 unset($this->group_dirs[$group]);
184 function idExists($id, $group) {
186 return file_exists($this->getFilename($id, $group));
187 } // end func idExists
190 * Deletes all expired files.
192 * Garbage collection for files is a rather "expensive", "long time"
193 * operation. All files in the cache directory have to be examined which
194 * means that they must be opened for reading, the expiration date has to be
195 * read from them and if neccessary they have to be unlinked (removed).
196 * If you have a user comment for a good default gc probability please add it to
197 * to the inline docs.
199 * @param integer Maximum lifetime in seconds of an no longer used/touched entry
200 * @throws Cache_Error
202 function garbageCollection($maxlifetime) {
204 $this->flushPreload();
207 $ok = $this->doGarbageCollection($maxlifetime, $this->cache_dir);
209 // check the space used by the cache entries
210 if ($this->total_size > $this->highwater) {
212 krsort($this->entries);
213 reset($this->entries);
215 while ($this->total_size > $this->lowwater && list($lastmod, $entry) = each($this->entries)) {
216 if (@unlink($entry['file']))
217 $this->total_size -= $entry['size'];
219 new CacheError("Can't delete {$entry["file"]}. Check the permissions.");
224 $this->entries = array();
225 $this->total_size = 0;
228 } // end func garbageCollection
231 * Does the recursive gc procedure, protected.
233 * @param integer Maximum lifetime in seconds of an no longer used/touched entry
234 * @param string directory to examine - don't sets this parameter, it's used for a
235 * recursive function call!
236 * @throws Cache_Error
238 function doGarbageCollection($maxlifetime, $dir) {
240 if (!($dh = opendir($dir)))
241 return new Cache_Error("Can't access cache directory '$dir'. Check permissions and path.", __FILE__, __LINE__);
243 while ($file = readdir($dh)) {
244 if ('.' == $file || '..' == $file)
247 $file = $dir . $file;
249 $this->doGarbageCollection($maxlifetime,$file . '/');
253 // skip trouble makers but inform the user
254 if (!($fh = @fopen($file, 'rb'))) {
255 new Cache_Error("Can't access cache file '$file', skipping it. Check permissions and path.", __FILE__, __LINE__);
259 $expire = fgets($fh, 12);
261 $lastused = filemtime($file);
263 $this->entries[$lastused] = array('file' => $file, 'size' => filesize($file));
264 $this->total_size += filesize($file);
267 if (( ($expire && $expire <= time()) || ($lastused <= (time() - $maxlifetime)) ) && !unlink($file))
268 new Cache_Error("Can't unlink cache file '$file', skipping. Check permissions and path.", __FILE__, __LINE__);
273 // flush the disk state cache
276 } // end func doGarbageCollection
279 * Returns the filename for the specified id.
281 * @param string dataset ID
282 * @param string cache group
283 * @return string full filename with the path
286 function getFilename($id, $group) {
288 if (isset($this->group_dirs[$group]))
289 return $this->group_dirs[$group] . $this->filename_prefix . $id;
291 $dir = $this->cache_dir . $group . '/';
292 if (!file_exists($dir)) {
297 $this->group_dirs[$group] = $dir;
299 return $dir . $this->filename_prefix . $id;
300 } // end func getFilename
303 * Deletes a directory and all files in it.
305 * @param string directory
306 * @return integer number of removed files
307 * @throws Cache_Error
309 function deleteDir($dir) {
310 if (!($dh = opendir($dir)))
311 return new Cache_Error("Can't remove directory '$dir'. Check permissions and path.", __FILE__, __LINE__);
315 while ($file = readdir($dh)) {
316 if ('.' == $file || '..' == $file)
319 $file = $dir . $file;
322 $num = $this->deleteDir($file . '/');
324 $num_removed += $num;
330 // according to php-manual the following is needed for windows installations.
333 if ($dir != $this->cache_dir) { //delete the sub-dir entries itself also, but not the cache-dir.
339 } // end func deleteDir