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 // $Id: file.php 293864 2010-01-23 03:49:21Z clockwerx $
21 require_once 'lib/pear/Cache/Container.php';
24 * Stores cache contents in a file.
26 * @author Ulf Wendel <ulf.wendel@phpdoc.de>
27 * @version $Id: file.php 293864 2010-01-23 03:49:21Z clockwerx $
29 class Cache_Container_file extends Cache_Container
35 * With file container, it's possible, that you get corrupted
36 * data-entries under bad circumstances. The file locking must
37 * improve this problem but it's experimental stuff. So the
38 * default value is false. But it seems to give good results
42 var $fileLocking = false;
45 * Directory where to put the cache files.
47 * @var string Make sure to add a trailing slash
52 * Filename prefix for cache files.
54 * You can use the filename prefix to implement a "domain" based cache or just
55 * to give the files a more descriptive name. The word "domain" is borroed from
56 * a user authentification system. One user id (cached dataset with the ID x)
57 * may exists in different domains (different filename prefix). You might want
58 * to use this to have different cache values for a production, development and
59 * quality assurance system. If you want the production cache not to be influenced
60 * by the quality assurance activities, use different filename prefixes for them.
62 * I personally don't think that you'll never need this, but 640kb happend to be
63 * not enough, so... you know what I mean. If you find a useful application of the
64 * feature please update this inline doc.
68 var $filename_prefix = '';
72 * List of cache entries, used within a gc run
79 * Total number of bytes required by all cache entries, used within a gc run.
87 * Max Line Length of userdata
89 * If set to 0, it will take the default
90 * ( 1024 in php 4.2, unlimited in php 4.3)
91 * see http://ch.php.net/manual/en/function.fgets.php
96 var $max_userdata_linelength = 257;
99 * Creates the cache directory if neccessary
101 * @param array Config options: ["cache_dir" => ..., "filename_prefix" => ...]
103 function __construct($options = '')
105 if (is_array($options)) {
106 $this->setOptions($options, array_merge($this->allowed_options, array('cache_dir', 'filename_prefix', 'max_userdata_linelength')));
109 if ($this->cache_dir) {
110 // make relative paths absolute for use in deconstructor.
111 // it looks like the deconstructor has problems with relative paths
112 if (OS_UNIX && '/' != $this->cache_dir[0] )
113 $this->cache_dir = realpath( getcwd() . '/' . $this->cache_dir) . '/';
115 // check if a trailing slash is in cache_dir
116 if ($this->cache_dir[strlen($this->cache_dir)-1] != DIRECTORY_SEPARATOR)
117 $this->cache_dir .= '/';
119 if (!file_exists($this->cache_dir) || !is_dir($this->cache_dir))
120 mkdir($this->cache_dir, 0755);
122 $this->entries = array();
123 $this->group_dirs = array();
125 } // end func contructor
127 function fetch($id, $group)
129 $file = $this->getFilename($id, $group);
130 if (PEAR::isError($file)) {
134 if (!file_exists($file)) {
135 return array(null, null, null);
137 // retrive the content
138 if (!($fh = @fopen($file, 'rb'))) {
139 return new Cache_Error("Can't access cache file '$file'. Check access rights and path.", __FILE__, __LINE__);
141 // File locking (shared lock)
142 if ($this->fileLocking) {
146 // 1st line: expiration date
147 // 2nd line: user data
148 // 3rd+ lines: cache data
149 $expire = trim(fgets($fh, 12));
150 if ($this->max_userdata_linelength == 0 ) {
151 $userdata = trim(fgets($fh));
153 $userdata = trim(fgets($fh, $this->max_userdata_linelength));
157 $buffer .= fread($fh, 8192);
159 $cachedata = $this->decode($buffer);
162 if ($this->fileLocking) {
167 // last usage date used by the gc - maxlifetime
168 // touch without second param produced stupid entries...
172 return array($expire, $cachedata, $userdata);
178 * WARNING: If you supply userdata it must not contain any linebreaks,
179 * otherwise it will break the filestructure.
181 function save($id, $cachedata, $expires, $group, $userdata)
183 $this->flushPreload($id, $group);
185 $file = $this->getFilename($id, $group);
186 if (!($fh = @fopen($file, 'wb'))) {
187 return new Cache_Error("Can't access '$file' to store cache data. Check access rights and path.", __FILE__, __LINE__);
190 // File locking (exclusive lock)
191 if ($this->fileLocking) {
195 // 1st line: expiration date
196 // 2nd line: user data
197 // 3rd+ lines: cache data
198 $expires = $this->getExpiresAbsolute($expires);
199 fwrite($fh, $expires . "\n");
200 fwrite($fh, $userdata . "\n");
201 fwrite($fh, $this->encode($cachedata));
204 if ($this->fileLocking) {
209 // I'm not sure if we need this
210 // i don't think we need this (chregu)
216 function remove($id, $group)
218 $this->flushPreload($id, $group);
220 $file = $this->getFilename($id, $group);
221 if (PEAR::isError($file)) {
225 if (file_exists($file)) {
235 function flush($group)
237 $this->flushPreload();
238 $dir = ($group) ? $this->cache_dir . $group . '/' : $this->cache_dir;
240 $num_removed = $this->deleteDir($dir);
241 unset($this->group_dirs[$group]);
247 function idExists($id, $group)
249 return file_exists($this->getFilename($id, $group));
250 } // end func idExists
253 * Deletes all expired files.
255 * Garbage collection for files is a rather "expensive", "long time"
256 * operation. All files in the cache directory have to be examined which
257 * means that they must be opened for reading, the expiration date has to be
258 * read from them and if neccessary they have to be unlinked (removed).
259 * If you have a user comment for a good default gc probability please add it to
260 * to the inline docs.
262 * @param integer Maximum lifetime in seconds of an no longer used/touched entry
263 * @throws Cache_Error
265 function garbageCollection($maxlifetime)
267 $this->flushPreload();
270 $ok = $this->doGarbageCollection($maxlifetime, $this->cache_dir);
272 // check the space used by the cache entries
273 if ($this->total_size > $this->highwater) {
275 krsort($this->entries);
276 reset($this->entries);
278 foreach ($this->entries as $lastmod => $entry) {
279 if ($this->total_size <= $this->lowwater) break;
280 if (@unlink($entry['file'])) {
281 $this->total_size -= $entry['size'];
283 new CacheError("Can't delete {$entry['file']}. Check the permissions.");
289 $this->entries = array();
290 $this->total_size = 0;
293 } // end func garbageCollection
296 * Does the recursive gc procedure, protected.
298 * @param integer Maximum lifetime in seconds of an no longer used/touched entry
299 * @param string directory to examine - don't sets this parameter, it's used for a
300 * recursive function call!
301 * @throws Cache_Error
303 function doGarbageCollection($maxlifetime, $dir)
305 if (!is_writable($dir) || !is_readable($dir) || !($dh = opendir($dir))) {
306 return new Cache_Error("Can't remove directory '$dir'. Check permissions and path.", __FILE__, __LINE__);
309 while ($file = readdir($dh)) {
310 if ('.' == $file || '..' == $file)
313 $file = $dir . $file;
315 $this->doGarbageCollection($maxlifetime,$file . '/');
319 // skip trouble makers but inform the user
320 if (!($fh = @fopen($file, 'rb'))) {
321 new Cache_Error("Can't access cache file '$file', skipping it. Check permissions and path.", __FILE__, __LINE__);
325 $expire = fgets($fh, 11);
327 $lastused = filemtime($file);
329 $this->entries[$lastused] = array('file' => $file, 'size' => filesize($file));
330 $this->total_size += filesize($file);
333 if (( ($expire && $expire <= time()) || ($lastused <= (time() - $maxlifetime)) ) && !unlink($file)) {
334 new Cache_Error("Can't unlink cache file '$file', skipping. Check permissions and path.", __FILE__, __LINE__);
340 // flush the disk state cache
343 } // end func doGarbageCollection
346 * Returns the filename for the specified id.
348 * @param string dataset ID
349 * @param string cache group
350 * @return string full filename with the path
353 function getFilename($id, $group)
355 if (isset($this->group_dirs[$group])) {
356 return $this->group_dirs[$group] . $this->filename_prefix . $id;
359 $dir = $this->cache_dir . $group . '/';
360 if (is_writeable($this->cache_dir)) {
361 if (!file_exists($dir)) {
362 mkdir($dir, 0755, true);
366 return new Cache_Error("Can't make directory '$dir'. Check permissions and path.", __FILE__, __LINE__);
368 $this->group_dirs[$group] = $dir;
370 return $dir . $this->filename_prefix . $id;
371 } // end func getFilename
374 * Deletes a directory and all files in it.
376 * @param string directory
377 * @return integer number of removed files
378 * @throws Cache_Error
380 function deleteDir($dir)
382 if (!is_writable($dir) || !is_readable($dir) || !($dh = opendir($dir))) {
383 return new Cache_Error("Can't remove directory '$dir'. Check permissions and path.", __FILE__, __LINE__);
388 while (false !== $file = readdir($dh)) {
389 if ('.' == $file || '..' == $file)
392 $file = $dir . $file;
395 $num = $this->deleteDir($file . '/');
397 $num_removed += $num;
403 // according to php-manual the following is needed for windows installations.
406 if ($dir != $this->cache_dir) { //delete the sub-dir entries itself also, but not the cache-dir.
412 } // end func deleteDir