xref: /dokuwiki/inc/parserutils.php (revision 73022918a947abda7eee4d7d2302ffd28fdb78e0)
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 */
924870174SAndreas Gohruse dokuwiki\Extension\PluginInterface;
100db5771eSMichael Großeuse dokuwiki\Cache\CacheInstructions;
110db5771eSMichael Großeuse dokuwiki\Cache\CacheRenderer;
12e1d9dcc8SAndreas Gohruse dokuwiki\ChangeLog\PageChangeLog;
133a7140a1SAndreas Gohruse dokuwiki\Extension\PluginController;
14e1d9dcc8SAndreas Gohruse dokuwiki\Extension\Event;
1578b498a7SAndreas Gohruse dokuwiki\Extension\SyntaxPlugin;
16d4d8fb18SAndreas Gohruse dokuwiki\Parsing\Parser;
1778b498a7SAndreas Gohruse dokuwiki\Parsing\ParserMode\Acronym;
1878b498a7SAndreas Gohruse dokuwiki\Parsing\ParserMode\Camelcaselink;
1978b498a7SAndreas Gohruse dokuwiki\Parsing\ParserMode\Entity;
2078b498a7SAndreas Gohruse dokuwiki\Parsing\ParserMode\Formatting;
2178b498a7SAndreas Gohruse dokuwiki\Parsing\ParserMode\Smiley;
22d4d8fb18SAndreas Gohr
23c112d578Sandi/**
2465aa8490SMichael Hamann * How many pages shall be rendered for getting metadata during one request
2565aa8490SMichael Hamann * at maximum? Note that this limit isn't respected when METADATA_RENDER_UNLIMITED
2665aa8490SMichael Hamann * is passed as render parameter to p_get_metadata.
27ff725173SMichael Hamann */
2865aa8490SMichael Hamannif (!defined('P_GET_METADATA_RENDER_LIMIT')) define('P_GET_METADATA_RENDER_LIMIT', 5);
2967c15eceSMichael Hamann
3067c15eceSMichael Hamann/** Don't render metadata even if it is outdated or doesn't exist */
3167c15eceSMichael Hamanndefine('METADATA_DONT_RENDER', 0);
3265aa8490SMichael Hamann/**
3365aa8490SMichael Hamann * Render metadata when the page is really newer or the metadata doesn't exist.
3465aa8490SMichael Hamann * Uses just a simple check, but should work pretty well for loading simple
3565aa8490SMichael Hamann * metadata values like the page title and avoids rendering a lot of pages in
3665aa8490SMichael Hamann * one request. The P_GET_METADATA_RENDER_LIMIT is used in this mode.
3765aa8490SMichael Hamann * Use this if it is unlikely that the metadata value you are requesting
3865aa8490SMichael Hamann * does depend e.g. on pages that are included in the current page using
3965aa8490SMichael Hamann * the include plugin (this is very likely the case for the page title, but
4065aa8490SMichael Hamann * not for relation references).
4165aa8490SMichael Hamann */
4267c15eceSMichael Hamanndefine('METADATA_RENDER_USING_SIMPLE_CACHE', 1);
4365aa8490SMichael Hamann/**
4465aa8490SMichael Hamann * Render metadata using the metadata cache logic. The P_GET_METADATA_RENDER_LIMIT
4565aa8490SMichael Hamann * is used in this mode. Use this mode when you are requesting more complex
4665aa8490SMichael Hamann * metadata. Although this will cause rendering more often it might actually have
4765aa8490SMichael Hamann * the effect that less current metadata is returned as it is more likely than in
4865aa8490SMichael Hamann * the simple cache mode that metadata needs to be rendered for all pages at once
4965aa8490SMichael Hamann * which means that when the metadata for the page is requested that actually needs
5065aa8490SMichael Hamann * to be updated the limit might have been reached already.
5165aa8490SMichael Hamann */
5267c15eceSMichael Hamanndefine('METADATA_RENDER_USING_CACHE', 2);
5365aa8490SMichael Hamann/**
5465aa8490SMichael Hamann * Render metadata without limiting the number of pages for which metadata is
5565aa8490SMichael Hamann * rendered. Use this mode with care, normally it should only be used in places
5665aa8490SMichael Hamann * like the indexer or in cli scripts where the execution time normally isn't
5765aa8490SMichael Hamann * limited. This can be combined with the simple cache using
5865aa8490SMichael Hamann * METADATA_RENDER_USING_CACHE | METADATA_RENDER_UNLIMITED.
5965aa8490SMichael Hamann */
6065aa8490SMichael Hamanndefine('METADATA_RENDER_UNLIMITED', 4);
61ff725173SMichael Hamann
62ff725173SMichael Hamann/**
63c112d578Sandi * Returns the parsed Wikitext in XHTML for the given id and revision.
64c112d578Sandi *
65c112d578Sandi * If $excuse is true an explanation is returned if the file
66c112d578Sandi * wasn't found
67c112d578Sandi *
6842ea7f44SGerrit Uitslag * @param string $id page id
6942ea7f44SGerrit Uitslag * @param string|int $rev revision timestamp or empty string
7042ea7f44SGerrit Uitslag * @param bool $excuse
71f50a239bSTakamura * @param string $date_at
72f50a239bSTakamura *
7342ea7f44SGerrit Uitslag * @return null|string
7478b498a7SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
7578b498a7SAndreas Gohr *
76c112d578Sandi */
7778b498a7SAndreas Gohrfunction p_wiki_xhtml($id, $rev = '', $excuse = true, $date_at = '')
7878b498a7SAndreas Gohr{
79c112d578Sandi    $file = wikiFN($id, $rev);
80c112d578Sandi    $ret = '';
81c112d578Sandi
82c112d578Sandi    //ensure $id is in global $ID (needed for parsing)
831e76272cSandi    global $ID;
843ff8773bSAndreas Gohr    $keep = $ID;
851e76272cSandi    $ID = $id;
86c112d578Sandi
875c2eed9aSlisps    if ($rev || $date_at) {
8879e79377SAndreas Gohr        if (file_exists($file)) {
8964159a61SAndreas Gohr            //no caching on old revisions
9064159a61SAndreas Gohr            $ret = p_render('xhtml', p_get_instructions(io_readWikiPage($file, $id, $rev)), $info, $date_at);
91c112d578Sandi        } elseif ($excuse) {
92c112d578Sandi            $ret = p_locale_xhtml('norev');
93c112d578Sandi        }
9424870174SAndreas Gohr    } elseif (file_exists($file)) {
954b5f4f4eSchris        $ret = p_cached_output($file, 'xhtml', $id);
96c112d578Sandi    } elseif ($excuse) {
972eaa0567Speterfromearth        //check if the page once existed
98e1d9dcc8SAndreas Gohr        $changelog = new PageChangeLog($id);
992eaa0567Speterfromearth        if ($changelog->hasRevisions()) {
1002eaa0567Speterfromearth            $ret = p_locale_xhtml('onceexisted');
1012eaa0567Speterfromearth        } else {
102c112d578Sandi            $ret = p_locale_xhtml('newpage');
103c112d578Sandi        }
104c112d578Sandi    }
105c112d578Sandi
1063ff8773bSAndreas Gohr    //restore ID (just in case)
1073ff8773bSAndreas Gohr    $ID = $keep;
1083ff8773bSAndreas Gohr
109c112d578Sandi    return $ret;
110c112d578Sandi}
111c112d578Sandi
112c112d578Sandi/**
113c112d578Sandi * Returns the specified local text in parsed format
114c112d578Sandi *
11542ea7f44SGerrit Uitslag * @param string $id page id
11642ea7f44SGerrit Uitslag * @return null|string
11778b498a7SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
11878b498a7SAndreas Gohr *
119c112d578Sandi */
12078b498a7SAndreas Gohrfunction p_locale_xhtml($id)
12178b498a7SAndreas Gohr{
122c112d578Sandi    //fetch parsed locale
12365f6b58fSAnna Dabrowska    $data = ['id' => $id, 'html' => ''];
12465f6b58fSAnna Dabrowska
12565f6b58fSAnna Dabrowska    $event = new Event('PARSER_LOCALE_XHTML', $data);
12665f6b58fSAnna Dabrowska    if ($event->advise_before()) {
12765f6b58fSAnna Dabrowska        $data['html'] = p_cached_output(localeFN($data['id']));
12865f6b58fSAnna Dabrowska    }
12965f6b58fSAnna Dabrowska    $event->advise_after();
13065f6b58fSAnna Dabrowska
13165f6b58fSAnna Dabrowska    return $data['html'];
132c112d578Sandi}
133c112d578Sandi
134c112d578Sandi/**
1354b5f4f4eSchris * Returns the given file parsed into the requested output format
1364b5f4f4eSchris *
13742ea7f44SGerrit Uitslag * @param string $file filename, path to file
13842ea7f44SGerrit Uitslag * @param string $format
13942ea7f44SGerrit Uitslag * @param string $id page id
14042ea7f44SGerrit Uitslag * @return null|string
14178b498a7SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
14278b498a7SAndreas Gohr * @author Chris Smith <chris@jalakai.co.uk>
14378b498a7SAndreas Gohr *
1444b5f4f4eSchris */
14578b498a7SAndreas Gohrfunction p_cached_output($file, $format = 'xhtml', $id = '')
14678b498a7SAndreas Gohr{
147c112d578Sandi    global $conf;
148c112d578Sandi
1490db5771eSMichael Große    $cache = new CacheRenderer($id, $file, $format);
1504b5f4f4eSchris    if ($cache->useCache()) {
15185767031SAndreas Gohr        $parsed = $cache->retrieveCache(false);
1527de86af9SGerrit Uitslag        if ($conf['allowdebug'] && $format == 'xhtml') {
1537de86af9SGerrit Uitslag            $parsed .= "\n<!-- cachefile {$cache->cache} used -->\n";
1547de86af9SGerrit Uitslag        }
155c112d578Sandi    } else {
1564b5f4f4eSchris        $parsed = p_render($format, p_cached_instructions($file, false, $id), $info);
157c112d578Sandi
158abca2f79SEduardo Mozart de Oliveira        if (!empty($info['cache']) && $cache->storeCache($parsed)) { // storeCache() attempts to save cachefile
1597de86af9SGerrit Uitslag            if ($conf['allowdebug'] && $format == 'xhtml') {
1607de86af9SGerrit Uitslag                $parsed .= "\n<!-- no cachefile used, but created {$cache->cache} -->\n";
1617de86af9SGerrit Uitslag            }
162c112d578Sandi        } else {
1634b5f4f4eSchris            $cache->removeCache(); //try to delete cachefile
1647de86af9SGerrit Uitslag            if ($conf['allowdebug'] && $format == 'xhtml') {
1657de86af9SGerrit Uitslag                $parsed .= "\n<!-- no cachefile used, caching forbidden -->\n";
1667de86af9SGerrit Uitslag            }
167c112d578Sandi        }
168c112d578Sandi    }
169c112d578Sandi
170c112d578Sandi    return $parsed;
171c112d578Sandi}
172c112d578Sandi
173c112d578Sandi/**
174c112d578Sandi * Returns the render instructions for a file
175c112d578Sandi *
176c112d578Sandi * Uses and creates a serialized cache file
177c112d578Sandi *
17842ea7f44SGerrit Uitslag * @param string $file filename, path to file
17942ea7f44SGerrit Uitslag * @param bool $cacheonly
18042ea7f44SGerrit Uitslag * @param string $id page id
18142ea7f44SGerrit Uitslag * @return array|null
18278b498a7SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
18378b498a7SAndreas Gohr *
184c112d578Sandi */
18578b498a7SAndreas Gohrfunction p_cached_instructions($file, $cacheonly = false, $id = '')
18678b498a7SAndreas Gohr{
18747b2d319SAndreas Gohr    static $run = null;
18878b498a7SAndreas Gohr    if (is_null($run)) $run = [];
189c112d578Sandi
1900db5771eSMichael Große    $cache = new CacheInstructions($id, $file);
191c112d578Sandi
1920d24b616SMichael Hamann    if ($cacheonly || $cache->useCache() || (isset($run[$file]) && !defined('DOKU_UNITTEST'))) {
1934b5f4f4eSchris        return $cache->retrieveCache();
19479e79377SAndreas Gohr    } elseif (file_exists($file)) {
195c112d578Sandi        // no cache - do some work
196bde4e341SGalaxyMaster        $ins = p_get_instructions(io_readWikiPage($file, $id));
197cbaf4259SChris Smith        if ($cache->storeCache($ins)) {
19847b2d319SAndreas Gohr            $run[$file] = true; // we won't rebuild these instructions in the same run again
199cbaf4259SChris Smith        } else {
200cbaf4259SChris Smith            msg('Unable to save cache file. Hint: disk full; file permissions; safe_mode setting.', -1);
201cbaf4259SChris Smith        }
202c112d578Sandi        return $ins;
203c112d578Sandi    }
204c112d578Sandi
2053b3f8916SAndreas Gohr    return null;
206c112d578Sandi}
207c112d578Sandi
208c112d578Sandi/**
209c112d578Sandi * turns a page into a list of instructions
210c112d578Sandi *
21178b498a7SAndreas Gohr * @param string $text raw wiki syntax text
21278b498a7SAndreas Gohr * @return array a list of instruction arrays
213c112d578Sandi * @author Harry Fuecks <hfuecks@gmail.com>
214c112d578Sandi * @author Andreas Gohr <andi@splitbrain.org>
21542ea7f44SGerrit Uitslag *
216c112d578Sandi */
21778b498a7SAndreas Gohrfunction p_get_instructions($text)
21878b498a7SAndreas Gohr{
219c112d578Sandi
220107b01d6Sandi    $modes = p_get_parsermodes();
221ee20e7d1Sandi
22247f73ecfSAndreas Gohr    // Create the parser and handler
223d4d8fb18SAndreas Gohr    $Parser = new Parser(new Doku_Handler());
224c112d578Sandi
225107b01d6Sandi    //add modes to parser
226107b01d6Sandi    foreach ($modes as $mode) {
227107b01d6Sandi        $Parser->addMode($mode['mode'], $mode['obj']);
228c112d578Sandi    }
229c112d578Sandi
230c112d578Sandi    // Do the parsing
231cbb44eabSAndreas Gohr    Event::createAndTrigger('PARSER_WIKITEXT_PREPROCESS', $text);
23278b498a7SAndreas Gohr    return $Parser->parse($text);
233c112d578Sandi}
234c112d578Sandi
235c112d578Sandi/**
23639a89382SEsther Brunner * returns the metadata of a page
23739a89382SEsther Brunner *
2384a819402SMichael Hamann * @param string $id The id of the page the metadata should be returned from
23964159a61SAndreas Gohr * @param string $key The key of the metdata value that shall be read (by default everything)
24064159a61SAndreas Gohr *                        separate hierarchies by " " like "date created"
24167c15eceSMichael Hamann * @param int $render If the page should be rendererd - possible values:
24265aa8490SMichael Hamann *     METADATA_DONT_RENDER, METADATA_RENDER_USING_SIMPLE_CACHE, METADATA_RENDER_USING_CACHE
24365aa8490SMichael Hamann *     METADATA_RENDER_UNLIMITED (also combined with the previous two options),
24465aa8490SMichael Hamann *     default: METADATA_RENDER_USING_CACHE
2454a819402SMichael Hamann * @return mixed The requested metadata fields
2464a819402SMichael Hamann *
24739a89382SEsther Brunner * @author Esther Brunner <esther@kaffeehaus.ch>
24898214867SMichael Hamann * @author Michael Hamann <michael@content-space.de>
24939a89382SEsther Brunner */
25078b498a7SAndreas Gohrfunction p_get_metadata($id, $key = '', $render = METADATA_RENDER_USING_CACHE)
25178b498a7SAndreas Gohr{
2521172f8dcSAdrian Lang    global $ID;
25365aa8490SMichael Hamann    static $render_count = 0;
25465aa8490SMichael Hamann    // track pages that have already been rendered in order to avoid rendering the same page
25565aa8490SMichael Hamann    // again
25678b498a7SAndreas Gohr    static $rendered_pages = [];
2576afe8dcaSchris
2580a7e3bceSchris    // cache the current page
2590a7e3bceSchris    // Benchmarking shows the current page's metadata is generally the only page metadata
2600a7e3bceSchris    // accessed several times. This may catch a few other pages, but that shouldn't be an issue.
2610a7e3bceSchris    $cache = ($ID == $id);
2620a7e3bceSchris    $meta = p_read_metadata($id, $cache);
26339a89382SEsther Brunner
26467c15eceSMichael Hamann    if (!is_numeric($render)) {
26567c15eceSMichael Hamann        if ($render) {
26667c15eceSMichael Hamann            $render = METADATA_RENDER_USING_SIMPLE_CACHE;
26767c15eceSMichael Hamann        } else {
26867c15eceSMichael Hamann            $render = METADATA_DONT_RENDER;
26967c15eceSMichael Hamann        }
27067c15eceSMichael Hamann    }
27167c15eceSMichael Hamann
27298214867SMichael Hamann    // prevent recursive calls in the cache
27398214867SMichael Hamann    static $recursion = false;
27465aa8490SMichael Hamann    if (!$recursion && $render != METADATA_DONT_RENDER && !isset($rendered_pages[$id]) && page_exists($id)) {
27598214867SMichael Hamann        $recursion = true;
27698214867SMichael Hamann
2770db5771eSMichael Große        $cachefile = new CacheRenderer($id, wikiFN($id), 'metadata');
27898214867SMichael Hamann
27967c15eceSMichael Hamann        $do_render = false;
28065aa8490SMichael Hamann        if ($render & METADATA_RENDER_UNLIMITED || $render_count < P_GET_METADATA_RENDER_LIMIT) {
28165aa8490SMichael Hamann            if ($render & METADATA_RENDER_USING_SIMPLE_CACHE) {
28267c15eceSMichael Hamann                $pagefn = wikiFN($id);
28367c15eceSMichael Hamann                $metafn = metaFN($id, '.meta');
28479e79377SAndreas Gohr                if (!file_exists($metafn) || @filemtime($pagefn) > @filemtime($cachefile->cache)) {
28567c15eceSMichael Hamann                    $do_render = true;
28667c15eceSMichael Hamann                }
28767c15eceSMichael Hamann            } elseif (!$cachefile->useCache()) {
28867c15eceSMichael Hamann                $do_render = true;
28967c15eceSMichael Hamann            }
29065aa8490SMichael Hamann        }
29167c15eceSMichael Hamann        if ($do_render) {
2920d24b616SMichael Hamann            if (!defined('DOKU_UNITTEST')) {
29365aa8490SMichael Hamann                ++$render_count;
29465aa8490SMichael Hamann                $rendered_pages[$id] = true;
2950d24b616SMichael Hamann            }
29669ba640bSMichael Hamann            $old_meta = $meta;
29739a89382SEsther Brunner            $meta = p_render_metadata($id, $meta);
29869ba640bSMichael Hamann            // only update the file when the metadata has been changed
29969ba640bSMichael Hamann            if ($meta == $old_meta || p_save_metadata($id, $meta)) {
30098214867SMichael Hamann                // store a timestamp in order to make sure that the cachefile is touched
3013d6feb16SMichael Hamann                // this timestamp is also stored when the meta data is still the same
30298214867SMichael Hamann                $cachefile->storeCache(time());
3033d6feb16SMichael Hamann            } else {
30498214867SMichael Hamann                msg('Unable to save metadata file. Hint: disk full; file permissions; safe_mode setting.', -1);
30598214867SMichael Hamann            }
30698214867SMichael Hamann        }
30798214867SMichael Hamann
30898214867SMichael Hamann        $recursion = false;
3096afe8dcaSchris    }
31039a89382SEsther Brunner
311ebf65d37SAdrian Lang    $val = $meta['current'];
312ebf65d37SAdrian Lang
31339a89382SEsther Brunner    // filter by $key
314569a0019SAdrian Lang    foreach (preg_split('/\s+/', $key, 2, PREG_SPLIT_NO_EMPTY) as $cur_key) {
315ebf65d37SAdrian Lang        if (!isset($val[$cur_key])) {
316ebf65d37SAdrian Lang            return null;
31766d29756SChris Smith        }
318ebf65d37SAdrian Lang        $val = $val[$cur_key];
31939a89382SEsther Brunner    }
320ebf65d37SAdrian Lang    return $val;
32139a89382SEsther Brunner}
32239a89382SEsther Brunner
32339a89382SEsther Brunner/**
32439a89382SEsther Brunner * sets metadata elements of a page
32539a89382SEsther Brunner *
326a365baeeSDominik Eckelmann * @see http://www.dokuwiki.org/devel:metadata#functions_to_get_and_set_metadata
327a365baeeSDominik Eckelmann *
328e1d9dcc8SAndreas Gohr * @param string $id is the ID of a wiki page
329e1d9dcc8SAndreas Gohr * @param array $data is an array with key ⇒ value pairs to be set in the metadata
330e1d9dcc8SAndreas Gohr * @param boolean $render whether or not the page metadata should be generated with the renderer
331e1d9dcc8SAndreas Gohr * @param boolean $persistent indicates whether or not the particular metadata value will persist through
332a365baeeSDominik Eckelmann *                            the next metadata rendering.
333a365baeeSDominik Eckelmann * @return boolean true on success
334a365baeeSDominik Eckelmann *
33539a89382SEsther Brunner * @author Esther Brunner <esther@kaffeehaus.ch>
3360e5fde48SMichael Hamann * @author Michael Hamann <michael@content-space.de>
33739a89382SEsther Brunner */
33878b498a7SAndreas Gohrfunction p_set_metadata($id, $data, $render = false, $persistent = true)
33978b498a7SAndreas Gohr{
34039a89382SEsther Brunner    if (!is_array($data)) return false;
34139a89382SEsther Brunner
3420e5fde48SMichael Hamann    global $ID, $METADATA_RENDERERS;
3430a7e3bceSchris
3440e5fde48SMichael Hamann    // if there is currently a renderer change the data in the renderer instead
3450e5fde48SMichael Hamann    if (isset($METADATA_RENDERERS[$id])) {
3460e5fde48SMichael Hamann        $orig =& $METADATA_RENDERERS[$id];
3470e5fde48SMichael Hamann        $meta = $orig;
3480e5fde48SMichael Hamann    } else {
3490a7e3bceSchris        // cache the current page
3500a7e3bceSchris        $cache = ($ID == $id);
3510a7e3bceSchris        $orig = p_read_metadata($id, $cache);
35239a89382SEsther Brunner
35339a89382SEsther Brunner        // render metadata first?
3540a7e3bceSchris        $meta = $render ? p_render_metadata($id, $orig) : $orig;
3550e5fde48SMichael Hamann    }
35639a89382SEsther Brunner
35739a89382SEsther Brunner    // now add the passed metadata
35878b498a7SAndreas Gohr    $protected = ['description', 'date', 'contributor'];
35939a89382SEsther Brunner    foreach ($data as $key => $value) {
36039a89382SEsther Brunner
36139a89382SEsther Brunner        // be careful with sub-arrays of $meta['relation']
36239a89382SEsther Brunner        if ($key == 'relation') {
3630a7e3bceSchris
36439a89382SEsther Brunner            foreach ($value as $subkey => $subvalue) {
36531b10b49SMichael Hamann                if (isset($meta['current'][$key][$subkey]) && is_array($meta['current'][$key][$subkey])) {
3662d102494SPhy                    $meta['current'][$key][$subkey] = array_replace($meta['current'][$key][$subkey], (array)$subvalue);
36731b10b49SMichael Hamann                } else {
36831b10b49SMichael Hamann                    $meta['current'][$key][$subkey] = $subvalue;
36931b10b49SMichael Hamann                }
37031b10b49SMichael Hamann                if ($persistent) {
37131b10b49SMichael Hamann                    if (isset($meta['persistent'][$key][$subkey]) && is_array($meta['persistent'][$key][$subkey])) {
37264159a61SAndreas Gohr                        $meta['persistent'][$key][$subkey] = array_replace(
37364159a61SAndreas Gohr                            $meta['persistent'][$key][$subkey],
37464159a61SAndreas Gohr                            (array)$subvalue
37564159a61SAndreas Gohr                        );
37631b10b49SMichael Hamann                    } else {
37731b10b49SMichael Hamann                        $meta['persistent'][$key][$subkey] = $subvalue;
37831b10b49SMichael Hamann                    }
37931b10b49SMichael Hamann                }
38039a89382SEsther Brunner            }
38139a89382SEsther Brunner
38239a89382SEsther Brunner            // be careful with some senisitive arrays of $meta
38339a89382SEsther Brunner        } elseif (in_array($key, $protected)) {
3840a7e3bceSchris
38566d29756SChris Smith            // these keys, must have subkeys - a legitimate value must be an array
38639a89382SEsther Brunner            if (is_array($value)) {
38724870174SAndreas Gohr                $meta['current'][$key] = empty($meta['current'][$key]) ?
38824870174SAndreas Gohr                    $value :
38924870174SAndreas Gohr                    array_replace((array)$meta['current'][$key], $value);
3900a7e3bceSchris
3910a7e3bceSchris                if ($persistent) {
39224870174SAndreas Gohr                    $meta['persistent'][$key] = empty($meta['persistent'][$key]) ?
39324870174SAndreas Gohr                        $value :
39424870174SAndreas Gohr                        array_replace((array)$meta['persistent'][$key], $value);
3950a7e3bceSchris                }
39639a89382SEsther Brunner            }
39739a89382SEsther Brunner
39839a89382SEsther Brunner            // no special treatment for the rest
39939a89382SEsther Brunner        } else {
4000a7e3bceSchris            $meta['current'][$key] = $value;
4010a7e3bceSchris            if ($persistent) $meta['persistent'][$key] = $value;
40239a89382SEsther Brunner        }
40339a89382SEsther Brunner    }
40439a89382SEsther Brunner
40539a89382SEsther Brunner    // save only if metadata changed
40639a89382SEsther Brunner    if ($meta == $orig) return true;
4076afe8dcaSchris
4080e5fde48SMichael Hamann    if (isset($METADATA_RENDERERS[$id])) {
4090e5fde48SMichael Hamann        // set both keys individually as the renderer has references to the individual keys
4100e5fde48SMichael Hamann        $METADATA_RENDERERS[$id]['current'] = $meta['current'];
4110e5fde48SMichael Hamann        $METADATA_RENDERERS[$id]['persistent'] = $meta['persistent'];
4121c56be7bSMichael Hamann        return true;
4130e5fde48SMichael Hamann    } else {
4141172f8dcSAdrian Lang        return p_save_metadata($id, $meta);
41539a89382SEsther Brunner    }
4160e5fde48SMichael Hamann}
41739a89382SEsther Brunner
41839a89382SEsther Brunner/**
4193d1f9ec3SMichael Klier * Purges the non-persistant part of the meta data
4203d1f9ec3SMichael Klier * used on page deletion
4213d1f9ec3SMichael Klier *
42242ea7f44SGerrit Uitslag * @param string $id page id
42342ea7f44SGerrit Uitslag * @return bool  success / fail
42478b498a7SAndreas Gohr * @author Michael Klier <chi@chimeric.de>
42578b498a7SAndreas Gohr *
4263d1f9ec3SMichael Klier */
42778b498a7SAndreas Gohrfunction p_purge_metadata($id)
42878b498a7SAndreas Gohr{
4293d1f9ec3SMichael Klier    $meta = p_read_metadata($id);
4303d1f9ec3SMichael Klier    foreach ($meta['current'] as $key => $value) {
431056bf31fSDamien Regad        if (isset($meta[$key]) && is_array($meta[$key])) {
43278b498a7SAndreas Gohr            $meta['current'][$key] = [];
4333d1f9ec3SMichael Klier        } else {
4343d1f9ec3SMichael Klier            $meta['current'][$key] = '';
4353d1f9ec3SMichael Klier        }
4361172f8dcSAdrian Lang
4373d1f9ec3SMichael Klier    }
4381172f8dcSAdrian Lang    return p_save_metadata($id, $meta);
4393d1f9ec3SMichael Klier}
4403d1f9ec3SMichael Klier
4413d1f9ec3SMichael Klier/**
4420a7e3bceSchris * read the metadata from source/cache for $id
4430a7e3bceSchris * (internal use only - called by p_get_metadata & p_set_metadata)
4440a7e3bceSchris *
4450a7e3bceSchris * @param string $id absolute wiki page id
4460a7e3bceSchris * @param bool $cache whether or not to cache metadata in memory
4470a7e3bceSchris *                             (only use for metadata likely to be accessed several times)
4480a7e3bceSchris *
4490a7e3bceSchris * @return   array             metadata
45078b498a7SAndreas Gohr * @author   Christopher Smith <chris@jalakai.co.uk>
45178b498a7SAndreas Gohr *
4520a7e3bceSchris */
45378b498a7SAndreas Gohrfunction p_read_metadata($id, $cache = false)
45478b498a7SAndreas Gohr{
4550a7e3bceSchris    global $cache_metadata;
4560a7e3bceSchris
4573a50618cSgweissbach    if (isset($cache_metadata[(string)$id])) return $cache_metadata[(string)$id];
4580a7e3bceSchris
4590a7e3bceSchris    $file = metaFN($id, '.meta');
46064159a61SAndreas Gohr    $meta = file_exists($file) ?
46164159a61SAndreas Gohr        unserialize(io_readFile($file, false)) :
46278b498a7SAndreas Gohr        ['current' => [], 'persistent' => []];
4630a7e3bceSchris
4640a7e3bceSchris    if ($cache) {
4653a50618cSgweissbach        $cache_metadata[(string)$id] = $meta;
4660a7e3bceSchris    }
4670a7e3bceSchris
4680a7e3bceSchris    return $meta;
4690a7e3bceSchris}
4700a7e3bceSchris
4710a7e3bceSchris/**
4721172f8dcSAdrian Lang * This is the backend function to save a metadata array to a file
4731172f8dcSAdrian Lang *
4741172f8dcSAdrian Lang * @param string $id absolute wiki page id
4751172f8dcSAdrian Lang * @param array $meta metadata
4761172f8dcSAdrian Lang *
4771172f8dcSAdrian Lang * @return   bool              success / fail
4781172f8dcSAdrian Lang */
47978b498a7SAndreas Gohrfunction p_save_metadata($id, $meta)
48078b498a7SAndreas Gohr{
4811172f8dcSAdrian Lang    // sync cached copies, including $INFO metadata
4821172f8dcSAdrian Lang    global $cache_metadata, $INFO;
4831172f8dcSAdrian Lang
4841172f8dcSAdrian Lang    if (isset($cache_metadata[$id])) $cache_metadata[$id] = $meta;
485056bf31fSDamien Regad    if (!empty($INFO) && isset($INFO['id']) && ($id == $INFO['id'])) {
486056bf31fSDamien Regad        $INFO['meta'] = $meta['current'];
487056bf31fSDamien Regad    }
4881172f8dcSAdrian Lang
4891172f8dcSAdrian Lang    return io_saveFile(metaFN($id, '.meta'), serialize($meta));
4901172f8dcSAdrian Lang}
4911172f8dcSAdrian Lang
4921172f8dcSAdrian Lang/**
49339a89382SEsther Brunner * renders the metadata of a page
49439a89382SEsther Brunner *
49542ea7f44SGerrit Uitslag * @param string $id page id
49642ea7f44SGerrit Uitslag * @param array $orig the original metadata
49742ea7f44SGerrit Uitslag * @return array|null array('current'=> array,'persistent'=> array);
49878b498a7SAndreas Gohr * @author Esther Brunner <esther@kaffeehaus.ch>
49978b498a7SAndreas Gohr *
50039a89382SEsther Brunner */
50178b498a7SAndreas Gohrfunction p_render_metadata($id, $orig)
50278b498a7SAndreas Gohr{
50348924015SAndreas Gohr    // make sure the correct ID is in global ID
5040e5fde48SMichael Hamann    global $ID, $METADATA_RENDERERS;
5050e5fde48SMichael Hamann
5060e5fde48SMichael Hamann    // avoid recursive rendering processes for the same id
5075b76ad91SChristopher Smith    if (isset($METADATA_RENDERERS[$id])) {
5080e5fde48SMichael Hamann        return $orig;
5095b76ad91SChristopher Smith    }
5100e5fde48SMichael Hamann
5110e5fde48SMichael Hamann    // store the original metadata in the global $METADATA_RENDERERS so p_set_metadata can use it
5120e5fde48SMichael Hamann    $METADATA_RENDERERS[$id] =& $orig;
5130e5fde48SMichael Hamann
51448924015SAndreas Gohr    $keep = $ID;
51548924015SAndreas Gohr    $ID = $id;
51648924015SAndreas Gohr
5170a7e3bceSchris    // add an extra key for the event - to tell event handlers the page whose metadata this is
5180a7e3bceSchris    $orig['page'] = $id;
519e1d9dcc8SAndreas Gohr    $evt = new Event('PARSER_METADATA_RENDER', $orig);
5200a7e3bceSchris    if ($evt->advise_before()) {
5210a7e3bceSchris
52239a89382SEsther Brunner        // get instructions
5234b5f4f4eSchris        $instructions = p_cached_instructions(wikiFN($id), false, $id);
52448924015SAndreas Gohr        if (is_null($instructions)) {
52548924015SAndreas Gohr            $ID = $keep;
5260e5fde48SMichael Hamann            unset($METADATA_RENDERERS[$id]);
52748924015SAndreas Gohr            return null; // something went wrong with the instructions
52848924015SAndreas Gohr        }
52939a89382SEsther Brunner
53039a89382SEsther Brunner        // set up the renderer
53167f9913dSAndreas Gohr        $renderer = new Doku_Renderer_metadata();
5320e5fde48SMichael Hamann        $renderer->meta =& $orig['current'];
5330e5fde48SMichael Hamann        $renderer->persistent =& $orig['persistent'];
53439a89382SEsther Brunner
53539a89382SEsther Brunner        // loop through the instructions
53639a89382SEsther Brunner        foreach ($instructions as $instruction) {
53739a89382SEsther Brunner            // execute the callback against the renderer
53878b498a7SAndreas Gohr            call_user_func_array([&$renderer, $instruction[0]], (array)$instruction[1]);
53939a89382SEsther Brunner        }
54039a89382SEsther Brunner
54178b498a7SAndreas Gohr        $evt->result = ['current' => &$renderer->meta, 'persistent' => &$renderer->persistent];
5420a7e3bceSchris    }
5430a7e3bceSchris    $evt->advise_after();
5440a7e3bceSchris
5450e5fde48SMichael Hamann    // clean up
54648924015SAndreas Gohr    $ID = $keep;
5470e5fde48SMichael Hamann    unset($METADATA_RENDERERS[$id]);
5480a7e3bceSchris    return $evt->result;
54939a89382SEsther Brunner}
55039a89382SEsther Brunner
55139a89382SEsther Brunner/**
552107b01d6Sandi * returns all available parser syntax modes in correct order
553107b01d6Sandi *
55478b498a7SAndreas Gohr * @return array[] with for each plugin the array('sort' => sortnumber, 'mode' => mode string, 'obj'  => plugin object)
555107b01d6Sandi * @author Andreas Gohr <andi@splitbrain.org>
55642ea7f44SGerrit Uitslag *
557107b01d6Sandi */
55878b498a7SAndreas Gohrfunction p_get_parsermodes()
55978b498a7SAndreas Gohr{
560107b01d6Sandi    global $conf;
561107b01d6Sandi
562107b01d6Sandi    //reuse old data
563107b01d6Sandi    static $modes = null;
5640d24b616SMichael Hamann    if ($modes != null && !defined('DOKU_UNITTEST')) {
565107b01d6Sandi        return $modes;
566107b01d6Sandi    }
567107b01d6Sandi
568107b01d6Sandi    //import parser classes and mode definitions
569107b01d6Sandi    require_once DOKU_INC . 'inc/parser/parser.php';
570107b01d6Sandi
571107b01d6Sandi    // we now collect all syntax modes and their objects, then they will
572107b01d6Sandi    // be sorted and added to the parser in correct order
57378b498a7SAndreas Gohr    $modes = [];
574107b01d6Sandi
575107b01d6Sandi    // add syntax plugins
576107b01d6Sandi    $pluginlist = plugin_list('syntax');
57724870174SAndreas Gohr    if ($pluginlist !== []) {
578107b01d6Sandi        global $PARSER_MODES;
579107b01d6Sandi        foreach ($pluginlist as $p) {
58078b498a7SAndreas Gohr            /** @var SyntaxPlugin $obj */
58151bc2534SAndreas Gohr            if (!($obj = plugin_load('syntax', $p)) instanceof PluginInterface) continue;
582107b01d6Sandi            $PARSER_MODES[$obj->getType()][] = "plugin_$p"; //register mode type
583107b01d6Sandi            //add to modes
58478b498a7SAndreas Gohr            $modes[] = [
585107b01d6Sandi                'sort' => $obj->getSort(),
586107b01d6Sandi                'mode' => "plugin_$p",
587107b01d6Sandi                'obj' => $obj,
58878b498a7SAndreas Gohr            ];
589a46d0d65SAndreas Gohr            unset($obj); //remove the reference
590107b01d6Sandi        }
591107b01d6Sandi    }
592107b01d6Sandi
593107b01d6Sandi    // add default modes
59478b498a7SAndreas Gohr    $std_modes = [
59578b498a7SAndreas Gohr        'listblock', 'preformatted', 'notoc', 'nocache', 'header', 'table', 'linebreak', 'footnote', 'hr',
59678b498a7SAndreas Gohr        'unformatted', 'code', 'file', 'quote', 'internallink', 'rss', 'media', 'externallink',
59778b498a7SAndreas Gohr        'emaillink', 'windowssharelink', 'eol'
59878b498a7SAndreas Gohr    ];
599e77ea1bcSAndreas Gohr    if ($conf['typography']) {
600e77ea1bcSAndreas Gohr        $std_modes[] = 'quotes';
601e77ea1bcSAndreas Gohr        $std_modes[] = 'multiplyentity';
602e77ea1bcSAndreas Gohr    }
603107b01d6Sandi    foreach ($std_modes as $m) {
604be906b56SAndreas Gohr        $class = 'dokuwiki\\Parsing\\ParserMode\\' . ucfirst($m);
605107b01d6Sandi        $obj = new $class();
60624870174SAndreas Gohr        $modes[] = ['sort' => $obj->getSort(), 'mode' => $m, 'obj' => $obj];
607107b01d6Sandi    }
608107b01d6Sandi
609107b01d6Sandi    // add formatting modes
61078b498a7SAndreas Gohr    $fmt_modes = [
61178b498a7SAndreas Gohr        'strong', 'emphasis', 'underline', 'monospace', 'subscript', 'superscript', 'deleted'
61278b498a7SAndreas Gohr    ];
613107b01d6Sandi    foreach ($fmt_modes as $m) {
61478b498a7SAndreas Gohr        $obj = new Formatting($m);
61524870174SAndreas Gohr        $modes[] = [
616107b01d6Sandi            'sort' => $obj->getSort(),
617107b01d6Sandi            'mode' => $m,
618107b01d6Sandi            'obj' => $obj
61924870174SAndreas Gohr        ];
620107b01d6Sandi    }
621107b01d6Sandi
622107b01d6Sandi    // add modes which need files
62378b498a7SAndreas Gohr    $obj = new Smiley(array_keys(getSmileys()));
62478b498a7SAndreas Gohr    $modes[] = ['sort' => $obj->getSort(), 'mode' => 'smiley', 'obj' => $obj];
62578b498a7SAndreas Gohr    $obj = new Acronym(array_keys(getAcronyms()));
62678b498a7SAndreas Gohr    $modes[] = ['sort' => $obj->getSort(), 'mode' => 'acronym', 'obj' => $obj];
62778b498a7SAndreas Gohr    $obj = new Entity(array_keys(getEntities()));
62878b498a7SAndreas Gohr    $modes[] = ['sort' => $obj->getSort(), 'mode' => 'entity', 'obj' => $obj];
629107b01d6Sandi
630107b01d6Sandi    // add optional camelcase mode
631107b01d6Sandi    if ($conf['camelcase']) {
63278b498a7SAndreas Gohr        $obj = new Camelcaselink();
63378b498a7SAndreas Gohr        $modes[] = ['sort' => $obj->getSort(), 'mode' => 'camelcaselink', 'obj' => $obj];
634107b01d6Sandi    }
635107b01d6Sandi
636107b01d6Sandi    //sort modes
637107b01d6Sandi    usort($modes, 'p_sort_modes');
638107b01d6Sandi
639107b01d6Sandi    return $modes;
640107b01d6Sandi}
641107b01d6Sandi
642107b01d6Sandi/**
643107b01d6Sandi * Callback function for usort
644107b01d6Sandi *
64542ea7f44SGerrit Uitslag * @param array $a
64642ea7f44SGerrit Uitslag * @param array $b
64742ea7f44SGerrit Uitslag * @return int $a is lower/equal/higher than $b
64878b498a7SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
64978b498a7SAndreas Gohr *
650107b01d6Sandi */
65178b498a7SAndreas Gohrfunction p_sort_modes($a, $b)
65278b498a7SAndreas Gohr{
65324870174SAndreas Gohr    return $a['sort'] <=> $b['sort'];
654107b01d6Sandi}
655107b01d6Sandi
656107b01d6Sandi/**
657ac83b9d8Sandi * Renders a list of instruction to the specified output mode
658c112d578Sandi *
6597a8cc57eSElan Ruusamäe * In the $info array is information from the renderer returned
6609dc2c2afSandi *
66142ea7f44SGerrit Uitslag * @param string $mode
662e3710957SGerrit Uitslag * @param array|null|false $instructions
66342ea7f44SGerrit Uitslag * @param array $info returns render info like enabled toc and cache
6647de86af9SGerrit Uitslag * @param string $date_at
66542ea7f44SGerrit Uitslag * @return null|string rendered output
66678b498a7SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
66778b498a7SAndreas Gohr *
66878b498a7SAndreas Gohr * @author Harry Fuecks <hfuecks@gmail.com>
669c112d578Sandi */
67078b498a7SAndreas Gohrfunction p_render($mode, $instructions, &$info, $date_at = '')
67178b498a7SAndreas Gohr{
672c112d578Sandi    if (is_null($instructions)) return '';
673e3710957SGerrit Uitslag    if ($instructions === false) return '';
674c112d578Sandi
675252398f0SChristopher Smith    $Renderer = p_get_renderer($mode);
676d968d3e5SChris Smith    if (is_null($Renderer)) return null;
677c327d6c4SAndreas Gohr
678d968d3e5SChris Smith    $Renderer->reset();
679c112d578Sandi
6805c2eed9aSlisps    if ($date_at) {
6815c2eed9aSlisps        $Renderer->date_at = $date_at;
6825c2eed9aSlisps    }
6835c2eed9aSlisps
684c112d578Sandi    $Renderer->smileys = getSmileys();
685c112d578Sandi    $Renderer->entities = getEntities();
686c112d578Sandi    $Renderer->acronyms = getAcronyms();
687c112d578Sandi    $Renderer->interwiki = getInterwiki();
688c112d578Sandi
689c112d578Sandi    // Loop through the instructions
690c112d578Sandi    foreach ($instructions as $instruction) {
691c112d578Sandi        // Execute the callback against the Renderer
6927c62086bSAndreas Gohr        if (method_exists($Renderer, $instruction[0])) {
69378b498a7SAndreas Gohr            call_user_func_array([&$Renderer, $instruction[0]], $instruction[1] ?: []);
694c112d578Sandi        }
6957c62086bSAndreas Gohr    }
6969dc2c2afSandi
6979dc2c2afSandi    //set info array
6989dc2c2afSandi    $info = $Renderer->info;
6999dc2c2afSandi
700677844afSchris    // Post process and return the output
70178b498a7SAndreas Gohr    $data = [$mode, & $Renderer->doc];
702cbb44eabSAndreas Gohr    Event::createAndTrigger('RENDERER_CONTENT_POSTPROCESS', $data);
703c112d578Sandi    return $Renderer->doc;
704c112d578Sandi}
705c112d578Sandi
706e3ab6fc5SMichael Hamann/**
707548d801fSChristopher Smith * Figure out the correct renderer class to use for $mode,
708548d801fSChristopher Smith * instantiate and return it
709548d801fSChristopher Smith *
7107e8500eeSGerrit Uitslag * @param string $mode Mode of the renderer to get
711e3ab6fc5SMichael Hamann * @return null|Doku_Renderer The renderer
712548d801fSChristopher Smith *
713548d801fSChristopher Smith * @author Christopher Smith <chris@jalakai.co.uk>
714e3ab6fc5SMichael Hamann */
71578b498a7SAndreas Gohrfunction p_get_renderer($mode)
71678b498a7SAndreas Gohr{
7173a7140a1SAndreas Gohr    /** @var PluginController $plugin_controller */
7187aea91afSChris Smith    global $conf, $plugin_controller;
719d968d3e5SChris Smith
72024870174SAndreas Gohr    $rname = empty($conf['renderer_' . $mode]) ? $mode : $conf['renderer_' . $mode];
7210cacf91fSLucas    $rclass = "Doku_Renderer_$rname";
7220cacf91fSLucas
723548d801fSChristopher Smith    // if requested earlier or a bundled renderer
7240cacf91fSLucas    if (class_exists($rclass)) {
72578b498a7SAndreas Gohr        return new $rclass();
7260cacf91fSLucas    }
727d968d3e5SChris Smith
7286e6d16edSChristopher Smith    // not bundled, see if its an enabled renderer plugin & when $mode is 'xhtml', the renderer can supply that format.
7290440ca46SGerrit Uitslag    /** @var Doku_Renderer $Renderer */
73011ac6abdSChristopher Smith    $Renderer = $plugin_controller->load('renderer', $rname);
7316e6d16edSChristopher Smith    if ($Renderer && is_a($Renderer, 'Doku_Renderer') && ($mode != 'xhtml' || $mode == $Renderer->getFormat())) {
73211ac6abdSChristopher Smith        return $Renderer;
73311ac6abdSChristopher Smith    }
734d968d3e5SChris Smith
73511ac6abdSChristopher Smith    // there is a configuration error!
736548d801fSChristopher Smith    // not bundled, not a valid enabled plugin, use $mode to try to fallback to a bundled renderer
73711ac6abdSChristopher Smith    $rclass = "Doku_Renderer_$mode";
738548d801fSChristopher Smith    if (class_exists($rclass)) {
73911ac6abdSChristopher Smith        // viewers should see renderered output, so restrict the warning to admins only
74011ac6abdSChristopher Smith        $msg = "No renderer '$rname' found for mode '$mode', check your plugins";
74111ac6abdSChristopher Smith        if ($mode == 'xhtml') {
74211ac6abdSChristopher Smith            $msg .= " and the 'renderer_xhtml' config setting";
74311ac6abdSChristopher Smith        }
74411ac6abdSChristopher Smith        $msg .= ".<br/>Attempting to fallback to the bundled renderer.";
745548d801fSChristopher Smith        msg($msg, -1, '', '', MSG_ADMINS_ONLY);
74611ac6abdSChristopher Smith
747*73022918SAndreas Gohr        $Renderer = new $rclass();
748548d801fSChristopher Smith        $Renderer->nocache();     // fallback only (and may include admin alerts), don't cache
749d968d3e5SChris Smith        return $Renderer;
750d968d3e5SChris Smith    }
751d968d3e5SChris Smith
752548d801fSChristopher Smith    // fallback failed, alert the world
753548d801fSChristopher Smith    msg("No renderer '$rname' found for mode '$mode'", -1);
754548d801fSChristopher Smith    return null;
755548d801fSChristopher Smith}
756548d801fSChristopher Smith
757bb0a59d4Sjan/**
758bb0a59d4Sjan * Gets the first heading from a file
759bb0a59d4Sjan *
760fc18c0fbSchris * @param string $id dokuwiki page id
76167c15eceSMichael Hamann * @param int $render rerender if first heading not known
76267c15eceSMichael Hamann *                             default: METADATA_RENDER_USING_SIMPLE_CACHE
76367c15eceSMichael Hamann *                             Possible values: METADATA_DONT_RENDER,
76467c15eceSMichael Hamann *                                              METADATA_RENDER_USING_SIMPLE_CACHE,
76565aa8490SMichael Hamann *                                              METADATA_RENDER_USING_CACHE,
76665aa8490SMichael Hamann *                                              METADATA_RENDER_UNLIMITED
767e3ab6fc5SMichael Hamann * @return string|null The first heading
76842ea7f44SGerrit Uitslag *
76995dbfe57SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
770bf0c93c2SMichael Hamann * @author Michael Hamann <michael@content-space.de>
771bb0a59d4Sjan */
77278b498a7SAndreas Gohrfunction p_get_first_heading($id, $render = METADATA_RENDER_USING_SIMPLE_CACHE)
77378b498a7SAndreas Gohr{
77465aa8490SMichael Hamann    return p_get_metadata(cleanID($id), 'title', $render);
775bb0a59d4Sjan}
776bb0a59d4Sjan
7778f7d700cSchris/**
7788f7d700cSchris * Wrapper for GeSHi Code Highlighter, provides caching of its output
7798f7d700cSchris *
7805d568b99SChris Smith * @param string $code source code to be highlighted
7815d568b99SChris Smith * @param string $language language to provide highlighting
7825d568b99SChris Smith * @param string $wrapper html element to wrap the returned highlighted text
783e3ab6fc5SMichael Hamann * @return string xhtml code
78442ea7f44SGerrit Uitslag *
7858f7d700cSchris * @author Christopher Smith <chris@jalakai.co.uk>
78635fbe9efSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
7878f7d700cSchris */
78878b498a7SAndreas Gohrfunction p_xhtml_cached_geshi($code, $language, $wrapper = 'pre', array $options = null)
78978b498a7SAndreas Gohr{
790ff1769deSAndreas Gohr    global $conf, $config_cascade, $INPUT;
79135fbe9efSAndreas Gohr    $language = strtolower($language);
7925d568b99SChris Smith
7935d568b99SChris Smith    // remove any leading or trailing blank lines
7945d568b99SChris Smith    $code = preg_replace('/^\s*?\n|\s*?\n$/', '', $code);
7955d568b99SChris Smith
796e2d88156SLarsDW223    $optionsmd5 = md5(serialize($options));
797e2d88156SLarsDW223    $cache = getCacheName($language . $code . $optionsmd5, ".code");
79835fbe9efSAndreas Gohr    $ctime = @filemtime($cache);
799ff1769deSAndreas Gohr    if ($ctime && !$INPUT->bool('purge') &&
80041d51802SAndreas Gohr        $ctime > filemtime(DOKU_INC . 'vendor/composer/installed.json') &&  // libraries changed
801f8121585SChris Smith        $ctime > filemtime(reset($config_cascade['main']['default']))) { // dokuwiki changed
8028f7d700cSchris        $highlighted_code = io_readFile($cache, false);
8038f7d700cSchris    } else {
8048f7d700cSchris
80541d51802SAndreas Gohr        $geshi = new GeSHi($code, $language);
8068f7d700cSchris        $geshi->set_encoding('utf-8');
8078f7d700cSchris        $geshi->enable_classes();
8088f7d700cSchris        $geshi->set_header_type(GESHI_HEADER_PRE);
8098f7d700cSchris        $geshi->set_link_target($conf['target']['extern']);
810e2d88156SLarsDW223        if ($options !== null) {
811e2d88156SLarsDW223            foreach ($options as $function => $params) {
81278b498a7SAndreas Gohr                if (is_callable([$geshi, $function])) {
813e2d88156SLarsDW223                    $geshi->$function($params);
814e2d88156SLarsDW223                }
815e2d88156SLarsDW223            }
816e2d88156SLarsDW223        }
8178f7d700cSchris
8185d568b99SChris Smith        // remove GeSHi's wrapper element (we'll replace it with our own later)
8195d568b99SChris Smith        // we need to use a GeSHi wrapper to avoid <BR> throughout the highlighted text
82069ddc332SAnika Henke        $highlighted_code = trim(preg_replace('!^<pre[^>]*>|</pre>$!', '', $geshi->parse_code()), "\n\r");
8218f7d700cSchris        io_saveFile($cache, $highlighted_code);
8228f7d700cSchris    }
8238f7d700cSchris
8245d568b99SChris Smith    // add a wrapper element if required
8255d568b99SChris Smith    if ($wrapper) {
8265d568b99SChris Smith        return "<$wrapper class=\"code $language\">$highlighted_code</$wrapper>";
8275d568b99SChris Smith    } else {
8288f7d700cSchris        return $highlighted_code;
8298f7d700cSchris    }
8305d568b99SChris Smith}
831