]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/pear/Cache/Container/imgfile.php
Remove svn:keywords
[SourceForge/phpwiki.git] / lib / pear / Cache / Container / imgfile.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 require_once('Cache/Container.php');
20
21 /**
22 * Stores cache contents in a file.
23 *
24 * @author   Ulf Wendel  <ulf.wendel@phpdoc.de>
25 * @version  
26 */
27 class Cache_Container_file extends Cache_Container {
28
29     /**
30     * Directory where to put the cache files.
31     *
32     * @var  string  Make sure to add a trailing slash
33     */
34     var $cache_dir = '';
35
36     /**
37     * Filename prefix for cache files.
38     *
39     * You can use the filename prefix to implement a "domain" based cache or just
40     * to give the files a more descriptive name. The word "domain" is borroed from
41     * a user authentication system. One user id (cached dataset with the ID x)
42     * may exists in different domains (different filename prefix). You might want
43     * to use this to have different cache values for a production, development and
44     * quality assurance system. If you want the production cache not to be influenced
45     * by the quality assurance activities, use different filename prefixes for them.
46     *
47     * I personally don't think that you'll never need this, but 640kb happend to be
48     * not enough, so... you know what I mean. If you find a useful application of the
49     * feature please update this inline doc.
50     *
51     * @var  string
52     */
53     var $filename_prefix = '';
54
55     /**
56     * List of cache entries, used within a gc run
57     *
58     * @var array
59     */
60     var $entries;
61
62     /**
63     * Total number of bytes required by all cache entries, used within a gc run.
64     *
65     * @var  int
66     */
67     var $total_size = 0;
68
69     /**
70     * Creates the cache directory if neccessary
71     *
72     * @param    array   Config options: ["cache_dir" => ..., "filename_prefix" => ...]
73     */
74      function Cache_Container_file($options = '') {
75         if (is_array($options))
76             $this->setOptions($options, array_merge($this->allowed_options, array('cache_dir', 'filename_prefix')));
77
78         clearstatcache();
79         if ($this->cache_dir)
80         {
81             // make relative paths absolute for use in deconstructor.
82             // it looks like the deconstructor has problems with relative paths
83             if (OS_UNIX && '/' != $this->cache_dir{0}  )
84                 $this->cache_dir = realpath( getcwd() . '/' . $this->cache_dir) . '/';
85
86             // check if a trailing slash is in cache_dir
87             if (!substr($this->cache_dir,-1) )
88                  $this->cache_dir .= '/';
89
90             if  (!file_exists($this->cache_dir) || !is_dir($this->cache_dir))
91                 mkdir($this->cache_dir, 0755);
92         }
93         $this->entries = array();
94         $this->group_dirs = array();
95
96     } // end func contructor
97
98     function fetch($id, $group) {
99         $file = $this->getFilename($id, $group);
100         if (!file_exists($file))
101             return array(NULL, NULL, NULL);
102
103         // retrive the content
104         if (!($fh = @fopen($file, 'rb')))
105             return new Cache_Error("Can't access cache file '$file'. Check access rights and path.", __FILE__, __LINE__);
106
107         // file format:
108         // 1st line: expiration date
109         // 2nd line: user data
110         // 3rd+ lines: cache data
111         $expire = trim(fgets($fh, 12));
112         $userdata = trim(fgets($fh, 257));
113         $cachedata = $this->decode(fread($fh, filesize($file)));
114         fclose($fh);
115
116 //JOHANNES START
117         if (is_array($cachedata))
118             if (file_exists($file.'.img')) {
119                 $fh = @fopen($file.'.img',"rb");
120                 $cachedata['image'] = fread($fh,filesize($file.'.img'));
121                 fclose($fh);
122             }
123 //JOHANNES END
124
125         // last usage date used by the gc - maxlifetime
126         // touch without second param produced stupid entries...
127         touch($file,time());
128         clearstatcache();
129
130         return array($expire, $cachedata, $userdata);
131     } // end func fetch
132
133     /**
134     * Stores a dataset.
135     *
136     * WARNING: If you supply userdata it must not contain any linebreaks,
137     * otherwise it will break the filestructure.
138     */
139     function save($id, $cachedata, $expires, $group, $userdata) {
140         $this->flushPreload($id, $group);
141
142         $file = $this->getFilename($id, $group);
143         if (!($fh = @fopen($file, 'wb')))
144             return new Cache_Error("Can't access '$file' to store cache data. Check access rights and path.", __FILE__, __LINE__);
145
146 //JOHANNES
147         if (is_array($cachedata)&&isset($cachedata['image'])) {
148             $image = $cachedata['image'];
149             unset($cachedata['image']);
150         }
151 //JOHANNES
152
153         // file format:
154         // 1st line: expiration date
155         // 2nd line: user data
156         // 3rd+ lines: cache data
157         $expires = $this->getExpiresAbsolute($expires);
158         fwrite($fh, $expires . "\n");
159         fwrite($fh, $userdata . "\n");
160         fwrite($fh, $this->encode($cachedata));
161
162         fclose($fh);
163
164         // I'm not sure if we need this
165     // i don't think we need this (chregu)
166         // touch($file);
167
168 //JOHANNES START
169         if ($image) {
170             $file = $this->getFilename($id, $group).'.img';
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__);
173             fwrite($fh, $image);
174             fclose($fh);
175         }
176 //JOHANNES END
177
178         return true;
179     } // end func save
180
181     function remove($id, $group) {
182         $this->flushPreload($id, $group);
183
184         $file = $this->getFilename($id, $group);
185         if (file_exists($file)) {
186
187             $ok = unlink($file);
188             clearstatcache();
189
190             return $ok;
191         }
192
193         return false;
194     } // end func remove
195
196     function flush($group) {
197         $this->flushPreload();
198         $dir = ($group) ? $this->cache_dir . $group . '/' : $this->cache_dir;
199
200         $num_removed = $this->deleteDir($dir);
201         unset($this->group_dirs[$group]);
202         clearstatcache();
203
204         return $num_removed;
205     } // end func flush
206
207     function idExists($id, $group) {
208
209         return file_exists($this->getFilename($id, $group));
210     } // end func idExists
211
212     /**
213     * Deletes all expired files.
214     *
215     * Garbage collection for files is a rather "expensive", "long time"
216     * operation. All files in the cache directory have to be examined which
217     * means that they must be opened for reading, the expiration date has to be
218     * read from them and if neccessary they have to be unlinked (removed).
219     * If you have a user comment for a good default gc probability please add it to
220     * to the inline docs.
221     *
222     * @param    integer Maximum lifetime in seconds of an no longer used/touched entry
223     * @throws   Cache_Error
224     */
225     function garbageCollection($maxlifetime) {
226
227         $this->flushPreload();
228         clearstatcache();
229
230         $ok = $this->doGarbageCollection($maxlifetime, $this->cache_dir);
231
232         // check the space used by the cache entries
233         if ($this->total_size > $this->highwater) {
234
235             krsort($this->entries);
236             reset($this->entries);
237
238             while ($this->total_size > $this->lowwater && list($lastmod, $entry) = each($this->entries)) {
239                 if (@unlink($entry['file']))
240                     $this->total_size -= $entry['size'];
241                 else
242                     new CacheError("Can't delete {$entry["file"]}. Check the permissions.");
243             }
244
245         }
246
247         $this->entries = array();
248         $this->total_size = 0;
249
250         return $ok;
251     } // end func garbageCollection
252
253     /**
254     * Does the recursive gc procedure, protected.
255     *
256     * @param    integer Maximum lifetime in seconds of an no longer used/touched entry
257     * @param    string  directory to examine - don't sets this parameter, it's used for a
258     *                   recursive function call!
259     * @throws   Cache_Error
260     */
261     function doGarbageCollection($maxlifetime, $dir) {
262
263         if (!($dh = opendir($dir)))
264             return new Cache_Error("Can't access cache directory '$dir'. Check permissions and path.", __FILE__, __LINE__);
265
266         while ($file = readdir($dh)) {
267             if ('.' == $file || '..' == $file)
268                 continue;
269 //JOHANNES START
270             if ('.img' == substr($file,-4))
271                 continue;
272 //JOHANNES END
273
274             $file = $dir . $file;
275             if (is_dir($file)) {
276                 $this->doGarbageCollection($maxlifetime,$file . '/');
277                 continue;
278             }
279
280             // skip trouble makers but inform the user
281             if (!($fh = @fopen($file, 'rb'))) {
282                 new Cache_Error("Can't access cache file '$file', skipping it. Check permissions and path.", __FILE__, __LINE__);
283                 continue;
284             }
285
286             $expire = fgets($fh, 12);
287             fclose($fh);
288             $lastused = filemtime($file);
289
290 //JOHANNES START
291             $x = 0;
292             if (file_exists($file.'.img'))
293                 $x = filesize($file.'.img');
294             $this->entries[$lastused] = array('file' => $file, 'size' => filesize($file)+$x);
295             $this->total_size += filesize($file)+$x;
296
297             // remove if expired
298             if ( ($expire && $expire <= time()) || ($lastused <= (time() - $maxlifetime)) ) {
299                 $ok = unlink($file);
300                 if ( file_exists($file.'.img') )
301                     $ok = $ok && unlink($file.'.img');
302                 if (!$ok)
303                     new Cache_Error("Can't unlink cache file '$file', skipping. Check permissions and path.", __FILE__, __LINE__);
304             }
305 //JOHANNES END
306         }
307
308         closedir($dh);
309
310         // flush the disk state cache
311         clearstatcache();
312
313     } // end func doGarbageCollection
314
315     /**
316     * Returns the filename for the specified id.
317     *
318     * @param    string  dataset ID
319     * @param    string  cache group
320     * @return   string  full filename with the path
321     * @access   public
322     */
323     function getFilename($id, $group) {
324
325         if (isset($this->group_dirs[$group]))
326             return $this->group_dirs[$group] . $this->filename_prefix . $id;
327
328         $dir = $this->cache_dir . $group . '/';
329         if (!file_exists($dir)) {
330             mkdir($dir, 0755);
331             clearstatcache();
332         }
333
334         $this->group_dirs[$group] = $dir;
335
336         return $dir . $this->filename_prefix . $id;
337     } // end func getFilename
338
339     /**
340     * Deletes a directory and all files in it.
341     *
342     * @param    string  directory
343     * @return   integer number of removed files
344     * @throws   Cache_Error
345     */
346     function deleteDir($dir) {
347         if (!($dh = opendir($dir)))
348             return new Cache_Error("Can't remove directory '$dir'. Check permissions and path.", __FILE__, __LINE__);
349
350         $num_removed = 0;
351
352         while ($file = readdir($dh)) {
353             if ('.' == $file || '..' == $file)
354                 continue;
355
356             $file = $dir . $file;
357             if (is_dir($file)) {
358                 $file .= '/';
359                 $num = $this->deleteDir($file . '/');
360                 if (is_int($num))
361                     $num_removed += $num;
362             } else {
363                 if (unlink($file))
364                     $num_removed++;
365             }
366         }
367         // according to php-manual the following is needed for windows installations.
368         closedir($dh);
369         unset( $dh);
370         if ($dir != $this->cache_dir) {  //delete the sub-dir entries  itself also, but not the cache-dir.
371             rmDir($dir);
372             $num_removed++;
373         }
374
375         return $num_removed;
376     } // end func deleteDir
377
378 } // end class file
379 ?>