xref: /dokuwiki/inc/parserutils.php (revision c8dd1b9d24a2f9905db764a0ac4646fb1e172af4)
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
110db5771eSMichael Großeuse dokuwiki\Cache\CacheInstructions;
120db5771eSMichael Großeuse dokuwiki\Cache\CacheRenderer;
13e1d9dcc8SAndreas Gohruse dokuwiki\ChangeLog\PageChangeLog;
143a7140a1SAndreas Gohruse dokuwiki\Extension\PluginController;
15e1d9dcc8SAndreas Gohruse dokuwiki\Extension\Event;
16*c8dd1b9dSAndreas Gohruse dokuwiki\Parsing\ModeRegistry;
17d4d8fb18SAndreas Gohruse dokuwiki\Parsing\Parser;
18d4d8fb18SAndreas Gohr
19c112d578Sandi/**
2065aa8490SMichael Hamann * How many pages shall be rendered for getting metadata during one request
2165aa8490SMichael Hamann * at maximum? Note that this limit isn't respected when METADATA_RENDER_UNLIMITED
2265aa8490SMichael Hamann * is passed as render parameter to p_get_metadata.
23ff725173SMichael Hamann */
2465aa8490SMichael Hamannif (!defined('P_GET_METADATA_RENDER_LIMIT')) define('P_GET_METADATA_RENDER_LIMIT', 5);
2567c15eceSMichael Hamann
2667c15eceSMichael Hamann/** Don't render metadata even if it is outdated or doesn't exist */
2767c15eceSMichael Hamanndefine('METADATA_DONT_RENDER', 0);
2865aa8490SMichael Hamann/**
2965aa8490SMichael Hamann * Render metadata when the page is really newer or the metadata doesn't exist.
3065aa8490SMichael Hamann * Uses just a simple check, but should work pretty well for loading simple
3165aa8490SMichael Hamann * metadata values like the page title and avoids rendering a lot of pages in
3265aa8490SMichael Hamann * one request. The P_GET_METADATA_RENDER_LIMIT is used in this mode.
3365aa8490SMichael Hamann * Use this if it is unlikely that the metadata value you are requesting
3465aa8490SMichael Hamann * does depend e.g. on pages that are included in the current page using
3565aa8490SMichael Hamann * the include plugin (this is very likely the case for the page title, but
3665aa8490SMichael Hamann * not for relation references).
3765aa8490SMichael Hamann */
3867c15eceSMichael Hamanndefine('METADATA_RENDER_USING_SIMPLE_CACHE', 1);
3965aa8490SMichael Hamann/**
4065aa8490SMichael Hamann * Render metadata using the metadata cache logic. The P_GET_METADATA_RENDER_LIMIT
4165aa8490SMichael Hamann * is used in this mode. Use this mode when you are requesting more complex
4265aa8490SMichael Hamann * metadata. Although this will cause rendering more often it might actually have
4365aa8490SMichael Hamann * the effect that less current metadata is returned as it is more likely than in
4465aa8490SMichael Hamann * the simple cache mode that metadata needs to be rendered for all pages at once
4565aa8490SMichael Hamann * which means that when the metadata for the page is requested that actually needs
4665aa8490SMichael Hamann * to be updated the limit might have been reached already.
4765aa8490SMichael Hamann */
4867c15eceSMichael Hamanndefine('METADATA_RENDER_USING_CACHE', 2);
4965aa8490SMichael Hamann/**
5065aa8490SMichael Hamann * Render metadata without limiting the number of pages for which metadata is
5165aa8490SMichael Hamann * rendered. Use this mode with care, normally it should only be used in places
5265aa8490SMichael Hamann * like the indexer or in cli scripts where the execution time normally isn't
5365aa8490SMichael Hamann * limited. This can be combined with the simple cache using
5465aa8490SMichael Hamann * METADATA_RENDER_USING_CACHE | METADATA_RENDER_UNLIMITED.
5565aa8490SMichael Hamann */
5665aa8490SMichael Hamanndefine('METADATA_RENDER_UNLIMITED', 4);
57ff725173SMichael Hamann
58ff725173SMichael Hamann/**
59c112d578Sandi * Returns the parsed Wikitext in XHTML for the given id and revision.
60c112d578Sandi *
61c112d578Sandi * If $excuse is true an explanation is returned if the file
62c112d578Sandi * wasn't found
63c112d578Sandi *
6442ea7f44SGerrit Uitslag * @param string $id page id
6542ea7f44SGerrit Uitslag * @param string|int $rev revision timestamp or empty string
6642ea7f44SGerrit Uitslag * @param bool $excuse
67f50a239bSTakamura * @param string $date_at
68f50a239bSTakamura *
6942ea7f44SGerrit Uitslag * @return null|string
7078b498a7SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
7178b498a7SAndreas Gohr *
72c112d578Sandi */
7378b498a7SAndreas Gohrfunction p_wiki_xhtml($id, $rev = '', $excuse = true, $date_at = '')
7478b498a7SAndreas Gohr{
75c112d578Sandi    $file = wikiFN($id, $rev);
76c112d578Sandi    $ret = '';
77c112d578Sandi
78c112d578Sandi    //ensure $id is in global $ID (needed for parsing)
791e76272cSandi    global $ID;
803ff8773bSAndreas Gohr    $keep = $ID;
811e76272cSandi    $ID = $id;
82c112d578Sandi
835c2eed9aSlisps    if ($rev || $date_at) {
8479e79377SAndreas Gohr        if (file_exists($file)) {
8564159a61SAndreas Gohr            //no caching on old revisions
8664159a61SAndreas Gohr            $ret = p_render('xhtml', p_get_instructions(io_readWikiPage($file, $id, $rev)), $info, $date_at);
87c112d578Sandi        } elseif ($excuse) {
88c112d578Sandi            $ret = p_locale_xhtml('norev');
89c112d578Sandi        }
9024870174SAndreas Gohr    } elseif (file_exists($file)) {
914b5f4f4eSchris        $ret = p_cached_output($file, 'xhtml', $id);
92c112d578Sandi    } elseif ($excuse) {
932eaa0567Speterfromearth        //check if the page once existed
94e1d9dcc8SAndreas Gohr        $changelog = new PageChangeLog($id);
952eaa0567Speterfromearth        if ($changelog->hasRevisions()) {
962eaa0567Speterfromearth            $ret = p_locale_xhtml('onceexisted');
972eaa0567Speterfromearth        } else {
98c112d578Sandi            $ret = p_locale_xhtml('newpage');
99c112d578Sandi        }
100c112d578Sandi    }
101c112d578Sandi
1023ff8773bSAndreas Gohr    //restore ID (just in case)
1033ff8773bSAndreas Gohr    $ID = $keep;
1043ff8773bSAndreas Gohr
105c112d578Sandi    return $ret;
106c112d578Sandi}
107c112d578Sandi
108c112d578Sandi/**
109c112d578Sandi * Returns the specified local text in parsed format
110c112d578Sandi *
11142ea7f44SGerrit Uitslag * @param string $id page id
11242ea7f44SGerrit Uitslag * @return null|string
11378b498a7SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
11478b498a7SAndreas Gohr *
115c112d578Sandi */
11678b498a7SAndreas Gohrfunction p_locale_xhtml($id)
11778b498a7SAndreas Gohr{
118c112d578Sandi    //fetch parsed locale
11965f6b58fSAnna Dabrowska    $data = ['id' => $id, 'html' => ''];
12065f6b58fSAnna Dabrowska
12165f6b58fSAnna Dabrowska    $event = new Event('PARSER_LOCALE_XHTML', $data);
12265f6b58fSAnna Dabrowska    if ($event->advise_before()) {
12365f6b58fSAnna Dabrowska        $data['html'] = p_cached_output(localeFN($data['id']));
12465f6b58fSAnna Dabrowska    }
12565f6b58fSAnna Dabrowska    $event->advise_after();
12665f6b58fSAnna Dabrowska
12765f6b58fSAnna Dabrowska    return $data['html'];
128c112d578Sandi}
129c112d578Sandi
130c112d578Sandi/**
1314b5f4f4eSchris * Returns the given file parsed into the requested output format
1324b5f4f4eSchris *
13342ea7f44SGerrit Uitslag * @param string $file filename, path to file
13442ea7f44SGerrit Uitslag * @param string $format
13542ea7f44SGerrit Uitslag * @param string $id page id
13642ea7f44SGerrit Uitslag * @return null|string
13778b498a7SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
13878b498a7SAndreas Gohr * @author Chris Smith <chris@jalakai.co.uk>
13978b498a7SAndreas Gohr *
1404b5f4f4eSchris */
14178b498a7SAndreas Gohrfunction p_cached_output($file, $format = 'xhtml', $id = '')
14278b498a7SAndreas Gohr{
143c112d578Sandi    global $conf;
144c112d578Sandi
1450db5771eSMichael Große    $cache = new CacheRenderer($id, $file, $format);
1464b5f4f4eSchris    if ($cache->useCache()) {
14785767031SAndreas Gohr        $parsed = $cache->retrieveCache(false);
1487de86af9SGerrit Uitslag        if ($conf['allowdebug'] && $format == 'xhtml') {
1497de86af9SGerrit Uitslag            $parsed .= "\n<!-- cachefile {$cache->cache} used -->\n";
1507de86af9SGerrit Uitslag        }
151c112d578Sandi    } else {
1524b5f4f4eSchris        $parsed = p_render($format, p_cached_instructions($file, false, $id), $info);
153c112d578Sandi
154abca2f79SEduardo Mozart de Oliveira        if (!empty($info['cache']) && $cache->storeCache($parsed)) { // storeCache() attempts to save cachefile
1557de86af9SGerrit Uitslag            if ($conf['allowdebug'] && $format == 'xhtml') {
1567de86af9SGerrit Uitslag                $parsed .= "\n<!-- no cachefile used, but created {$cache->cache} -->\n";
1577de86af9SGerrit Uitslag            }
158c112d578Sandi        } else {
1594b5f4f4eSchris            $cache->removeCache(); //try to delete cachefile
1607de86af9SGerrit Uitslag            if ($conf['allowdebug'] && $format == 'xhtml') {
1617de86af9SGerrit Uitslag                $parsed .= "\n<!-- no cachefile used, caching forbidden -->\n";
1627de86af9SGerrit Uitslag            }
163c112d578Sandi        }
164c112d578Sandi    }
165c112d578Sandi
166c112d578Sandi    return $parsed;
167c112d578Sandi}
168c112d578Sandi
169c112d578Sandi/**
170c112d578Sandi * Returns the render instructions for a file
171c112d578Sandi *
172c112d578Sandi * Uses and creates a serialized cache file
173c112d578Sandi *
17442ea7f44SGerrit Uitslag * @param string $file filename, path to file
17542ea7f44SGerrit Uitslag * @param bool $cacheonly
17642ea7f44SGerrit Uitslag * @param string $id page id
17742ea7f44SGerrit Uitslag * @return array|null
17878b498a7SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
17978b498a7SAndreas Gohr *
180c112d578Sandi */
18178b498a7SAndreas Gohrfunction p_cached_instructions($file, $cacheonly = false, $id = '')
18278b498a7SAndreas Gohr{
18347b2d319SAndreas Gohr    static $run = null;
18478b498a7SAndreas Gohr    if (is_null($run)) $run = [];
185c112d578Sandi
1860db5771eSMichael Große    $cache = new CacheInstructions($id, $file);
187c112d578Sandi
1880d24b616SMichael Hamann    if ($cacheonly || $cache->useCache() || (isset($run[$file]) && !defined('DOKU_UNITTEST'))) {
1894b5f4f4eSchris        return $cache->retrieveCache();
19079e79377SAndreas Gohr    } elseif (file_exists($file)) {
191c112d578Sandi        // no cache - do some work
192bde4e341SGalaxyMaster        $ins = p_get_instructions(io_readWikiPage($file, $id));
193cbaf4259SChris Smith        if ($cache->storeCache($ins)) {
19447b2d319SAndreas Gohr            $run[$file] = true; // we won't rebuild these instructions in the same run again
195cbaf4259SChris Smith        } else {
196cbaf4259SChris Smith            msg('Unable to save cache file. Hint: disk full; file permissions; safe_mode setting.', -1);
197cbaf4259SChris Smith        }
198c112d578Sandi        return $ins;
199c112d578Sandi    }
200c112d578Sandi
2013b3f8916SAndreas Gohr    return null;
202c112d578Sandi}
203c112d578Sandi
204c112d578Sandi/**
205c112d578Sandi * turns a page into a list of instructions
206c112d578Sandi *
20778b498a7SAndreas Gohr * @param string $text raw wiki syntax text
20878b498a7SAndreas Gohr * @return array a list of instruction arrays
209c112d578Sandi * @author Harry Fuecks <hfuecks@gmail.com>
210c112d578Sandi * @author Andreas Gohr <andi@splitbrain.org>
21142ea7f44SGerrit Uitslag *
212c112d578Sandi */
21378b498a7SAndreas Gohrfunction p_get_instructions($text)
21478b498a7SAndreas Gohr{
215c112d578Sandi
216*c8dd1b9dSAndreas Gohr    $modes = ModeRegistry::getInstance()->getModes();
217ee20e7d1Sandi
21847f73ecfSAndreas Gohr    // Create the parser and handler
219d4d8fb18SAndreas Gohr    $Parser = new Parser(new Doku_Handler());
220c112d578Sandi
221107b01d6Sandi    //add modes to parser
222107b01d6Sandi    foreach ($modes as $mode) {
223107b01d6Sandi        $Parser->addMode($mode['mode'], $mode['obj']);
224c112d578Sandi    }
225c112d578Sandi
226c112d578Sandi    // Do the parsing
227cbb44eabSAndreas Gohr    Event::createAndTrigger('PARSER_WIKITEXT_PREPROCESS', $text);
22878b498a7SAndreas Gohr    return $Parser->parse($text);
229c112d578Sandi}
230c112d578Sandi
231c112d578Sandi/**
23239a89382SEsther Brunner * returns the metadata of a page
23339a89382SEsther Brunner *
2344a819402SMichael Hamann * @param string $id The id of the page the metadata should be returned from
23564159a61SAndreas Gohr * @param string $key The key of the metdata value that shall be read (by default everything)
23664159a61SAndreas Gohr *                        separate hierarchies by " " like "date created"
23767c15eceSMichael Hamann * @param int $render If the page should be rendererd - possible values:
23865aa8490SMichael Hamann *     METADATA_DONT_RENDER, METADATA_RENDER_USING_SIMPLE_CACHE, METADATA_RENDER_USING_CACHE
23965aa8490SMichael Hamann *     METADATA_RENDER_UNLIMITED (also combined with the previous two options),
24065aa8490SMichael Hamann *     default: METADATA_RENDER_USING_CACHE
2414a819402SMichael Hamann * @return mixed The requested metadata fields
2424a819402SMichael Hamann *
24339a89382SEsther Brunner * @author Esther Brunner <esther@kaffeehaus.ch>
24498214867SMichael Hamann * @author Michael Hamann <michael@content-space.de>
24539a89382SEsther Brunner */
24678b498a7SAndreas Gohrfunction p_get_metadata($id, $key = '', $render = METADATA_RENDER_USING_CACHE)
24778b498a7SAndreas Gohr{
2481172f8dcSAdrian Lang    global $ID;
24965aa8490SMichael Hamann    static $render_count = 0;
25065aa8490SMichael Hamann    // track pages that have already been rendered in order to avoid rendering the same page
25165aa8490SMichael Hamann    // again
25278b498a7SAndreas Gohr    static $rendered_pages = [];
2536afe8dcaSchris
2540a7e3bceSchris    // cache the current page
2550a7e3bceSchris    // Benchmarking shows the current page's metadata is generally the only page metadata
2560a7e3bceSchris    // accessed several times. This may catch a few other pages, but that shouldn't be an issue.
2570a7e3bceSchris    $cache = ($ID == $id);
2580a7e3bceSchris    $meta = p_read_metadata($id, $cache);
25939a89382SEsther Brunner
26067c15eceSMichael Hamann    if (!is_numeric($render)) {
26167c15eceSMichael Hamann        if ($render) {
26267c15eceSMichael Hamann            $render = METADATA_RENDER_USING_SIMPLE_CACHE;
26367c15eceSMichael Hamann        } else {
26467c15eceSMichael Hamann            $render = METADATA_DONT_RENDER;
26567c15eceSMichael Hamann        }
26667c15eceSMichael Hamann    }
26767c15eceSMichael Hamann
26898214867SMichael Hamann    // prevent recursive calls in the cache
26998214867SMichael Hamann    static $recursion = false;
27065aa8490SMichael Hamann    if (!$recursion && $render != METADATA_DONT_RENDER && !isset($rendered_pages[$id]) && page_exists($id)) {
27198214867SMichael Hamann        $recursion = true;
27298214867SMichael Hamann
2730db5771eSMichael Große        $cachefile = new CacheRenderer($id, wikiFN($id), 'metadata');
27498214867SMichael Hamann
27567c15eceSMichael Hamann        $do_render = false;
27665aa8490SMichael Hamann        if ($render & METADATA_RENDER_UNLIMITED || $render_count < P_GET_METADATA_RENDER_LIMIT) {
27765aa8490SMichael Hamann            if ($render & METADATA_RENDER_USING_SIMPLE_CACHE) {
27867c15eceSMichael Hamann                $pagefn = wikiFN($id);
27967c15eceSMichael Hamann                $metafn = metaFN($id, '.meta');
28079e79377SAndreas Gohr                if (!file_exists($metafn) || @filemtime($pagefn) > @filemtime($cachefile->cache)) {
28167c15eceSMichael Hamann                    $do_render = true;
28267c15eceSMichael Hamann                }
28367c15eceSMichael Hamann            } elseif (!$cachefile->useCache()) {
28467c15eceSMichael Hamann                $do_render = true;
28567c15eceSMichael Hamann            }
28665aa8490SMichael Hamann        }
28767c15eceSMichael Hamann        if ($do_render) {
2880d24b616SMichael Hamann            if (!defined('DOKU_UNITTEST')) {
28965aa8490SMichael Hamann                ++$render_count;
29065aa8490SMichael Hamann                $rendered_pages[$id] = true;
2910d24b616SMichael Hamann            }
29269ba640bSMichael Hamann            $old_meta = $meta;
29339a89382SEsther Brunner            $meta = p_render_metadata($id, $meta);
29469ba640bSMichael Hamann            // only update the file when the metadata has been changed
29569ba640bSMichael Hamann            if ($meta == $old_meta || p_save_metadata($id, $meta)) {
29698214867SMichael Hamann                // store a timestamp in order to make sure that the cachefile is touched
2973d6feb16SMichael Hamann                // this timestamp is also stored when the meta data is still the same
29898214867SMichael Hamann                $cachefile->storeCache(time());
2993d6feb16SMichael Hamann            } else {
30098214867SMichael Hamann                msg('Unable to save metadata file. Hint: disk full; file permissions; safe_mode setting.', -1);
30198214867SMichael Hamann            }
30298214867SMichael Hamann        }
30398214867SMichael Hamann
30498214867SMichael Hamann        $recursion = false;
3056afe8dcaSchris    }
30639a89382SEsther Brunner
307fa1a0dc6STB Maulana Aghni    $val = $meta['current'] ?? null;
308ebf65d37SAdrian Lang
30939a89382SEsther Brunner    // filter by $key
310569a0019SAdrian Lang    foreach (preg_split('/\s+/', $key, 2, PREG_SPLIT_NO_EMPTY) as $cur_key) {
311ebf65d37SAdrian Lang        if (!isset($val[$cur_key])) {
312ebf65d37SAdrian Lang            return null;
31366d29756SChris Smith        }
314ebf65d37SAdrian Lang        $val = $val[$cur_key];
31539a89382SEsther Brunner    }
316ebf65d37SAdrian Lang    return $val;
31739a89382SEsther Brunner}
31839a89382SEsther Brunner
31939a89382SEsther Brunner/**
32039a89382SEsther Brunner * sets metadata elements of a page
32139a89382SEsther Brunner *
322a365baeeSDominik Eckelmann * @see http://www.dokuwiki.org/devel:metadata#functions_to_get_and_set_metadata
323a365baeeSDominik Eckelmann *
324e1d9dcc8SAndreas Gohr * @param string $id is the ID of a wiki page
325e1d9dcc8SAndreas Gohr * @param array $data is an array with key ⇒ value pairs to be set in the metadata
326e1d9dcc8SAndreas Gohr * @param boolean $render whether or not the page metadata should be generated with the renderer
327e1d9dcc8SAndreas Gohr * @param boolean $persistent indicates whether or not the particular metadata value will persist through
328a365baeeSDominik Eckelmann *                            the next metadata rendering.
329a365baeeSDominik Eckelmann * @return boolean true on success
330a365baeeSDominik Eckelmann *
33139a89382SEsther Brunner * @author Esther Brunner <esther@kaffeehaus.ch>
3320e5fde48SMichael Hamann * @author Michael Hamann <michael@content-space.de>
33339a89382SEsther Brunner */
33478b498a7SAndreas Gohrfunction p_set_metadata($id, $data, $render = false, $persistent = true)
33578b498a7SAndreas Gohr{
33639a89382SEsther Brunner    if (!is_array($data)) return false;
33739a89382SEsther Brunner
3380e5fde48SMichael Hamann    global $ID, $METADATA_RENDERERS;
3390a7e3bceSchris
3400e5fde48SMichael Hamann    // if there is currently a renderer change the data in the renderer instead
3410e5fde48SMichael Hamann    if (isset($METADATA_RENDERERS[$id])) {
3420e5fde48SMichael Hamann        $orig =& $METADATA_RENDERERS[$id];
3430e5fde48SMichael Hamann        $meta = $orig;
3440e5fde48SMichael Hamann    } else {
3450a7e3bceSchris        // cache the current page
3460a7e3bceSchris        $cache = ($ID == $id);
3470a7e3bceSchris        $orig = p_read_metadata($id, $cache);
34839a89382SEsther Brunner
34939a89382SEsther Brunner        // render metadata first?
3500a7e3bceSchris        $meta = $render ? p_render_metadata($id, $orig) : $orig;
3510e5fde48SMichael Hamann    }
35239a89382SEsther Brunner
35339a89382SEsther Brunner    // now add the passed metadata
35478b498a7SAndreas Gohr    $protected = ['description', 'date', 'contributor'];
35539a89382SEsther Brunner    foreach ($data as $key => $value) {
35639a89382SEsther Brunner        // be careful with sub-arrays of $meta['relation']
35739a89382SEsther Brunner        if ($key == 'relation') {
35839a89382SEsther Brunner            foreach ($value as $subkey => $subvalue) {
35931b10b49SMichael Hamann                if (isset($meta['current'][$key][$subkey]) && is_array($meta['current'][$key][$subkey])) {
3602d102494SPhy                    $meta['current'][$key][$subkey] = array_replace($meta['current'][$key][$subkey], (array)$subvalue);
36131b10b49SMichael Hamann                } else {
36231b10b49SMichael Hamann                    $meta['current'][$key][$subkey] = $subvalue;
36331b10b49SMichael Hamann                }
36431b10b49SMichael Hamann                if ($persistent) {
36531b10b49SMichael Hamann                    if (isset($meta['persistent'][$key][$subkey]) && is_array($meta['persistent'][$key][$subkey])) {
36664159a61SAndreas Gohr                        $meta['persistent'][$key][$subkey] = array_replace(
36764159a61SAndreas Gohr                            $meta['persistent'][$key][$subkey],
36864159a61SAndreas Gohr                            (array)$subvalue
36964159a61SAndreas Gohr                        );
37031b10b49SMichael Hamann                    } else {
37131b10b49SMichael Hamann                        $meta['persistent'][$key][$subkey] = $subvalue;
37231b10b49SMichael Hamann                    }
37331b10b49SMichael Hamann                }
37439a89382SEsther Brunner            }
37539a89382SEsther Brunner
37639a89382SEsther Brunner            // be careful with some senisitive arrays of $meta
377743a6908Ssplitbrain        } elseif (in_array($key, $protected, true)) {
37866d29756SChris Smith            // these keys, must have subkeys - a legitimate value must be an array
37939a89382SEsther Brunner            if (is_array($value)) {
38024870174SAndreas Gohr                $meta['current'][$key] = empty($meta['current'][$key]) ?
38124870174SAndreas Gohr                    $value :
38224870174SAndreas Gohr                    array_replace((array)$meta['current'][$key], $value);
3830a7e3bceSchris
3840a7e3bceSchris                if ($persistent) {
38524870174SAndreas Gohr                    $meta['persistent'][$key] = empty($meta['persistent'][$key]) ?
38624870174SAndreas Gohr                        $value :
38724870174SAndreas Gohr                        array_replace((array)$meta['persistent'][$key], $value);
3880a7e3bceSchris                }
38939a89382SEsther Brunner            }
39039a89382SEsther Brunner
39139a89382SEsther Brunner            // no special treatment for the rest
39239a89382SEsther Brunner        } else {
3930a7e3bceSchris            $meta['current'][$key] = $value;
3940a7e3bceSchris            if ($persistent) $meta['persistent'][$key] = $value;
39539a89382SEsther Brunner        }
39639a89382SEsther Brunner    }
39739a89382SEsther Brunner
39839a89382SEsther Brunner    // save only if metadata changed
39939a89382SEsther Brunner    if ($meta == $orig) return true;
4006afe8dcaSchris
4010e5fde48SMichael Hamann    if (isset($METADATA_RENDERERS[$id])) {
4020e5fde48SMichael Hamann        // set both keys individually as the renderer has references to the individual keys
4030e5fde48SMichael Hamann        $METADATA_RENDERERS[$id]['current'] = $meta['current'];
4040e5fde48SMichael Hamann        $METADATA_RENDERERS[$id]['persistent'] = $meta['persistent'];
4051c56be7bSMichael Hamann        return true;
4060e5fde48SMichael Hamann    } else {
4071172f8dcSAdrian Lang        return p_save_metadata($id, $meta);
40839a89382SEsther Brunner    }
4090e5fde48SMichael Hamann}
41039a89382SEsther Brunner
41139a89382SEsther Brunner/**
4123d1f9ec3SMichael Klier * Purges the non-persistant part of the meta data
4133d1f9ec3SMichael Klier * used on page deletion
4143d1f9ec3SMichael Klier *
41542ea7f44SGerrit Uitslag * @param string $id page id
41642ea7f44SGerrit Uitslag * @return bool  success / fail
41778b498a7SAndreas Gohr * @author Michael Klier <chi@chimeric.de>
41878b498a7SAndreas Gohr *
4193d1f9ec3SMichael Klier */
42078b498a7SAndreas Gohrfunction p_purge_metadata($id)
42178b498a7SAndreas Gohr{
4223d1f9ec3SMichael Klier    $meta = p_read_metadata($id);
4233d1f9ec3SMichael Klier    foreach ($meta['current'] as $key => $value) {
424056bf31fSDamien Regad        if (isset($meta[$key]) && is_array($meta[$key])) {
42578b498a7SAndreas Gohr            $meta['current'][$key] = [];
4263d1f9ec3SMichael Klier        } else {
4273d1f9ec3SMichael Klier            $meta['current'][$key] = '';
4283d1f9ec3SMichael Klier        }
4293d1f9ec3SMichael Klier    }
4301172f8dcSAdrian Lang    return p_save_metadata($id, $meta);
4313d1f9ec3SMichael Klier}
4323d1f9ec3SMichael Klier
4333d1f9ec3SMichael Klier/**
4340a7e3bceSchris * read the metadata from source/cache for $id
4350a7e3bceSchris * (internal use only - called by p_get_metadata & p_set_metadata)
4360a7e3bceSchris *
4370a7e3bceSchris * @param string $id absolute wiki page id
4380a7e3bceSchris * @param bool $cache whether or not to cache metadata in memory
4390a7e3bceSchris *                             (only use for metadata likely to be accessed several times)
4400a7e3bceSchris *
4410a7e3bceSchris * @return   array             metadata
44278b498a7SAndreas Gohr * @author   Christopher Smith <chris@jalakai.co.uk>
44378b498a7SAndreas Gohr *
4440a7e3bceSchris */
44578b498a7SAndreas Gohrfunction p_read_metadata($id, $cache = false)
44678b498a7SAndreas Gohr{
4470a7e3bceSchris    global $cache_metadata;
4480a7e3bceSchris
4493a50618cSgweissbach    if (isset($cache_metadata[(string)$id])) return $cache_metadata[(string)$id];
4500a7e3bceSchris
4510a7e3bceSchris    $file = metaFN($id, '.meta');
45264159a61SAndreas Gohr    $meta = file_exists($file) ?
45364159a61SAndreas Gohr        unserialize(io_readFile($file, false)) :
45478b498a7SAndreas Gohr        ['current' => [], 'persistent' => []];
4550a7e3bceSchris
4560a7e3bceSchris    if ($cache) {
4573a50618cSgweissbach        $cache_metadata[(string)$id] = $meta;
4580a7e3bceSchris    }
4590a7e3bceSchris
4600a7e3bceSchris    return $meta;
4610a7e3bceSchris}
4620a7e3bceSchris
4630a7e3bceSchris/**
4641172f8dcSAdrian Lang * This is the backend function to save a metadata array to a file
4651172f8dcSAdrian Lang *
4661172f8dcSAdrian Lang * @param string $id absolute wiki page id
4671172f8dcSAdrian Lang * @param array $meta metadata
4681172f8dcSAdrian Lang *
4691172f8dcSAdrian Lang * @return   bool              success / fail
4701172f8dcSAdrian Lang */
47178b498a7SAndreas Gohrfunction p_save_metadata($id, $meta)
47278b498a7SAndreas Gohr{
4731172f8dcSAdrian Lang    // sync cached copies, including $INFO metadata
4741172f8dcSAdrian Lang    global $cache_metadata, $INFO;
4751172f8dcSAdrian Lang
4761172f8dcSAdrian Lang    if (isset($cache_metadata[$id])) $cache_metadata[$id] = $meta;
477056bf31fSDamien Regad    if (!empty($INFO) && isset($INFO['id']) && ($id == $INFO['id'])) {
478056bf31fSDamien Regad        $INFO['meta'] = $meta['current'];
479056bf31fSDamien Regad    }
4801172f8dcSAdrian Lang
4811172f8dcSAdrian Lang    return io_saveFile(metaFN($id, '.meta'), serialize($meta));
4821172f8dcSAdrian Lang}
4831172f8dcSAdrian Lang
4841172f8dcSAdrian Lang/**
48539a89382SEsther Brunner * renders the metadata of a page
48639a89382SEsther Brunner *
48742ea7f44SGerrit Uitslag * @param string $id page id
48842ea7f44SGerrit Uitslag * @param array $orig the original metadata
48942ea7f44SGerrit Uitslag * @return array|null array('current'=> array,'persistent'=> array);
49078b498a7SAndreas Gohr * @author Esther Brunner <esther@kaffeehaus.ch>
49178b498a7SAndreas Gohr *
49239a89382SEsther Brunner */
49378b498a7SAndreas Gohrfunction p_render_metadata($id, $orig)
49478b498a7SAndreas Gohr{
49548924015SAndreas Gohr    // make sure the correct ID is in global ID
4960e5fde48SMichael Hamann    global $ID, $METADATA_RENDERERS;
4970e5fde48SMichael Hamann
4980e5fde48SMichael Hamann    // avoid recursive rendering processes for the same id
4995b76ad91SChristopher Smith    if (isset($METADATA_RENDERERS[$id])) {
5000e5fde48SMichael Hamann        return $orig;
5015b76ad91SChristopher Smith    }
5020e5fde48SMichael Hamann
5030e5fde48SMichael Hamann    // store the original metadata in the global $METADATA_RENDERERS so p_set_metadata can use it
5040e5fde48SMichael Hamann    $METADATA_RENDERERS[$id] =& $orig;
5050e5fde48SMichael Hamann
50648924015SAndreas Gohr    $keep = $ID;
50748924015SAndreas Gohr    $ID = $id;
50848924015SAndreas Gohr
5090a7e3bceSchris    // add an extra key for the event - to tell event handlers the page whose metadata this is
5100a7e3bceSchris    $orig['page'] = $id;
511e1d9dcc8SAndreas Gohr    $evt = new Event('PARSER_METADATA_RENDER', $orig);
5120a7e3bceSchris    if ($evt->advise_before()) {
51339a89382SEsther Brunner        // get instructions
5144b5f4f4eSchris        $instructions = p_cached_instructions(wikiFN($id), false, $id);
51548924015SAndreas Gohr        if (is_null($instructions)) {
51648924015SAndreas Gohr            $ID = $keep;
5170e5fde48SMichael Hamann            unset($METADATA_RENDERERS[$id]);
51848924015SAndreas Gohr            return null; // something went wrong with the instructions
51948924015SAndreas Gohr        }
52039a89382SEsther Brunner
52139a89382SEsther Brunner        // set up the renderer
52267f9913dSAndreas Gohr        $renderer = new Doku_Renderer_metadata();
5230e5fde48SMichael Hamann        $renderer->meta =& $orig['current'];
5240e5fde48SMichael Hamann        $renderer->persistent =& $orig['persistent'];
52539a89382SEsther Brunner
52639a89382SEsther Brunner        // loop through the instructions
52739a89382SEsther Brunner        foreach ($instructions as $instruction) {
52839a89382SEsther Brunner            // execute the callback against the renderer
52978b498a7SAndreas Gohr            call_user_func_array([&$renderer, $instruction[0]], (array)$instruction[1]);
53039a89382SEsther Brunner        }
53139a89382SEsther Brunner
53278b498a7SAndreas Gohr        $evt->result = ['current' => &$renderer->meta, 'persistent' => &$renderer->persistent];
5330a7e3bceSchris    }
5340a7e3bceSchris    $evt->advise_after();
5350a7e3bceSchris
5360e5fde48SMichael Hamann    // clean up
53748924015SAndreas Gohr    $ID = $keep;
5380e5fde48SMichael Hamann    unset($METADATA_RENDERERS[$id]);
5390a7e3bceSchris    return $evt->result;
54039a89382SEsther Brunner}
54139a89382SEsther Brunner
54239a89382SEsther Brunner/**
543ac83b9d8Sandi * Renders a list of instruction to the specified output mode
544c112d578Sandi *
5457a8cc57eSElan Ruusamäe * In the $info array is information from the renderer returned
5469dc2c2afSandi *
54742ea7f44SGerrit Uitslag * @param string $mode
548e3710957SGerrit Uitslag * @param array|null|false $instructions
54942ea7f44SGerrit Uitslag * @param array $info returns render info like enabled toc and cache
5507de86af9SGerrit Uitslag * @param string $date_at
55142ea7f44SGerrit Uitslag * @return null|string rendered output
55278b498a7SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
55378b498a7SAndreas Gohr *
55478b498a7SAndreas Gohr * @author Harry Fuecks <hfuecks@gmail.com>
555c112d578Sandi */
55678b498a7SAndreas Gohrfunction p_render($mode, $instructions, &$info, $date_at = '')
55778b498a7SAndreas Gohr{
558c112d578Sandi    if (is_null($instructions)) return '';
559e3710957SGerrit Uitslag    if ($instructions === false) return '';
560c112d578Sandi
561252398f0SChristopher Smith    $Renderer = p_get_renderer($mode);
562d968d3e5SChris Smith    if (is_null($Renderer)) return null;
563c327d6c4SAndreas Gohr
564d968d3e5SChris Smith    $Renderer->reset();
565c112d578Sandi
5665c2eed9aSlisps    if ($date_at) {
5675c2eed9aSlisps        $Renderer->date_at = $date_at;
5685c2eed9aSlisps    }
5695c2eed9aSlisps
570c112d578Sandi    $Renderer->smileys = getSmileys();
571c112d578Sandi    $Renderer->entities = getEntities();
572c112d578Sandi    $Renderer->acronyms = getAcronyms();
573c112d578Sandi    $Renderer->interwiki = getInterwiki();
574c112d578Sandi
575c112d578Sandi    // Loop through the instructions
576c112d578Sandi    foreach ($instructions as $instruction) {
577c112d578Sandi        // Execute the callback against the Renderer
5787c62086bSAndreas Gohr        if (method_exists($Renderer, $instruction[0])) {
57978b498a7SAndreas Gohr            call_user_func_array([&$Renderer, $instruction[0]], $instruction[1] ?: []);
580c112d578Sandi        }
5817c62086bSAndreas Gohr    }
5829dc2c2afSandi
5839dc2c2afSandi    //set info array
5849dc2c2afSandi    $info = $Renderer->info;
5859dc2c2afSandi
586677844afSchris    // Post process and return the output
58778b498a7SAndreas Gohr    $data = [$mode, & $Renderer->doc];
588cbb44eabSAndreas Gohr    Event::createAndTrigger('RENDERER_CONTENT_POSTPROCESS', $data);
589c112d578Sandi    return $Renderer->doc;
590c112d578Sandi}
591c112d578Sandi
592e3ab6fc5SMichael Hamann/**
593548d801fSChristopher Smith * Figure out the correct renderer class to use for $mode,
594548d801fSChristopher Smith * instantiate and return it
595548d801fSChristopher Smith *
5967e8500eeSGerrit Uitslag * @param string $mode Mode of the renderer to get
597e3ab6fc5SMichael Hamann * @return null|Doku_Renderer The renderer
598548d801fSChristopher Smith *
599548d801fSChristopher Smith * @author Christopher Smith <chris@jalakai.co.uk>
600e3ab6fc5SMichael Hamann */
60178b498a7SAndreas Gohrfunction p_get_renderer($mode)
60278b498a7SAndreas Gohr{
6033a7140a1SAndreas Gohr    /** @var PluginController $plugin_controller */
6047aea91afSChris Smith    global $conf, $plugin_controller;
605d968d3e5SChris Smith
60624870174SAndreas Gohr    $rname = empty($conf['renderer_' . $mode]) ? $mode : $conf['renderer_' . $mode];
6070cacf91fSLucas    $rclass = "Doku_Renderer_$rname";
6080cacf91fSLucas
609548d801fSChristopher Smith    // if requested earlier or a bundled renderer
6100cacf91fSLucas    if (class_exists($rclass)) {
61178b498a7SAndreas Gohr        return new $rclass();
6120cacf91fSLucas    }
613d968d3e5SChris Smith
6146e6d16edSChristopher Smith    // not bundled, see if its an enabled renderer plugin & when $mode is 'xhtml', the renderer can supply that format.
6150440ca46SGerrit Uitslag    /** @var Doku_Renderer $Renderer */
61611ac6abdSChristopher Smith    $Renderer = $plugin_controller->load('renderer', $rname);
6176e6d16edSChristopher Smith    if ($Renderer && is_a($Renderer, 'Doku_Renderer') && ($mode != 'xhtml' || $mode == $Renderer->getFormat())) {
61811ac6abdSChristopher Smith        return $Renderer;
61911ac6abdSChristopher Smith    }
620d968d3e5SChris Smith
62111ac6abdSChristopher Smith    // there is a configuration error!
622548d801fSChristopher Smith    // not bundled, not a valid enabled plugin, use $mode to try to fallback to a bundled renderer
62311ac6abdSChristopher Smith    $rclass = "Doku_Renderer_$mode";
624548d801fSChristopher Smith    if (class_exists($rclass)) {
62511ac6abdSChristopher Smith        // viewers should see renderered output, so restrict the warning to admins only
62611ac6abdSChristopher Smith        $msg = "No renderer '$rname' found for mode '$mode', check your plugins";
62711ac6abdSChristopher Smith        if ($mode == 'xhtml') {
62811ac6abdSChristopher Smith            $msg .= " and the 'renderer_xhtml' config setting";
62911ac6abdSChristopher Smith        }
63011ac6abdSChristopher Smith        $msg .= ".<br/>Attempting to fallback to the bundled renderer.";
631548d801fSChristopher Smith        msg($msg, -1, '', '', MSG_ADMINS_ONLY);
63211ac6abdSChristopher Smith
63373022918SAndreas Gohr        $Renderer = new $rclass();
634548d801fSChristopher Smith        $Renderer->nocache();     // fallback only (and may include admin alerts), don't cache
635d968d3e5SChris Smith        return $Renderer;
636d968d3e5SChris Smith    }
637d968d3e5SChris Smith
638548d801fSChristopher Smith    // fallback failed, alert the world
639548d801fSChristopher Smith    msg("No renderer '$rname' found for mode '$mode'", -1);
640548d801fSChristopher Smith    return null;
641548d801fSChristopher Smith}
642548d801fSChristopher Smith
643bb0a59d4Sjan/**
644bb0a59d4Sjan * Gets the first heading from a file
645bb0a59d4Sjan *
646fc18c0fbSchris * @param string $id dokuwiki page id
64767c15eceSMichael Hamann * @param int $render rerender if first heading not known
64867c15eceSMichael Hamann *                             default: METADATA_RENDER_USING_SIMPLE_CACHE
64967c15eceSMichael Hamann *                             Possible values: METADATA_DONT_RENDER,
65067c15eceSMichael Hamann *                                              METADATA_RENDER_USING_SIMPLE_CACHE,
65165aa8490SMichael Hamann *                                              METADATA_RENDER_USING_CACHE,
65265aa8490SMichael Hamann *                                              METADATA_RENDER_UNLIMITED
653e3ab6fc5SMichael Hamann * @return string|null The first heading
65442ea7f44SGerrit Uitslag *
65595dbfe57SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
656bf0c93c2SMichael Hamann * @author Michael Hamann <michael@content-space.de>
657bb0a59d4Sjan */
65878b498a7SAndreas Gohrfunction p_get_first_heading($id, $render = METADATA_RENDER_USING_SIMPLE_CACHE)
65978b498a7SAndreas Gohr{
66065aa8490SMichael Hamann    return p_get_metadata(cleanID($id), 'title', $render);
661bb0a59d4Sjan}
662bb0a59d4Sjan
6638f7d700cSchris/**
6648f7d700cSchris * Wrapper for GeSHi Code Highlighter, provides caching of its output
6658f7d700cSchris *
6665d568b99SChris Smith * @param string $code source code to be highlighted
6675d568b99SChris Smith * @param string $language language to provide highlighting
6685d568b99SChris Smith * @param string $wrapper html element to wrap the returned highlighted text
669e3ab6fc5SMichael Hamann * @return string xhtml code
67042ea7f44SGerrit Uitslag *
6718f7d700cSchris * @author Christopher Smith <chris@jalakai.co.uk>
67235fbe9efSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
6738f7d700cSchris */
67499a0b426SAndreas Gohrfunction p_xhtml_cached_geshi($code, $language, $wrapper = 'pre', ?array $options = null)
67578b498a7SAndreas Gohr{
676ff1769deSAndreas Gohr    global $conf, $config_cascade, $INPUT;
67735fbe9efSAndreas Gohr    $language = strtolower($language);
6785d568b99SChris Smith
6795d568b99SChris Smith    // remove any leading or trailing blank lines
6805d568b99SChris Smith    $code = preg_replace('/^\s*?\n|\s*?\n$/', '', $code);
6815d568b99SChris Smith
682e2d88156SLarsDW223    $optionsmd5 = md5(serialize($options));
683e2d88156SLarsDW223    $cache = getCacheName($language . $code . $optionsmd5, ".code");
68435fbe9efSAndreas Gohr    $ctime = @filemtime($cache);
6857d34963bSAndreas Gohr    if (
6867d34963bSAndreas Gohr        $ctime && !$INPUT->bool('purge') &&
68741d51802SAndreas Gohr        $ctime > filemtime(DOKU_INC . 'vendor/composer/installed.json') &&  // libraries changed
6887d34963bSAndreas Gohr        $ctime > filemtime(reset($config_cascade['main']['default']))
6897d34963bSAndreas Gohr    ) { // dokuwiki changed
6908f7d700cSchris        $highlighted_code = io_readFile($cache, false);
6918f7d700cSchris    } else {
69241d51802SAndreas Gohr        $geshi = new GeSHi($code, $language);
6938f7d700cSchris        $geshi->set_encoding('utf-8');
6948f7d700cSchris        $geshi->enable_classes();
6958f7d700cSchris        $geshi->set_header_type(GESHI_HEADER_PRE);
6968f7d700cSchris        $geshi->set_link_target($conf['target']['extern']);
697e2d88156SLarsDW223        if ($options !== null) {
698e2d88156SLarsDW223            foreach ($options as $function => $params) {
69978b498a7SAndreas Gohr                if (is_callable([$geshi, $function])) {
700e2d88156SLarsDW223                    $geshi->$function($params);
701e2d88156SLarsDW223                }
702e2d88156SLarsDW223            }
703e2d88156SLarsDW223        }
7048f7d700cSchris
7055d568b99SChris Smith        // remove GeSHi's wrapper element (we'll replace it with our own later)
7065d568b99SChris Smith        // we need to use a GeSHi wrapper to avoid <BR> throughout the highlighted text
70769ddc332SAnika Henke        $highlighted_code = trim(preg_replace('!^<pre[^>]*>|</pre>$!', '', $geshi->parse_code()), "\n\r");
7088f7d700cSchris        io_saveFile($cache, $highlighted_code);
7098f7d700cSchris    }
7108f7d700cSchris
7115d568b99SChris Smith    // add a wrapper element if required
7125d568b99SChris Smith    if ($wrapper) {
7135d568b99SChris Smith        return "<$wrapper class=\"code $language\">$highlighted_code</$wrapper>";
7145d568b99SChris Smith    } else {
7158f7d700cSchris        return $highlighted_code;
7168f7d700cSchris    }
7175d568b99SChris Smith}
718