xref: /dokuwiki/inc/parserutils.php (revision 47a02a102092be9e1e6f1ddaf158bdfffdb13d4f)
1<?php
2
3/**
4 * Utilities for accessing the parser
5 *
6 * @license    GPL 2 (http://www.gnu.org/licenses/gpl.html)
7 * @author     Harry Fuecks <hfuecks@gmail.com>
8 * @author     Andreas Gohr <andi@splitbrain.org>
9 */
10
11use dokuwiki\Cache\CacheInstructions;
12use dokuwiki\Cache\CacheRenderer;
13use dokuwiki\ChangeLog\PageChangeLog;
14use dokuwiki\Extension\PluginController;
15use dokuwiki\Extension\Event;
16use dokuwiki\Parsing\Handler;
17use dokuwiki\Parsing\ModeRegistry;
18use dokuwiki\Parsing\Parser;
19
20/**
21 * How many pages shall be rendered for getting metadata during one request
22 * at maximum? Note that this limit isn't respected when METADATA_RENDER_UNLIMITED
23 * is passed as render parameter to p_get_metadata.
24 */
25if (!defined('P_GET_METADATA_RENDER_LIMIT')) define('P_GET_METADATA_RENDER_LIMIT', 5);
26
27/** Don't render metadata even if it is outdated or doesn't exist */
28define('METADATA_DONT_RENDER', 0);
29/**
30 * Render metadata when the page is really newer or the metadata doesn't exist.
31 * Uses just a simple check, but should work pretty well for loading simple
32 * metadata values like the page title and avoids rendering a lot of pages in
33 * one request. The P_GET_METADATA_RENDER_LIMIT is used in this mode.
34 * Use this if it is unlikely that the metadata value you are requesting
35 * does depend e.g. on pages that are included in the current page using
36 * the include plugin (this is very likely the case for the page title, but
37 * not for relation references).
38 */
39define('METADATA_RENDER_USING_SIMPLE_CACHE', 1);
40/**
41 * Render metadata using the metadata cache logic. The P_GET_METADATA_RENDER_LIMIT
42 * is used in this mode. Use this mode when you are requesting more complex
43 * metadata. Although this will cause rendering more often it might actually have
44 * the effect that less current metadata is returned as it is more likely than in
45 * the simple cache mode that metadata needs to be rendered for all pages at once
46 * which means that when the metadata for the page is requested that actually needs
47 * to be updated the limit might have been reached already.
48 */
49define('METADATA_RENDER_USING_CACHE', 2);
50/**
51 * Render metadata without limiting the number of pages for which metadata is
52 * rendered. Use this mode with care, normally it should only be used in places
53 * like the indexer or in cli scripts where the execution time normally isn't
54 * limited. This can be combined with the simple cache using
55 * METADATA_RENDER_USING_CACHE | METADATA_RENDER_UNLIMITED.
56 */
57define('METADATA_RENDER_UNLIMITED', 4);
58
59/**
60 * Returns the parsed Wikitext in XHTML for the given id and revision.
61 *
62 * If $excuse is true an explanation is returned if the file
63 * wasn't found
64 *
65 * @param string $id page id
66 * @param string|int $rev revision timestamp or empty string
67 * @param bool $excuse
68 * @param string $date_at
69 *
70 * @return null|string
71 * @author Andreas Gohr <andi@splitbrain.org>
72 *
73 */
74function p_wiki_xhtml($id, $rev = '', $excuse = true, $date_at = '')
75{
76    $file = wikiFN($id, $rev);
77    $ret = '';
78
79    //ensure $id is in global $ID (needed for parsing)
80    global $ID;
81    $keep = $ID;
82    $ID = $id;
83
84    if ($rev || $date_at) {
85        if (file_exists($file)) {
86            //no caching on old revisions
87            $ret = p_render('xhtml', p_get_instructions(io_readWikiPage($file, $id, $rev)), $info, $date_at);
88        } elseif ($excuse) {
89            $ret = p_locale_xhtml('norev');
90        }
91    } elseif (file_exists($file)) {
92        $ret = p_cached_output($file, 'xhtml', $id);
93    } elseif ($excuse) {
94        //check if the page once existed
95        $changelog = new PageChangeLog($id);
96        if ($changelog->hasRevisions()) {
97            $ret = p_locale_xhtml('onceexisted');
98        } else {
99            $ret = p_locale_xhtml('newpage');
100        }
101    }
102
103    //restore ID (just in case)
104    $ID = $keep;
105
106    return $ret;
107}
108
109/**
110 * Returns the specified local text in parsed format
111 *
112 * @param string $id page id
113 * @return null|string
114 * @author Andreas Gohr <andi@splitbrain.org>
115 *
116 */
117function p_locale_xhtml($id)
118{
119    //fetch parsed locale
120    $data = ['id' => $id, 'html' => ''];
121
122    $event = new Event('PARSER_LOCALE_XHTML', $data);
123    if ($event->advise_before()) {
124        $data['html'] = p_cached_output(localeFN($data['id']));
125    }
126    $event->advise_after();
127
128    return $data['html'];
129}
130
131/**
132 * Returns the given file parsed into the requested output format
133 *
134 * @param string $file filename, path to file
135 * @param string $format
136 * @param string $id page id
137 * @return null|string
138 * @author Andreas Gohr <andi@splitbrain.org>
139 * @author Chris Smith <chris@jalakai.co.uk>
140 *
141 */
142function p_cached_output($file, $format = 'xhtml', $id = '')
143{
144    global $conf;
145
146    $cache = new CacheRenderer($id, $file, $format);
147    if ($cache->useCache()) {
148        $parsed = $cache->retrieveCache(false);
149        if ($conf['allowdebug'] && $format == 'xhtml') {
150            $parsed .= "\n<!-- cachefile {$cache->cache} used -->\n";
151        }
152    } else {
153        $parsed = p_render($format, p_cached_instructions($file, false, $id), $info);
154
155        if (!empty($info['cache']) && $cache->storeCache($parsed)) { // storeCache() attempts to save cachefile
156            if ($conf['allowdebug'] && $format == 'xhtml') {
157                $parsed .= "\n<!-- no cachefile used, but created {$cache->cache} -->\n";
158            }
159        } else {
160            $cache->removeCache(); //try to delete cachefile
161            if ($conf['allowdebug'] && $format == 'xhtml') {
162                $parsed .= "\n<!-- no cachefile used, caching forbidden -->\n";
163            }
164        }
165    }
166
167    return $parsed;
168}
169
170/**
171 * Returns the render instructions for a file
172 *
173 * Uses and creates a serialized cache file
174 *
175 * @param string $file filename, path to file
176 * @param bool $cacheonly
177 * @param string $id page id
178 * @return array|null
179 * @author Andreas Gohr <andi@splitbrain.org>
180 *
181 */
182function p_cached_instructions($file, $cacheonly = false, $id = '')
183{
184    static $run = null;
185    if (is_null($run)) $run = [];
186
187    $cache = new CacheInstructions($id, $file);
188
189    if ($cacheonly || $cache->useCache() || (isset($run[$file]) && !defined('DOKU_UNITTEST'))) {
190        return $cache->retrieveCache();
191    } elseif (file_exists($file)) {
192        // no cache - do some work
193        $ins = p_get_instructions(io_readWikiPage($file, $id));
194        if ($cache->storeCache($ins)) {
195            $run[$file] = true; // we won't rebuild these instructions in the same run again
196        } else {
197            msg('Unable to save cache file. Hint: disk full; file permissions; safe_mode setting.', -1);
198        }
199        return $ins;
200    }
201
202    return null;
203}
204
205/**
206 * turns a page into a list of instructions
207 *
208 * This is the one place in the parser pipeline where the configured wiki
209 * syntax preference ($conf['syntax']) is read. From here on the syntax is
210 * a parameter carried by the ModeRegistry, never a global lookup.
211 *
212 * @param string $text raw wiki syntax text
213 * @return array a list of instruction arrays
214 * @author Harry Fuecks <hfuecks@gmail.com>
215 * @author Andreas Gohr <andi@splitbrain.org>
216 *
217 */
218function p_get_instructions($text)
219{
220    global $conf;
221
222    $registry = new ModeRegistry($conf['syntax']);
223
224    // Create the parser and handler
225    $Handler = new Handler($registry);
226    $Parser = new Parser($Handler, $registry);
227
228    //add modes to parser
229    foreach ($registry->getModes() as $mode) {
230        $Parser->addMode($mode['mode'], $mode['obj']);
231    }
232
233    // Do the parsing
234    Event::createAndTrigger('PARSER_WIKITEXT_PREPROCESS', $text);
235    return $Parser->parse($text);
236}
237
238/**
239 * returns the metadata of a page
240 *
241 * @param string $id The id of the page the metadata should be returned from
242 * @param string $key The key of the metdata value that shall be read (by default everything)
243 *                        separate hierarchies by " " like "date created"
244 * @param int $render If the page should be rendererd - possible values:
245 *     METADATA_DONT_RENDER, METADATA_RENDER_USING_SIMPLE_CACHE, METADATA_RENDER_USING_CACHE
246 *     METADATA_RENDER_UNLIMITED (also combined with the previous two options),
247 *     default: METADATA_RENDER_USING_CACHE
248 * @return mixed The requested metadata fields
249 *
250 * @author Esther Brunner <esther@kaffeehaus.ch>
251 * @author Michael Hamann <michael@content-space.de>
252 */
253function p_get_metadata($id, $key = '', $render = METADATA_RENDER_USING_CACHE)
254{
255    global $ID;
256    static $render_count = 0;
257    // track pages that have already been rendered in order to avoid rendering the same page
258    // again
259    static $rendered_pages = [];
260
261    // cache the current page
262    // Benchmarking shows the current page's metadata is generally the only page metadata
263    // accessed several times. This may catch a few other pages, but that shouldn't be an issue.
264    $cache = ($ID == $id);
265    $meta = p_read_metadata($id, $cache);
266
267    if (!is_numeric($render)) {
268        if ($render) {
269            $render = METADATA_RENDER_USING_SIMPLE_CACHE;
270        } else {
271            $render = METADATA_DONT_RENDER;
272        }
273    }
274
275    // prevent recursive calls in the cache
276    static $recursion = false;
277    if (!$recursion && $render != METADATA_DONT_RENDER && !isset($rendered_pages[$id]) && page_exists($id)) {
278        $recursion = true;
279
280        $cachefile = new CacheRenderer($id, wikiFN($id), 'metadata');
281
282        $do_render = false;
283        if ($render & METADATA_RENDER_UNLIMITED || $render_count < P_GET_METADATA_RENDER_LIMIT) {
284            if ($render & METADATA_RENDER_USING_SIMPLE_CACHE) {
285                $pagefn = wikiFN($id);
286                $metafn = metaFN($id, '.meta');
287                if (!file_exists($metafn) || @filemtime($pagefn) > @filemtime($cachefile->cache)) {
288                    $do_render = true;
289                }
290            } elseif (!$cachefile->useCache()) {
291                $do_render = true;
292            }
293        }
294        if ($do_render) {
295            if (!defined('DOKU_UNITTEST')) {
296                ++$render_count;
297                $rendered_pages[$id] = true;
298            }
299            $old_meta = $meta;
300            $meta = p_render_metadata($id, $meta);
301            // only update the file when the metadata has been changed
302            if ($meta == $old_meta || p_save_metadata($id, $meta)) {
303                // store a timestamp in order to make sure that the cachefile is touched
304                // this timestamp is also stored when the meta data is still the same
305                $cachefile->storeCache(time());
306            } else {
307                msg('Unable to save metadata file. Hint: disk full; file permissions; safe_mode setting.', -1);
308            }
309        }
310
311        $recursion = false;
312    }
313
314    $val = $meta['current'] ?? null;
315
316    // filter by $key
317    foreach (preg_split('/\s+/', $key, 2, PREG_SPLIT_NO_EMPTY) as $cur_key) {
318        if (!isset($val[$cur_key])) {
319            return null;
320        }
321        $val = $val[$cur_key];
322    }
323    return $val;
324}
325
326/**
327 * sets metadata elements of a page
328 *
329 * @see http://www.dokuwiki.org/devel:metadata#functions_to_get_and_set_metadata
330 *
331 * @param string $id is the ID of a wiki page
332 * @param array $data is an array with key ⇒ value pairs to be set in the metadata
333 * @param boolean $render whether or not the page metadata should be generated with the renderer
334 * @param boolean $persistent indicates whether or not the particular metadata value will persist through
335 *                            the next metadata rendering.
336 * @return boolean true on success
337 *
338 * @author Esther Brunner <esther@kaffeehaus.ch>
339 * @author Michael Hamann <michael@content-space.de>
340 */
341function p_set_metadata($id, $data, $render = false, $persistent = true)
342{
343    if (!is_array($data)) return false;
344
345    global $ID, $METADATA_RENDERERS;
346
347    // if there is currently a renderer change the data in the renderer instead
348    if (isset($METADATA_RENDERERS[$id])) {
349        $orig =& $METADATA_RENDERERS[$id];
350        $meta = $orig;
351    } else {
352        // cache the current page
353        $cache = ($ID == $id);
354        $orig = p_read_metadata($id, $cache);
355
356        // render metadata first?
357        $meta = $render ? p_render_metadata($id, $orig) : $orig;
358    }
359
360    // now add the passed metadata
361    $protected = ['description', 'date', 'contributor'];
362    foreach ($data as $key => $value) {
363        // be careful with sub-arrays of $meta['relation']
364        if ($key == 'relation') {
365            foreach ($value as $subkey => $subvalue) {
366                if (isset($meta['current'][$key][$subkey]) && is_array($meta['current'][$key][$subkey])) {
367                    $meta['current'][$key][$subkey] = array_replace($meta['current'][$key][$subkey], (array)$subvalue);
368                } else {
369                    $meta['current'][$key][$subkey] = $subvalue;
370                }
371                if ($persistent) {
372                    if (isset($meta['persistent'][$key][$subkey]) && is_array($meta['persistent'][$key][$subkey])) {
373                        $meta['persistent'][$key][$subkey] = array_replace(
374                            $meta['persistent'][$key][$subkey],
375                            (array)$subvalue
376                        );
377                    } else {
378                        $meta['persistent'][$key][$subkey] = $subvalue;
379                    }
380                }
381            }
382
383            // be careful with some senisitive arrays of $meta
384        } elseif (in_array($key, $protected, true)) {
385            // these keys, must have subkeys - a legitimate value must be an array
386            if (is_array($value)) {
387                $meta['current'][$key] = empty($meta['current'][$key]) ?
388                    $value :
389                    array_replace((array)$meta['current'][$key], $value);
390
391                if ($persistent) {
392                    $meta['persistent'][$key] = empty($meta['persistent'][$key]) ?
393                        $value :
394                        array_replace((array)$meta['persistent'][$key], $value);
395                }
396            }
397
398            // no special treatment for the rest
399        } else {
400            $meta['current'][$key] = $value;
401            if ($persistent) $meta['persistent'][$key] = $value;
402        }
403    }
404
405    // save only if metadata changed
406    if ($meta == $orig) return true;
407
408    if (isset($METADATA_RENDERERS[$id])) {
409        // set both keys individually as the renderer has references to the individual keys
410        $METADATA_RENDERERS[$id]['current'] = $meta['current'];
411        $METADATA_RENDERERS[$id]['persistent'] = $meta['persistent'];
412        return true;
413    } else {
414        return p_save_metadata($id, $meta);
415    }
416}
417
418/**
419 * Purges the non-persistant part of the meta data
420 * used on page deletion
421 *
422 * @param string $id page id
423 * @return bool  success / fail
424 * @author Michael Klier <chi@chimeric.de>
425 *
426 */
427function p_purge_metadata($id)
428{
429    $meta = p_read_metadata($id);
430    foreach ($meta['current'] as $key => $value) {
431        if (isset($meta[$key]) && is_array($meta[$key])) {
432            $meta['current'][$key] = [];
433        } else {
434            $meta['current'][$key] = '';
435        }
436    }
437    return p_save_metadata($id, $meta);
438}
439
440/**
441 * read the metadata from source/cache for $id
442 * (internal use only - called by p_get_metadata & p_set_metadata)
443 *
444 * @param string $id absolute wiki page id
445 * @param bool $cache whether or not to cache metadata in memory
446 *                             (only use for metadata likely to be accessed several times)
447 *
448 * @return   array             metadata
449 * @author   Christopher Smith <chris@jalakai.co.uk>
450 *
451 */
452function p_read_metadata($id, $cache = false)
453{
454    global $cache_metadata;
455
456    if (isset($cache_metadata[(string)$id])) return $cache_metadata[(string)$id];
457
458    $file = metaFN($id, '.meta');
459    $meta = file_exists($file) ?
460        unserialize(io_readFile($file, false)) :
461        ['current' => [], 'persistent' => []];
462
463    if ($cache) {
464        $cache_metadata[(string)$id] = $meta;
465    }
466
467    return $meta;
468}
469
470/**
471 * This is the backend function to save a metadata array to a file
472 *
473 * @param string $id absolute wiki page id
474 * @param array $meta metadata
475 *
476 * @return   bool              success / fail
477 */
478function p_save_metadata($id, $meta)
479{
480    // sync cached copies, including $INFO metadata
481    global $cache_metadata, $INFO;
482
483    if (isset($cache_metadata[$id])) $cache_metadata[$id] = $meta;
484    if (!empty($INFO) && isset($INFO['id']) && ($id == $INFO['id'])) {
485        $INFO['meta'] = $meta['current'];
486    }
487
488    return io_saveFile(metaFN($id, '.meta'), serialize($meta));
489}
490
491/**
492 * renders the metadata of a page
493 *
494 * @param string $id page id
495 * @param array $orig the original metadata
496 * @return array|null array('current'=> array,'persistent'=> array);
497 * @author Esther Brunner <esther@kaffeehaus.ch>
498 *
499 */
500function p_render_metadata($id, $orig)
501{
502    // make sure the correct ID is in global ID
503    global $ID, $METADATA_RENDERERS;
504
505    // avoid recursive rendering processes for the same id
506    if (isset($METADATA_RENDERERS[$id])) {
507        return $orig;
508    }
509
510    // store the original metadata in the global $METADATA_RENDERERS so p_set_metadata can use it
511    $METADATA_RENDERERS[$id] =& $orig;
512
513    $keep = $ID;
514    $ID = $id;
515
516    // add an extra key for the event - to tell event handlers the page whose metadata this is
517    $orig['page'] = $id;
518    $evt = new Event('PARSER_METADATA_RENDER', $orig);
519    if ($evt->advise_before()) {
520        // get instructions
521        $instructions = p_cached_instructions(wikiFN($id), false, $id);
522        if (is_null($instructions)) {
523            $ID = $keep;
524            unset($METADATA_RENDERERS[$id]);
525            return null; // something went wrong with the instructions
526        }
527
528        // set up the renderer
529        $renderer = new Doku_Renderer_metadata();
530        $renderer->meta =& $orig['current'];
531        $renderer->persistent =& $orig['persistent'];
532
533        // loop through the instructions
534        foreach ($instructions as $instruction) {
535            // execute the callback against the renderer
536            call_user_func_array([&$renderer, $instruction[0]], (array)$instruction[1]);
537        }
538
539        $evt->result = ['current' => &$renderer->meta, 'persistent' => &$renderer->persistent];
540    }
541    $evt->advise_after();
542
543    // clean up
544    $ID = $keep;
545    unset($METADATA_RENDERERS[$id]);
546    return $evt->result;
547}
548
549/**
550 * Renders a list of instruction to the specified output mode
551 *
552 * In the $info array is information from the renderer returned
553 *
554 * @param string $mode
555 * @param array|null|false $instructions
556 * @param array $info returns render info like enabled toc and cache
557 * @param string $date_at
558 * @return null|string rendered output
559 * @author Andreas Gohr <andi@splitbrain.org>
560 *
561 * @author Harry Fuecks <hfuecks@gmail.com>
562 */
563function p_render($mode, $instructions, &$info, $date_at = '')
564{
565    if (is_null($instructions)) return '';
566    if ($instructions === false) return '';
567
568    $Renderer = p_get_renderer($mode);
569    if (is_null($Renderer)) return null;
570
571    $Renderer->reset();
572
573    if ($date_at) {
574        $Renderer->date_at = $date_at;
575    }
576
577    $Renderer->smileys = getSmileys();
578    $Renderer->entities = getEntities();
579    $Renderer->acronyms = getAcronyms();
580    $Renderer->interwiki = getInterwiki();
581
582    // Loop through the instructions
583    foreach ($instructions as $instruction) {
584        // Execute the callback against the Renderer
585        if (method_exists($Renderer, $instruction[0])) {
586            call_user_func_array([&$Renderer, $instruction[0]], $instruction[1] ?: []);
587        }
588    }
589
590    //set info array
591    $info = $Renderer->info;
592
593    // Post process and return the output
594    $data = [$mode, & $Renderer->doc];
595    Event::createAndTrigger('RENDERER_CONTENT_POSTPROCESS', $data);
596    return $Renderer->doc;
597}
598
599/**
600 * Figure out the correct renderer class to use for $mode,
601 * instantiate and return it
602 *
603 * @param string $mode Mode of the renderer to get
604 * @return null|Doku_Renderer The renderer
605 *
606 * @author Christopher Smith <chris@jalakai.co.uk>
607 */
608function p_get_renderer($mode)
609{
610    /** @var PluginController $plugin_controller */
611    global $conf, $plugin_controller;
612
613    $rname = empty($conf['renderer_' . $mode]) ? $mode : $conf['renderer_' . $mode];
614    $rclass = "Doku_Renderer_$rname";
615
616    // if requested earlier or a bundled renderer
617    if (class_exists($rclass)) {
618        return new $rclass();
619    }
620
621    // not bundled, see if its an enabled renderer plugin & when $mode is 'xhtml', the renderer can supply that format.
622    /** @var Doku_Renderer $Renderer */
623    $Renderer = $plugin_controller->load('renderer', $rname);
624    if ($Renderer && is_a($Renderer, 'Doku_Renderer') && ($mode != 'xhtml' || $mode == $Renderer->getFormat())) {
625        return $Renderer;
626    }
627
628    // there is a configuration error!
629    // not bundled, not a valid enabled plugin, use $mode to try to fallback to a bundled renderer
630    $rclass = "Doku_Renderer_$mode";
631    if (class_exists($rclass)) {
632        // viewers should see renderered output, so restrict the warning to admins only
633        $msg = "No renderer '$rname' found for mode '$mode', check your plugins";
634        if ($mode == 'xhtml') {
635            $msg .= " and the 'renderer_xhtml' config setting";
636        }
637        $msg .= ".<br/>Attempting to fallback to the bundled renderer.";
638        msg($msg, -1, '', '', MSG_ADMINS_ONLY);
639
640        $Renderer = new $rclass();
641        $Renderer->nocache();     // fallback only (and may include admin alerts), don't cache
642        return $Renderer;
643    }
644
645    // fallback failed, alert the world
646    msg("No renderer '$rname' found for mode '$mode'", -1);
647    return null;
648}
649
650/**
651 * Gets the first heading from a file
652 *
653 * @param string $id dokuwiki page id
654 * @param int $render rerender if first heading not known
655 *                             default: METADATA_RENDER_USING_SIMPLE_CACHE
656 *                             Possible values: METADATA_DONT_RENDER,
657 *                                              METADATA_RENDER_USING_SIMPLE_CACHE,
658 *                                              METADATA_RENDER_USING_CACHE,
659 *                                              METADATA_RENDER_UNLIMITED
660 * @return string|null The first heading
661 *
662 * @author Andreas Gohr <andi@splitbrain.org>
663 * @author Michael Hamann <michael@content-space.de>
664 */
665function p_get_first_heading($id, $render = METADATA_RENDER_USING_SIMPLE_CACHE)
666{
667    return p_get_metadata(cleanID($id), 'title', $render);
668}
669
670/**
671 * Wrapper for GeSHi Code Highlighter, provides caching of its output
672 *
673 * @param string $code source code to be highlighted
674 * @param string $language language to provide highlighting
675 * @param string $wrapper html element to wrap the returned highlighted text
676 * @return string xhtml code
677 *
678 * @author Christopher Smith <chris@jalakai.co.uk>
679 * @author Andreas Gohr <andi@splitbrain.org>
680 */
681function p_xhtml_cached_geshi($code, $language, $wrapper = 'pre', ?array $options = null)
682{
683    global $conf, $config_cascade, $INPUT;
684    $language = strtolower($language);
685
686    // remove any leading or trailing blank lines
687    $code = preg_replace('/^\s*?\n|\s*?\n$/', '', $code);
688
689    $optionsmd5 = md5(serialize($options));
690    $cache = getCacheName($language . $code . $optionsmd5, ".code");
691    $ctime = @filemtime($cache);
692    if (
693        $ctime && !$INPUT->bool('purge') &&
694        $ctime > filemtime(DOKU_INC . 'vendor/composer/installed.json') &&  // libraries changed
695        $ctime > filemtime(reset($config_cascade['main']['default']))
696    ) { // dokuwiki changed
697        $highlighted_code = io_readFile($cache, false);
698    } else {
699        $geshi = new GeSHi($code, $language);
700        $geshi->set_encoding('utf-8');
701        $geshi->enable_classes();
702        $geshi->set_header_type(GESHI_HEADER_PRE);
703        $geshi->set_link_target($conf['target']['extern']);
704        if ($options !== null) {
705            foreach ($options as $function => $params) {
706                if (is_callable([$geshi, $function])) {
707                    $geshi->$function($params);
708                }
709            }
710        }
711
712        // remove GeSHi's wrapper element (we'll replace it with our own later)
713        // we need to use a GeSHi wrapper to avoid <BR> throughout the highlighted text
714        $highlighted_code = trim(preg_replace('!^<pre[^>]*>|</pre>$!', '', $geshi->parse_code()), "\n\r");
715        io_saveFile($cache, $highlighted_code);
716    }
717
718    // add a wrapper element if required
719    if ($wrapper) {
720        return "<$wrapper class=\"code $language\">$highlighted_code</$wrapper>";
721    } else {
722        return $highlighted_code;
723    }
724}
725