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 = '';
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)));
120 if (is_array($cachedata))
121 if (file_exists($file.'.img')) {
122 $fh = @fopen($file.'.img',"rb");
123 $cachedata['image'] = fread($fh,filesize($file.'.img'));
128 // last usage date used by the gc - maxlifetime
129 // touch without second param produced stupid entries...
133 return array($expire, $cachedata, $userdata);
139 * WARNING: If you supply userdata it must not contain any linebreaks,
140 * otherwise it will break the filestructure.
142 function save($id, $cachedata, $expires, $group, $userdata) {
143 $this->flushPreload($id, $group);
145 $file = $this->getFilename($id, $group);
146 if (!($fh = @fopen($file, 'wb')))
147 return new Cache_Error("Can't access '$file' to store cache data. Check access rights and path.", __FILE__, __LINE__);
150 if (is_array($cachedata)&&isset($cachedata['image'])) {
151 $image = $cachedata['image'];
152 unset($cachedata['image']);
157 // 1st line: expiration date
158 // 2nd line: user data
159 // 3rd+ lines: cache data
160 $expires = $this->getExpiresAbsolute($expires);
161 fwrite($fh, $expires . "\n");
162 fwrite($fh, $userdata . "\n");
163 fwrite($fh, $this->encode($cachedata));
167 // I'm not sure if we need this
168 // i don't think we need this (chregu)
173 $file = $this->getFilename($id, $group).'.img';
174 if (!($fh = @fopen($file, 'wb')))
175 return new Cache_Error("Can't access '$file' to store cache data. Check access rights and path.", __FILE__, __LINE__);
184 function remove($id, $group) {
185 $this->flushPreload($id, $group);
187 $file = $this->getFilename($id, $group);
188 if (file_exists($file)) {
199 function flush($group) {
200 $this->flushPreload();
201 $dir = ($group) ? $this->cache_dir . $group . '/' : $this->cache_dir;
203 $num_removed = $this->deleteDir($dir);
204 unset($this->group_dirs[$group]);
210 function idExists($id, $group) {
212 return file_exists($this->getFilename($id, $group));
213 } // end func idExists
216 * Deletes all expired files.
218 * Garbage collection for files is a rather "expensive", "long time"
219 * operation. All files in the cache directory have to be examined which
220 * means that they must be opened for reading, the expiration date has to be
221 * read from them and if neccessary they have to be unlinked (removed).
222 * If you have a user comment for a good default gc probability please add it to
223 * to the inline docs.
225 * @param integer Maximum lifetime in seconds of an no longer used/touched entry
226 * @throws Cache_Error
228 function garbageCollection($maxlifetime) {
230 $this->flushPreload();
233 $ok = $this->doGarbageCollection($maxlifetime, $this->cache_dir);
235 // check the space used by the cache entries
236 if ($this->total_size > $this->highwater) {
238 krsort($this->entries);
239 reset($this->entries);
241 while ($this->total_size > $this->lowwater && list($lastmod, $entry) = each($this->entries)) {
242 if (@unlink($entry['file']))
243 $this->total_size -= $entry['size'];
245 new CacheError("Can't delete {$entry["file"]}. Check the permissions.");
250 $this->entries = array();
251 $this->total_size = 0;
254 } // end func garbageCollection
257 * Does the recursive gc procedure, protected.
259 * @param integer Maximum lifetime in seconds of an no longer used/touched entry
260 * @param string directory to examine - don't sets this parameter, it's used for a
261 * recursive function call!
262 * @throws Cache_Error
264 function doGarbageCollection($maxlifetime, $dir) {
266 if (!($dh = opendir($dir)))
267 return new Cache_Error("Can't access cache directory '$dir'. Check permissions and path.", __FILE__, __LINE__);
269 while ($file = readdir($dh)) {
270 if ('.' == $file || '..' == $file)
273 if ('.img' == substr($file,-4))
277 $file = $dir . $file;
279 $this->doGarbageCollection($maxlifetime,$file . '/');
283 // skip trouble makers but inform the user
284 if (!($fh = @fopen($file, 'rb'))) {
285 new Cache_Error("Can't access cache file '$file', skipping it. Check permissions and path.", __FILE__, __LINE__);
289 $expire = fgets($fh, 12);
291 $lastused = filemtime($file);
295 if (file_exists($file.'.img'))
296 $x = filesize($file.'.img');
297 $this->entries[$lastused] = array('file' => $file, 'size' => filesize($file)+$x);
298 $this->total_size += filesize($file)+$x;
301 if ( ($expire && $expire <= time()) || ($lastused <= (time() - $maxlifetime)) ) {
303 if ( file_exists($file.'.img') )
304 $ok = $ok && unlink($file.'.img');
306 new Cache_Error("Can't unlink cache file '$file', skipping. Check permissions and path.", __FILE__, __LINE__);
313 // flush the disk state cache
316 } // end func doGarbageCollection
319 * Returns the filename for the specified id.
321 * @param string dataset ID
322 * @param string cache group
323 * @return string full filename with the path
326 function getFilename($id, $group) {
328 if (isset($this->group_dirs[$group]))
329 return $this->group_dirs[$group] . $this->filename_prefix . $id;
331 $dir = $this->cache_dir . $group . '/';
332 if (!file_exists($dir)) {
337 $this->group_dirs[$group] = $dir;
339 return $dir . $this->filename_prefix . $id;
340 } // end func getFilename
343 * Deletes a directory and all files in it.
345 * @param string directory
346 * @return integer number of removed files
347 * @throws Cache_Error
349 function deleteDir($dir) {
350 if (!($dh = opendir($dir)))
351 return new Cache_Error("Can't remove directory '$dir'. Check permissions and path.", __FILE__, __LINE__);
355 while ($file = readdir($dh)) {
356 if ('.' == $file || '..' == $file)
359 $file = $dir . $file;
362 $num = $this->deleteDir($file . '/');
364 $num_removed += $num;
370 // according to php-manual the following is needed for windows installations.
373 if ($dir != $this->cache_dir) { //delete the sub-dir entries itself also, but not the cache-dir.
379 } // end func deleteDir