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 // +----------------------------------------------------------------------+
21 require_once('Cache/Container.php');
24 * Stores cache contents in a file.
26 * @author Ulf Wendel <ulf.wendel@phpdoc.de>
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 = '';
58 * List of cache entries, used within a gc run
65 * Total number of bytes required by all cache entries, used within a gc run.
72 * Creates the cache directory if neccessary
74 * @param array Config options: ["cache_dir" => ..., "filename_prefix" => ...]
76 function Cache_Container_file($options = '') {
77 if (is_array($options))
78 $this->setOptions($options, array_merge($this->allowed_options, array('cache_dir', 'filename_prefix')));
83 // make relative paths absolute for use in deconstructor.
84 // it looks like the deconstructor has problems with relative paths
85 if (OS_UNIX && '/' != $this->cache_dir{0} )
86 $this->cache_dir = realpath( getcwd() . '/' . $this->cache_dir) . '/';
88 // check if a trailing slash is in cache_dir
89 if (!substr($this->cache_dir,-1) )
90 $this->cache_dir .= '/';
92 if (!file_exists($this->cache_dir) || !is_dir($this->cache_dir))
93 mkdir($this->cache_dir, 0755);
95 $this->entries = array();
96 $this->group_dirs = array();
98 } // end func contructor
100 function fetch($id, $group) {
101 $file = $this->getFilename($id, $group);
102 if (!file_exists($file))
103 return array(NULL, NULL, NULL);
105 // retrive the content
106 if (!($fh = @fopen($file, 'rb')))
107 return new Cache_Error("Can't access cache file '$file'. Check access rights and path.", __FILE__, __LINE__);
110 // 1st line: expiration date
111 // 2nd line: user data
112 // 3rd+ lines: cache data
113 $expire = trim(fgets($fh, 12));
114 $userdata = trim(fgets($fh, 257));
115 $cachedata = $this->decode(fread($fh, filesize($file)));
119 if (is_array($cachedata))
120 if (file_exists($file.'.img')) {
121 $fh = @fopen($file.'.img',"rb");
122 $cachedata['image'] = fread($fh,filesize($file.'.img'));
127 // last usage date used by the gc - maxlifetime
128 // touch without second param produced stupid entries...
132 return array($expire, $cachedata, $userdata);
138 * WARNING: If you supply userdata it must not contain any linebreaks,
139 * otherwise it will break the filestructure.
141 function save($id, $cachedata, $expires, $group, $userdata) {
142 $this->flushPreload($id, $group);
144 $file = $this->getFilename($id, $group);
145 if (!($fh = @fopen($file, 'wb')))
146 return new Cache_Error("Can't access '$file' to store cache data. Check access rights and path.", __FILE__, __LINE__);
149 if (is_array($cachedata)&&isset($cachedata['image'])) {
150 $image = $cachedata['image'];
151 unset($cachedata['image']);
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));
166 // I'm not sure if we need this
167 // i don't think we need this (chregu)
172 $file = $this->getFilename($id, $group).'.img';
173 if (!($fh = @fopen($file, 'wb')))
174 return new Cache_Error("Can't access '$file' to store cache data. Check access rights and path.", __FILE__, __LINE__);
183 function remove($id, $group) {
184 $this->flushPreload($id, $group);
186 $file = $this->getFilename($id, $group);
187 if (file_exists($file)) {
198 function flush($group) {
199 $this->flushPreload();
200 $dir = ($group) ? $this->cache_dir . $group . '/' : $this->cache_dir;
202 $num_removed = $this->deleteDir($dir);
203 unset($this->group_dirs[$group]);
209 function idExists($id, $group) {
211 return file_exists($this->getFilename($id, $group));
212 } // end func idExists
215 * Deletes all expired files.
217 * Garbage collection for files is a rather "expensive", "long time"
218 * operation. All files in the cache directory have to be examined which
219 * means that they must be opened for reading, the expiration date has to be
220 * read from them and if neccessary they have to be unlinked (removed).
221 * If you have a user comment for a good default gc probability please add it to
222 * to the inline docs.
224 * @param integer Maximum lifetime in seconds of an no longer used/touched entry
225 * @throws Cache_Error
227 function garbageCollection($maxlifetime) {
229 $this->flushPreload();
232 $ok = $this->doGarbageCollection($maxlifetime, $this->cache_dir);
234 // check the space used by the cache entries
235 if ($this->total_size > $this->highwater) {
237 krsort($this->entries);
238 reset($this->entries);
240 while ($this->total_size > $this->lowwater && list($lastmod, $entry) = each($this->entries)) {
241 if (@unlink($entry['file']))
242 $this->total_size -= $entry['size'];
244 new CacheError("Can't delete {$entry["file"]}. Check the permissions.");
249 $this->entries = array();
250 $this->total_size = 0;
253 } // end func garbageCollection
256 * Does the recursive gc procedure, protected.
258 * @param integer Maximum lifetime in seconds of an no longer used/touched entry
259 * @param string directory to examine - don't sets this parameter, it's used for a
260 * recursive function call!
261 * @throws Cache_Error
263 function doGarbageCollection($maxlifetime, $dir) {
265 if (!($dh = opendir($dir)))
266 return new Cache_Error("Can't access cache directory '$dir'. Check permissions and path.", __FILE__, __LINE__);
268 while ($file = readdir($dh)) {
269 if ('.' == $file || '..' == $file)
272 if ('.img' == substr($file,-4))
276 $file = $dir . $file;
278 $this->doGarbageCollection($maxlifetime,$file . '/');
282 // skip trouble makers but inform the user
283 if (!($fh = @fopen($file, 'rb'))) {
284 new Cache_Error("Can't access cache file '$file', skipping it. Check permissions and path.", __FILE__, __LINE__);
288 $expire = fgets($fh, 12);
290 $lastused = filemtime($file);
294 if (file_exists($file.'.img'))
295 $x = filesize($file.'.img');
296 $this->entries[$lastused] = array('file' => $file, 'size' => filesize($file)+$x);
297 $this->total_size += filesize($file)+$x;
300 if ( ($expire && $expire <= time()) || ($lastused <= (time() - $maxlifetime)) ) {
302 if ( file_exists($file.'.img') )
303 $ok = $ok && unlink($file.'.img');
305 new Cache_Error("Can't unlink cache file '$file', skipping. Check permissions and path.", __FILE__, __LINE__);
312 // flush the disk state cache
315 } // end func doGarbageCollection
318 * Returns the filename for the specified id.
320 * @param string dataset ID
321 * @param string cache group
322 * @return string full filename with the path
325 function getFilename($id, $group) {
327 if (isset($this->group_dirs[$group]))
328 return $this->group_dirs[$group] . $this->filename_prefix . $id;
330 $dir = $this->cache_dir . $group . '/';
331 if (!file_exists($dir)) {
336 $this->group_dirs[$group] = $dir;
338 return $dir . $this->filename_prefix . $id;
339 } // end func getFilename
342 * Deletes a directory and all files in it.
344 * @param string directory
345 * @return integer number of removed files
346 * @throws Cache_Error
348 function deleteDir($dir) {
349 if (!($dh = opendir($dir)))
350 return new Cache_Error("Can't remove directory '$dir'. Check permissions and path.", __FILE__, __LINE__);
354 while ($file = readdir($dh)) {
355 if ('.' == $file || '..' == $file)
358 $file = $dir . $file;
361 $num = $this->deleteDir($file . '/');
363 $num_removed += $num;
369 // according to php-manual the following is needed for windows installations.
372 if ($dir != $this->cache_dir) { //delete the sub-dir entries itself also, but not the cache-dir.
378 } // end func deleteDir