xref: /dokuwiki/inc/cache.php (revision 06da270e039cf517a6bd847ca0cd4a7819c9f879)
1<?php
2/**
3 * Generic class to handle caching
4 *
5 * @license    GPL 2 (http://www.gnu.org/licenses/gpl.html)
6 * @author     Chris Smith <chris@jalakai.co.uk>
7 */
8
9if(!defined('DOKU_INC')) die('meh.');
10
11/**
12 * Generic handling of caching
13 */
14class cache {
15    public $key = '';          // primary identifier for this item
16    public $ext = '';          // file ext for cache data, secondary identifier for this item
17    public $cache = '';        // cache file name
18    public $depends = array(); // array containing cache dependency information,
19                               //   used by _useCache to determine cache validity
20
21    var $_event = '';       // event to be triggered during useCache
22    var $_time;
23    var $_nocache = false;  // if set to true, cache will not be used or stored
24
25    /**
26     * @param string $key primary identifier
27     * @param string $ext file extension
28     */
29    public function cache($key,$ext) {
30        $this->key = $key;
31        $this->ext = $ext;
32        $this->cache = getCacheName($key,$ext);
33    }
34
35    /**
36     * public method to determine whether the cache can be used
37     *
38     * to assist in centralisation of event triggering and calculation of cache statistics,
39     * don't override this function override _useCache()
40     *
41     * @param  array   $depends   array of cache dependencies, support dependecies:
42     *                            'age'   => max age of the cache in seconds
43     *                            'files' => cache must be younger than mtime of each file
44     *                                       (nb. dependency passes if file doesn't exist)
45     *
46     * @return bool    true if cache can be used, false otherwise
47     */
48    public function useCache($depends=array()) {
49        $this->depends = $depends;
50        $this->_addDependencies();
51
52        if ($this->_event) {
53            return $this->_stats(trigger_event($this->_event,$this,array($this,'_useCache')));
54        } else {
55            return $this->_stats($this->_useCache());
56        }
57    }
58
59    /**
60     * private method containing cache use decision logic
61     *
62     * this function processes the following keys in the depends array
63     *   purge - force a purge on any non empty value
64     *   age   - expire cache if older than age (seconds)
65     *   files - expire cache if any file in this array was updated more recently than the cache
66     *
67     * Note that this function needs to be public as it is used as callback for the event handler
68     *
69     * can be overridden
70     *
71     * @return bool               see useCache()
72     */
73    public function _useCache() {
74
75        if ($this->_nocache) return false;                              // caching turned off
76        if (!empty($this->depends['purge'])) return false;              // purge requested?
77        if (!($this->_time = @filemtime($this->cache))) return false;   // cache exists?
78
79        // cache too old?
80        if (!empty($this->depends['age']) && ((time() - $this->_time) > $this->depends['age'])) return false;
81
82        if (!empty($this->depends['files'])) {
83            foreach ($this->depends['files'] as $file) {
84                if ($this->_time <= @filemtime($file)) return false;         // cache older than files it depends on?
85            }
86        }
87
88        return true;
89    }
90
91    /**
92     * add dependencies to the depends array
93     *
94     * this method should only add dependencies,
95     * it should not remove any existing dependencies and
96     * it should only overwrite a dependency when the new value is more stringent than the old
97     */
98    protected function _addDependencies() {
99        global $INPUT;
100        if ($INPUT->has('purge')) $this->depends['purge'] = true;   // purge requested
101    }
102
103    /**
104     * retrieve the cached data
105     *
106     * @param   bool   $clean   true to clean line endings, false to leave line endings alone
107     * @return  string          cache contents
108     */
109    public function retrieveCache($clean=true) {
110        return io_readFile($this->cache, $clean);
111    }
112
113    /**
114     * cache $data
115     *
116     * @param   string $data   the data to be cached
117     * @return  bool           true on success, false otherwise
118     */
119    public function storeCache($data) {
120        if ($this->_nocache) return false;
121
122        return io_savefile($this->cache, $data);
123    }
124
125    /**
126     * remove any cached data associated with this cache instance
127     */
128    public function removeCache() {
129        @unlink($this->cache);
130    }
131
132    /**
133     * Record cache hits statistics.
134     * (Only when debugging allowed, to reduce overhead.)
135     *
136     * @param    bool   $success   result of this cache use attempt
137     * @return   bool              pass-thru $success value
138     */
139    protected function _stats($success) {
140        global $conf;
141        static $stats = null;
142        static $file;
143
144        if (!$conf['allowdebug']) { return $success; }
145
146        if (is_null($stats)) {
147            $file = $conf['cachedir'].'/cache_stats.txt';
148            $lines = explode("\n",io_readFile($file));
149
150            foreach ($lines as $line) {
151                $i = strpos($line,',');
152                $stats[substr($line,0,$i)] = $line;
153            }
154        }
155
156        if (isset($stats[$this->ext])) {
157            list($ext,$count,$hits) = explode(',',$stats[$this->ext]);
158        } else {
159            $ext = $this->ext;
160            $count = 0;
161            $hits = 0;
162        }
163
164        $count++;
165        if ($success) $hits++;
166        $stats[$this->ext] = "$ext,$count,$hits";
167
168        io_saveFile($file,join("\n",$stats));
169
170        return $success;
171    }
172}
173
174/**
175 * Parser caching
176 */
177class cache_parser extends cache {
178
179    public $file = '';       // source file for cache
180    public $mode = '';       // input mode (represents the processing the input file will undergo)
181
182    var $_event = 'PARSER_CACHE_USE';
183
184    /**
185     *
186     * @param string $id page id
187     * @param string $file source file for cache
188     * @param string $mode input mode
189     */
190    public function cache_parser($id, $file, $mode) {
191        if ($id) $this->page = $id;
192        $this->file = $file;
193        $this->mode = $mode;
194
195        parent::cache($file.$_SERVER['HTTP_HOST'].$_SERVER['SERVER_PORT'],'.'.$mode);
196    }
197
198    /**
199     * method contains cache use decision logic
200     *
201     * @return bool               see useCache()
202     */
203    public function _useCache() {
204
205        if (!@file_exists($this->file)) return false;                   // source exists?
206        return parent::_useCache();
207    }
208
209    protected function _addDependencies() {
210
211        // parser cache file dependencies ...
212        $files = array($this->file,                              // ... source
213                DOKU_INC.'inc/parser/parser.php',                // ... parser
214                DOKU_INC.'inc/parser/handler.php',               // ... handler
215                );
216        $files = array_merge($files, getConfigFiles('main'));    // ... wiki settings
217
218        $this->depends['files'] = !empty($this->depends['files']) ? array_merge($files, $this->depends['files']) : $files;
219        parent::_addDependencies();
220    }
221
222}
223
224/**
225 * Caching of data of renderer
226 */
227class cache_renderer extends cache_parser {
228
229    /**
230     * method contains cache use decision logic
231     *
232     * @return bool               see useCache()
233     */
234    public function _useCache() {
235        global $conf;
236
237        if (!parent::_useCache()) return false;
238
239        if (!isset($this->page)) {
240            return true;
241        }
242
243        if ($this->_time < @filemtime(metaFN($this->page,'.meta'))) return false;         // meta cache older than file it depends on?
244
245        // check current link existence is consistent with cache version
246        // first check the purgefile
247        // - if the cache is more recent than the purgefile we know no links can have been updated
248        if ($this->_time >= @filemtime($conf['cachedir'].'/purgefile')) {
249            return true;
250        }
251
252        // for wiki pages, check metadata dependencies
253        $metadata = p_get_metadata($this->page);
254
255        if (!isset($metadata['relation']['references']) ||
256                empty($metadata['relation']['references'])) {
257            return true;
258        }
259
260        foreach ($metadata['relation']['references'] as $id => $exists) {
261            if ($exists != page_exists($id,'',false)) return false;
262        }
263
264        return true;
265    }
266
267    protected function _addDependencies() {
268        global $conf;
269
270        // default renderer cache file 'age' is dependent on 'cachetime' setting, two special values:
271        //    -1 : do not cache (should not be overridden)
272        //    0  : cache never expires (can be overridden) - no need to set depends['age']
273        if ($conf['cachetime'] == -1) {
274            $this->_nocache = true;
275            return;
276        } elseif ($conf['cachetime'] > 0) {
277            $this->depends['age'] = isset($this->depends['age']) ?
278                min($this->depends['age'],$conf['cachetime']) : $conf['cachetime'];
279        }
280
281        // renderer cache file dependencies ...
282        $files = array(
283                DOKU_INC.'inc/parser/'.$this->mode.'.php',       // ... the renderer
284                );
285
286        // page implies metadata and possibly some other dependencies
287        if (isset($this->page)) {
288
289            $valid = p_get_metadata($this->page, 'date valid');         // for xhtml this will render the metadata if needed
290            if (!empty($valid['age'])) {
291                $this->depends['age'] = isset($this->depends['age']) ?
292                    min($this->depends['age'],$valid['age']) : $valid['age'];
293            }
294        }
295
296        $this->depends['files'] = !empty($this->depends['files']) ? array_merge($files, $this->depends['files']) : $files;
297        parent::_addDependencies();
298    }
299}
300
301/**
302 * Caching of parser instructions
303 */
304class cache_instructions extends cache_parser {
305
306    /**
307     * @param string $id page id
308     * @param string $file source file for cache
309     */
310    public function cache_instructions($id, $file) {
311        parent::cache_parser($id, $file, 'i');
312    }
313
314    /**
315     * retrieve the cached data
316     *
317     * @param   bool   $clean   true to clean line endings, false to leave line endings alone
318     * @return  string          cache contents
319     */
320    public function retrieveCache($clean=true) {
321        $contents = io_readFile($this->cache, false);
322        return !empty($contents) ? unserialize($contents) : array();
323    }
324
325    /**
326     * cache $instructions
327     *
328     * @param   string $instructions  the instruction to be cached
329     * @return  bool                  true on success, false otherwise
330     */
331    public function storeCache($instructions) {
332        if ($this->_nocache) return false;
333
334        return io_savefile($this->cache,serialize($instructions));
335    }
336}
337