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