xref: /dokuwiki/inc/cache.php (revision 8f3419f56b9bfbb3aa4d40fe411f44e448ad8656)
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
11cefd14cbSGerrit Uitslag/**
12cefd14cbSGerrit Uitslag * Generic handling of caching
13cefd14cbSGerrit 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;
23b2356002SChristopher Smith    var $_nocache = false;  // if set to true, cache will not be used or stored
244b5f4f4eSchris
25c59b3e00SGerrit Uitslag    /**
26c59b3e00SGerrit Uitslag     * @param string $key primary identifier
27c59b3e00SGerrit Uitslag     * @param string $ext file extension
28c59b3e00SGerrit Uitslag     */
29c59b3e00SGerrit Uitslag    public function cache($key,$ext) {
304b5f4f4eSchris        $this->key = $key;
314b5f4f4eSchris        $this->ext = $ext;
324b5f4f4eSchris        $this->cache = getCacheName($key,$ext);
334b5f4f4eSchris    }
344b5f4f4eSchris
354b5f4f4eSchris    /**
364b5f4f4eSchris     * public method to determine whether the cache can be used
374b5f4f4eSchris     *
38b2356002SChristopher Smith     * to assist in centralisation of event triggering and calculation of cache statistics,
394b5f4f4eSchris     * don't override this function override _useCache()
404b5f4f4eSchris     *
414b5f4f4eSchris     * @param  array   $depends   array of cache dependencies, support dependecies:
424b5f4f4eSchris     *                            'age'   => max age of the cache in seconds
434b5f4f4eSchris     *                            'files' => cache must be younger than mtime of each file
44ce6b63d9Schris     *                                       (nb. dependency passes if file doesn't exist)
454b5f4f4eSchris     *
464b5f4f4eSchris     * @return bool    true if cache can be used, false otherwise
474b5f4f4eSchris     */
48c59b3e00SGerrit Uitslag    public function useCache($depends=array()) {
494b5f4f4eSchris        $this->depends = $depends;
500abe1d3eSchris        $this->_addDependencies();
514b5f4f4eSchris
524b5f4f4eSchris        if ($this->_event) {
534b5f4f4eSchris            return $this->_stats(trigger_event($this->_event,$this,array($this,'_useCache')));
544b5f4f4eSchris        } else {
554b5f4f4eSchris            return $this->_stats($this->_useCache());
564b5f4f4eSchris        }
574b5f4f4eSchris    }
584b5f4f4eSchris
590abe1d3eSchris    /**
604b5f4f4eSchris     * private method containing cache use decision logic
614b5f4f4eSchris     *
620abe1d3eSchris     * this function processes the following keys in the depends array
630abe1d3eSchris     *   purge - force a purge on any non empty value
640abe1d3eSchris     *   age   - expire cache if older than age (seconds)
650abe1d3eSchris     *   files - expire cache if any file in this array was updated more recently than the cache
660abe1d3eSchris     *
67a8795974SMichael Hamann     * Note that this function needs to be public as it is used as callback for the event handler
68a8795974SMichael Hamann     *
690abe1d3eSchris     * can be overridden
704b5f4f4eSchris     *
714b5f4f4eSchris     * @return bool               see useCache()
724b5f4f4eSchris     */
73a8795974SMichael Hamann    public function _useCache() {
744b5f4f4eSchris
75b2356002SChristopher Smith        if ($this->_nocache) return false;                              // caching turned off
760abe1d3eSchris        if (!empty($this->depends['purge'])) return false;              // purge requested?
774b5f4f4eSchris        if (!($this->_time = @filemtime($this->cache))) return false;   // cache exists?
784b5f4f4eSchris
794b5f4f4eSchris        // cache too old?
804b5f4f4eSchris        if (!empty($this->depends['age']) && ((time() - $this->_time) > $this->depends['age'])) return false;
814b5f4f4eSchris
824b5f4f4eSchris        if (!empty($this->depends['files'])) {
834b5f4f4eSchris            foreach ($this->depends['files'] as $file) {
84a257b0bdSMartin Doucha                if ($this->_time <= @filemtime($file)) return false;         // cache older than files it depends on?
854b5f4f4eSchris            }
864b5f4f4eSchris        }
874b5f4f4eSchris
884b5f4f4eSchris        return true;
894b5f4f4eSchris    }
904b5f4f4eSchris
914b5f4f4eSchris    /**
920abe1d3eSchris     * add dependencies to the depends array
930abe1d3eSchris     *
940abe1d3eSchris     * this method should only add dependencies,
950abe1d3eSchris     * it should not remove any existing dependencies and
960abe1d3eSchris     * it should only overwrite a dependency when the new value is more stringent than the old
970abe1d3eSchris     */
98c59b3e00SGerrit Uitslag    protected function _addDependencies() {
997d01a0eaSTom N Harris        global $INPUT;
1007d01a0eaSTom N Harris        if ($INPUT->has('purge')) $this->depends['purge'] = true;   // purge requested
1010abe1d3eSchris    }
1020abe1d3eSchris
1030abe1d3eSchris    /**
1044b5f4f4eSchris     * retrieve the cached data
1054b5f4f4eSchris     *
1064b5f4f4eSchris     * @param   bool   $clean   true to clean line endings, false to leave line endings alone
1074b5f4f4eSchris     * @return  string          cache contents
1084b5f4f4eSchris     */
109c59b3e00SGerrit Uitslag    public function retrieveCache($clean=true) {
1104b5f4f4eSchris        return io_readFile($this->cache, $clean);
1114b5f4f4eSchris    }
1124b5f4f4eSchris
1134b5f4f4eSchris    /**
1144b5f4f4eSchris     * cache $data
1154b5f4f4eSchris     *
1164b5f4f4eSchris     * @param   string $data   the data to be cached
117cbaf4259SChris Smith     * @return  bool           true on success, false otherwise
1184b5f4f4eSchris     */
119c59b3e00SGerrit Uitslag    public function storeCache($data) {
120b2356002SChristopher Smith        if ($this->_nocache) return false;
121b2356002SChristopher Smith
122cbaf4259SChris Smith        return io_savefile($this->cache, $data);
1234b5f4f4eSchris    }
1244b5f4f4eSchris
1254b5f4f4eSchris    /**
1264b5f4f4eSchris     * remove any cached data associated with this cache instance
1274b5f4f4eSchris     */
128c59b3e00SGerrit Uitslag    public function removeCache() {
1294b5f4f4eSchris        @unlink($this->cache);
1304b5f4f4eSchris    }
1314b5f4f4eSchris
1324b5f4f4eSchris    /**
13333c1bd61SBen Coburn     * Record cache hits statistics.
13433c1bd61SBen Coburn     * (Only when debugging allowed, to reduce overhead.)
1354b5f4f4eSchris     *
1364b5f4f4eSchris     * @param    bool   $success   result of this cache use attempt
1374b5f4f4eSchris     * @return   bool              pass-thru $success value
1384b5f4f4eSchris     */
139c59b3e00SGerrit Uitslag    protected function _stats($success) {
1404b5f4f4eSchris        global $conf;
14149eb6e38SAndreas Gohr        static $stats = null;
1424b5f4f4eSchris        static $file;
1434b5f4f4eSchris
14433c1bd61SBen Coburn        if (!$conf['allowdebug']) { return $success; }
14533c1bd61SBen Coburn
1464b5f4f4eSchris        if (is_null($stats)) {
1474b5f4f4eSchris            $file = $conf['cachedir'].'/cache_stats.txt';
1484b5f4f4eSchris            $lines = explode("\n",io_readFile($file));
1494b5f4f4eSchris
1504b5f4f4eSchris            foreach ($lines as $line) {
1514b5f4f4eSchris                $i = strpos($line,',');
1524b5f4f4eSchris                $stats[substr($line,0,$i)] = $line;
1534b5f4f4eSchris            }
1544b5f4f4eSchris        }
1554b5f4f4eSchris
1564b5f4f4eSchris        if (isset($stats[$this->ext])) {
1570abe1d3eSchris            list($ext,$count,$hits) = explode(',',$stats[$this->ext]);
1584b5f4f4eSchris        } else {
1594b5f4f4eSchris            $ext = $this->ext;
1604b5f4f4eSchris            $count = 0;
1610abe1d3eSchris            $hits = 0;
1624b5f4f4eSchris        }
1634b5f4f4eSchris
1644b5f4f4eSchris        $count++;
1650abe1d3eSchris        if ($success) $hits++;
1660abe1d3eSchris        $stats[$this->ext] = "$ext,$count,$hits";
1674b5f4f4eSchris
1684b5f4f4eSchris        io_saveFile($file,join("\n",$stats));
1694b5f4f4eSchris
1704b5f4f4eSchris        return $success;
1714b5f4f4eSchris    }
1724b5f4f4eSchris}
1734b5f4f4eSchris
174cefd14cbSGerrit Uitslag/**
175cefd14cbSGerrit Uitslag * Parser caching
176cefd14cbSGerrit Uitslag */
1774b5f4f4eSchrisclass cache_parser extends cache {
1784b5f4f4eSchris
179c59b3e00SGerrit Uitslag    public $file = '';       // source file for cache
180c59b3e00SGerrit Uitslag    public $mode = '';       // input mode (represents the processing the input file will undergo)
181*8f3419f5SAndreas Gohr    public $page = '';
1824b5f4f4eSchris
1834b5f4f4eSchris    var $_event = 'PARSER_CACHE_USE';
1844b5f4f4eSchris
185c59b3e00SGerrit Uitslag    /**
186c59b3e00SGerrit Uitslag     *
187c59b3e00SGerrit Uitslag     * @param string $id page id
188c59b3e00SGerrit Uitslag     * @param string $file source file for cache
189c59b3e00SGerrit Uitslag     * @param string $mode input mode
190c59b3e00SGerrit Uitslag     */
191c59b3e00SGerrit Uitslag    public function cache_parser($id, $file, $mode) {
1924b5f4f4eSchris        if ($id) $this->page = $id;
1934b5f4f4eSchris        $this->file = $file;
1944b5f4f4eSchris        $this->mode = $mode;
1954b5f4f4eSchris
1964b5f4f4eSchris        parent::cache($file.$_SERVER['HTTP_HOST'].$_SERVER['SERVER_PORT'],'.'.$mode);
1974b5f4f4eSchris    }
1984b5f4f4eSchris
199c59b3e00SGerrit Uitslag    /**
200c59b3e00SGerrit Uitslag     * method contains cache use decision logic
201c59b3e00SGerrit Uitslag     *
202c59b3e00SGerrit Uitslag     * @return bool               see useCache()
203c59b3e00SGerrit Uitslag     */
204a8795974SMichael Hamann    public function _useCache() {
2054b5f4f4eSchris
2064b5f4f4eSchris        if (!@file_exists($this->file)) return false;                   // source exists?
2070abe1d3eSchris        return parent::_useCache();
2080abe1d3eSchris    }
2094b5f4f4eSchris
210c59b3e00SGerrit Uitslag    protected function _addDependencies() {
2114b5f4f4eSchris
2124b5f4f4eSchris        // parser cache file dependencies ...
2134b5f4f4eSchris        $files = array($this->file,                              // ... source
2144b5f4f4eSchris                DOKU_INC.'inc/parser/parser.php',                // ... parser
2154b5f4f4eSchris                DOKU_INC.'inc/parser/handler.php',               // ... handler
2164b5f4f4eSchris                );
217f8121585SChris Smith        $files = array_merge($files, getConfigFiles('main'));    // ... wiki settings
2184b5f4f4eSchris
2194b5f4f4eSchris        $this->depends['files'] = !empty($this->depends['files']) ? array_merge($files, $this->depends['files']) : $files;
2200abe1d3eSchris        parent::_addDependencies();
2214b5f4f4eSchris    }
2224b5f4f4eSchris
2234b5f4f4eSchris}
2244b5f4f4eSchris
225cefd14cbSGerrit Uitslag/**
226cefd14cbSGerrit Uitslag * Caching of data of renderer
227cefd14cbSGerrit Uitslag */
2284b5f4f4eSchrisclass cache_renderer extends cache_parser {
229c59b3e00SGerrit Uitslag
230c59b3e00SGerrit Uitslag    /**
231c59b3e00SGerrit Uitslag     * method contains cache use decision logic
232c59b3e00SGerrit Uitslag     *
233c59b3e00SGerrit Uitslag     * @return bool               see useCache()
234c59b3e00SGerrit Uitslag     */
235a8795974SMichael Hamann    public function _useCache() {
236b9991f57Schris        global $conf;
2374b5f4f4eSchris
2380abe1d3eSchris        if (!parent::_useCache()) return false;
2394b5f4f4eSchris
240c0322273SAdrian Lang        if (!isset($this->page)) {
241c0322273SAdrian Lang            return true;
242c0322273SAdrian Lang        }
243c0322273SAdrian Lang
2442302d6beSMartin Doucha        if ($this->_time < @filemtime(metaFN($this->page,'.meta'))) return false;         // meta cache older than file it depends on?
2452302d6beSMartin Doucha
246c0322273SAdrian Lang        // check current link existence is consistent with cache version
247c0322273SAdrian Lang        // first check the purgefile
248c0322273SAdrian Lang        // - if the cache is more recent than the purgefile we know no links can have been updated
2492e3d6a01SKazutaka Miyasaka        if ($this->_time >= @filemtime($conf['cachedir'].'/purgefile')) {
250c0322273SAdrian Lang            return true;
251c0322273SAdrian Lang        }
252c0322273SAdrian Lang
253ce6b63d9Schris        // for wiki pages, check metadata dependencies
254ce6b63d9Schris        $metadata = p_get_metadata($this->page);
2550abe1d3eSchris
256c0322273SAdrian Lang        if (!isset($metadata['relation']['references']) ||
2572e3d6a01SKazutaka Miyasaka                empty($metadata['relation']['references'])) {
258c0322273SAdrian Lang            return true;
259c0322273SAdrian Lang        }
2600abe1d3eSchris
261c0322273SAdrian Lang        foreach ($metadata['relation']['references'] as $id => $exists) {
262103c256aSChris Smith            if ($exists != page_exists($id,'',false)) return false;
2634b5f4f4eSchris        }
2644b5f4f4eSchris
2654b5f4f4eSchris        return true;
2664b5f4f4eSchris    }
2670abe1d3eSchris
268c59b3e00SGerrit Uitslag    protected function _addDependencies() {
269b2356002SChristopher Smith        global $conf;
270b2356002SChristopher Smith
271b2356002SChristopher Smith        // default renderer cache file 'age' is dependent on 'cachetime' setting, two special values:
272b2356002SChristopher Smith        //    -1 : do not cache (should not be overridden)
273b2356002SChristopher Smith        //    0  : cache never expires (can be overridden) - no need to set depends['age']
274b2356002SChristopher Smith        if ($conf['cachetime'] == -1) {
275b2356002SChristopher Smith            $this->_nocache = true;
276b2356002SChristopher Smith            return;
277b2356002SChristopher Smith        } elseif ($conf['cachetime'] > 0) {
278b2356002SChristopher Smith            $this->depends['age'] = isset($this->depends['age']) ?
279b2356002SChristopher Smith                min($this->depends['age'],$conf['cachetime']) : $conf['cachetime'];
280b2356002SChristopher Smith        }
2810abe1d3eSchris
2820abe1d3eSchris        // renderer cache file dependencies ...
2830abe1d3eSchris        $files = array(
2840abe1d3eSchris                DOKU_INC.'inc/parser/'.$this->mode.'.php',       // ... the renderer
2850abe1d3eSchris                );
286ce6b63d9Schris
287ce6b63d9Schris        // page implies metadata and possibly some other dependencies
288ce6b63d9Schris        if (isset($this->page)) {
2890a69dff7Schris
29098214867SMichael Hamann            $valid = p_get_metadata($this->page, 'date valid');         // for xhtml this will render the metadata if needed
2910a69dff7Schris            if (!empty($valid['age'])) {
2920a69dff7Schris                $this->depends['age'] = isset($this->depends['age']) ?
2930a69dff7Schris                    min($this->depends['age'],$valid['age']) : $valid['age'];
2940a69dff7Schris            }
295ce6b63d9Schris        }
2960abe1d3eSchris
2970abe1d3eSchris        $this->depends['files'] = !empty($this->depends['files']) ? array_merge($files, $this->depends['files']) : $files;
2980abe1d3eSchris        parent::_addDependencies();
2990abe1d3eSchris    }
3004b5f4f4eSchris}
3014b5f4f4eSchris
302cefd14cbSGerrit Uitslag/**
303cefd14cbSGerrit Uitslag * Caching of parser instructions
304cefd14cbSGerrit Uitslag */
3054b5f4f4eSchrisclass cache_instructions extends cache_parser {
3064b5f4f4eSchris
307c59b3e00SGerrit Uitslag    /**
308c59b3e00SGerrit Uitslag     * @param string $id page id
309c59b3e00SGerrit Uitslag     * @param string $file source file for cache
310c59b3e00SGerrit Uitslag     */
311c59b3e00SGerrit Uitslag    public function cache_instructions($id, $file) {
3124b5f4f4eSchris        parent::cache_parser($id, $file, 'i');
3134b5f4f4eSchris    }
3144b5f4f4eSchris
315c59b3e00SGerrit Uitslag    /**
316c59b3e00SGerrit Uitslag     * retrieve the cached data
317c59b3e00SGerrit Uitslag     *
318c59b3e00SGerrit Uitslag     * @param   bool   $clean   true to clean line endings, false to leave line endings alone
319c59b3e00SGerrit Uitslag     * @return  string          cache contents
320c59b3e00SGerrit Uitslag     */
321c59b3e00SGerrit Uitslag    public function retrieveCache($clean=true) {
3224b5f4f4eSchris        $contents = io_readFile($this->cache, false);
3234b5f4f4eSchris        return !empty($contents) ? unserialize($contents) : array();
3244b5f4f4eSchris    }
3254b5f4f4eSchris
326c59b3e00SGerrit Uitslag    /**
327c59b3e00SGerrit Uitslag     * cache $instructions
328c59b3e00SGerrit Uitslag     *
329c59b3e00SGerrit Uitslag     * @param   string $instructions  the instruction to be cached
330c59b3e00SGerrit Uitslag     * @return  bool                  true on success, false otherwise
331c59b3e00SGerrit Uitslag     */
332c59b3e00SGerrit Uitslag    public function storeCache($instructions) {
333b2356002SChristopher Smith        if ($this->_nocache) return false;
334b2356002SChristopher Smith
335cbaf4259SChris Smith        return io_savefile($this->cache,serialize($instructions));
3364b5f4f4eSchris    }
3374b5f4f4eSchris}
338