xref: /dokuwiki/inc/parserutils.php (revision 99a0b4268939573d3e046affd7b2795d97513f54)
1c112d578Sandi<?php
2d4f83172SAndreas Gohr
3c112d578Sandi/**
4b8595a66SAndreas Gohr * Utilities for accessing the parser
5c112d578Sandi *
6c112d578Sandi * @license    GPL 2 (http://www.gnu.org/licenses/gpl.html)
7c112d578Sandi * @author     Harry Fuecks <hfuecks@gmail.com>
8c112d578Sandi * @author     Andreas Gohr <andi@splitbrain.org>
9c112d578Sandi */
10d4f83172SAndreas Gohr
1124870174SAndreas Gohruse dokuwiki\Extension\PluginInterface;
120db5771eSMichael Großeuse dokuwiki\Cache\CacheInstructions;
130db5771eSMichael Großeuse dokuwiki\Cache\CacheRenderer;
14e1d9dcc8SAndreas Gohruse dokuwiki\ChangeLog\PageChangeLog;
153a7140a1SAndreas Gohruse dokuwiki\Extension\PluginController;
16e1d9dcc8SAndreas Gohruse dokuwiki\Extension\Event;
1778b498a7SAndreas Gohruse dokuwiki\Extension\SyntaxPlugin;
18d4d8fb18SAndreas Gohruse dokuwiki\Parsing\Parser;
1978b498a7SAndreas Gohruse dokuwiki\Parsing\ParserMode\Acronym;
2078b498a7SAndreas Gohruse dokuwiki\Parsing\ParserMode\Camelcaselink;
2178b498a7SAndreas Gohruse dokuwiki\Parsing\ParserMode\Entity;
2278b498a7SAndreas Gohruse dokuwiki\Parsing\ParserMode\Formatting;
2378b498a7SAndreas Gohruse dokuwiki\Parsing\ParserMode\Smiley;
24d4d8fb18SAndreas Gohr
25c112d578Sandi/**
2665aa8490SMichael Hamann * How many pages shall be rendered for getting metadata during one request
2765aa8490SMichael Hamann * at maximum? Note that this limit isn't respected when METADATA_RENDER_UNLIMITED
2865aa8490SMichael Hamann * is passed as render parameter to p_get_metadata.
29ff725173SMichael Hamann */
3065aa8490SMichael Hamannif (!defined('P_GET_METADATA_RENDER_LIMIT')) define('P_GET_METADATA_RENDER_LIMIT', 5);
3167c15eceSMichael Hamann
3267c15eceSMichael Hamann/** Don't render metadata even if it is outdated or doesn't exist */
3367c15eceSMichael Hamanndefine('METADATA_DONT_RENDER', 0);
3465aa8490SMichael Hamann/**
3565aa8490SMichael Hamann * Render metadata when the page is really newer or the metadata doesn't exist.
3665aa8490SMichael Hamann * Uses just a simple check, but should work pretty well for loading simple
3765aa8490SMichael Hamann * metadata values like the page title and avoids rendering a lot of pages in
3865aa8490SMichael Hamann * one request. The P_GET_METADATA_RENDER_LIMIT is used in this mode.
3965aa8490SMichael Hamann * Use this if it is unlikely that the metadata value you are requesting
4065aa8490SMichael Hamann * does depend e.g. on pages that are included in the current page using
4165aa8490SMichael Hamann * the include plugin (this is very likely the case for the page title, but
4265aa8490SMichael Hamann * not for relation references).
4365aa8490SMichael Hamann */
4467c15eceSMichael Hamanndefine('METADATA_RENDER_USING_SIMPLE_CACHE', 1);
4565aa8490SMichael Hamann/**
4665aa8490SMichael Hamann * Render metadata using the metadata cache logic. The P_GET_METADATA_RENDER_LIMIT
4765aa8490SMichael Hamann * is used in this mode. Use this mode when you are requesting more complex
4865aa8490SMichael Hamann * metadata. Although this will cause rendering more often it might actually have
4965aa8490SMichael Hamann * the effect that less current metadata is returned as it is more likely than in
5065aa8490SMichael Hamann * the simple cache mode that metadata needs to be rendered for all pages at once
5165aa8490SMichael Hamann * which means that when the metadata for the page is requested that actually needs
5265aa8490SMichael Hamann * to be updated the limit might have been reached already.
5365aa8490SMichael Hamann */
5467c15eceSMichael Hamanndefine('METADATA_RENDER_USING_CACHE', 2);
5565aa8490SMichael Hamann/**
5665aa8490SMichael Hamann * Render metadata without limiting the number of pages for which metadata is
5765aa8490SMichael Hamann * rendered. Use this mode with care, normally it should only be used in places
5865aa8490SMichael Hamann * like the indexer or in cli scripts where the execution time normally isn't
5965aa8490SMichael Hamann * limited. This can be combined with the simple cache using
6065aa8490SMichael Hamann * METADATA_RENDER_USING_CACHE | METADATA_RENDER_UNLIMITED.
6165aa8490SMichael Hamann */
6265aa8490SMichael Hamanndefine('METADATA_RENDER_UNLIMITED', 4);
63ff725173SMichael Hamann
64ff725173SMichael Hamann/**
65c112d578Sandi * Returns the parsed Wikitext in XHTML for the given id and revision.
66c112d578Sandi *
67c112d578Sandi * If $excuse is true an explanation is returned if the file
68c112d578Sandi * wasn't found
69c112d578Sandi *
7042ea7f44SGerrit Uitslag * @param string $id page id
7142ea7f44SGerrit Uitslag * @param string|int $rev revision timestamp or empty string
7242ea7f44SGerrit Uitslag * @param bool $excuse
73f50a239bSTakamura * @param string $date_at
74f50a239bSTakamura *
7542ea7f44SGerrit Uitslag * @return null|string
7678b498a7SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
7778b498a7SAndreas Gohr *
78c112d578Sandi */
7978b498a7SAndreas Gohrfunction p_wiki_xhtml($id, $rev = '', $excuse = true, $date_at = '')
8078b498a7SAndreas Gohr{
81c112d578Sandi    $file = wikiFN($id, $rev);
82c112d578Sandi    $ret = '';
83c112d578Sandi
84c112d578Sandi    //ensure $id is in global $ID (needed for parsing)
851e76272cSandi    global $ID;
863ff8773bSAndreas Gohr    $keep = $ID;
871e76272cSandi    $ID = $id;
88c112d578Sandi
895c2eed9aSlisps    if ($rev || $date_at) {
9079e79377SAndreas Gohr        if (file_exists($file)) {
9164159a61SAndreas Gohr            //no caching on old revisions
9264159a61SAndreas Gohr            $ret = p_render('xhtml', p_get_instructions(io_readWikiPage($file, $id, $rev)), $info, $date_at);
93c112d578Sandi        } elseif ($excuse) {
94c112d578Sandi            $ret = p_locale_xhtml('norev');
95c112d578Sandi        }
9624870174SAndreas Gohr    } elseif (file_exists($file)) {
974b5f4f4eSchris        $ret = p_cached_output($file, 'xhtml', $id);
98c112d578Sandi    } elseif ($excuse) {
992eaa0567Speterfromearth        //check if the page once existed
100e1d9dcc8SAndreas Gohr        $changelog = new PageChangeLog($id);
1012eaa0567Speterfromearth        if ($changelog->hasRevisions()) {
1022eaa0567Speterfromearth            $ret = p_locale_xhtml('onceexisted');
1032eaa0567Speterfromearth        } else {
104c112d578Sandi            $ret = p_locale_xhtml('newpage');
105c112d578Sandi        }
106c112d578Sandi    }
107c112d578Sandi
1083ff8773bSAndreas Gohr    //restore ID (just in case)
1093ff8773bSAndreas Gohr    $ID = $keep;
1103ff8773bSAndreas Gohr
111c112d578Sandi    return $ret;
112c112d578Sandi}
113c112d578Sandi
114c112d578Sandi/**
115c112d578Sandi * Returns the specified local text in parsed format
116c112d578Sandi *
11742ea7f44SGerrit Uitslag * @param string $id page id
11842ea7f44SGerrit Uitslag * @return null|string
11978b498a7SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
12078b498a7SAndreas Gohr *
121c112d578Sandi */
12278b498a7SAndreas Gohrfunction p_locale_xhtml($id)
12378b498a7SAndreas Gohr{
124c112d578Sandi    //fetch parsed locale
12565f6b58fSAnna Dabrowska    $data = ['id' => $id, 'html' => ''];
12665f6b58fSAnna Dabrowska
12765f6b58fSAnna Dabrowska    $event = new Event('PARSER_LOCALE_XHTML', $data);
12865f6b58fSAnna Dabrowska    if ($event->advise_before()) {
12965f6b58fSAnna Dabrowska        $data['html'] = p_cached_output(localeFN($data['id']));
13065f6b58fSAnna Dabrowska    }
13165f6b58fSAnna Dabrowska    $event->advise_after();
13265f6b58fSAnna Dabrowska
13365f6b58fSAnna Dabrowska    return $data['html'];
134c112d578Sandi}
135c112d578Sandi
136c112d578Sandi/**
1374b5f4f4eSchris * Returns the given file parsed into the requested output format
1384b5f4f4eSchris *
13942ea7f44SGerrit Uitslag * @param string $file filename, path to file
14042ea7f44SGerrit Uitslag * @param string $format
14142ea7f44SGerrit Uitslag * @param string $id page id
14242ea7f44SGerrit Uitslag * @return null|string
14378b498a7SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
14478b498a7SAndreas Gohr * @author Chris Smith <chris@jalakai.co.uk>
14578b498a7SAndreas Gohr *
1464b5f4f4eSchris */
14778b498a7SAndreas Gohrfunction p_cached_output($file, $format = 'xhtml', $id = '')
14878b498a7SAndreas Gohr{
149c112d578Sandi    global $conf;
150c112d578Sandi
1510db5771eSMichael Große    $cache = new CacheRenderer($id, $file, $format);
1524b5f4f4eSchris    if ($cache->useCache()) {
15385767031SAndreas Gohr        $parsed = $cache->retrieveCache(false);
1547de86af9SGerrit Uitslag        if ($conf['allowdebug'] && $format == 'xhtml') {
1557de86af9SGerrit Uitslag            $parsed .= "\n<!-- cachefile {$cache->cache} used -->\n";
1567de86af9SGerrit Uitslag        }
157c112d578Sandi    } else {
1584b5f4f4eSchris        $parsed = p_render($format, p_cached_instructions($file, false, $id), $info);
159c112d578Sandi
160abca2f79SEduardo Mozart de Oliveira        if (!empty($info['cache']) && $cache->storeCache($parsed)) { // storeCache() attempts to save cachefile
1617de86af9SGerrit Uitslag            if ($conf['allowdebug'] && $format == 'xhtml') {
1627de86af9SGerrit Uitslag                $parsed .= "\n<!-- no cachefile used, but created {$cache->cache} -->\n";
1637de86af9SGerrit Uitslag            }
164c112d578Sandi        } else {
1654b5f4f4eSchris            $cache->removeCache(); //try to delete cachefile
1667de86af9SGerrit Uitslag            if ($conf['allowdebug'] && $format == 'xhtml') {
1677de86af9SGerrit Uitslag                $parsed .= "\n<!-- no cachefile used, caching forbidden -->\n";
1687de86af9SGerrit Uitslag            }
169c112d578Sandi        }
170c112d578Sandi    }
171c112d578Sandi
172c112d578Sandi    return $parsed;
173c112d578Sandi}
174c112d578Sandi
175c112d578Sandi/**
176c112d578Sandi * Returns the render instructions for a file
177c112d578Sandi *
178c112d578Sandi * Uses and creates a serialized cache file
179c112d578Sandi *
18042ea7f44SGerrit Uitslag * @param string $file filename, path to file
18142ea7f44SGerrit Uitslag * @param bool $cacheonly
18242ea7f44SGerrit Uitslag * @param string $id page id
18342ea7f44SGerrit Uitslag * @return array|null
18478b498a7SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
18578b498a7SAndreas Gohr *
186c112d578Sandi */
18778b498a7SAndreas Gohrfunction p_cached_instructions($file, $cacheonly = false, $id = '')
18878b498a7SAndreas Gohr{
18947b2d319SAndreas Gohr    static $run = null;
19078b498a7SAndreas Gohr    if (is_null($run)) $run = [];
191c112d578Sandi
1920db5771eSMichael Große    $cache = new CacheInstructions($id, $file);
193c112d578Sandi
1940d24b616SMichael Hamann    if ($cacheonly || $cache->useCache() || (isset($run[$file]) && !defined('DOKU_UNITTEST'))) {
1954b5f4f4eSchris        return $cache->retrieveCache();
19679e79377SAndreas Gohr    } elseif (file_exists($file)) {
197c112d578Sandi        // no cache - do some work
198bde4e341SGalaxyMaster        $ins = p_get_instructions(io_readWikiPage($file, $id));
199cbaf4259SChris Smith        if ($cache->storeCache($ins)) {
20047b2d319SAndreas Gohr            $run[$file] = true; // we won't rebuild these instructions in the same run again
201cbaf4259SChris Smith        } else {
202cbaf4259SChris Smith            msg('Unable to save cache file. Hint: disk full; file permissions; safe_mode setting.', -1);
203cbaf4259SChris Smith        }
204c112d578Sandi        return $ins;
205c112d578Sandi    }
206c112d578Sandi
2073b3f8916SAndreas Gohr    return null;
208c112d578Sandi}
209c112d578Sandi
210c112d578Sandi/**
211c112d578Sandi * turns a page into a list of instructions
212c112d578Sandi *
21378b498a7SAndreas Gohr * @param string $text raw wiki syntax text
21478b498a7SAndreas Gohr * @return array a list of instruction arrays
215c112d578Sandi * @author Harry Fuecks <hfuecks@gmail.com>
216c112d578Sandi * @author Andreas Gohr <andi@splitbrain.org>
21742ea7f44SGerrit Uitslag *
218c112d578Sandi */
21978b498a7SAndreas Gohrfunction p_get_instructions($text)
22078b498a7SAndreas Gohr{
221c112d578Sandi
222107b01d6Sandi    $modes = p_get_parsermodes();
223ee20e7d1Sandi
22447f73ecfSAndreas Gohr    // Create the parser and handler
225d4d8fb18SAndreas Gohr    $Parser = new Parser(new Doku_Handler());
226c112d578Sandi
227107b01d6Sandi    //add modes to parser
228107b01d6Sandi    foreach ($modes as $mode) {
229107b01d6Sandi        $Parser->addMode($mode['mode'], $mode['obj']);
230c112d578Sandi    }
231c112d578Sandi
232c112d578Sandi    // Do the parsing
233cbb44eabSAndreas Gohr    Event::createAndTrigger('PARSER_WIKITEXT_PREPROCESS', $text);
23478b498a7SAndreas Gohr    return $Parser->parse($text);
235c112d578Sandi}
236c112d578Sandi
237c112d578Sandi/**
23839a89382SEsther Brunner * returns the metadata of a page
23939a89382SEsther Brunner *
2404a819402SMichael Hamann * @param string $id The id of the page the metadata should be returned from
24164159a61SAndreas Gohr * @param string $key The key of the metdata value that shall be read (by default everything)
24264159a61SAndreas Gohr *                        separate hierarchies by " " like "date created"
24367c15eceSMichael Hamann * @param int $render If the page should be rendererd - possible values:
24465aa8490SMichael Hamann *     METADATA_DONT_RENDER, METADATA_RENDER_USING_SIMPLE_CACHE, METADATA_RENDER_USING_CACHE
24565aa8490SMichael Hamann *     METADATA_RENDER_UNLIMITED (also combined with the previous two options),
24665aa8490SMichael Hamann *     default: METADATA_RENDER_USING_CACHE
2474a819402SMichael Hamann * @return mixed The requested metadata fields
2484a819402SMichael Hamann *
24939a89382SEsther Brunner * @author Esther Brunner <esther@kaffeehaus.ch>
25098214867SMichael Hamann * @author Michael Hamann <michael@content-space.de>
25139a89382SEsther Brunner */
25278b498a7SAndreas Gohrfunction p_get_metadata($id, $key = '', $render = METADATA_RENDER_USING_CACHE)
25378b498a7SAndreas Gohr{
2541172f8dcSAdrian Lang    global $ID;
25565aa8490SMichael Hamann    static $render_count = 0;
25665aa8490SMichael Hamann    // track pages that have already been rendered in order to avoid rendering the same page
25765aa8490SMichael Hamann    // again
25878b498a7SAndreas Gohr    static $rendered_pages = [];
2596afe8dcaSchris
2600a7e3bceSchris    // cache the current page
2610a7e3bceSchris    // Benchmarking shows the current page's metadata is generally the only page metadata
2620a7e3bceSchris    // accessed several times. This may catch a few other pages, but that shouldn't be an issue.
2630a7e3bceSchris    $cache = ($ID == $id);
2640a7e3bceSchris    $meta = p_read_metadata($id, $cache);
26539a89382SEsther Brunner
26667c15eceSMichael Hamann    if (!is_numeric($render)) {
26767c15eceSMichael Hamann        if ($render) {
26867c15eceSMichael Hamann            $render = METADATA_RENDER_USING_SIMPLE_CACHE;
26967c15eceSMichael Hamann        } else {
27067c15eceSMichael Hamann            $render = METADATA_DONT_RENDER;
27167c15eceSMichael Hamann        }
27267c15eceSMichael Hamann    }
27367c15eceSMichael Hamann
27498214867SMichael Hamann    // prevent recursive calls in the cache
27598214867SMichael Hamann    static $recursion = false;
27665aa8490SMichael Hamann    if (!$recursion && $render != METADATA_DONT_RENDER && !isset($rendered_pages[$id]) && page_exists($id)) {
27798214867SMichael Hamann        $recursion = true;
27898214867SMichael Hamann
2790db5771eSMichael Große        $cachefile = new CacheRenderer($id, wikiFN($id), 'metadata');
28098214867SMichael Hamann
28167c15eceSMichael Hamann        $do_render = false;
28265aa8490SMichael Hamann        if ($render & METADATA_RENDER_UNLIMITED || $render_count < P_GET_METADATA_RENDER_LIMIT) {
28365aa8490SMichael Hamann            if ($render & METADATA_RENDER_USING_SIMPLE_CACHE) {
28467c15eceSMichael Hamann                $pagefn = wikiFN($id);
28567c15eceSMichael Hamann                $metafn = metaFN($id, '.meta');
28679e79377SAndreas Gohr                if (!file_exists($metafn) || @filemtime($pagefn) > @filemtime($cachefile->cache)) {
28767c15eceSMichael Hamann                    $do_render = true;
28867c15eceSMichael Hamann                }
28967c15eceSMichael Hamann            } elseif (!$cachefile->useCache()) {
29067c15eceSMichael Hamann                $do_render = true;
29167c15eceSMichael Hamann            }
29265aa8490SMichael Hamann        }
29367c15eceSMichael Hamann        if ($do_render) {
2940d24b616SMichael Hamann            if (!defined('DOKU_UNITTEST')) {
29565aa8490SMichael Hamann                ++$render_count;
29665aa8490SMichael Hamann                $rendered_pages[$id] = true;
2970d24b616SMichael Hamann            }
29869ba640bSMichael Hamann            $old_meta = $meta;
29939a89382SEsther Brunner            $meta = p_render_metadata($id, $meta);
30069ba640bSMichael Hamann            // only update the file when the metadata has been changed
30169ba640bSMichael Hamann            if ($meta == $old_meta || p_save_metadata($id, $meta)) {
30298214867SMichael Hamann                // store a timestamp in order to make sure that the cachefile is touched
3033d6feb16SMichael Hamann                // this timestamp is also stored when the meta data is still the same
30498214867SMichael Hamann                $cachefile->storeCache(time());
3053d6feb16SMichael Hamann            } else {
30698214867SMichael Hamann                msg('Unable to save metadata file. Hint: disk full; file permissions; safe_mode setting.', -1);
30798214867SMichael Hamann            }
30898214867SMichael Hamann        }
30998214867SMichael Hamann
31098214867SMichael Hamann        $recursion = false;
3116afe8dcaSchris    }
31239a89382SEsther Brunner
313fa1a0dc6STB Maulana Aghni    $val = $meta['current'] ?? null;
314ebf65d37SAdrian Lang
31539a89382SEsther Brunner    // filter by $key
316569a0019SAdrian Lang    foreach (preg_split('/\s+/', $key, 2, PREG_SPLIT_NO_EMPTY) as $cur_key) {
317ebf65d37SAdrian Lang        if (!isset($val[$cur_key])) {
318ebf65d37SAdrian Lang            return null;
31966d29756SChris Smith        }
320ebf65d37SAdrian Lang        $val = $val[$cur_key];
32139a89382SEsther Brunner    }
322ebf65d37SAdrian Lang    return $val;
32339a89382SEsther Brunner}
32439a89382SEsther Brunner
32539a89382SEsther Brunner/**
32639a89382SEsther Brunner * sets metadata elements of a page
32739a89382SEsther Brunner *
328a365baeeSDominik Eckelmann * @see http://www.dokuwiki.org/devel:metadata#functions_to_get_and_set_metadata
329a365baeeSDominik Eckelmann *
330e1d9dcc8SAndreas Gohr * @param string $id is the ID of a wiki page
331e1d9dcc8SAndreas Gohr * @param array $data is an array with key ⇒ value pairs to be set in the metadata
332e1d9dcc8SAndreas Gohr * @param boolean $render whether or not the page metadata should be generated with the renderer
333e1d9dcc8SAndreas Gohr * @param boolean $persistent indicates whether or not the particular metadata value will persist through
334a365baeeSDominik Eckelmann *                            the next metadata rendering.
335a365baeeSDominik Eckelmann * @return boolean true on success
336a365baeeSDominik Eckelmann *
33739a89382SEsther Brunner * @author Esther Brunner <esther@kaffeehaus.ch>
3380e5fde48SMichael Hamann * @author Michael Hamann <michael@content-space.de>
33939a89382SEsther Brunner */
34078b498a7SAndreas Gohrfunction p_set_metadata($id, $data, $render = false, $persistent = true)
34178b498a7SAndreas Gohr{
34239a89382SEsther Brunner    if (!is_array($data)) return false;
34339a89382SEsther Brunner
3440e5fde48SMichael Hamann    global $ID, $METADATA_RENDERERS;
3450a7e3bceSchris
3460e5fde48SMichael Hamann    // if there is currently a renderer change the data in the renderer instead
3470e5fde48SMichael Hamann    if (isset($METADATA_RENDERERS[$id])) {
3480e5fde48SMichael Hamann        $orig =& $METADATA_RENDERERS[$id];
3490e5fde48SMichael Hamann        $meta = $orig;
3500e5fde48SMichael Hamann    } else {
3510a7e3bceSchris        // cache the current page
3520a7e3bceSchris        $cache = ($ID == $id);
3530a7e3bceSchris        $orig = p_read_metadata($id, $cache);
35439a89382SEsther Brunner
35539a89382SEsther Brunner        // render metadata first?
3560a7e3bceSchris        $meta = $render ? p_render_metadata($id, $orig) : $orig;
3570e5fde48SMichael Hamann    }
35839a89382SEsther Brunner
35939a89382SEsther Brunner    // now add the passed metadata
36078b498a7SAndreas Gohr    $protected = ['description', 'date', 'contributor'];
36139a89382SEsther Brunner    foreach ($data as $key => $value) {
36239a89382SEsther Brunner        // be careful with sub-arrays of $meta['relation']
36339a89382SEsther Brunner        if ($key == 'relation') {
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)) {
38466d29756SChris Smith            // these keys, must have subkeys - a legitimate value must be an array
38539a89382SEsther Brunner            if (is_array($value)) {
38624870174SAndreas Gohr                $meta['current'][$key] = empty($meta['current'][$key]) ?
38724870174SAndreas Gohr                    $value :
38824870174SAndreas Gohr                    array_replace((array)$meta['current'][$key], $value);
3890a7e3bceSchris
3900a7e3bceSchris                if ($persistent) {
39124870174SAndreas Gohr                    $meta['persistent'][$key] = empty($meta['persistent'][$key]) ?
39224870174SAndreas Gohr                        $value :
39324870174SAndreas Gohr                        array_replace((array)$meta['persistent'][$key], $value);
3940a7e3bceSchris                }
39539a89382SEsther Brunner            }
39639a89382SEsther Brunner
39739a89382SEsther Brunner            // no special treatment for the rest
39839a89382SEsther Brunner        } else {
3990a7e3bceSchris            $meta['current'][$key] = $value;
4000a7e3bceSchris            if ($persistent) $meta['persistent'][$key] = $value;
40139a89382SEsther Brunner        }
40239a89382SEsther Brunner    }
40339a89382SEsther Brunner
40439a89382SEsther Brunner    // save only if metadata changed
40539a89382SEsther Brunner    if ($meta == $orig) return true;
4066afe8dcaSchris
4070e5fde48SMichael Hamann    if (isset($METADATA_RENDERERS[$id])) {
4080e5fde48SMichael Hamann        // set both keys individually as the renderer has references to the individual keys
4090e5fde48SMichael Hamann        $METADATA_RENDERERS[$id]['current'] = $meta['current'];
4100e5fde48SMichael Hamann        $METADATA_RENDERERS[$id]['persistent'] = $meta['persistent'];
4111c56be7bSMichael Hamann        return true;
4120e5fde48SMichael Hamann    } else {
4131172f8dcSAdrian Lang        return p_save_metadata($id, $meta);
41439a89382SEsther Brunner    }
4150e5fde48SMichael Hamann}
41639a89382SEsther Brunner
41739a89382SEsther Brunner/**
4183d1f9ec3SMichael Klier * Purges the non-persistant part of the meta data
4193d1f9ec3SMichael Klier * used on page deletion
4203d1f9ec3SMichael Klier *
42142ea7f44SGerrit Uitslag * @param string $id page id
42242ea7f44SGerrit Uitslag * @return bool  success / fail
42378b498a7SAndreas Gohr * @author Michael Klier <chi@chimeric.de>
42478b498a7SAndreas Gohr *
4253d1f9ec3SMichael Klier */
42678b498a7SAndreas Gohrfunction p_purge_metadata($id)
42778b498a7SAndreas Gohr{
4283d1f9ec3SMichael Klier    $meta = p_read_metadata($id);
4293d1f9ec3SMichael Klier    foreach ($meta['current'] as $key => $value) {
430056bf31fSDamien Regad        if (isset($meta[$key]) && is_array($meta[$key])) {
43178b498a7SAndreas Gohr            $meta['current'][$key] = [];
4323d1f9ec3SMichael Klier        } else {
4333d1f9ec3SMichael Klier            $meta['current'][$key] = '';
4343d1f9ec3SMichael Klier        }
4353d1f9ec3SMichael Klier    }
4361172f8dcSAdrian Lang    return p_save_metadata($id, $meta);
4373d1f9ec3SMichael Klier}
4383d1f9ec3SMichael Klier
4393d1f9ec3SMichael Klier/**
4400a7e3bceSchris * read the metadata from source/cache for $id
4410a7e3bceSchris * (internal use only - called by p_get_metadata & p_set_metadata)
4420a7e3bceSchris *
4430a7e3bceSchris * @param string $id absolute wiki page id
4440a7e3bceSchris * @param bool $cache whether or not to cache metadata in memory
4450a7e3bceSchris *                             (only use for metadata likely to be accessed several times)
4460a7e3bceSchris *
4470a7e3bceSchris * @return   array             metadata
44878b498a7SAndreas Gohr * @author   Christopher Smith <chris@jalakai.co.uk>
44978b498a7SAndreas Gohr *
4500a7e3bceSchris */
45178b498a7SAndreas Gohrfunction p_read_metadata($id, $cache = false)
45278b498a7SAndreas Gohr{
4530a7e3bceSchris    global $cache_metadata;
4540a7e3bceSchris
4553a50618cSgweissbach    if (isset($cache_metadata[(string)$id])) return $cache_metadata[(string)$id];
4560a7e3bceSchris
4570a7e3bceSchris    $file = metaFN($id, '.meta');
45864159a61SAndreas Gohr    $meta = file_exists($file) ?
45964159a61SAndreas Gohr        unserialize(io_readFile($file, false)) :
46078b498a7SAndreas Gohr        ['current' => [], 'persistent' => []];
4610a7e3bceSchris
4620a7e3bceSchris    if ($cache) {
4633a50618cSgweissbach        $cache_metadata[(string)$id] = $meta;
4640a7e3bceSchris    }
4650a7e3bceSchris
4660a7e3bceSchris    return $meta;
4670a7e3bceSchris}
4680a7e3bceSchris
4690a7e3bceSchris/**
4701172f8dcSAdrian Lang * This is the backend function to save a metadata array to a file
4711172f8dcSAdrian Lang *
4721172f8dcSAdrian Lang * @param string $id absolute wiki page id
4731172f8dcSAdrian Lang * @param array $meta metadata
4741172f8dcSAdrian Lang *
4751172f8dcSAdrian Lang * @return   bool              success / fail
4761172f8dcSAdrian Lang */
47778b498a7SAndreas Gohrfunction p_save_metadata($id, $meta)
47878b498a7SAndreas Gohr{
4791172f8dcSAdrian Lang    // sync cached copies, including $INFO metadata
4801172f8dcSAdrian Lang    global $cache_metadata, $INFO;
4811172f8dcSAdrian Lang
4821172f8dcSAdrian Lang    if (isset($cache_metadata[$id])) $cache_metadata[$id] = $meta;
483056bf31fSDamien Regad    if (!empty($INFO) && isset($INFO['id']) && ($id == $INFO['id'])) {
484056bf31fSDamien Regad        $INFO['meta'] = $meta['current'];
485056bf31fSDamien Regad    }
4861172f8dcSAdrian Lang
4871172f8dcSAdrian Lang    return io_saveFile(metaFN($id, '.meta'), serialize($meta));
4881172f8dcSAdrian Lang}
4891172f8dcSAdrian Lang
4901172f8dcSAdrian Lang/**
49139a89382SEsther Brunner * renders the metadata of a page
49239a89382SEsther Brunner *
49342ea7f44SGerrit Uitslag * @param string $id page id
49442ea7f44SGerrit Uitslag * @param array $orig the original metadata
49542ea7f44SGerrit Uitslag * @return array|null array('current'=> array,'persistent'=> array);
49678b498a7SAndreas Gohr * @author Esther Brunner <esther@kaffeehaus.ch>
49778b498a7SAndreas Gohr *
49839a89382SEsther Brunner */
49978b498a7SAndreas Gohrfunction p_render_metadata($id, $orig)
50078b498a7SAndreas Gohr{
50148924015SAndreas Gohr    // make sure the correct ID is in global ID
5020e5fde48SMichael Hamann    global $ID, $METADATA_RENDERERS;
5030e5fde48SMichael Hamann
5040e5fde48SMichael Hamann    // avoid recursive rendering processes for the same id
5055b76ad91SChristopher Smith    if (isset($METADATA_RENDERERS[$id])) {
5060e5fde48SMichael Hamann        return $orig;
5075b76ad91SChristopher Smith    }
5080e5fde48SMichael Hamann
5090e5fde48SMichael Hamann    // store the original metadata in the global $METADATA_RENDERERS so p_set_metadata can use it
5100e5fde48SMichael Hamann    $METADATA_RENDERERS[$id] =& $orig;
5110e5fde48SMichael Hamann
51248924015SAndreas Gohr    $keep = $ID;
51348924015SAndreas Gohr    $ID = $id;
51448924015SAndreas Gohr
5150a7e3bceSchris    // add an extra key for the event - to tell event handlers the page whose metadata this is
5160a7e3bceSchris    $orig['page'] = $id;
517e1d9dcc8SAndreas Gohr    $evt = new Event('PARSER_METADATA_RENDER', $orig);
5180a7e3bceSchris    if ($evt->advise_before()) {
51939a89382SEsther Brunner        // get instructions
5204b5f4f4eSchris        $instructions = p_cached_instructions(wikiFN($id), false, $id);
52148924015SAndreas Gohr        if (is_null($instructions)) {
52248924015SAndreas Gohr            $ID = $keep;
5230e5fde48SMichael Hamann            unset($METADATA_RENDERERS[$id]);
52448924015SAndreas Gohr            return null; // something went wrong with the instructions
52548924015SAndreas Gohr        }
52639a89382SEsther Brunner
52739a89382SEsther Brunner        // set up the renderer
52867f9913dSAndreas Gohr        $renderer = new Doku_Renderer_metadata();
5290e5fde48SMichael Hamann        $renderer->meta =& $orig['current'];
5300e5fde48SMichael Hamann        $renderer->persistent =& $orig['persistent'];
53139a89382SEsther Brunner
53239a89382SEsther Brunner        // loop through the instructions
53339a89382SEsther Brunner        foreach ($instructions as $instruction) {
53439a89382SEsther Brunner            // execute the callback against the renderer
53578b498a7SAndreas Gohr            call_user_func_array([&$renderer, $instruction[0]], (array)$instruction[1]);
53639a89382SEsther Brunner        }
53739a89382SEsther Brunner
53878b498a7SAndreas Gohr        $evt->result = ['current' => &$renderer->meta, 'persistent' => &$renderer->persistent];
5390a7e3bceSchris    }
5400a7e3bceSchris    $evt->advise_after();
5410a7e3bceSchris
5420e5fde48SMichael Hamann    // clean up
54348924015SAndreas Gohr    $ID = $keep;
5440e5fde48SMichael Hamann    unset($METADATA_RENDERERS[$id]);
5450a7e3bceSchris    return $evt->result;
54639a89382SEsther Brunner}
54739a89382SEsther Brunner
54839a89382SEsther Brunner/**
549107b01d6Sandi * returns all available parser syntax modes in correct order
550107b01d6Sandi *
55178b498a7SAndreas Gohr * @return array[] with for each plugin the array('sort' => sortnumber, 'mode' => mode string, 'obj'  => plugin object)
552107b01d6Sandi * @author Andreas Gohr <andi@splitbrain.org>
55342ea7f44SGerrit Uitslag *
554107b01d6Sandi */
55578b498a7SAndreas Gohrfunction p_get_parsermodes()
55678b498a7SAndreas Gohr{
557107b01d6Sandi    global $conf;
558107b01d6Sandi
559107b01d6Sandi    //reuse old data
560107b01d6Sandi    static $modes = null;
5610d24b616SMichael Hamann    if ($modes != null && !defined('DOKU_UNITTEST')) {
562107b01d6Sandi        return $modes;
563107b01d6Sandi    }
564107b01d6Sandi
565107b01d6Sandi    //import parser classes and mode definitions
566107b01d6Sandi    require_once DOKU_INC . 'inc/parser/parser.php';
567107b01d6Sandi
568107b01d6Sandi    // we now collect all syntax modes and their objects, then they will
569107b01d6Sandi    // be sorted and added to the parser in correct order
57078b498a7SAndreas Gohr    $modes = [];
571107b01d6Sandi
572107b01d6Sandi    // add syntax plugins
573107b01d6Sandi    $pluginlist = plugin_list('syntax');
57424870174SAndreas Gohr    if ($pluginlist !== []) {
575107b01d6Sandi        global $PARSER_MODES;
576107b01d6Sandi        foreach ($pluginlist as $p) {
57778b498a7SAndreas Gohr            /** @var SyntaxPlugin $obj */
578e6a82646SAndreas Gohr            $obj = plugin_load('syntax', $p);
579e6a82646SAndreas Gohr            if (!$obj instanceof PluginInterface) continue;
580107b01d6Sandi            $PARSER_MODES[$obj->getType()][] = "plugin_$p"; //register mode type
581107b01d6Sandi            //add to modes
58278b498a7SAndreas Gohr            $modes[] = [
583107b01d6Sandi                'sort' => $obj->getSort(),
584107b01d6Sandi                'mode' => "plugin_$p",
585107b01d6Sandi                'obj' => $obj,
58678b498a7SAndreas Gohr            ];
587a46d0d65SAndreas Gohr            unset($obj); //remove the reference
588107b01d6Sandi        }
589107b01d6Sandi    }
590107b01d6Sandi
591107b01d6Sandi    // add default modes
59278b498a7SAndreas Gohr    $std_modes = [
59378b498a7SAndreas Gohr        'listblock', 'preformatted', 'notoc', 'nocache', 'header', 'table', 'linebreak', 'footnote', 'hr',
59478b498a7SAndreas Gohr        'unformatted', 'code', 'file', 'quote', 'internallink', 'rss', 'media', 'externallink',
59578b498a7SAndreas Gohr        'emaillink', 'windowssharelink', 'eol'
59678b498a7SAndreas Gohr    ];
597e77ea1bcSAndreas Gohr    if ($conf['typography']) {
598e77ea1bcSAndreas Gohr        $std_modes[] = 'quotes';
599e77ea1bcSAndreas Gohr        $std_modes[] = 'multiplyentity';
600e77ea1bcSAndreas Gohr    }
601107b01d6Sandi    foreach ($std_modes as $m) {
602be906b56SAndreas Gohr        $class = 'dokuwiki\\Parsing\\ParserMode\\' . ucfirst($m);
603107b01d6Sandi        $obj = new $class();
60424870174SAndreas Gohr        $modes[] = ['sort' => $obj->getSort(), 'mode' => $m, 'obj' => $obj];
605107b01d6Sandi    }
606107b01d6Sandi
607107b01d6Sandi    // add formatting modes
60878b498a7SAndreas Gohr    $fmt_modes = [
60978b498a7SAndreas Gohr        'strong', 'emphasis', 'underline', 'monospace', 'subscript', 'superscript', 'deleted'
61078b498a7SAndreas Gohr    ];
611107b01d6Sandi    foreach ($fmt_modes as $m) {
61278b498a7SAndreas Gohr        $obj = new Formatting($m);
61324870174SAndreas Gohr        $modes[] = [
614107b01d6Sandi            'sort' => $obj->getSort(),
615107b01d6Sandi            'mode' => $m,
616107b01d6Sandi            'obj' => $obj
61724870174SAndreas Gohr        ];
618107b01d6Sandi    }
619107b01d6Sandi
620107b01d6Sandi    // add modes which need files
62178b498a7SAndreas Gohr    $obj = new Smiley(array_keys(getSmileys()));
62278b498a7SAndreas Gohr    $modes[] = ['sort' => $obj->getSort(), 'mode' => 'smiley', 'obj' => $obj];
62378b498a7SAndreas Gohr    $obj = new Acronym(array_keys(getAcronyms()));
62478b498a7SAndreas Gohr    $modes[] = ['sort' => $obj->getSort(), 'mode' => 'acronym', 'obj' => $obj];
62578b498a7SAndreas Gohr    $obj = new Entity(array_keys(getEntities()));
62678b498a7SAndreas Gohr    $modes[] = ['sort' => $obj->getSort(), 'mode' => 'entity', 'obj' => $obj];
627107b01d6Sandi
628107b01d6Sandi    // add optional camelcase mode
629107b01d6Sandi    if ($conf['camelcase']) {
63078b498a7SAndreas Gohr        $obj = new Camelcaselink();
63178b498a7SAndreas Gohr        $modes[] = ['sort' => $obj->getSort(), 'mode' => 'camelcaselink', 'obj' => $obj];
632107b01d6Sandi    }
633107b01d6Sandi
634107b01d6Sandi    //sort modes
635107b01d6Sandi    usort($modes, 'p_sort_modes');
636107b01d6Sandi
637107b01d6Sandi    return $modes;
638107b01d6Sandi}
639107b01d6Sandi
640107b01d6Sandi/**
641107b01d6Sandi * Callback function for usort
642107b01d6Sandi *
64342ea7f44SGerrit Uitslag * @param array $a
64442ea7f44SGerrit Uitslag * @param array $b
64542ea7f44SGerrit Uitslag * @return int $a is lower/equal/higher than $b
64678b498a7SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
64778b498a7SAndreas Gohr *
648107b01d6Sandi */
64978b498a7SAndreas Gohrfunction p_sort_modes($a, $b)
65078b498a7SAndreas Gohr{
65124870174SAndreas Gohr    return $a['sort'] <=> $b['sort'];
652107b01d6Sandi}
653107b01d6Sandi
654107b01d6Sandi/**
655ac83b9d8Sandi * Renders a list of instruction to the specified output mode
656c112d578Sandi *
6577a8cc57eSElan Ruusamäe * In the $info array is information from the renderer returned
6589dc2c2afSandi *
65942ea7f44SGerrit Uitslag * @param string $mode
660e3710957SGerrit Uitslag * @param array|null|false $instructions
66142ea7f44SGerrit Uitslag * @param array $info returns render info like enabled toc and cache
6627de86af9SGerrit Uitslag * @param string $date_at
66342ea7f44SGerrit Uitslag * @return null|string rendered output
66478b498a7SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
66578b498a7SAndreas Gohr *
66678b498a7SAndreas Gohr * @author Harry Fuecks <hfuecks@gmail.com>
667c112d578Sandi */
66878b498a7SAndreas Gohrfunction p_render($mode, $instructions, &$info, $date_at = '')
66978b498a7SAndreas Gohr{
670c112d578Sandi    if (is_null($instructions)) return '';
671e3710957SGerrit Uitslag    if ($instructions === false) return '';
672c112d578Sandi
673252398f0SChristopher Smith    $Renderer = p_get_renderer($mode);
674d968d3e5SChris Smith    if (is_null($Renderer)) return null;
675c327d6c4SAndreas Gohr
676d968d3e5SChris Smith    $Renderer->reset();
677c112d578Sandi
6785c2eed9aSlisps    if ($date_at) {
6795c2eed9aSlisps        $Renderer->date_at = $date_at;
6805c2eed9aSlisps    }
6815c2eed9aSlisps
682c112d578Sandi    $Renderer->smileys = getSmileys();
683c112d578Sandi    $Renderer->entities = getEntities();
684c112d578Sandi    $Renderer->acronyms = getAcronyms();
685c112d578Sandi    $Renderer->interwiki = getInterwiki();
686c112d578Sandi
687c112d578Sandi    // Loop through the instructions
688c112d578Sandi    foreach ($instructions as $instruction) {
689c112d578Sandi        // Execute the callback against the Renderer
6907c62086bSAndreas Gohr        if (method_exists($Renderer, $instruction[0])) {
69178b498a7SAndreas Gohr            call_user_func_array([&$Renderer, $instruction[0]], $instruction[1] ?: []);
692c112d578Sandi        }
6937c62086bSAndreas Gohr    }
6949dc2c2afSandi
6959dc2c2afSandi    //set info array
6969dc2c2afSandi    $info = $Renderer->info;
6979dc2c2afSandi
698677844afSchris    // Post process and return the output
69978b498a7SAndreas Gohr    $data = [$mode, & $Renderer->doc];
700cbb44eabSAndreas Gohr    Event::createAndTrigger('RENDERER_CONTENT_POSTPROCESS', $data);
701c112d578Sandi    return $Renderer->doc;
702c112d578Sandi}
703c112d578Sandi
704e3ab6fc5SMichael Hamann/**
705548d801fSChristopher Smith * Figure out the correct renderer class to use for $mode,
706548d801fSChristopher Smith * instantiate and return it
707548d801fSChristopher Smith *
7087e8500eeSGerrit Uitslag * @param string $mode Mode of the renderer to get
709e3ab6fc5SMichael Hamann * @return null|Doku_Renderer The renderer
710548d801fSChristopher Smith *
711548d801fSChristopher Smith * @author Christopher Smith <chris@jalakai.co.uk>
712e3ab6fc5SMichael Hamann */
71378b498a7SAndreas Gohrfunction p_get_renderer($mode)
71478b498a7SAndreas Gohr{
7153a7140a1SAndreas Gohr    /** @var PluginController $plugin_controller */
7167aea91afSChris Smith    global $conf, $plugin_controller;
717d968d3e5SChris Smith
71824870174SAndreas Gohr    $rname = empty($conf['renderer_' . $mode]) ? $mode : $conf['renderer_' . $mode];
7190cacf91fSLucas    $rclass = "Doku_Renderer_$rname";
7200cacf91fSLucas
721548d801fSChristopher Smith    // if requested earlier or a bundled renderer
7220cacf91fSLucas    if (class_exists($rclass)) {
72378b498a7SAndreas Gohr        return new $rclass();
7240cacf91fSLucas    }
725d968d3e5SChris Smith
7266e6d16edSChristopher Smith    // not bundled, see if its an enabled renderer plugin & when $mode is 'xhtml', the renderer can supply that format.
7270440ca46SGerrit Uitslag    /** @var Doku_Renderer $Renderer */
72811ac6abdSChristopher Smith    $Renderer = $plugin_controller->load('renderer', $rname);
7296e6d16edSChristopher Smith    if ($Renderer && is_a($Renderer, 'Doku_Renderer') && ($mode != 'xhtml' || $mode == $Renderer->getFormat())) {
73011ac6abdSChristopher Smith        return $Renderer;
73111ac6abdSChristopher Smith    }
732d968d3e5SChris Smith
73311ac6abdSChristopher Smith    // there is a configuration error!
734548d801fSChristopher Smith    // not bundled, not a valid enabled plugin, use $mode to try to fallback to a bundled renderer
73511ac6abdSChristopher Smith    $rclass = "Doku_Renderer_$mode";
736548d801fSChristopher Smith    if (class_exists($rclass)) {
73711ac6abdSChristopher Smith        // viewers should see renderered output, so restrict the warning to admins only
73811ac6abdSChristopher Smith        $msg = "No renderer '$rname' found for mode '$mode', check your plugins";
73911ac6abdSChristopher Smith        if ($mode == 'xhtml') {
74011ac6abdSChristopher Smith            $msg .= " and the 'renderer_xhtml' config setting";
74111ac6abdSChristopher Smith        }
74211ac6abdSChristopher Smith        $msg .= ".<br/>Attempting to fallback to the bundled renderer.";
743548d801fSChristopher Smith        msg($msg, -1, '', '', MSG_ADMINS_ONLY);
74411ac6abdSChristopher Smith
74573022918SAndreas Gohr        $Renderer = new $rclass();
746548d801fSChristopher Smith        $Renderer->nocache();     // fallback only (and may include admin alerts), don't cache
747d968d3e5SChris Smith        return $Renderer;
748d968d3e5SChris Smith    }
749d968d3e5SChris Smith
750548d801fSChristopher Smith    // fallback failed, alert the world
751548d801fSChristopher Smith    msg("No renderer '$rname' found for mode '$mode'", -1);
752548d801fSChristopher Smith    return null;
753548d801fSChristopher Smith}
754548d801fSChristopher Smith
755bb0a59d4Sjan/**
756bb0a59d4Sjan * Gets the first heading from a file
757bb0a59d4Sjan *
758fc18c0fbSchris * @param string $id dokuwiki page id
75967c15eceSMichael Hamann * @param int $render rerender if first heading not known
76067c15eceSMichael Hamann *                             default: METADATA_RENDER_USING_SIMPLE_CACHE
76167c15eceSMichael Hamann *                             Possible values: METADATA_DONT_RENDER,
76267c15eceSMichael Hamann *                                              METADATA_RENDER_USING_SIMPLE_CACHE,
76365aa8490SMichael Hamann *                                              METADATA_RENDER_USING_CACHE,
76465aa8490SMichael Hamann *                                              METADATA_RENDER_UNLIMITED
765e3ab6fc5SMichael Hamann * @return string|null The first heading
76642ea7f44SGerrit Uitslag *
76795dbfe57SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
768bf0c93c2SMichael Hamann * @author Michael Hamann <michael@content-space.de>
769bb0a59d4Sjan */
77078b498a7SAndreas Gohrfunction p_get_first_heading($id, $render = METADATA_RENDER_USING_SIMPLE_CACHE)
77178b498a7SAndreas Gohr{
77265aa8490SMichael Hamann    return p_get_metadata(cleanID($id), 'title', $render);
773bb0a59d4Sjan}
774bb0a59d4Sjan
7758f7d700cSchris/**
7768f7d700cSchris * Wrapper for GeSHi Code Highlighter, provides caching of its output
7778f7d700cSchris *
7785d568b99SChris Smith * @param string $code source code to be highlighted
7795d568b99SChris Smith * @param string $language language to provide highlighting
7805d568b99SChris Smith * @param string $wrapper html element to wrap the returned highlighted text
781e3ab6fc5SMichael Hamann * @return string xhtml code
78242ea7f44SGerrit Uitslag *
7838f7d700cSchris * @author Christopher Smith <chris@jalakai.co.uk>
78435fbe9efSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
7858f7d700cSchris */
786*99a0b426SAndreas Gohrfunction p_xhtml_cached_geshi($code, $language, $wrapper = 'pre', ?array $options = null)
78778b498a7SAndreas Gohr{
788ff1769deSAndreas Gohr    global $conf, $config_cascade, $INPUT;
78935fbe9efSAndreas Gohr    $language = strtolower($language);
7905d568b99SChris Smith
7915d568b99SChris Smith    // remove any leading or trailing blank lines
7925d568b99SChris Smith    $code = preg_replace('/^\s*?\n|\s*?\n$/', '', $code);
7935d568b99SChris Smith
794e2d88156SLarsDW223    $optionsmd5 = md5(serialize($options));
795e2d88156SLarsDW223    $cache = getCacheName($language . $code . $optionsmd5, ".code");
79635fbe9efSAndreas Gohr    $ctime = @filemtime($cache);
7977d34963bSAndreas Gohr    if (
7987d34963bSAndreas Gohr        $ctime && !$INPUT->bool('purge') &&
79941d51802SAndreas Gohr        $ctime > filemtime(DOKU_INC . 'vendor/composer/installed.json') &&  // libraries changed
8007d34963bSAndreas Gohr        $ctime > filemtime(reset($config_cascade['main']['default']))
8017d34963bSAndreas Gohr    ) { // dokuwiki changed
8028f7d700cSchris        $highlighted_code = io_readFile($cache, false);
8038f7d700cSchris    } else {
80441d51802SAndreas Gohr        $geshi = new GeSHi($code, $language);
8058f7d700cSchris        $geshi->set_encoding('utf-8');
8068f7d700cSchris        $geshi->enable_classes();
8078f7d700cSchris        $geshi->set_header_type(GESHI_HEADER_PRE);
8088f7d700cSchris        $geshi->set_link_target($conf['target']['extern']);
809e2d88156SLarsDW223        if ($options !== null) {
810e2d88156SLarsDW223            foreach ($options as $function => $params) {
81178b498a7SAndreas Gohr                if (is_callable([$geshi, $function])) {
812e2d88156SLarsDW223                    $geshi->$function($params);
813e2d88156SLarsDW223                }
814e2d88156SLarsDW223            }
815e2d88156SLarsDW223        }
8168f7d700cSchris
8175d568b99SChris Smith        // remove GeSHi's wrapper element (we'll replace it with our own later)
8185d568b99SChris Smith        // we need to use a GeSHi wrapper to avoid <BR> throughout the highlighted text
81969ddc332SAnika Henke        $highlighted_code = trim(preg_replace('!^<pre[^>]*>|</pre>$!', '', $geshi->parse_code()), "\n\r");
8208f7d700cSchris        io_saveFile($cache, $highlighted_code);
8218f7d700cSchris    }
8228f7d700cSchris
8235d568b99SChris Smith    // add a wrapper element if required
8245d568b99SChris Smith    if ($wrapper) {
8255d568b99SChris Smith        return "<$wrapper class=\"code $language\">$highlighted_code</$wrapper>";
8265d568b99SChris Smith    } else {
8278f7d700cSchris        return $highlighted_code;
8288f7d700cSchris    }
8295d568b99SChris Smith}
830