xref: /dokuwiki/inc/cache.php (revision fc4ff0c349240d12ff91559183e1103ad2c5fa91)
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
24    /**
25     * @param string $key primary identifier
26     * @param string $ext file extension
27     */
28    public function cache($key,$ext) {
29        $this->key = $key;
30        $this->ext = $ext;
31        $this->cache = getCacheName($key,$ext);
32    }
33
34    /**
35     * public method to determine whether the cache can be used
36     *
37     * to assist in cetralisation of event triggering and calculation of cache statistics,
38     * don't override this function override _useCache()
39     *
40     * @param  array   $depends   array of cache dependencies, support dependecies:
41     *                            'age'   => max age of the cache in seconds
42     *                            'files' => cache must be younger than mtime of each file
43     *                                       (nb. dependency passes if file doesn't exist)
44     *
45     * @return bool    true if cache can be used, false otherwise
46     */
47    public function useCache($depends=array()) {
48        $this->depends = $depends;
49        $this->_addDependencies();
50
51        if ($this->_event) {
52            return $this->_stats(trigger_event($this->_event,$this,array($this,'_useCache')));
53        } else {
54            return $this->_stats($this->_useCache());
55        }
56    }
57
58    /**
59     * private method containing cache use decision logic
60     *
61     * this function processes the following keys in the depends array
62     *   purge - force a purge on any non empty value
63     *   age   - expire cache if older than age (seconds)
64     *   files - expire cache if any file in this array was updated more recently than the cache
65     *
66     * Note that this function needs to be public as it is used as callback for the event handler
67     *
68     * can be overridden
69     *
70     * @return bool               see useCache()
71     */
72    public function _useCache() {
73
74        if (!empty($this->depends['purge'])) return false;              // purge requested?
75        if (!($this->_time = @filemtime($this->cache))) return false;   // cache exists?
76
77        // cache too old?
78        if (!empty($this->depends['age']) && ((time() - $this->_time) > $this->depends['age'])) return false;
79
80        if (!empty($this->depends['files'])) {
81            foreach ($this->depends['files'] as $file) {
82                if ($this->_time <= @filemtime($file)) return false;         // cache older than files it depends on?
83            }
84        }
85
86        return true;
87    }
88
89    /**
90     * add dependencies to the depends array
91     *
92     * this method should only add dependencies,
93     * it should not remove any existing dependencies and
94     * it should only overwrite a dependency when the new value is more stringent than the old
95     */
96    protected function _addDependencies() {
97        global $INPUT;
98        if ($INPUT->has('purge')) $this->depends['purge'] = true;   // purge requested
99    }
100
101    /**
102     * retrieve the cached data
103     *
104     * @param   bool   $clean   true to clean line endings, false to leave line endings alone
105     * @return  string          cache contents
106     */
107    public function retrieveCache($clean=true) {
108        return io_readFile($this->cache, $clean);
109    }
110
111    /**
112     * cache $data
113     *
114     * @param   string $data   the data to be cached
115     * @return  bool           true on success, false otherwise
116     */
117    public function storeCache($data) {
118        return io_savefile($this->cache, $data);
119    }
120
121    /**
122     * remove any cached data associated with this cache instance
123     */
124    public function removeCache() {
125        @unlink($this->cache);
126    }
127
128    /**
129     * Record cache hits statistics.
130     * (Only when debugging allowed, to reduce overhead.)
131     *
132     * @param    bool   $success   result of this cache use attempt
133     * @return   bool              pass-thru $success value
134     */
135    protected function _stats($success) {
136        global $conf;
137        static $stats = null;
138        static $file;
139
140        if (!$conf['allowdebug']) { return $success; }
141
142        if (is_null($stats)) {
143            $file = $conf['cachedir'].'/cache_stats.txt';
144            $lines = explode("\n",io_readFile($file));
145
146            foreach ($lines as $line) {
147                $i = strpos($line,',');
148                $stats[substr($line,0,$i)] = $line;
149            }
150        }
151
152        if (isset($stats[$this->ext])) {
153            list($ext,$count,$hits) = explode(',',$stats[$this->ext]);
154        } else {
155            $ext = $this->ext;
156            $count = 0;
157            $hits = 0;
158        }
159
160        $count++;
161        if ($success) $hits++;
162        $stats[$this->ext] = "$ext,$count,$hits";
163
164        io_saveFile($file,join("\n",$stats));
165
166        return $success;
167    }
168}
169
170/**
171 * Parser caching
172 */
173class cache_parser extends cache {
174
175    public $file = '';       // source file for cache
176    public $mode = '';       // input mode (represents the processing the input file will undergo)
177
178    var $_event = 'PARSER_CACHE_USE';
179
180    /**
181     *
182     * @param string $id page id
183     * @param string $file source file for cache
184     * @param string $mode input mode
185     */
186    public function cache_parser($id, $file, $mode) {
187        if ($id) $this->page = $id;
188        $this->file = $file;
189        $this->mode = $mode;
190
191        parent::cache($file.$_SERVER['HTTP_HOST'].$_SERVER['SERVER_PORT'],'.'.$mode);
192    }
193
194    /**
195     * method contains cache use decision logic
196     *
197     * @return bool               see useCache()
198     */
199    public function _useCache() {
200
201        if (!@file_exists($this->file)) return false;                   // source exists?
202        return parent::_useCache();
203    }
204
205    protected function _addDependencies() {
206        global $conf;
207
208        $this->depends['age'] = isset($this->depends['age']) ?
209            min($this->depends['age'],$conf['cachetime']) : $conf['cachetime'];
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
269        // renderer cache file dependencies ...
270        $files = array(
271                DOKU_INC.'inc/parser/'.$this->mode.'.php',       // ... the renderer
272                );
273
274        // page implies metadata and possibly some other dependencies
275        if (isset($this->page)) {
276
277            $valid = p_get_metadata($this->page, 'date valid');         // for xhtml this will render the metadata if needed
278            if (!empty($valid['age'])) {
279                $this->depends['age'] = isset($this->depends['age']) ?
280                    min($this->depends['age'],$valid['age']) : $valid['age'];
281            }
282        }
283
284        $this->depends['files'] = !empty($this->depends['files']) ? array_merge($files, $this->depends['files']) : $files;
285        parent::_addDependencies();
286    }
287}
288
289/**
290 * Caching of parser instructions
291 */
292class cache_instructions extends cache_parser {
293
294    /**
295     * @param string $id page id
296     * @param string $file source file for cache
297     */
298    public function cache_instructions($id, $file) {
299        parent::cache_parser($id, $file, 'i');
300    }
301
302    /**
303     * retrieve the cached data
304     *
305     * @param   bool   $clean   true to clean line endings, false to leave line endings alone
306     * @return  string          cache contents
307     */
308    public function retrieveCache($clean=true) {
309        $contents = io_readFile($this->cache, false);
310        return !empty($contents) ? unserialize($contents) : array();
311    }
312
313    /**
314     * cache $instructions
315     *
316     * @param   string $instructions  the instruction to be cached
317     * @return  bool                  true on success, false otherwise
318     */
319    public function storeCache($instructions) {
320        return io_savefile($this->cache,serialize($instructions));
321    }
322}
323