xref: /dokuwiki/inc/parserutils.php (revision 99ba9fe6e3cd8a1c51c481f04675e48dec842773)
1c112d578Sandi<?php
2c112d578Sandi/**
3b8595a66SAndreas Gohr * Utilities for accessing the parser
4c112d578Sandi *
5c112d578Sandi * @license    GPL 2 (http://www.gnu.org/licenses/gpl.html)
6c112d578Sandi * @author     Harry Fuecks <hfuecks@gmail.com>
7c112d578Sandi * @author     Andreas Gohr <andi@splitbrain.org>
8c112d578Sandi */
9c112d578Sandi
10fa8adffeSAndreas Gohrif(!defined('DOKU_INC')) die('meh.');
11c112d578Sandi
12c112d578Sandi/**
1365aa8490SMichael Hamann * How many pages shall be rendered for getting metadata during one request
1465aa8490SMichael Hamann * at maximum? Note that this limit isn't respected when METADATA_RENDER_UNLIMITED
1565aa8490SMichael Hamann * is passed as render parameter to p_get_metadata.
16ff725173SMichael Hamann */
1765aa8490SMichael Hamannif (!defined('P_GET_METADATA_RENDER_LIMIT')) define('P_GET_METADATA_RENDER_LIMIT', 5);
1867c15eceSMichael Hamann
1967c15eceSMichael Hamann/** Don't render metadata even if it is outdated or doesn't exist */
2067c15eceSMichael Hamanndefine('METADATA_DONT_RENDER', 0);
2165aa8490SMichael Hamann/**
2265aa8490SMichael Hamann * Render metadata when the page is really newer or the metadata doesn't exist.
2365aa8490SMichael Hamann * Uses just a simple check, but should work pretty well for loading simple
2465aa8490SMichael Hamann * metadata values like the page title and avoids rendering a lot of pages in
2565aa8490SMichael Hamann * one request. The P_GET_METADATA_RENDER_LIMIT is used in this mode.
2665aa8490SMichael Hamann * Use this if it is unlikely that the metadata value you are requesting
2765aa8490SMichael Hamann * does depend e.g. on pages that are included in the current page using
2865aa8490SMichael Hamann * the include plugin (this is very likely the case for the page title, but
2965aa8490SMichael Hamann * not for relation references).
3065aa8490SMichael Hamann */
3167c15eceSMichael Hamanndefine('METADATA_RENDER_USING_SIMPLE_CACHE', 1);
3265aa8490SMichael Hamann/**
3365aa8490SMichael Hamann * Render metadata using the metadata cache logic. The P_GET_METADATA_RENDER_LIMIT
3465aa8490SMichael Hamann * is used in this mode. Use this mode when you are requesting more complex
3565aa8490SMichael Hamann * metadata. Although this will cause rendering more often it might actually have
3665aa8490SMichael Hamann * the effect that less current metadata is returned as it is more likely than in
3765aa8490SMichael Hamann * the simple cache mode that metadata needs to be rendered for all pages at once
3865aa8490SMichael Hamann * which means that when the metadata for the page is requested that actually needs
3965aa8490SMichael Hamann * to be updated the limit might have been reached already.
4065aa8490SMichael Hamann */
4167c15eceSMichael Hamanndefine('METADATA_RENDER_USING_CACHE', 2);
4265aa8490SMichael Hamann/**
4365aa8490SMichael Hamann * Render metadata without limiting the number of pages for which metadata is
4465aa8490SMichael Hamann * rendered. Use this mode with care, normally it should only be used in places
4565aa8490SMichael Hamann * like the indexer or in cli scripts where the execution time normally isn't
4665aa8490SMichael Hamann * limited. This can be combined with the simple cache using
4765aa8490SMichael Hamann * METADATA_RENDER_USING_CACHE | METADATA_RENDER_UNLIMITED.
4865aa8490SMichael Hamann */
4965aa8490SMichael Hamanndefine('METADATA_RENDER_UNLIMITED', 4);
50ff725173SMichael Hamann
51ff725173SMichael Hamann/**
52c112d578Sandi * Returns the parsed Wikitext in XHTML for the given id and revision.
53c112d578Sandi *
54c112d578Sandi * If $excuse is true an explanation is returned if the file
55c112d578Sandi * wasn't found
56c112d578Sandi *
57c112d578Sandi * @author Andreas Gohr <andi@splitbrain.org>
58c112d578Sandi */
59c112d578Sandifunction p_wiki_xhtml($id, $rev='', $excuse=true){
60c112d578Sandi    $file = wikiFN($id,$rev);
61c112d578Sandi    $ret  = '';
62c112d578Sandi
63c112d578Sandi    //ensure $id is in global $ID (needed for parsing)
641e76272cSandi    global $ID;
653ff8773bSAndreas Gohr    $keep = $ID;
661e76272cSandi    $ID   = $id;
67c112d578Sandi
68c112d578Sandi    if($rev){
69c112d578Sandi        if(@file_exists($file)){
70bde4e341SGalaxyMaster            $ret = p_render('xhtml',p_get_instructions(io_readWikiPage($file,$id,$rev)),$info); //no caching on old revisions
71c112d578Sandi        }elseif($excuse){
72c112d578Sandi            $ret = p_locale_xhtml('norev');
73c112d578Sandi        }
74c112d578Sandi    }else{
75c112d578Sandi        if(@file_exists($file)){
764b5f4f4eSchris            $ret = p_cached_output($file,'xhtml',$id);
77c112d578Sandi        }elseif($excuse){
78c112d578Sandi            $ret = p_locale_xhtml('newpage');
79c112d578Sandi        }
80c112d578Sandi    }
81c112d578Sandi
823ff8773bSAndreas Gohr    //restore ID (just in case)
833ff8773bSAndreas Gohr    $ID = $keep;
843ff8773bSAndreas Gohr
85c112d578Sandi    return $ret;
86c112d578Sandi}
87c112d578Sandi
88c112d578Sandi/**
89c112d578Sandi * Returns the specified local text in parsed format
90c112d578Sandi *
91c112d578Sandi * @author Andreas Gohr <andi@splitbrain.org>
92c112d578Sandi */
93c112d578Sandifunction p_locale_xhtml($id){
94c112d578Sandi    //fetch parsed locale
954b5f4f4eSchris    $html = p_cached_output(localeFN($id));
96c112d578Sandi    return $html;
97c112d578Sandi}
98c112d578Sandi
99c112d578Sandi/**
1004b5f4f4eSchris * Returns the given file parsed into the requested output format
1014b5f4f4eSchris *
1024b5f4f4eSchris * @author Andreas Gohr <andi@splitbrain.org>
1034b5f4f4eSchris * @author Chris Smith <chris@jalakai.co.uk>
1044b5f4f4eSchris */
1054b5f4f4eSchrisfunction p_cached_output($file, $format='xhtml', $id='') {
106c112d578Sandi    global $conf;
107c112d578Sandi
1084b5f4f4eSchris    $cache = new cache_renderer($id, $file, $format);
1094b5f4f4eSchris    if ($cache->useCache()) {
11085767031SAndreas Gohr        $parsed = $cache->retrieveCache(false);
111ea2a4271SAndreas Gohr        if($conf['allowdebug'] && $format=='xhtml') $parsed .= "\n<!-- cachefile {$cache->cache} used -->\n";
112c112d578Sandi    } else {
1134b5f4f4eSchris        $parsed = p_render($format, p_cached_instructions($file,false,$id), $info);
114c112d578Sandi
1159dc2c2afSandi        if ($info['cache']) {
1164b5f4f4eSchris            $cache->storeCache($parsed);               //save cachefile
117ea2a4271SAndreas Gohr            if($conf['allowdebug'] && $format=='xhtml') $parsed .= "\n<!-- no cachefile used, but created {$cache->cache} -->\n";
118c112d578Sandi        }else{
1194b5f4f4eSchris            $cache->removeCache();                     //try to delete cachefile
120ea2a4271SAndreas Gohr            if($conf['allowdebug'] && $format=='xhtml') $parsed .= "\n<!-- no cachefile used, caching forbidden -->\n";
121c112d578Sandi        }
122c112d578Sandi    }
123c112d578Sandi
124c112d578Sandi    return $parsed;
125c112d578Sandi}
126c112d578Sandi
127c112d578Sandi/**
128c112d578Sandi * Returns the render instructions for a file
129c112d578Sandi *
130c112d578Sandi * Uses and creates a serialized cache file
131c112d578Sandi *
132c112d578Sandi * @author Andreas Gohr <andi@splitbrain.org>
133c112d578Sandi */
1344b5f4f4eSchrisfunction p_cached_instructions($file,$cacheonly=false,$id='') {
13547b2d319SAndreas Gohr    static $run = null;
13647b2d319SAndreas Gohr    if(is_null($run)) $run = array();
137c112d578Sandi
1384b5f4f4eSchris    $cache = new cache_instructions($id, $file);
139c112d578Sandi
1400d24b616SMichael Hamann    if ($cacheonly || $cache->useCache() || (isset($run[$file]) && !defined('DOKU_UNITTEST'))) {
1414b5f4f4eSchris        return $cache->retrieveCache();
142c112d578Sandi    } else if (@file_exists($file)) {
143c112d578Sandi        // no cache - do some work
144bde4e341SGalaxyMaster        $ins = p_get_instructions(io_readWikiPage($file,$id));
145cbaf4259SChris Smith        if ($cache->storeCache($ins)) {
14647b2d319SAndreas Gohr            $run[$file] = true; // we won't rebuild these instructions in the same run again
147cbaf4259SChris Smith        } else {
148cbaf4259SChris Smith            msg('Unable to save cache file. Hint: disk full; file permissions; safe_mode setting.',-1);
149cbaf4259SChris Smith        }
150c112d578Sandi        return $ins;
151c112d578Sandi    }
152c112d578Sandi
1533b3f8916SAndreas Gohr    return null;
154c112d578Sandi}
155c112d578Sandi
156c112d578Sandi/**
157c112d578Sandi * turns a page into a list of instructions
158c112d578Sandi *
159c112d578Sandi * @author Harry Fuecks <hfuecks@gmail.com>
160c112d578Sandi * @author Andreas Gohr <andi@splitbrain.org>
161*99ba9fe6SAndreas Gohr * @param string $text raw wiki syntax text
162*99ba9fe6SAndreas Gohr * @return array a list of instruction arrays
163c112d578Sandi */
1646bbae538Sandifunction p_get_instructions($text){
165c112d578Sandi
166107b01d6Sandi    $modes = p_get_parsermodes();
167ee20e7d1Sandi
168c112d578Sandi    // Create the parser
16967f9913dSAndreas Gohr    $Parser = new Doku_Parser();
170c112d578Sandi
171c112d578Sandi    // Add the Handler
17267f9913dSAndreas Gohr    $Parser->Handler = new Doku_Handler();
173c112d578Sandi
174107b01d6Sandi    //add modes to parser
175107b01d6Sandi    foreach($modes as $mode){
176107b01d6Sandi        $Parser->addMode($mode['mode'],$mode['obj']);
177c112d578Sandi    }
178c112d578Sandi
179c112d578Sandi    // Do the parsing
180677844afSchris    trigger_event('PARSER_WIKITEXT_PREPROCESS', $text);
181a2d649c4Sandi    $p = $Parser->parse($text);
182ee20e7d1Sandi    //  dbg($p);
183a2d649c4Sandi    return $p;
184c112d578Sandi}
185c112d578Sandi
186c112d578Sandi/**
18739a89382SEsther Brunner * returns the metadata of a page
18839a89382SEsther Brunner *
1894a819402SMichael Hamann * @param string $id The id of the page the metadata should be returned from
1904a819402SMichael Hamann * @param string $key The key of the metdata value that shall be read (by default everything) - separate hierarchies by " " like "date created"
19167c15eceSMichael Hamann * @param int $render If the page should be rendererd - possible values:
19265aa8490SMichael Hamann *     METADATA_DONT_RENDER, METADATA_RENDER_USING_SIMPLE_CACHE, METADATA_RENDER_USING_CACHE
19365aa8490SMichael Hamann *     METADATA_RENDER_UNLIMITED (also combined with the previous two options),
19465aa8490SMichael Hamann *     default: METADATA_RENDER_USING_CACHE
1954a819402SMichael Hamann * @return mixed The requested metadata fields
1964a819402SMichael Hamann *
19739a89382SEsther Brunner * @author Esther Brunner <esther@kaffeehaus.ch>
19898214867SMichael Hamann * @author Michael Hamann <michael@content-space.de>
19939a89382SEsther Brunner */
20067c15eceSMichael Hamannfunction p_get_metadata($id, $key='', $render=METADATA_RENDER_USING_CACHE){
2011172f8dcSAdrian Lang    global $ID;
20265aa8490SMichael Hamann    static $render_count = 0;
20365aa8490SMichael Hamann    // track pages that have already been rendered in order to avoid rendering the same page
20465aa8490SMichael Hamann    // again
20565aa8490SMichael Hamann    static $rendered_pages = array();
2066afe8dcaSchris
2070a7e3bceSchris    // cache the current page
2080a7e3bceSchris    // Benchmarking shows the current page's metadata is generally the only page metadata
2090a7e3bceSchris    // accessed several times. This may catch a few other pages, but that shouldn't be an issue.
2100a7e3bceSchris    $cache = ($ID == $id);
2110a7e3bceSchris    $meta = p_read_metadata($id, $cache);
21239a89382SEsther Brunner
21367c15eceSMichael Hamann    if (!is_numeric($render)) {
21467c15eceSMichael Hamann        if ($render) {
21567c15eceSMichael Hamann            $render = METADATA_RENDER_USING_SIMPLE_CACHE;
21667c15eceSMichael Hamann        } else {
21767c15eceSMichael Hamann            $render = METADATA_DONT_RENDER;
21867c15eceSMichael Hamann        }
21967c15eceSMichael Hamann    }
22067c15eceSMichael Hamann
22198214867SMichael Hamann    // prevent recursive calls in the cache
22298214867SMichael Hamann    static $recursion = false;
22365aa8490SMichael Hamann    if (!$recursion && $render != METADATA_DONT_RENDER && !isset($rendered_pages[$id])&& page_exists($id)){
22498214867SMichael Hamann        $recursion = true;
22598214867SMichael Hamann
22698214867SMichael Hamann        $cachefile = new cache_renderer($id, wikiFN($id), 'metadata');
22798214867SMichael Hamann
22867c15eceSMichael Hamann        $do_render = false;
22965aa8490SMichael Hamann        if ($render & METADATA_RENDER_UNLIMITED || $render_count < P_GET_METADATA_RENDER_LIMIT) {
23065aa8490SMichael Hamann            if ($render & METADATA_RENDER_USING_SIMPLE_CACHE) {
23167c15eceSMichael Hamann                $pagefn = wikiFN($id);
23267c15eceSMichael Hamann                $metafn = metaFN($id, '.meta');
23367c15eceSMichael Hamann                if (!@file_exists($metafn) || @filemtime($pagefn) > @filemtime($cachefile->cache)) {
23467c15eceSMichael Hamann                    $do_render = true;
23567c15eceSMichael Hamann                }
23667c15eceSMichael Hamann            } elseif (!$cachefile->useCache()){
23767c15eceSMichael Hamann                $do_render = true;
23867c15eceSMichael Hamann            }
23965aa8490SMichael Hamann        }
24067c15eceSMichael Hamann        if ($do_render) {
2410d24b616SMichael Hamann            if (!defined('DOKU_UNITTEST')) {
24265aa8490SMichael Hamann                ++$render_count;
24365aa8490SMichael Hamann                $rendered_pages[$id] = true;
2440d24b616SMichael Hamann            }
24569ba640bSMichael Hamann            $old_meta = $meta;
24639a89382SEsther Brunner            $meta = p_render_metadata($id, $meta);
24769ba640bSMichael Hamann            // only update the file when the metadata has been changed
24869ba640bSMichael Hamann            if ($meta == $old_meta || p_save_metadata($id, $meta)) {
24998214867SMichael Hamann                // store a timestamp in order to make sure that the cachefile is touched
2503d6feb16SMichael Hamann                // this timestamp is also stored when the meta data is still the same
25198214867SMichael Hamann                $cachefile->storeCache(time());
2523d6feb16SMichael Hamann            } else {
25398214867SMichael Hamann                msg('Unable to save metadata file. Hint: disk full; file permissions; safe_mode setting.',-1);
25498214867SMichael Hamann            }
25598214867SMichael Hamann        }
25698214867SMichael Hamann
25798214867SMichael Hamann        $recursion = false;
2586afe8dcaSchris    }
25939a89382SEsther Brunner
260ebf65d37SAdrian Lang    $val = $meta['current'];
261ebf65d37SAdrian Lang
26239a89382SEsther Brunner    // filter by $key
263569a0019SAdrian Lang    foreach(preg_split('/\s+/', $key, 2, PREG_SPLIT_NO_EMPTY) as $cur_key) {
264ebf65d37SAdrian Lang        if (!isset($val[$cur_key])) {
265ebf65d37SAdrian Lang            return null;
26666d29756SChris Smith        }
267ebf65d37SAdrian Lang        $val = $val[$cur_key];
26839a89382SEsther Brunner    }
269ebf65d37SAdrian Lang    return $val;
27039a89382SEsther Brunner}
27139a89382SEsther Brunner
27239a89382SEsther Brunner/**
27339a89382SEsther Brunner * sets metadata elements of a page
27439a89382SEsther Brunner *
275a365baeeSDominik Eckelmann * @see http://www.dokuwiki.org/devel:metadata#functions_to_get_and_set_metadata
276a365baeeSDominik Eckelmann *
277a365baeeSDominik Eckelmann * @param String  $id         is the ID of a wiki page
278a365baeeSDominik Eckelmann * @param Array   $data       is an array with key ⇒ value pairs to be set in the metadata
279a365baeeSDominik Eckelmann * @param Boolean $render     whether or not the page metadata should be generated with the renderer
280a365baeeSDominik Eckelmann * @param Boolean $persistent indicates whether or not the particular metadata value will persist through
281a365baeeSDominik Eckelmann *                            the next metadata rendering.
282a365baeeSDominik Eckelmann * @return boolean true on success
283a365baeeSDominik Eckelmann *
28439a89382SEsther Brunner * @author Esther Brunner <esther@kaffeehaus.ch>
2850e5fde48SMichael Hamann * @author Michael Hamann <michael@content-space.de>
28639a89382SEsther Brunner */
2870a7e3bceSchrisfunction p_set_metadata($id, $data, $render=false, $persistent=true){
28839a89382SEsther Brunner    if (!is_array($data)) return false;
28939a89382SEsther Brunner
2900e5fde48SMichael Hamann    global $ID, $METADATA_RENDERERS;
2910a7e3bceSchris
2920e5fde48SMichael Hamann    // if there is currently a renderer change the data in the renderer instead
2930e5fde48SMichael Hamann    if (isset($METADATA_RENDERERS[$id])) {
2940e5fde48SMichael Hamann        $orig =& $METADATA_RENDERERS[$id];
2950e5fde48SMichael Hamann        $meta = $orig;
2960e5fde48SMichael Hamann    } else {
2970a7e3bceSchris        // cache the current page
2980a7e3bceSchris        $cache = ($ID == $id);
2990a7e3bceSchris        $orig = p_read_metadata($id, $cache);
30039a89382SEsther Brunner
30139a89382SEsther Brunner        // render metadata first?
3020a7e3bceSchris        $meta = $render ? p_render_metadata($id, $orig) : $orig;
3030e5fde48SMichael Hamann    }
30439a89382SEsther Brunner
30539a89382SEsther Brunner    // now add the passed metadata
30639a89382SEsther Brunner    $protected = array('description', 'date', 'contributor');
30739a89382SEsther Brunner    foreach ($data as $key => $value){
30839a89382SEsther Brunner
30939a89382SEsther Brunner        // be careful with sub-arrays of $meta['relation']
31039a89382SEsther Brunner        if ($key == 'relation'){
3110a7e3bceSchris
31239a89382SEsther Brunner            foreach ($value as $subkey => $subvalue){
31331b10b49SMichael Hamann                if(isset($meta['current'][$key][$subkey]) && is_array($meta['current'][$key][$subkey])) {
31431b10b49SMichael Hamann                    $meta['current'][$key][$subkey] = array_merge($meta['current'][$key][$subkey], (array)$subvalue);
31531b10b49SMichael Hamann                } else {
31631b10b49SMichael Hamann                    $meta['current'][$key][$subkey] = $subvalue;
31731b10b49SMichael Hamann                }
31831b10b49SMichael Hamann                if($persistent) {
31931b10b49SMichael Hamann                    if(isset($meta['persistent'][$key][$subkey]) && is_array($meta['persistent'][$key][$subkey])) {
32031b10b49SMichael Hamann                        $meta['persistent'][$key][$subkey] = array_merge($meta['persistent'][$key][$subkey], (array)$subvalue);
32131b10b49SMichael Hamann                    } else {
32231b10b49SMichael Hamann                        $meta['persistent'][$key][$subkey] = $subvalue;
32331b10b49SMichael Hamann                    }
32431b10b49SMichael Hamann                }
32539a89382SEsther Brunner            }
32639a89382SEsther Brunner
32739a89382SEsther Brunner            // be careful with some senisitive arrays of $meta
32839a89382SEsther Brunner        } elseif (in_array($key, $protected)){
3290a7e3bceSchris
33066d29756SChris Smith            // these keys, must have subkeys - a legitimate value must be an array
33139a89382SEsther Brunner            if (is_array($value)) {
33231b10b49SMichael Hamann                $meta['current'][$key] = !empty($meta['current'][$key]) ? array_merge((array)$meta['current'][$key],$value) : $value;
3330a7e3bceSchris
3340a7e3bceSchris                if ($persistent) {
33531b10b49SMichael Hamann                    $meta['persistent'][$key] = !empty($meta['persistent'][$key]) ? array_merge((array)$meta['persistent'][$key],$value) : $value;
3360a7e3bceSchris                }
33739a89382SEsther Brunner            }
33839a89382SEsther Brunner
33939a89382SEsther Brunner            // no special treatment for the rest
34039a89382SEsther Brunner        } else {
3410a7e3bceSchris            $meta['current'][$key] = $value;
3420a7e3bceSchris            if ($persistent) $meta['persistent'][$key] = $value;
34339a89382SEsther Brunner        }
34439a89382SEsther Brunner    }
34539a89382SEsther Brunner
34639a89382SEsther Brunner    // save only if metadata changed
34739a89382SEsther Brunner    if ($meta == $orig) return true;
3486afe8dcaSchris
3490e5fde48SMichael Hamann    if (isset($METADATA_RENDERERS[$id])) {
3500e5fde48SMichael Hamann        // set both keys individually as the renderer has references to the individual keys
3510e5fde48SMichael Hamann        $METADATA_RENDERERS[$id]['current']    = $meta['current'];
3520e5fde48SMichael Hamann        $METADATA_RENDERERS[$id]['persistent'] = $meta['persistent'];
3531c56be7bSMichael Hamann        return true;
3540e5fde48SMichael Hamann    } else {
3551172f8dcSAdrian Lang        return p_save_metadata($id, $meta);
35639a89382SEsther Brunner    }
3570e5fde48SMichael Hamann}
35839a89382SEsther Brunner
35939a89382SEsther Brunner/**
3603d1f9ec3SMichael Klier * Purges the non-persistant part of the meta data
3613d1f9ec3SMichael Klier * used on page deletion
3623d1f9ec3SMichael Klier *
3633d1f9ec3SMichael Klier * @author Michael Klier <chi@chimeric.de>
3643d1f9ec3SMichael Klier */
3653d1f9ec3SMichael Klierfunction p_purge_metadata($id) {
3663d1f9ec3SMichael Klier    $meta = p_read_metadata($id);
3673d1f9ec3SMichael Klier    foreach($meta['current'] as $key => $value) {
3683d1f9ec3SMichael Klier        if(is_array($meta[$key])) {
3693d1f9ec3SMichael Klier            $meta['current'][$key] = array();
3703d1f9ec3SMichael Klier        } else {
3713d1f9ec3SMichael Klier            $meta['current'][$key] = '';
3723d1f9ec3SMichael Klier        }
3731172f8dcSAdrian Lang
3743d1f9ec3SMichael Klier    }
3751172f8dcSAdrian Lang    return p_save_metadata($id, $meta);
3763d1f9ec3SMichael Klier}
3773d1f9ec3SMichael Klier
3783d1f9ec3SMichael Klier/**
3790a7e3bceSchris * read the metadata from source/cache for $id
3800a7e3bceSchris * (internal use only - called by p_get_metadata & p_set_metadata)
3810a7e3bceSchris *
3820a7e3bceSchris * @author   Christopher Smith <chris@jalakai.co.uk>
3830a7e3bceSchris *
3840a7e3bceSchris * @param    string   $id      absolute wiki page id
3850a7e3bceSchris * @param    bool     $cache   whether or not to cache metadata in memory
3860a7e3bceSchris *                             (only use for metadata likely to be accessed several times)
3870a7e3bceSchris *
3880a7e3bceSchris * @return   array             metadata
3890a7e3bceSchris */
3900a7e3bceSchrisfunction p_read_metadata($id,$cache=false) {
3910a7e3bceSchris    global $cache_metadata;
3920a7e3bceSchris
3933a50618cSgweissbach    if (isset($cache_metadata[(string)$id])) return $cache_metadata[(string)$id];
3940a7e3bceSchris
3950a7e3bceSchris    $file = metaFN($id, '.meta');
3960a7e3bceSchris    $meta = @file_exists($file) ? unserialize(io_readFile($file, false)) : array('current'=>array(),'persistent'=>array());
3970a7e3bceSchris
3980a7e3bceSchris    if ($cache) {
3993a50618cSgweissbach        $cache_metadata[(string)$id] = $meta;
4000a7e3bceSchris    }
4010a7e3bceSchris
4020a7e3bceSchris    return $meta;
4030a7e3bceSchris}
4040a7e3bceSchris
4050a7e3bceSchris/**
4061172f8dcSAdrian Lang * This is the backend function to save a metadata array to a file
4071172f8dcSAdrian Lang *
4081172f8dcSAdrian Lang * @param    string   $id      absolute wiki page id
4091172f8dcSAdrian Lang * @param    array    $meta    metadata
4101172f8dcSAdrian Lang *
4111172f8dcSAdrian Lang * @return   bool              success / fail
4121172f8dcSAdrian Lang */
4131172f8dcSAdrian Langfunction p_save_metadata($id, $meta) {
4141172f8dcSAdrian Lang    // sync cached copies, including $INFO metadata
4151172f8dcSAdrian Lang    global $cache_metadata, $INFO;
4161172f8dcSAdrian Lang
4171172f8dcSAdrian Lang    if (isset($cache_metadata[$id])) $cache_metadata[$id] = $meta;
4181172f8dcSAdrian Lang    if (!empty($INFO) && ($id == $INFO['id'])) { $INFO['meta'] = $meta['current']; }
4191172f8dcSAdrian Lang
4201172f8dcSAdrian Lang    return io_saveFile(metaFN($id, '.meta'), serialize($meta));
4211172f8dcSAdrian Lang}
4221172f8dcSAdrian Lang
4231172f8dcSAdrian Lang/**
42439a89382SEsther Brunner * renders the metadata of a page
42539a89382SEsther Brunner *
42639a89382SEsther Brunner * @author Esther Brunner <esther@kaffeehaus.ch>
42739a89382SEsther Brunner */
42839a89382SEsther Brunnerfunction p_render_metadata($id, $orig){
42948924015SAndreas Gohr    // make sure the correct ID is in global ID
4300e5fde48SMichael Hamann    global $ID, $METADATA_RENDERERS;
4310e5fde48SMichael Hamann
4320e5fde48SMichael Hamann    // avoid recursive rendering processes for the same id
4330e5fde48SMichael Hamann    if (isset($METADATA_RENDERERS[$id]))
4340e5fde48SMichael Hamann        return $orig;
4350e5fde48SMichael Hamann
4360e5fde48SMichael Hamann    // store the original metadata in the global $METADATA_RENDERERS so p_set_metadata can use it
4370e5fde48SMichael Hamann    $METADATA_RENDERERS[$id] =& $orig;
4380e5fde48SMichael Hamann
43948924015SAndreas Gohr    $keep = $ID;
44048924015SAndreas Gohr    $ID   = $id;
44148924015SAndreas Gohr
4420a7e3bceSchris    // add an extra key for the event - to tell event handlers the page whose metadata this is
4430a7e3bceSchris    $orig['page'] = $id;
4440a7e3bceSchris    $evt = new Doku_Event('PARSER_METADATA_RENDER', $orig);
4450a7e3bceSchris    if ($evt->advise_before()) {
4460a7e3bceSchris
44739a89382SEsther Brunner        require_once DOKU_INC."inc/parser/metadata.php";
44839a89382SEsther Brunner
44939a89382SEsther Brunner        // get instructions
4504b5f4f4eSchris        $instructions = p_cached_instructions(wikiFN($id),false,$id);
45148924015SAndreas Gohr        if(is_null($instructions)){
45248924015SAndreas Gohr            $ID = $keep;
4530e5fde48SMichael Hamann            unset($METADATA_RENDERERS[$id]);
45448924015SAndreas Gohr            return null; // something went wrong with the instructions
45548924015SAndreas Gohr        }
45639a89382SEsther Brunner
45739a89382SEsther Brunner        // set up the renderer
45867f9913dSAndreas Gohr        $renderer = new Doku_Renderer_metadata();
4590e5fde48SMichael Hamann        $renderer->meta =& $orig['current'];
4600e5fde48SMichael Hamann        $renderer->persistent =& $orig['persistent'];
46139a89382SEsther Brunner
46239a89382SEsther Brunner        // loop through the instructions
46339a89382SEsther Brunner        foreach ($instructions as $instruction){
46439a89382SEsther Brunner            // execute the callback against the renderer
4653b748871SAndreas Gohr            call_user_func_array(array(&$renderer, $instruction[0]), (array) $instruction[1]);
46639a89382SEsther Brunner        }
46739a89382SEsther Brunner
4680e5fde48SMichael Hamann        $evt->result = array('current'=>&$renderer->meta,'persistent'=>&$renderer->persistent);
4690a7e3bceSchris    }
4700a7e3bceSchris    $evt->advise_after();
4710a7e3bceSchris
4720e5fde48SMichael Hamann    // clean up
47348924015SAndreas Gohr    $ID = $keep;
4740e5fde48SMichael Hamann    unset($METADATA_RENDERERS[$id]);
4750a7e3bceSchris    return $evt->result;
47639a89382SEsther Brunner}
47739a89382SEsther Brunner
47839a89382SEsther Brunner/**
479107b01d6Sandi * returns all available parser syntax modes in correct order
480107b01d6Sandi *
481107b01d6Sandi * @author Andreas Gohr <andi@splitbrain.org>
482107b01d6Sandi */
483107b01d6Sandifunction p_get_parsermodes(){
484107b01d6Sandi    global $conf;
485107b01d6Sandi
486107b01d6Sandi    //reuse old data
487107b01d6Sandi    static $modes = null;
4880d24b616SMichael Hamann    if($modes != null && !defined('DOKU_UNITTEST')){
489107b01d6Sandi        return $modes;
490107b01d6Sandi    }
491107b01d6Sandi
492107b01d6Sandi    //import parser classes and mode definitions
493107b01d6Sandi    require_once DOKU_INC . 'inc/parser/parser.php';
494107b01d6Sandi
495107b01d6Sandi    // we now collect all syntax modes and their objects, then they will
496107b01d6Sandi    // be sorted and added to the parser in correct order
497107b01d6Sandi    $modes = array();
498107b01d6Sandi
499107b01d6Sandi    // add syntax plugins
500107b01d6Sandi    $pluginlist = plugin_list('syntax');
501107b01d6Sandi    if(count($pluginlist)){
502107b01d6Sandi        global $PARSER_MODES;
503107b01d6Sandi        $obj = null;
504107b01d6Sandi        foreach($pluginlist as $p){
505e3ab6fc5SMichael Hamann            /** @var DokuWiki_Syntax_Plugin $obj */
506e8b5a4f9SAndreas Gohr            if(!$obj = plugin_load('syntax',$p)) continue; //attempt to load plugin into $obj
507107b01d6Sandi            $PARSER_MODES[$obj->getType()][] = "plugin_$p"; //register mode type
508107b01d6Sandi            //add to modes
509107b01d6Sandi            $modes[] = array(
510107b01d6Sandi                    'sort' => $obj->getSort(),
511107b01d6Sandi                    'mode' => "plugin_$p",
512107b01d6Sandi                    'obj'  => $obj,
513107b01d6Sandi                    );
514a46d0d65SAndreas Gohr            unset($obj); //remove the reference
515107b01d6Sandi        }
516107b01d6Sandi    }
517107b01d6Sandi
518107b01d6Sandi    // add default modes
519107b01d6Sandi    $std_modes = array('listblock','preformatted','notoc','nocache',
520107b01d6Sandi            'header','table','linebreak','footnote','hr',
521107b01d6Sandi            'unformatted','php','html','code','file','quote',
522e77ea1bcSAndreas Gohr            'internallink','rss','media','externallink',
523e77ea1bcSAndreas Gohr            'emaillink','windowssharelink','eol');
524e77ea1bcSAndreas Gohr    if($conf['typography']){
525e77ea1bcSAndreas Gohr        $std_modes[] = 'quotes';
526e77ea1bcSAndreas Gohr        $std_modes[] = 'multiplyentity';
527e77ea1bcSAndreas Gohr    }
528107b01d6Sandi    foreach($std_modes as $m){
529107b01d6Sandi        $class = "Doku_Parser_Mode_$m";
530107b01d6Sandi        $obj   = new $class();
531107b01d6Sandi        $modes[] = array(
532107b01d6Sandi                'sort' => $obj->getSort(),
533107b01d6Sandi                'mode' => $m,
534107b01d6Sandi                'obj'  => $obj
535107b01d6Sandi                );
536107b01d6Sandi    }
537107b01d6Sandi
538107b01d6Sandi    // add formatting modes
539107b01d6Sandi    $fmt_modes = array('strong','emphasis','underline','monospace',
540107b01d6Sandi            'subscript','superscript','deleted');
541107b01d6Sandi    foreach($fmt_modes as $m){
542107b01d6Sandi        $obj   = new Doku_Parser_Mode_formatting($m);
543107b01d6Sandi        $modes[] = array(
544107b01d6Sandi                'sort' => $obj->getSort(),
545107b01d6Sandi                'mode' => $m,
546107b01d6Sandi                'obj'  => $obj
547107b01d6Sandi                );
548107b01d6Sandi    }
549107b01d6Sandi
550107b01d6Sandi    // add modes which need files
551107b01d6Sandi    $obj     = new Doku_Parser_Mode_smiley(array_keys(getSmileys()));
552107b01d6Sandi    $modes[] = array('sort' => $obj->getSort(), 'mode' => 'smiley','obj'  => $obj );
553107b01d6Sandi    $obj     = new Doku_Parser_Mode_acronym(array_keys(getAcronyms()));
554107b01d6Sandi    $modes[] = array('sort' => $obj->getSort(), 'mode' => 'acronym','obj'  => $obj );
555107b01d6Sandi    $obj     = new Doku_Parser_Mode_entity(array_keys(getEntities()));
556107b01d6Sandi    $modes[] = array('sort' => $obj->getSort(), 'mode' => 'entity','obj'  => $obj );
557107b01d6Sandi
558107b01d6Sandi    // add optional camelcase mode
559107b01d6Sandi    if($conf['camelcase']){
560107b01d6Sandi        $obj     = new Doku_Parser_Mode_camelcaselink();
561107b01d6Sandi        $modes[] = array('sort' => $obj->getSort(), 'mode' => 'camelcaselink','obj'  => $obj );
562107b01d6Sandi    }
563107b01d6Sandi
564107b01d6Sandi    //sort modes
565107b01d6Sandi    usort($modes,'p_sort_modes');
566107b01d6Sandi
567107b01d6Sandi    return $modes;
568107b01d6Sandi}
569107b01d6Sandi
570107b01d6Sandi/**
571107b01d6Sandi * Callback function for usort
572107b01d6Sandi *
573107b01d6Sandi * @author Andreas Gohr <andi@splitbrain.org>
574107b01d6Sandi */
575107b01d6Sandifunction p_sort_modes($a, $b){
576107b01d6Sandi    if($a['sort'] == $b['sort']) return 0;
577107b01d6Sandi    return ($a['sort'] < $b['sort']) ? -1 : 1;
578107b01d6Sandi}
579107b01d6Sandi
580107b01d6Sandi/**
581ac83b9d8Sandi * Renders a list of instruction to the specified output mode
582c112d578Sandi *
5837a8cc57eSElan Ruusamäe * In the $info array is information from the renderer returned
5849dc2c2afSandi *
585c112d578Sandi * @author Harry Fuecks <hfuecks@gmail.com>
586c112d578Sandi * @author Andreas Gohr <andi@splitbrain.org>
587c112d578Sandi */
5889dc2c2afSandifunction p_render($mode,$instructions,&$info){
589c112d578Sandi    if(is_null($instructions)) return '';
590c112d578Sandi
591d968d3e5SChris Smith    $Renderer =& p_get_renderer($mode);
592d968d3e5SChris Smith    if (is_null($Renderer)) return null;
593c327d6c4SAndreas Gohr
594d968d3e5SChris Smith    $Renderer->reset();
595c112d578Sandi
596c112d578Sandi    $Renderer->smileys = getSmileys();
597c112d578Sandi    $Renderer->entities = getEntities();
598c112d578Sandi    $Renderer->acronyms = getAcronyms();
599c112d578Sandi    $Renderer->interwiki = getInterwiki();
600c112d578Sandi
601c112d578Sandi    // Loop through the instructions
602c112d578Sandi    foreach ( $instructions as $instruction ) {
603c112d578Sandi        // Execute the callback against the Renderer
6047c62086bSAndreas Gohr        if(method_exists($Renderer, $instruction[0])){
6056340dabcSAndreas Gohr            call_user_func_array(array(&$Renderer, $instruction[0]), $instruction[1] ? $instruction[1] : array());
606c112d578Sandi        }
6077c62086bSAndreas Gohr    }
6089dc2c2afSandi
6099dc2c2afSandi    //set info array
6109dc2c2afSandi    $info = $Renderer->info;
6119dc2c2afSandi
612677844afSchris    // Post process and return the output
613677844afSchris    $data = array($mode,& $Renderer->doc);
614677844afSchris    trigger_event('RENDERER_CONTENT_POSTPROCESS',$data);
615c112d578Sandi    return $Renderer->doc;
616c112d578Sandi}
617c112d578Sandi
618e3ab6fc5SMichael Hamann/**
619e3ab6fc5SMichael Hamann * @param $mode string Mode of the renderer to get
620e3ab6fc5SMichael Hamann * @return null|Doku_Renderer The renderer
621e3ab6fc5SMichael Hamann */
622d968d3e5SChris Smithfunction & p_get_renderer($mode) {
623e3ab6fc5SMichael Hamann    /** @var Doku_Plugin_Controller $plugin_controller */
6247aea91afSChris Smith    global $conf, $plugin_controller;
625d968d3e5SChris Smith
626d968d3e5SChris Smith    $rname = !empty($conf['renderer_'.$mode]) ? $conf['renderer_'.$mode] : $mode;
6270cacf91fSLucas    $rclass = "Doku_Renderer_$rname";
6280cacf91fSLucas
6290cacf91fSLucas    if( class_exists($rclass) ) {
6305e40b274SChristopher Smith        $Renderer = new $rclass();
6315e40b274SChristopher Smith        return $Renderer;
6320cacf91fSLucas    }
633d968d3e5SChris Smith
634d968d3e5SChris Smith    // try default renderer first:
635d968d3e5SChris Smith    $file = DOKU_INC."inc/parser/$rname.php";
636d968d3e5SChris Smith    if(@file_exists($file)){
637d968d3e5SChris Smith        require_once $file;
638d968d3e5SChris Smith
639d968d3e5SChris Smith        if ( !class_exists($rclass) ) {
640d968d3e5SChris Smith            trigger_error("Unable to resolve render class $rclass",E_USER_WARNING);
641d968d3e5SChris Smith            msg("Renderer '$rname' for $mode not valid",-1);
642d968d3e5SChris Smith            return null;
643d968d3e5SChris Smith        }
64467f9913dSAndreas Gohr        $Renderer = new $rclass();
645d968d3e5SChris Smith    }else{
6467b27382cSGina Haeussge        // Maybe a plugin/component is available?
647f19d1038SGerrit Uitslag        $Renderer = $plugin_controller->load('renderer',$rname);
6487aea91afSChris Smith
6490a6ae52fSMichael Hamann        if(!isset($Renderer) || is_null($Renderer)){
650d968d3e5SChris Smith            msg("No renderer '$rname' found for mode '$mode'",-1);
651d968d3e5SChris Smith            return null;
652d968d3e5SChris Smith        }
653d968d3e5SChris Smith    }
654d968d3e5SChris Smith
655d968d3e5SChris Smith    return $Renderer;
656d968d3e5SChris Smith}
657d968d3e5SChris Smith
658bb0a59d4Sjan/**
659bb0a59d4Sjan * Gets the first heading from a file
660bb0a59d4Sjan *
661fc18c0fbSchris * @param   string   $id       dokuwiki page id
66267c15eceSMichael Hamann * @param   int      $render   rerender if first heading not known
66367c15eceSMichael Hamann *                             default: METADATA_RENDER_USING_SIMPLE_CACHE
66467c15eceSMichael Hamann *                             Possible values: METADATA_DONT_RENDER,
66567c15eceSMichael Hamann *                                              METADATA_RENDER_USING_SIMPLE_CACHE,
66665aa8490SMichael Hamann *                                              METADATA_RENDER_USING_CACHE,
66765aa8490SMichael Hamann *                                              METADATA_RENDER_UNLIMITED
668fc18c0fbSchris *
669e3ab6fc5SMichael Hamann * @return string|null The first heading
67095dbfe57SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
671bf0c93c2SMichael Hamann * @author Michael Hamann <michael@content-space.de>
672bb0a59d4Sjan */
67367c15eceSMichael Hamannfunction p_get_first_heading($id, $render=METADATA_RENDER_USING_SIMPLE_CACHE){
67465aa8490SMichael Hamann    return p_get_metadata(cleanID($id),'title',$render);
675bb0a59d4Sjan}
676bb0a59d4Sjan
6778f7d700cSchris/**
6788f7d700cSchris * Wrapper for GeSHi Code Highlighter, provides caching of its output
6798f7d700cSchris *
6805d568b99SChris Smith * @param  string   $code       source code to be highlighted
6815d568b99SChris Smith * @param  string   $language   language to provide highlighting
6825d568b99SChris Smith * @param  string   $wrapper    html element to wrap the returned highlighted text
6835d568b99SChris Smith *
684e3ab6fc5SMichael Hamann * @return string xhtml code
6858f7d700cSchris * @author Christopher Smith <chris@jalakai.co.uk>
68635fbe9efSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
6878f7d700cSchris */
6885d568b99SChris Smithfunction p_xhtml_cached_geshi($code, $language, $wrapper='pre') {
689ff1769deSAndreas Gohr    global $conf, $config_cascade, $INPUT;
69035fbe9efSAndreas Gohr    $language = strtolower($language);
6915d568b99SChris Smith
6925d568b99SChris Smith    // remove any leading or trailing blank lines
6935d568b99SChris Smith    $code = preg_replace('/^\s*?\n|\s*?\n$/','',$code);
6945d568b99SChris Smith
6958f7d700cSchris    $cache = getCacheName($language.$code,".code");
69635fbe9efSAndreas Gohr    $ctime = @filemtime($cache);
697ff1769deSAndreas Gohr    if($ctime && !$INPUT->bool('purge') &&
698f8121585SChris Smith            $ctime > filemtime(DOKU_INC.'inc/geshi.php') &&                 // geshi changed
699f8121585SChris Smith            $ctime > @filemtime(DOKU_INC.'inc/geshi/'.$language.'.php') &&  // language syntax definition changed
700f8121585SChris Smith            $ctime > filemtime(reset($config_cascade['main']['default']))){ // dokuwiki changed
7018f7d700cSchris        $highlighted_code = io_readFile($cache, false);
7028f7d700cSchris
7038f7d700cSchris    } else {
7048f7d700cSchris
70535fbe9efSAndreas Gohr        $geshi = new GeSHi($code, $language, DOKU_INC . 'inc/geshi');
7068f7d700cSchris        $geshi->set_encoding('utf-8');
7078f7d700cSchris        $geshi->enable_classes();
7088f7d700cSchris        $geshi->set_header_type(GESHI_HEADER_PRE);
7098f7d700cSchris        $geshi->set_link_target($conf['target']['extern']);
7108f7d700cSchris
7115d568b99SChris Smith        // remove GeSHi's wrapper element (we'll replace it with our own later)
7125d568b99SChris Smith        // we need to use a GeSHi wrapper to avoid <BR> throughout the highlighted text
71369ddc332SAnika Henke        $highlighted_code = trim(preg_replace('!^<pre[^>]*>|</pre>$!','',$geshi->parse_code()),"\n\r");
7148f7d700cSchris        io_saveFile($cache,$highlighted_code);
7158f7d700cSchris    }
7168f7d700cSchris
7175d568b99SChris Smith    // add a wrapper element if required
7185d568b99SChris Smith    if ($wrapper) {
7195d568b99SChris Smith        return "<$wrapper class=\"code $language\">$highlighted_code</$wrapper>";
7205d568b99SChris Smith    } else {
7218f7d700cSchris        return $highlighted_code;
7228f7d700cSchris    }
7235d568b99SChris Smith}
7248f7d700cSchris
725