]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/pear/Cache/Container/file.php
authenti(fi)cation spelling
[SourceForge/phpwiki.git] / lib / pear / Cache / Container / file.php
1 <?php
2 // +----------------------------------------------------------------------+
3 // | PHP Version 4                                                        |
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 // +----------------------------------------------------------------------+
18 //
19 // $Id: file.php,v 1.2 2004-03-14 16:24:36 rurban Exp $
20
21 require_once('lib/pear/Cache/Container.php');
22
23 /**
24 * Stores cache contents in a file.
25 *
26 * @author   Ulf Wendel  <ulf.wendel@phpdoc.de>
27 * @version  $Id: file.php,v 1.2 2004-03-14 16:24:36 rurban Exp $
28 */
29 class Cache_Container_file extends Cache_Container {
30
31     /**
32     * Directory where to put the cache files.
33     *
34     * @var  string  Make sure to add a trailing slash
35     */
36     var $cache_dir = '';
37
38     /**
39     * Filename prefix for cache files.
40     *
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.
48     *
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.
52     *
53     * @var  string
54     */
55     var $filename_prefix = '';
56     
57     
58     /**
59     * List of cache entries, used within a gc run
60     * 
61     * @var array
62     */
63     var $entries;
64     
65     /**
66     * Total number of bytes required by all cache entries, used within a gc run.
67     * 
68     * @var  int
69     */
70     var $total_size = 0;
71
72     /**
73     * Creates the cache directory if neccessary
74     *
75     * @param    array   Config options: ["cache_dir" => ..., "filename_prefix" => ...]
76     */
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')));
80         
81         clearstatcache();
82         if ($this->cache_dir)
83         {
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) . '/';
88
89             // check if a trailing slash is in cache_dir
90             if (!substr($this->cache_dir,-1) ) 
91                  $this->cache_dir .= '/';
92
93             if  (!file_exists($this->cache_dir) || !is_dir($this->cache_dir))
94                 mkdir($this->cache_dir, 0755);
95         }
96         $this->entries = array();
97         $this->group_dirs = array();
98                     
99     } // end func contructor
100
101     function fetch($id, $group) {
102         $file = $this->getFilename($id, $group);
103         if (!file_exists($file))
104             return array(NULL, NULL, NULL);
105
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__);
109
110         // file format:
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)));
117         fclose($fh);
118
119         // last usage date used by the gc - maxlifetime
120         // touch without second param produced stupid entries...
121         touch($file,time());
122         clearstatcache();
123         
124         return array($expire, $cachedata, $userdata);
125     } // end func fetch
126
127     /**
128     * Stores a dataset.
129     *
130     * WARNING: If you supply userdata it must not contain any linebreaks,
131     * otherwise it will break the filestructure.
132     */
133     function save($id, $cachedata, $expires, $group, $userdata) {
134         $this->flushPreload($id, $group);
135
136         $file = $this->getFilename($id, $group);
137         if (!($fh = @fopen($file, 'wb')))
138             return new Cache_Error("Can't access '$file' to store cache data. Check access rights and path.", __FILE__, __LINE__);
139
140         // file format:
141         // 1st line: expiration date
142         // 2nd line: user data
143         // 3rd+ lines: cache data
144         $expires = $this->getExpiresAbsolute($expires);
145         fwrite($fh, $expires . "\n");
146         fwrite($fh, $userdata . "\n");
147         fwrite($fh, $this->encode($cachedata));
148
149         fclose($fh);
150
151         // I'm not sure if we need this
152         // i don't think we need this (chregu)
153         // touch($file);
154
155         return true;
156     } // end func save
157
158     function remove($id, $group) {
159         $this->flushPreload($id, $group);
160
161         $file = $this->getFilename($id, $group);
162         if (file_exists($file)) {
163
164             $ok = unlink($file);
165             clearstatcache();
166
167             return $ok;
168         }
169
170         return false;
171     } // end func remove
172
173     function flush($group) {
174         $this->flushPreload();
175         $dir = ($group) ? $this->cache_dir . $group . '/' : $this->cache_dir;
176
177         $num_removed = $this->deleteDir($dir);
178         unset($this->group_dirs[$group]);
179         clearstatcache();
180
181         return $num_removed;
182     } // end func flush
183
184     function idExists($id, $group) {
185
186         return file_exists($this->getFilename($id, $group));
187     } // end func idExists
188
189     /**
190     * Deletes all expired files.
191     *
192     * Garbage collection for files is a rather "expensive", "long time"
193     * operation. All files in the cache directory have to be examined which
194     * means that they must be opened for reading, the expiration date has to be
195     * read from them and if neccessary they have to be unlinked (removed).
196     * If you have a user comment for a good default gc probability please add it to
197     * to the inline docs.
198     *
199     * @param    integer Maximum lifetime in seconds of an no longer used/touched entry
200     * @throws   Cache_Error
201     */
202     function garbageCollection($maxlifetime) {
203
204         $this->flushPreload();
205         clearstatcache();
206
207         $ok = $this->doGarbageCollection($maxlifetime, $this->cache_dir);
208
209         // check the space used by the cache entries        
210         if ($this->total_size > $this->highwater) {
211         
212             krsort($this->entries);
213             reset($this->entries);
214             
215             while ($this->total_size > $this->lowwater && list($lastmod, $entry) = each($this->entries)) {
216                 if (@unlink($entry['file']))
217                     $this->total_size -= $entry['size'];
218                 else
219                     new CacheError("Can't delete {$entry["file"]}. Check the permissions.");
220             }
221             
222         }
223         
224         $this->entries = array();
225         $this->total_size = 0;
226         
227         return $ok;
228     } // end func garbageCollection
229     
230     /**
231     * Does the recursive gc procedure, protected.
232     *
233     * @param    integer Maximum lifetime in seconds of an no longer used/touched entry
234     * @param    string  directory to examine - don't sets this parameter, it's used for a
235     *                   recursive function call!
236     * @throws   Cache_Error
237     */
238     function doGarbageCollection($maxlifetime, $dir) {
239            
240         if (!($dh = opendir($dir)))
241             return new Cache_Error("Can't access cache directory '$dir'. Check permissions and path.", __FILE__, __LINE__);
242
243         while ($file = readdir($dh)) {
244             if ('.' == $file || '..' == $file)
245                 continue;
246
247             $file = $dir . $file;
248             if (is_dir($file)) {
249                 $this->doGarbageCollection($maxlifetime,$file . '/');
250                 continue;
251             }
252
253             // skip trouble makers but inform the user
254             if (!($fh = @fopen($file, 'rb'))) {
255                 new Cache_Error("Can't access cache file '$file', skipping it. Check permissions and path.", __FILE__, __LINE__);
256                 continue;
257             }
258
259             $expire = fgets($fh, 12);
260             fclose($fh);
261             $lastused = filemtime($file);
262             
263             $this->entries[$lastused] = array('file' => $file, 'size' => filesize($file));
264             $this->total_size += filesize($file);
265             
266             // remove if expired
267             if (( ($expire && $expire <= time()) || ($lastused <= (time() - $maxlifetime)) ) && !unlink($file))
268                 new Cache_Error("Can't unlink cache file '$file', skipping. Check permissions and path.", __FILE__, __LINE__);
269         }
270
271         closedir($dh);
272
273         // flush the disk state cache
274         clearstatcache();
275
276     } // end func doGarbageCollection
277
278     /**
279     * Returns the filename for the specified id.
280     *
281     * @param    string  dataset ID
282     * @param    string  cache group
283     * @return   string  full filename with the path
284     * @access   public
285     */
286     function getFilename($id, $group) {
287
288         if (isset($this->group_dirs[$group]))
289             return $this->group_dirs[$group] . $this->filename_prefix . $id;
290
291         $dir = $this->cache_dir . $group . '/';
292         if (!file_exists($dir)) {
293             mkdir($dir, 0755);
294             clearstatcache();
295         }
296
297         $this->group_dirs[$group] = $dir;
298
299         return $dir . $this->filename_prefix . $id;
300     } // end func getFilename
301
302     /**
303     * Deletes a directory and all files in it.
304     *
305     * @param    string  directory
306     * @return   integer number of removed files
307     * @throws   Cache_Error
308     */
309     function deleteDir($dir) {
310         if (!($dh = opendir($dir)))
311             return new Cache_Error("Can't remove directory '$dir'. Check permissions and path.", __FILE__, __LINE__);
312
313         $num_removed = 0;
314
315         while ($file = readdir($dh)) {
316             if ('.' == $file || '..' == $file)
317                 continue;
318
319             $file = $dir . $file;
320             if (is_dir($file)) {
321                 $file .= '/';
322                 $num = $this->deleteDir($file . '/');
323                 if (is_int($num))
324                     $num_removed += $num;
325             } else {
326                 if (unlink($file))
327                     $num_removed++;
328             }
329         }
330         // according to php-manual the following is needed for windows installations.
331         closedir($dh);
332         unset( $dh);
333         if ($dir != $this->cache_dir) {  //delete the sub-dir entries  itself also, but not the cache-dir.
334             rmDir($dir);
335             $num_removed++;
336         }
337
338         return $num_removed;
339     } // end func deleteDir
340     
341 } // end class file
342 ?>