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 require_once('Cache/Container.php');
22 * Stores cache contents in a file.
24 * @author Ulf Wendel <ulf.wendel@phpdoc.de>
27 class Cache_Container_file extends Cache_Container {
30 * Directory where to put the cache files.
32 * @var string Make sure to add a trailing slash
37 * Filename prefix for cache files.
39 * You can use the filename prefix to implement a "domain" based cache or just
40 * to give the files a more descriptive name. The word "domain" is borroed from
41 * a user authentication system. One user id (cached dataset with the ID x)
42 * may exists in different domains (different filename prefix). You might want
43 * to use this to have different cache values for a production, development and
44 * quality assurance system. If you want the production cache not to be influenced
45 * by the quality assurance activities, use different filename prefixes for them.
47 * I personally don't think that you'll never need this, but 640kb happend to be
48 * not enough, so... you know what I mean. If you find a useful application of the
49 * feature please update this inline doc.
53 var $filename_prefix = '';
56 * List of cache entries, used within a gc run
63 * Total number of bytes required by all cache entries, used within a gc run.
70 * Creates the cache directory if neccessary
72 * @param array Config options: ["cache_dir" => ..., "filename_prefix" => ...]
74 function Cache_Container_file($options = '') {
75 if (is_array($options))
76 $this->setOptions($options, array_merge($this->allowed_options, array('cache_dir', 'filename_prefix')));
81 // make relative paths absolute for use in deconstructor.
82 // it looks like the deconstructor has problems with relative paths
83 if (OS_UNIX && '/' != $this->cache_dir{0} )
84 $this->cache_dir = realpath( getcwd() . '/' . $this->cache_dir) . '/';
86 // check if a trailing slash is in cache_dir
87 if (!substr($this->cache_dir,-1) )
88 $this->cache_dir .= '/';
90 if (!file_exists($this->cache_dir) || !is_dir($this->cache_dir))
91 mkdir($this->cache_dir, 0755);
93 $this->entries = array();
94 $this->group_dirs = array();
96 } // end func contructor
98 function fetch($id, $group) {
99 $file = $this->getFilename($id, $group);
100 if (!file_exists($file))
101 return array(NULL, NULL, NULL);
103 // retrive the content
104 if (!($fh = @fopen($file, 'rb')))
105 return new Cache_Error("Can't access cache file '$file'. Check access rights and path.", __FILE__, __LINE__);
108 // 1st line: expiration date
109 // 2nd line: user data
110 // 3rd+ lines: cache data
111 $expire = trim(fgets($fh, 12));
112 $userdata = trim(fgets($fh, 257));
113 $cachedata = $this->decode(fread($fh, filesize($file)));
117 if (is_array($cachedata))
118 if (file_exists($file.'.img')) {
119 $fh = @fopen($file.'.img',"rb");
120 $cachedata['image'] = fread($fh,filesize($file.'.img'));
125 // last usage date used by the gc - maxlifetime
126 // touch without second param produced stupid entries...
130 return array($expire, $cachedata, $userdata);
136 * WARNING: If you supply userdata it must not contain any linebreaks,
137 * otherwise it will break the filestructure.
139 function save($id, $cachedata, $expires, $group, $userdata) {
140 $this->flushPreload($id, $group);
142 $file = $this->getFilename($id, $group);
143 if (!($fh = @fopen($file, 'wb')))
144 return new Cache_Error("Can't access '$file' to store cache data. Check access rights and path.", __FILE__, __LINE__);
147 if (is_array($cachedata)&&isset($cachedata['image'])) {
148 $image = $cachedata['image'];
149 unset($cachedata['image']);
154 // 1st line: expiration date
155 // 2nd line: user data
156 // 3rd+ lines: cache data
157 $expires = $this->getExpiresAbsolute($expires);
158 fwrite($fh, $expires . "\n");
159 fwrite($fh, $userdata . "\n");
160 fwrite($fh, $this->encode($cachedata));
164 // I'm not sure if we need this
165 // i don't think we need this (chregu)
170 $file = $this->getFilename($id, $group).'.img';
171 if (!($fh = @fopen($file, 'wb')))
172 return new Cache_Error("Can't access '$file' to store cache data. Check access rights and path.", __FILE__, __LINE__);
181 function remove($id, $group) {
182 $this->flushPreload($id, $group);
184 $file = $this->getFilename($id, $group);
185 if (file_exists($file)) {
196 function flush($group) {
197 $this->flushPreload();
198 $dir = ($group) ? $this->cache_dir . $group . '/' : $this->cache_dir;
200 $num_removed = $this->deleteDir($dir);
201 unset($this->group_dirs[$group]);
207 function idExists($id, $group) {
209 return file_exists($this->getFilename($id, $group));
210 } // end func idExists
213 * Deletes all expired files.
215 * Garbage collection for files is a rather "expensive", "long time"
216 * operation. All files in the cache directory have to be examined which
217 * means that they must be opened for reading, the expiration date has to be
218 * read from them and if neccessary they have to be unlinked (removed).
219 * If you have a user comment for a good default gc probability please add it to
220 * to the inline docs.
222 * @param integer Maximum lifetime in seconds of an no longer used/touched entry
223 * @throws Cache_Error
225 function garbageCollection($maxlifetime) {
227 $this->flushPreload();
230 $ok = $this->doGarbageCollection($maxlifetime, $this->cache_dir);
232 // check the space used by the cache entries
233 if ($this->total_size > $this->highwater) {
235 krsort($this->entries);
236 reset($this->entries);
238 while ($this->total_size > $this->lowwater && list($lastmod, $entry) = each($this->entries)) {
239 if (@unlink($entry['file']))
240 $this->total_size -= $entry['size'];
242 new CacheError("Can't delete {$entry["file"]}. Check the permissions.");
247 $this->entries = array();
248 $this->total_size = 0;
251 } // end func garbageCollection
254 * Does the recursive gc procedure, protected.
256 * @param integer Maximum lifetime in seconds of an no longer used/touched entry
257 * @param string directory to examine - don't sets this parameter, it's used for a
258 * recursive function call!
259 * @throws Cache_Error
261 function doGarbageCollection($maxlifetime, $dir) {
263 if (!($dh = opendir($dir)))
264 return new Cache_Error("Can't access cache directory '$dir'. Check permissions and path.", __FILE__, __LINE__);
266 while ($file = readdir($dh)) {
267 if ('.' == $file || '..' == $file)
270 if ('.img' == substr($file,-4))
274 $file = $dir . $file;
276 $this->doGarbageCollection($maxlifetime,$file . '/');
280 // skip trouble makers but inform the user
281 if (!($fh = @fopen($file, 'rb'))) {
282 new Cache_Error("Can't access cache file '$file', skipping it. Check permissions and path.", __FILE__, __LINE__);
286 $expire = fgets($fh, 12);
288 $lastused = filemtime($file);
292 if (file_exists($file.'.img'))
293 $x = filesize($file.'.img');
294 $this->entries[$lastused] = array('file' => $file, 'size' => filesize($file)+$x);
295 $this->total_size += filesize($file)+$x;
298 if ( ($expire && $expire <= time()) || ($lastused <= (time() - $maxlifetime)) ) {
300 if ( file_exists($file.'.img') )
301 $ok = $ok && unlink($file.'.img');
303 new Cache_Error("Can't unlink cache file '$file', skipping. Check permissions and path.", __FILE__, __LINE__);
310 // flush the disk state cache
313 } // end func doGarbageCollection
316 * Returns the filename for the specified id.
318 * @param string dataset ID
319 * @param string cache group
320 * @return string full filename with the path
323 function getFilename($id, $group) {
325 if (isset($this->group_dirs[$group]))
326 return $this->group_dirs[$group] . $this->filename_prefix . $id;
328 $dir = $this->cache_dir . $group . '/';
329 if (!file_exists($dir)) {
334 $this->group_dirs[$group] = $dir;
336 return $dir . $this->filename_prefix . $id;
337 } // end func getFilename
340 * Deletes a directory and all files in it.
342 * @param string directory
343 * @return integer number of removed files
344 * @throws Cache_Error
346 function deleteDir($dir) {
347 if (!($dh = opendir($dir)))
348 return new Cache_Error("Can't remove directory '$dir'. Check permissions and path.", __FILE__, __LINE__);
352 while ($file = readdir($dh)) {
353 if ('.' == $file || '..' == $file)
356 $file = $dir . $file;
359 $num = $this->deleteDir($file . '/');
361 $num_removed += $num;
367 // according to php-manual the following is needed for windows installations.
370 if ($dir != $this->cache_dir) { //delete the sub-dir entries itself also, but not the cache-dir.
376 } // end func deleteDir