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 // +----------------------------------------------------------------------+
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 {
32 * With file container, it's possible, that you get corrupted
33 * data-entries under bad circumstances. The file locking must
34 * improve this problem but it's experimental stuff. So the
35 * default value is false. But it seems to give good results
39 var $fileLocking = false;
42 * Directory where to put the cache files.
44 * @var string Make sure to add a trailing slash
49 * Filename prefix for cache files.
51 * You can use the filename prefix to implement a "domain" based cache or just
52 * to give the files a more descriptive name. The word "domain" is borroed from
53 * a user authentification system. One user id (cached dataset with the ID x)
54 * may exists in different domains (different filename prefix). You might want
55 * to use this to have different cache values for a production, development and
56 * quality assurance system. If you want the production cache not to be influenced
57 * by the quality assurance activities, use different filename prefixes for them.
59 * I personally don't think that you'll never need this, but 640kb happend to be
60 * not enough, so... you know what I mean. If you find a useful application of the
61 * feature please update this inline doc.
65 var $filename_prefix = '';
68 * List of cache entries, used within a gc run
75 * Total number of bytes required by all cache entries, used within a gc run.
82 * Max Line Length of userdata
84 * If set to 0, it will take the default
85 * ( 1024 in php 4.2, unlimited in php 4.3)
86 * see http://ch.php.net/manual/en/function.fgets.php
91 var $max_userdata_linelength = 257;
94 * Creates the cache directory if neccessary
96 * @param array Config options: ["cache_dir" => ..., "filename_prefix" => ...]
98 function Cache_Container_file($options = '') {
99 if (is_array($options))
100 $this->setOptions($options, array_merge($this->allowed_options, array('cache_dir', 'filename_prefix', 'max_userdata_linelength')));
103 if ($this->cache_dir)
105 // make relative paths absolute for use in deconstructor.
106 // it looks like the deconstructor has problems with relative paths
107 if (OS_UNIX && '/' != $this->cache_dir{0} )
108 $this->cache_dir = realpath( getcwd() . '/' . $this->cache_dir) . '/';
110 // check if a trailing slash is in cache_dir
111 if ($this->cache_dir{strlen($this->cache_dir)-1} != DIRECTORY_SEPARATOR)
112 $this->cache_dir .= '/';
114 if (!file_exists($this->cache_dir) || !is_dir($this->cache_dir))
115 mkdir($this->cache_dir, 0755);
117 $this->entries = array();
118 $this->group_dirs = array();
120 } // end func contructor
122 function fetch($id, $group) {
123 $file = $this->getFilename($id, $group);
124 if (!file_exists($file))
125 return array(NULL, NULL, NULL);
127 // retrive the content
128 if (!($fh = @fopen($file, 'rb')))
129 return new Cache_Error("Can't access cache file '$file'. Check access rights and path.", __FILE__, __LINE__);
131 // File locking (shared lock)
132 if ($this->fileLocking)
136 // 1st line: expiration date
137 // 2nd line: user data
138 // 3rd+ lines: cache data
139 $expire = trim(fgets($fh, 12));
140 if ($this->max_userdata_linelength == 0 ) {
141 $userdata = trim(fgets($fh));
143 $userdata = trim(fgets($fh, $this->max_userdata_linelength));
145 $cachedata = $this->decode(fread($fh, filesize($file)));
148 if ($this->fileLocking)
153 // last usage date used by the gc - maxlifetime
154 // touch without second param produced stupid entries...
158 return array($expire, $cachedata, $userdata);
164 * WARNING: If you supply userdata it must not contain any linebreaks,
165 * otherwise it will break the filestructure.
167 function save($id, $cachedata, $expires, $group, $userdata) {
168 $this->flushPreload($id, $group);
170 $file = $this->getFilename($id, $group);
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__);
174 // File locking (exclusive lock)
175 if ($this->fileLocking)
179 // 1st line: expiration date
180 // 2nd line: user data
181 // 3rd+ lines: cache data
182 $expires = $this->getExpiresAbsolute($expires);
183 fwrite($fh, $expires . "\n");
184 fwrite($fh, $userdata . "\n");
185 fwrite($fh, $this->encode($cachedata));
188 if ($this->fileLocking)
193 // I'm not sure if we need this
194 // i don't think we need this (chregu)
200 function remove($id, $group) {
201 $this->flushPreload($id, $group);
203 $file = $this->getFilename($id, $group);
204 if (file_exists($file)) {
215 function flush($group) {
216 $this->flushPreload();
217 $dir = ($group) ? $this->cache_dir . $group . '/' : $this->cache_dir;
219 $num_removed = $this->deleteDir($dir);
220 unset($this->group_dirs[$group]);
226 function idExists($id, $group) {
228 return file_exists($this->getFilename($id, $group));
229 } // end func idExists
232 * Deletes all expired files.
234 * Garbage collection for files is a rather "expensive", "long time"
235 * operation. All files in the cache directory have to be examined which
236 * means that they must be opened for reading, the expiration date has to be
237 * read from them and if neccessary they have to be unlinked (removed).
238 * If you have a user comment for a good default gc probability please add it to
239 * to the inline docs.
241 * @param integer Maximum lifetime in seconds of an no longer used/touched entry
242 * @throws Cache_Error
244 function garbageCollection($maxlifetime) {
246 $this->flushPreload();
249 $ok = $this->doGarbageCollection($maxlifetime, $this->cache_dir);
251 // check the space used by the cache entries
252 if ($this->total_size > $this->highwater) {
254 krsort($this->entries);
255 reset($this->entries);
257 while ($this->total_size > $this->lowwater && list($lastmod, $entry) = each($this->entries)) {
258 if (@unlink($entry['file']))
259 $this->total_size -= $entry['size'];
261 new CacheError("Can't delete {$entry["file"]}. Check the permissions.");
266 $this->entries = array();
267 $this->total_size = 0;
270 } // end func garbageCollection
273 * Does the recursive gc procedure, protected.
275 * @param integer Maximum lifetime in seconds of an no longer used/touched entry
276 * @param string directory to examine - don't sets this parameter, it's used for a
277 * recursive function call!
278 * @throws Cache_Error
280 function doGarbageCollection($maxlifetime, $dir) {
282 if (!($dh = opendir($dir)))
283 return new Cache_Error("Can't access cache directory '$dir'. Check permissions and path.", __FILE__, __LINE__);
285 while ($file = readdir($dh)) {
286 if ('.' == $file || '..' == $file)
289 $file = $dir . $file;
291 $this->doGarbageCollection($maxlifetime,$file . '/');
295 // skip trouble makers but inform the user
296 if (!($fh = @fopen($file, 'rb'))) {
297 new Cache_Error("Can't access cache file '$file', skipping it. Check permissions and path.", __FILE__, __LINE__);
301 $expire = fgets($fh, 11);
303 $lastused = filemtime($file);
305 $this->entries[$lastused] = array('file' => $file, 'size' => filesize($file));
306 $this->total_size += filesize($file);
309 if (( ($expire && $expire <= time()) || ($lastused <= (time() - $maxlifetime)) ) && !unlink($file))
310 new Cache_Error("Can't unlink cache file '$file', skipping. Check permissions and path.", __FILE__, __LINE__);
315 // flush the disk state cache
318 } // end func doGarbageCollection
321 * Returns the filename for the specified id.
323 * @param string dataset ID
324 * @param string cache group
325 * @return string full filename with the path
328 function getFilename($id, $group) {
330 if (isset($this->group_dirs[$group]))
331 return $this->group_dirs[$group] . $this->filename_prefix . $id;
333 $dir = $this->cache_dir . $group . '/';
334 if (!file_exists($dir)) {
339 $this->group_dirs[$group] = $dir;
341 return $dir . $this->filename_prefix . $id;
342 } // end func getFilename
345 * Deletes a directory and all files in it.
347 * @param string directory
348 * @return integer number of removed files
349 * @throws Cache_Error
351 function deleteDir($dir) {
352 if (!($dh = opendir($dir)))
353 return new Cache_Error("Can't remove directory '$dir'. Check permissions and path.", __FILE__, __LINE__);
357 while (false !== $file = readdir($dh)) {
358 if ('.' == $file || '..' == $file)
361 $file = $dir . $file;
364 $num = $this->deleteDir($file . '/');
366 $num_removed += $num;
372 // according to php-manual the following is needed for windows installations.
375 if ($dir != $this->cache_dir) { //delete the sub-dir entries itself also, but not the cache-dir.
381 } // end func deleteDir