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