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 = '';
70 * List of cache entries, used within a gc run
77 * Total number of bytes required by all cache entries, used within a gc run.
84 * Max Line Length of userdata
86 * If set to 0, it will take the default
87 * ( 1024 in php 4.2, unlimited in php 4.3)
88 * see http://ch.php.net/manual/en/function.fgets.php
93 var $max_userdata_linelength = 257;
96 * Creates the cache directory if neccessary
98 * @param array Config options: ["cache_dir" => ..., "filename_prefix" => ...]
100 function Cache_Container_file($options = '') {
101 if (is_array($options))
102 $this->setOptions($options, array_merge($this->allowed_options, array('cache_dir', 'filename_prefix', 'max_userdata_linelength')));
105 if ($this->cache_dir)
107 // make relative paths absolute for use in deconstructor.
108 // it looks like the deconstructor has problems with relative paths
109 if (OS_UNIX && '/' != $this->cache_dir{0} )
110 $this->cache_dir = realpath( getcwd() . '/' . $this->cache_dir) . '/';
112 // check if a trailing slash is in cache_dir
113 if ($this->cache_dir{strlen($this->cache_dir)-1} != DIRECTORY_SEPARATOR)
114 $this->cache_dir .= '/';
116 if (!file_exists($this->cache_dir) || !is_dir($this->cache_dir))
117 mkdir($this->cache_dir, 0755);
119 $this->entries = array();
120 $this->group_dirs = array();
122 } // end func contructor
124 function fetch($id, $group) {
125 $file = $this->getFilename($id, $group);
126 if (!file_exists($file))
127 return array(NULL, NULL, NULL);
129 // retrive the content
130 if (!($fh = @fopen($file, 'rb')))
131 return new Cache_Error("Can't access cache file '$file'. Check access rights and path.", __FILE__, __LINE__);
133 // File locking (shared lock)
134 if ($this->fileLocking)
138 // 1st line: expiration date
139 // 2nd line: user data
140 // 3rd+ lines: cache data
141 $expire = trim(fgets($fh, 12));
142 if ($this->max_userdata_linelength == 0 ) {
143 $userdata = trim(fgets($fh));
145 $userdata = trim(fgets($fh, $this->max_userdata_linelength));
147 $cachedata = $this->decode(fread($fh, filesize($file)));
150 if ($this->fileLocking)
155 // last usage date used by the gc - maxlifetime
156 // touch without second param produced stupid entries...
160 return array($expire, $cachedata, $userdata);
166 * WARNING: If you supply userdata it must not contain any linebreaks,
167 * otherwise it will break the filestructure.
169 function save($id, $cachedata, $expires, $group, $userdata) {
170 $this->flushPreload($id, $group);
172 $file = $this->getFilename($id, $group);
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__);
176 // File locking (exclusive lock)
177 if ($this->fileLocking)
181 // 1st line: expiration date
182 // 2nd line: user data
183 // 3rd+ lines: cache data
184 $expires = $this->getExpiresAbsolute($expires);
185 fwrite($fh, $expires . "\n");
186 fwrite($fh, $userdata . "\n");
187 fwrite($fh, $this->encode($cachedata));
190 if ($this->fileLocking)
195 // I'm not sure if we need this
196 // i don't think we need this (chregu)
202 function remove($id, $group) {
203 $this->flushPreload($id, $group);
205 $file = $this->getFilename($id, $group);
206 if (file_exists($file)) {
217 function flush($group) {
218 $this->flushPreload();
219 $dir = ($group) ? $this->cache_dir . $group . '/' : $this->cache_dir;
221 $num_removed = $this->deleteDir($dir);
222 unset($this->group_dirs[$group]);
228 function idExists($id, $group) {
230 return file_exists($this->getFilename($id, $group));
231 } // end func idExists
234 * Deletes all expired files.
236 * Garbage collection for files is a rather "expensive", "long time"
237 * operation. All files in the cache directory have to be examined which
238 * means that they must be opened for reading, the expiration date has to be
239 * read from them and if neccessary they have to be unlinked (removed).
240 * If you have a user comment for a good default gc probability please add it to
241 * to the inline docs.
243 * @param integer Maximum lifetime in seconds of an no longer used/touched entry
244 * @throws Cache_Error
246 function garbageCollection($maxlifetime) {
248 $this->flushPreload();
251 $ok = $this->doGarbageCollection($maxlifetime, $this->cache_dir);
253 // check the space used by the cache entries
254 if ($this->total_size > $this->highwater) {
256 krsort($this->entries);
257 reset($this->entries);
259 while ($this->total_size > $this->lowwater && list($lastmod, $entry) = each($this->entries)) {
260 if (@unlink($entry['file']))
261 $this->total_size -= $entry['size'];
263 new CacheError("Can't delete {$entry["file"]}. Check the permissions.");
268 $this->entries = array();
269 $this->total_size = 0;
272 } // end func garbageCollection
275 * Does the recursive gc procedure, protected.
277 * @param integer Maximum lifetime in seconds of an no longer used/touched entry
278 * @param string directory to examine - don't sets this parameter, it's used for a
279 * recursive function call!
280 * @throws Cache_Error
282 function doGarbageCollection($maxlifetime, $dir) {
284 if (!($dh = opendir($dir)))
285 return new Cache_Error("Can't access cache directory '$dir'. Check permissions and path.", __FILE__, __LINE__);
287 while ($file = readdir($dh)) {
288 if ('.' == $file || '..' == $file)
291 $file = $dir . $file;
293 $this->doGarbageCollection($maxlifetime,$file . '/');
297 // skip trouble makers but inform the user
298 if (!($fh = @fopen($file, 'rb'))) {
299 new Cache_Error("Can't access cache file '$file', skipping it. Check permissions and path.", __FILE__, __LINE__);
303 $expire = fgets($fh, 11);
305 $lastused = filemtime($file);
307 $this->entries[$lastused] = array('file' => $file, 'size' => filesize($file));
308 $this->total_size += filesize($file);
311 if (( ($expire && $expire <= time()) || ($lastused <= (time() - $maxlifetime)) ) && !unlink($file))
312 new Cache_Error("Can't unlink cache file '$file', skipping. Check permissions and path.", __FILE__, __LINE__);
317 // flush the disk state cache
320 } // end func doGarbageCollection
323 * Returns the filename for the specified id.
325 * @param string dataset ID
326 * @param string cache group
327 * @return string full filename with the path
330 function getFilename($id, $group) {
332 if (isset($this->group_dirs[$group]))
333 return $this->group_dirs[$group] . $this->filename_prefix . $id;
335 $dir = $this->cache_dir . $group . '/';
336 if (!file_exists($dir)) {
341 $this->group_dirs[$group] = $dir;
343 return $dir . $this->filename_prefix . $id;
344 } // end func getFilename
347 * Deletes a directory and all files in it.
349 * @param string directory
350 * @return integer number of removed files
351 * @throws Cache_Error
353 function deleteDir($dir) {
354 if (!($dh = opendir($dir)))
355 return new Cache_Error("Can't remove directory '$dir'. Check permissions and path.", __FILE__, __LINE__);
359 while (false !== $file = readdir($dh)) {
360 if ('.' == $file || '..' == $file)
363 $file = $dir . $file;
366 $num = $this->deleteDir($file . '/');
368 $num_removed += $num;
374 // according to php-manual the following is needed for windows installations.
377 if ($dir != $this->cache_dir) { //delete the sub-dir entries itself also, but not the cache-dir.
383 } // end func deleteDir