2 // +----------------------------------------------------------------------+
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 // +----------------------------------------------------------------------+
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 {
34 * With file container, it's possible, that you get corrupted
35 * data-entries under bad circumstances. The file locking must
36 * improve this problem but it's experimental stuff. So the
37 * default value is false. But it seems to give good results
41 var $fileLocking = false;
44 * Directory where to put the cache files.
46 * @var string Make sure to add a trailing slash
51 * Filename prefix for cache files.
53 * You can use the filename prefix to implement a "domain" based cache or just
54 * to give the files a more descriptive name. The word "domain" is borroed from
55 * a user authentification system. One user id (cached dataset with the ID x)
56 * may exists in different domains (different filename prefix). You might want
57 * to use this to have different cache values for a production, development and
58 * quality assurance system. If you want the production cache not to be influenced
59 * by the quality assurance activities, use different filename prefixes for them.
61 * I personally don't think that you'll never need this, but 640kb happend to be
62 * not enough, so... you know what I mean. If you find a useful application of the
63 * feature please update this inline doc.
67 var $filename_prefix = '';
71 * List of cache entries, used within a gc run
78 * Total number of bytes required by all cache entries, used within a gc run.
86 * Max Line Length of userdata
88 * If set to 0, it will take the default
89 * ( 1024 in php 4.2, unlimited in php 4.3)
90 * see http://ch.php.net/manual/en/function.fgets.php
95 var $max_userdata_linelength = 257;
98 * Creates the cache directory if neccessary
100 * @param array Config options: ["cache_dir" => ..., "filename_prefix" => ...]
102 function Cache_Container_file($options = '') {
103 if (is_array($options))
104 $this->setOptions($options, array_merge($this->allowed_options, array('cache_dir', 'filename_prefix', 'max_userdata_linelength')));
107 if ($this->cache_dir)
109 // make relative paths absolute for use in deconstructor.
110 // it looks like the deconstructor has problems with relative paths
111 if (OS_UNIX && '/' != $this->cache_dir{0} )
112 $this->cache_dir = realpath( getcwd() . '/' . $this->cache_dir) . '/';
114 // check if a trailing slash is in cache_dir
115 if ($this->cache_dir{strlen($this->cache_dir)-1} != DIRECTORY_SEPARATOR)
116 $this->cache_dir .= '/';
118 if (!file_exists($this->cache_dir) || !is_dir($this->cache_dir))
119 mkdir($this->cache_dir, 0755);
121 $this->entries = array();
122 $this->group_dirs = array();
124 } // end func contructor
126 function fetch($id, $group) {
127 $file = $this->getFilename($id, $group);
128 if (!file_exists($file))
129 return array(NULL, NULL, NULL);
131 // retrive the content
132 if (!($fh = @fopen($file, 'rb')))
133 return new Cache_Error("Can't access cache file '$file'. Check access rights and path.", __FILE__, __LINE__);
135 // File locking (shared lock)
136 if ($this->fileLocking)
140 // 1st line: expiration date
141 // 2nd line: user data
142 // 3rd+ lines: cache data
143 $expire = trim(fgets($fh, 12));
144 if ($this->max_userdata_linelength == 0 ) {
145 $userdata = trim(fgets($fh));
147 $userdata = trim(fgets($fh, $this->max_userdata_linelength));
149 $cachedata = $this->decode(fread($fh, filesize($file)));
152 if ($this->fileLocking)
157 // last usage date used by the gc - maxlifetime
158 // touch without second param produced stupid entries...
162 return array($expire, $cachedata, $userdata);
168 * WARNING: If you supply userdata it must not contain any linebreaks,
169 * otherwise it will break the filestructure.
171 function save($id, $cachedata, $expires, $group, $userdata) {
172 $this->flushPreload($id, $group);
174 $file = $this->getFilename($id, $group);
175 if (!($fh = @fopen($file, 'wb')))
176 return new Cache_Error("Can't access '$file' to store cache data. Check access rights and path.", __FILE__, __LINE__);
178 // File locking (exclusive lock)
179 if ($this->fileLocking)
183 // 1st line: expiration date
184 // 2nd line: user data
185 // 3rd+ lines: cache data
186 $expires = $this->getExpiresAbsolute($expires);
187 fwrite($fh, $expires . "\n");
188 fwrite($fh, $userdata . "\n");
189 fwrite($fh, $this->encode($cachedata));
192 if ($this->fileLocking)
197 // I'm not sure if we need this
198 // i don't think we need this (chregu)
204 function remove($id, $group) {
205 $this->flushPreload($id, $group);
207 $file = $this->getFilename($id, $group);
208 if (file_exists($file)) {
219 function flush($group) {
220 $this->flushPreload();
221 $dir = ($group) ? $this->cache_dir . $group . '/' : $this->cache_dir;
223 $num_removed = $this->deleteDir($dir);
224 unset($this->group_dirs[$group]);
230 function idExists($id, $group) {
232 return file_exists($this->getFilename($id, $group));
233 } // end func idExists
236 * Deletes all expired files.
238 * Garbage collection for files is a rather "expensive", "long time"
239 * operation. All files in the cache directory have to be examined which
240 * means that they must be opened for reading, the expiration date has to be
241 * read from them and if neccessary they have to be unlinked (removed).
242 * If you have a user comment for a good default gc probability please add it to
243 * to the inline docs.
245 * @param integer Maximum lifetime in seconds of an no longer used/touched entry
246 * @throws Cache_Error
248 function garbageCollection($maxlifetime) {
250 $this->flushPreload();
253 $ok = $this->doGarbageCollection($maxlifetime, $this->cache_dir);
255 // check the space used by the cache entries
256 if ($this->total_size > $this->highwater) {
258 krsort($this->entries);
259 reset($this->entries);
261 while ($this->total_size > $this->lowwater && list($lastmod, $entry) = each($this->entries)) {
262 if (@unlink($entry['file']))
263 $this->total_size -= $entry['size'];
265 new CacheError("Can't delete {$entry["file"]}. Check the permissions.");
270 $this->entries = array();
271 $this->total_size = 0;
274 } // end func garbageCollection
277 * Does the recursive gc procedure, protected.
279 * @param integer Maximum lifetime in seconds of an no longer used/touched entry
280 * @param string directory to examine - don't sets this parameter, it's used for a
281 * recursive function call!
282 * @throws Cache_Error
284 function doGarbageCollection($maxlifetime, $dir) {
286 if (!($dh = opendir($dir)))
287 return new Cache_Error("Can't access cache directory '$dir'. Check permissions and path.", __FILE__, __LINE__);
289 while ($file = readdir($dh)) {
290 if ('.' == $file || '..' == $file)
293 $file = $dir . $file;
295 $this->doGarbageCollection($maxlifetime,$file . '/');
299 // skip trouble makers but inform the user
300 if (!($fh = @fopen($file, 'rb'))) {
301 new Cache_Error("Can't access cache file '$file', skipping it. Check permissions and path.", __FILE__, __LINE__);
305 $expire = fgets($fh, 11);
307 $lastused = filemtime($file);
309 $this->entries[$lastused] = array('file' => $file, 'size' => filesize($file));
310 $this->total_size += filesize($file);
313 if (( ($expire && $expire <= time()) || ($lastused <= (time() - $maxlifetime)) ) && !unlink($file))
314 new Cache_Error("Can't unlink cache file '$file', skipping. Check permissions and path.", __FILE__, __LINE__);
319 // flush the disk state cache
322 } // end func doGarbageCollection
325 * Returns the filename for the specified id.
327 * @param string dataset ID
328 * @param string cache group
329 * @return string full filename with the path
332 function getFilename($id, $group) {
334 if (isset($this->group_dirs[$group]))
335 return $this->group_dirs[$group] . $this->filename_prefix . $id;
337 $dir = $this->cache_dir . $group . '/';
338 if (!file_exists($dir)) {
343 $this->group_dirs[$group] = $dir;
345 return $dir . $this->filename_prefix . $id;
346 } // end func getFilename
349 * Deletes a directory and all files in it.
351 * @param string directory
352 * @return integer number of removed files
353 * @throws Cache_Error
355 function deleteDir($dir) {
356 if (!($dh = opendir($dir)))
357 return new Cache_Error("Can't remove directory '$dir'. Check permissions and path.", __FILE__, __LINE__);
361 while (false !== $file = readdir($dh)) {
362 if ('.' == $file || '..' == $file)
365 $file = $dir . $file;
368 $num = $this->deleteDir($file . '/');
370 $num_removed += $num;
376 // according to php-manual the following is needed for windows installations.
379 if ($dir != $this->cache_dir) { //delete the sub-dir entries itself also, but not the cache-dir.
385 } // end func deleteDir