xref: /dokuwiki/inc/cache.php (revision cefd14cbc4f6dabfb2fb7b7ffb6b68d4501afd4f)
14b5f4f4eSchris<?php
24b5f4f4eSchris/**
34b5f4f4eSchris * Generic class to handle caching
44b5f4f4eSchris *
54b5f4f4eSchris * @license    GPL 2 (http://www.gnu.org/licenses/gpl.html)
64b5f4f4eSchris * @author     Chris Smith <chris@jalakai.co.uk>
74b5f4f4eSchris */
84b5f4f4eSchris
9fa8adffeSAndreas Gohrif(!defined('DOKU_INC')) die('meh.');
104b5f4f4eSchris
11*cefd14cbSGerrit Uitslag/**
12*cefd14cbSGerrit Uitslag * Generic handling of caching
13*cefd14cbSGerrit Uitslag */
144b5f4f4eSchrisclass cache {
15c59b3e00SGerrit Uitslag    public $key = '';          // primary identifier for this item
16c59b3e00SGerrit Uitslag    public $ext = '';          // file ext for cache data, secondary identifier for this item
17c59b3e00SGerrit Uitslag    public $cache = '';        // cache file name
18c59b3e00SGerrit Uitslag    public $depends = array(); // array containing cache dependency information,
190abe1d3eSchris    //   used by _useCache to determine cache validity
204b5f4f4eSchris
214b5f4f4eSchris    var $_event = '';       // event to be triggered during useCache
22d7fd4c3eSGerrit Uitslag    var $_time;
234b5f4f4eSchris
24c59b3e00SGerrit Uitslag    /**
25c59b3e00SGerrit Uitslag     * @param string $key primary identifier
26c59b3e00SGerrit Uitslag     * @param string $ext file extension
27c59b3e00SGerrit Uitslag     */
28c59b3e00SGerrit Uitslag    public function cache($key,$ext) {
294b5f4f4eSchris        $this->key = $key;
304b5f4f4eSchris        $this->ext = $ext;
314b5f4f4eSchris        $this->cache = getCacheName($key,$ext);
324b5f4f4eSchris    }
334b5f4f4eSchris
344b5f4f4eSchris    /**
354b5f4f4eSchris     * public method to determine whether the cache can be used
364b5f4f4eSchris     *
374b5f4f4eSchris     * to assist in cetralisation of event triggering and calculation of cache statistics,
384b5f4f4eSchris     * don't override this function override _useCache()
394b5f4f4eSchris     *
404b5f4f4eSchris     * @param  array   $depends   array of cache dependencies, support dependecies:
414b5f4f4eSchris     *                            'age'   => max age of the cache in seconds
424b5f4f4eSchris     *                            'files' => cache must be younger than mtime of each file
43ce6b63d9Schris     *                                       (nb. dependency passes if file doesn't exist)
444b5f4f4eSchris     *
454b5f4f4eSchris     * @return bool    true if cache can be used, false otherwise
464b5f4f4eSchris     */
47c59b3e00SGerrit Uitslag    public function useCache($depends=array()) {
484b5f4f4eSchris        $this->depends = $depends;
490abe1d3eSchris        $this->_addDependencies();
504b5f4f4eSchris
514b5f4f4eSchris        if ($this->_event) {
524b5f4f4eSchris            return $this->_stats(trigger_event($this->_event,$this,array($this,'_useCache')));
534b5f4f4eSchris        } else {
544b5f4f4eSchris            return $this->_stats($this->_useCache());
554b5f4f4eSchris        }
564b5f4f4eSchris    }
574b5f4f4eSchris
580abe1d3eSchris    /**
594b5f4f4eSchris     * private method containing cache use decision logic
604b5f4f4eSchris     *
610abe1d3eSchris     * this function processes the following keys in the depends array
620abe1d3eSchris     *   purge - force a purge on any non empty value
630abe1d3eSchris     *   age   - expire cache if older than age (seconds)
640abe1d3eSchris     *   files - expire cache if any file in this array was updated more recently than the cache
650abe1d3eSchris     *
660abe1d3eSchris     * can be overridden
674b5f4f4eSchris     *
684b5f4f4eSchris     * @return bool               see useCache()
694b5f4f4eSchris     */
70c59b3e00SGerrit Uitslag    protected function _useCache() {
714b5f4f4eSchris
720abe1d3eSchris        if (!empty($this->depends['purge'])) return false;              // purge requested?
734b5f4f4eSchris        if (!($this->_time = @filemtime($this->cache))) return false;   // cache exists?
744b5f4f4eSchris
754b5f4f4eSchris        // cache too old?
764b5f4f4eSchris        if (!empty($this->depends['age']) && ((time() - $this->_time) > $this->depends['age'])) return false;
774b5f4f4eSchris
784b5f4f4eSchris        if (!empty($this->depends['files'])) {
794b5f4f4eSchris            foreach ($this->depends['files'] as $file) {
80a257b0bdSMartin Doucha                if ($this->_time <= @filemtime($file)) return false;         // cache older than files it depends on?
814b5f4f4eSchris            }
824b5f4f4eSchris        }
834b5f4f4eSchris
844b5f4f4eSchris        return true;
854b5f4f4eSchris    }
864b5f4f4eSchris
874b5f4f4eSchris    /**
880abe1d3eSchris     * add dependencies to the depends array
890abe1d3eSchris     *
900abe1d3eSchris     * this method should only add dependencies,
910abe1d3eSchris     * it should not remove any existing dependencies and
920abe1d3eSchris     * it should only overwrite a dependency when the new value is more stringent than the old
930abe1d3eSchris     */
94c59b3e00SGerrit Uitslag    protected function _addDependencies() {
957d01a0eaSTom N Harris        global $INPUT;
967d01a0eaSTom N Harris        if ($INPUT->has('purge')) $this->depends['purge'] = true;   // purge requested
970abe1d3eSchris    }
980abe1d3eSchris
990abe1d3eSchris    /**
1004b5f4f4eSchris     * retrieve the cached data
1014b5f4f4eSchris     *
1024b5f4f4eSchris     * @param   bool   $clean   true to clean line endings, false to leave line endings alone
1034b5f4f4eSchris     * @return  string          cache contents
1044b5f4f4eSchris     */
105c59b3e00SGerrit Uitslag    public function retrieveCache($clean=true) {
1064b5f4f4eSchris        return io_readFile($this->cache, $clean);
1074b5f4f4eSchris    }
1084b5f4f4eSchris
1094b5f4f4eSchris    /**
1104b5f4f4eSchris     * cache $data
1114b5f4f4eSchris     *
1124b5f4f4eSchris     * @param   string $data   the data to be cached
113cbaf4259SChris Smith     * @return  bool           true on success, false otherwise
1144b5f4f4eSchris     */
115c59b3e00SGerrit Uitslag    public function storeCache($data) {
116cbaf4259SChris Smith        return io_savefile($this->cache, $data);
1174b5f4f4eSchris    }
1184b5f4f4eSchris
1194b5f4f4eSchris    /**
1204b5f4f4eSchris     * remove any cached data associated with this cache instance
1214b5f4f4eSchris     */
122c59b3e00SGerrit Uitslag    public function removeCache() {
1234b5f4f4eSchris        @unlink($this->cache);
1244b5f4f4eSchris    }
1254b5f4f4eSchris
1264b5f4f4eSchris    /**
12733c1bd61SBen Coburn     * Record cache hits statistics.
12833c1bd61SBen Coburn     * (Only when debugging allowed, to reduce overhead.)
1294b5f4f4eSchris     *
1304b5f4f4eSchris     * @param    bool   $success   result of this cache use attempt
1314b5f4f4eSchris     * @return   bool              pass-thru $success value
1324b5f4f4eSchris     */
133c59b3e00SGerrit Uitslag    protected function _stats($success) {
1344b5f4f4eSchris        global $conf;
13549eb6e38SAndreas Gohr        static $stats = null;
1364b5f4f4eSchris        static $file;
1374b5f4f4eSchris
13833c1bd61SBen Coburn        if (!$conf['allowdebug']) { return $success; }
13933c1bd61SBen Coburn
1404b5f4f4eSchris        if (is_null($stats)) {
1414b5f4f4eSchris            $file = $conf['cachedir'].'/cache_stats.txt';
1424b5f4f4eSchris            $lines = explode("\n",io_readFile($file));
1434b5f4f4eSchris
1444b5f4f4eSchris            foreach ($lines as $line) {
1454b5f4f4eSchris                $i = strpos($line,',');
1464b5f4f4eSchris                $stats[substr($line,0,$i)] = $line;
1474b5f4f4eSchris            }
1484b5f4f4eSchris        }
1494b5f4f4eSchris
1504b5f4f4eSchris        if (isset($stats[$this->ext])) {
1510abe1d3eSchris            list($ext,$count,$hits) = explode(',',$stats[$this->ext]);
1524b5f4f4eSchris        } else {
1534b5f4f4eSchris            $ext = $this->ext;
1544b5f4f4eSchris            $count = 0;
1550abe1d3eSchris            $hits = 0;
1564b5f4f4eSchris        }
1574b5f4f4eSchris
1584b5f4f4eSchris        $count++;
1590abe1d3eSchris        if ($success) $hits++;
1600abe1d3eSchris        $stats[$this->ext] = "$ext,$count,$hits";
1614b5f4f4eSchris
1624b5f4f4eSchris        io_saveFile($file,join("\n",$stats));
1634b5f4f4eSchris
1644b5f4f4eSchris        return $success;
1654b5f4f4eSchris    }
1664b5f4f4eSchris}
1674b5f4f4eSchris
168*cefd14cbSGerrit Uitslag/**
169*cefd14cbSGerrit Uitslag * Parser caching
170*cefd14cbSGerrit Uitslag */
1714b5f4f4eSchrisclass cache_parser extends cache {
1724b5f4f4eSchris
173c59b3e00SGerrit Uitslag    public $file = '';       // source file for cache
174c59b3e00SGerrit Uitslag    public $mode = '';       // input mode (represents the processing the input file will undergo)
1754b5f4f4eSchris
1764b5f4f4eSchris    var $_event = 'PARSER_CACHE_USE';
1774b5f4f4eSchris
178c59b3e00SGerrit Uitslag    /**
179c59b3e00SGerrit Uitslag     *
180c59b3e00SGerrit Uitslag     * @param string $id page id
181c59b3e00SGerrit Uitslag     * @param string $file source file for cache
182c59b3e00SGerrit Uitslag     * @param string $mode input mode
183c59b3e00SGerrit Uitslag     */
184c59b3e00SGerrit Uitslag    public function cache_parser($id, $file, $mode) {
1854b5f4f4eSchris        if ($id) $this->page = $id;
1864b5f4f4eSchris        $this->file = $file;
1874b5f4f4eSchris        $this->mode = $mode;
1884b5f4f4eSchris
1894b5f4f4eSchris        parent::cache($file.$_SERVER['HTTP_HOST'].$_SERVER['SERVER_PORT'],'.'.$mode);
1904b5f4f4eSchris    }
1914b5f4f4eSchris
192c59b3e00SGerrit Uitslag    /**
193c59b3e00SGerrit Uitslag     * method contains cache use decision logic
194c59b3e00SGerrit Uitslag     *
195c59b3e00SGerrit Uitslag     * @return bool               see useCache()
196c59b3e00SGerrit Uitslag     */
197c59b3e00SGerrit Uitslag    protected function _useCache() {
1984b5f4f4eSchris
1994b5f4f4eSchris        if (!@file_exists($this->file)) return false;                   // source exists?
2000abe1d3eSchris        return parent::_useCache();
2010abe1d3eSchris    }
2024b5f4f4eSchris
203c59b3e00SGerrit Uitslag    protected function _addDependencies() {
204c59b3e00SGerrit Uitslag        global $conf;
2050abe1d3eSchris
2060abe1d3eSchris        $this->depends['age'] = isset($this->depends['age']) ?
2070abe1d3eSchris            min($this->depends['age'],$conf['cachetime']) : $conf['cachetime'];
2084b5f4f4eSchris
2094b5f4f4eSchris        // parser cache file dependencies ...
2104b5f4f4eSchris        $files = array($this->file,                              // ... source
2114b5f4f4eSchris                DOKU_INC.'inc/parser/parser.php',                // ... parser
2124b5f4f4eSchris                DOKU_INC.'inc/parser/handler.php',               // ... handler
2134b5f4f4eSchris                );
214f8121585SChris Smith        $files = array_merge($files, getConfigFiles('main'));    // ... wiki settings
2154b5f4f4eSchris
2164b5f4f4eSchris        $this->depends['files'] = !empty($this->depends['files']) ? array_merge($files, $this->depends['files']) : $files;
2170abe1d3eSchris        parent::_addDependencies();
2184b5f4f4eSchris    }
2194b5f4f4eSchris
2204b5f4f4eSchris}
2214b5f4f4eSchris
222*cefd14cbSGerrit Uitslag/**
223*cefd14cbSGerrit Uitslag * Caching of data of renderer
224*cefd14cbSGerrit Uitslag */
2254b5f4f4eSchrisclass cache_renderer extends cache_parser {
226c59b3e00SGerrit Uitslag
227c59b3e00SGerrit Uitslag    /**
228c59b3e00SGerrit Uitslag     * method contains cache use decision logic
229c59b3e00SGerrit Uitslag     *
230c59b3e00SGerrit Uitslag     * @return bool               see useCache()
231c59b3e00SGerrit Uitslag     */
232c59b3e00SGerrit Uitslag    protected function _useCache() {
233b9991f57Schris        global $conf;
2344b5f4f4eSchris
2350abe1d3eSchris        if (!parent::_useCache()) return false;
2364b5f4f4eSchris
237c0322273SAdrian Lang        if (!isset($this->page)) {
238c0322273SAdrian Lang            return true;
239c0322273SAdrian Lang        }
240c0322273SAdrian Lang
2412302d6beSMartin Doucha        if ($this->_time < @filemtime(metaFN($this->page,'.meta'))) return false;         // meta cache older than file it depends on?
2422302d6beSMartin Doucha
243c0322273SAdrian Lang        // check current link existence is consistent with cache version
244c0322273SAdrian Lang        // first check the purgefile
245c0322273SAdrian Lang        // - if the cache is more recent than the purgefile we know no links can have been updated
2462e3d6a01SKazutaka Miyasaka        if ($this->_time >= @filemtime($conf['cachedir'].'/purgefile')) {
247c0322273SAdrian Lang            return true;
248c0322273SAdrian Lang        }
249c0322273SAdrian Lang
250ce6b63d9Schris        // for wiki pages, check metadata dependencies
251ce6b63d9Schris        $metadata = p_get_metadata($this->page);
2520abe1d3eSchris
253c0322273SAdrian Lang        if (!isset($metadata['relation']['references']) ||
2542e3d6a01SKazutaka Miyasaka                empty($metadata['relation']['references'])) {
255c0322273SAdrian Lang            return true;
256c0322273SAdrian Lang        }
2570abe1d3eSchris
258c0322273SAdrian Lang        foreach ($metadata['relation']['references'] as $id => $exists) {
259103c256aSChris Smith            if ($exists != page_exists($id,'',false)) return false;
2604b5f4f4eSchris        }
2614b5f4f4eSchris
2624b5f4f4eSchris        return true;
2634b5f4f4eSchris    }
2640abe1d3eSchris
265c59b3e00SGerrit Uitslag    protected function _addDependencies() {
2660abe1d3eSchris
2670abe1d3eSchris        // renderer cache file dependencies ...
2680abe1d3eSchris        $files = array(
2690abe1d3eSchris                DOKU_INC.'inc/parser/'.$this->mode.'.php',       // ... the renderer
2700abe1d3eSchris                );
271ce6b63d9Schris
272ce6b63d9Schris        // page implies metadata and possibly some other dependencies
273ce6b63d9Schris        if (isset($this->page)) {
2740a69dff7Schris
27598214867SMichael Hamann            $valid = p_get_metadata($this->page, 'date valid');         // for xhtml this will render the metadata if needed
2760a69dff7Schris            if (!empty($valid['age'])) {
2770a69dff7Schris                $this->depends['age'] = isset($this->depends['age']) ?
2780a69dff7Schris                    min($this->depends['age'],$valid['age']) : $valid['age'];
2790a69dff7Schris            }
280ce6b63d9Schris        }
2810abe1d3eSchris
2820abe1d3eSchris        $this->depends['files'] = !empty($this->depends['files']) ? array_merge($files, $this->depends['files']) : $files;
2830abe1d3eSchris        parent::_addDependencies();
2840abe1d3eSchris    }
2854b5f4f4eSchris}
2864b5f4f4eSchris
287*cefd14cbSGerrit Uitslag/**
288*cefd14cbSGerrit Uitslag * Caching of parser instructions
289*cefd14cbSGerrit Uitslag */
2904b5f4f4eSchrisclass cache_instructions extends cache_parser {
2914b5f4f4eSchris
292c59b3e00SGerrit Uitslag    /**
293c59b3e00SGerrit Uitslag     * @param string $id page id
294c59b3e00SGerrit Uitslag     * @param string $file source file for cache
295c59b3e00SGerrit Uitslag     */
296c59b3e00SGerrit Uitslag    public function cache_instructions($id, $file) {
2974b5f4f4eSchris        parent::cache_parser($id, $file, 'i');
2984b5f4f4eSchris    }
2994b5f4f4eSchris
300c59b3e00SGerrit Uitslag    /**
301c59b3e00SGerrit Uitslag     * retrieve the cached data
302c59b3e00SGerrit Uitslag     *
303c59b3e00SGerrit Uitslag     * @param   bool   $clean   true to clean line endings, false to leave line endings alone
304c59b3e00SGerrit Uitslag     * @return  string          cache contents
305c59b3e00SGerrit Uitslag     */
306c59b3e00SGerrit Uitslag    public function retrieveCache($clean=true) {
3074b5f4f4eSchris        $contents = io_readFile($this->cache, false);
3084b5f4f4eSchris        return !empty($contents) ? unserialize($contents) : array();
3094b5f4f4eSchris    }
3104b5f4f4eSchris
311c59b3e00SGerrit Uitslag    /**
312c59b3e00SGerrit Uitslag     * cache $instructions
313c59b3e00SGerrit Uitslag     *
314c59b3e00SGerrit Uitslag     * @param   string $instructions  the instruction to be cached
315c59b3e00SGerrit Uitslag     * @return  bool                  true on success, false otherwise
316c59b3e00SGerrit Uitslag     */
317c59b3e00SGerrit Uitslag    public function storeCache($instructions) {
318cbaf4259SChris Smith        return io_savefile($this->cache,serialize($instructions));
3194b5f4f4eSchris    }
3204b5f4f4eSchris}
321