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