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