xref: /dokuwiki/inc/parserutils.php (revision 71096e46fcbfaeaa808667aba794e77fe2780169)
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 * @param string $text raw wiki syntax text
209 * @return array a list of instruction arrays
210 * @author Harry Fuecks <hfuecks@gmail.com>
211 * @author Andreas Gohr <andi@splitbrain.org>
212 *
213 */
214function p_get_instructions($text)
215{
216
217    $modes = ModeRegistry::getInstance()->getModes();
218
219    // Create the parser and handler
220    $Parser = new Parser(new Handler());
221
222    //add modes to parser
223    foreach ($modes as $mode) {
224        $Parser->addMode($mode['mode'], $mode['obj']);
225    }
226
227    // Do the parsing
228    Event::createAndTrigger('PARSER_WIKITEXT_PREPROCESS', $text);
229    return $Parser->parse($text);
230}
231
232/**
233 * returns the metadata of a page
234 *
235 * @param string $id The id of the page the metadata should be returned from
236 * @param string $key The key of the metdata value that shall be read (by default everything)
237 *                        separate hierarchies by " " like "date created"
238 * @param int $render If the page should be rendererd - possible values:
239 *     METADATA_DONT_RENDER, METADATA_RENDER_USING_SIMPLE_CACHE, METADATA_RENDER_USING_CACHE
240 *     METADATA_RENDER_UNLIMITED (also combined with the previous two options),
241 *     default: METADATA_RENDER_USING_CACHE
242 * @return mixed The requested metadata fields
243 *
244 * @author Esther Brunner <esther@kaffeehaus.ch>
245 * @author Michael Hamann <michael@content-space.de>
246 */
247function p_get_metadata($id, $key = '', $render = METADATA_RENDER_USING_CACHE)
248{
249    global $ID;
250    static $render_count = 0;
251    // track pages that have already been rendered in order to avoid rendering the same page
252    // again
253    static $rendered_pages = [];
254
255    // cache the current page
256    // Benchmarking shows the current page's metadata is generally the only page metadata
257    // accessed several times. This may catch a few other pages, but that shouldn't be an issue.
258    $cache = ($ID == $id);
259    $meta = p_read_metadata($id, $cache);
260
261    if (!is_numeric($render)) {
262        if ($render) {
263            $render = METADATA_RENDER_USING_SIMPLE_CACHE;
264        } else {
265            $render = METADATA_DONT_RENDER;
266        }
267    }
268
269    // prevent recursive calls in the cache
270    static $recursion = false;
271    if (!$recursion && $render != METADATA_DONT_RENDER && !isset($rendered_pages[$id]) && page_exists($id)) {
272        $recursion = true;
273
274        $cachefile = new CacheRenderer($id, wikiFN($id), 'metadata');
275
276        $do_render = false;
277        if ($render & METADATA_RENDER_UNLIMITED || $render_count < P_GET_METADATA_RENDER_LIMIT) {
278            if ($render & METADATA_RENDER_USING_SIMPLE_CACHE) {
279                $pagefn = wikiFN($id);
280                $metafn = metaFN($id, '.meta');
281                if (!file_exists($metafn) || @filemtime($pagefn) > @filemtime($cachefile->cache)) {
282                    $do_render = true;
283                }
284            } elseif (!$cachefile->useCache()) {
285                $do_render = true;
286            }
287        }
288        if ($do_render) {
289            if (!defined('DOKU_UNITTEST')) {
290                ++$render_count;
291                $rendered_pages[$id] = true;
292            }
293            $old_meta = $meta;
294            $meta = p_render_metadata($id, $meta);
295            // only update the file when the metadata has been changed
296            if ($meta == $old_meta || p_save_metadata($id, $meta)) {
297                // store a timestamp in order to make sure that the cachefile is touched
298                // this timestamp is also stored when the meta data is still the same
299                $cachefile->storeCache(time());
300            } else {
301                msg('Unable to save metadata file. Hint: disk full; file permissions; safe_mode setting.', -1);
302            }
303        }
304
305        $recursion = false;
306    }
307
308    $val = $meta['current'] ?? null;
309
310    // filter by $key
311    foreach (preg_split('/\s+/', $key, 2, PREG_SPLIT_NO_EMPTY) as $cur_key) {
312        if (!isset($val[$cur_key])) {
313            return null;
314        }
315        $val = $val[$cur_key];
316    }
317    return $val;
318}
319
320/**
321 * sets metadata elements of a page
322 *
323 * @see http://www.dokuwiki.org/devel:metadata#functions_to_get_and_set_metadata
324 *
325 * @param string $id is the ID of a wiki page
326 * @param array $data is an array with key ⇒ value pairs to be set in the metadata
327 * @param boolean $render whether or not the page metadata should be generated with the renderer
328 * @param boolean $persistent indicates whether or not the particular metadata value will persist through
329 *                            the next metadata rendering.
330 * @return boolean true on success
331 *
332 * @author Esther Brunner <esther@kaffeehaus.ch>
333 * @author Michael Hamann <michael@content-space.de>
334 */
335function p_set_metadata($id, $data, $render = false, $persistent = true)
336{
337    if (!is_array($data)) return false;
338
339    global $ID, $METADATA_RENDERERS;
340
341    // if there is currently a renderer change the data in the renderer instead
342    if (isset($METADATA_RENDERERS[$id])) {
343        $orig =& $METADATA_RENDERERS[$id];
344        $meta = $orig;
345    } else {
346        // cache the current page
347        $cache = ($ID == $id);
348        $orig = p_read_metadata($id, $cache);
349
350        // render metadata first?
351        $meta = $render ? p_render_metadata($id, $orig) : $orig;
352    }
353
354    // now add the passed metadata
355    $protected = ['description', 'date', 'contributor'];
356    foreach ($data as $key => $value) {
357        // be careful with sub-arrays of $meta['relation']
358        if ($key == 'relation') {
359            foreach ($value as $subkey => $subvalue) {
360                if (isset($meta['current'][$key][$subkey]) && is_array($meta['current'][$key][$subkey])) {
361                    $meta['current'][$key][$subkey] = array_replace($meta['current'][$key][$subkey], (array)$subvalue);
362                } else {
363                    $meta['current'][$key][$subkey] = $subvalue;
364                }
365                if ($persistent) {
366                    if (isset($meta['persistent'][$key][$subkey]) && is_array($meta['persistent'][$key][$subkey])) {
367                        $meta['persistent'][$key][$subkey] = array_replace(
368                            $meta['persistent'][$key][$subkey],
369                            (array)$subvalue
370                        );
371                    } else {
372                        $meta['persistent'][$key][$subkey] = $subvalue;
373                    }
374                }
375            }
376
377            // be careful with some senisitive arrays of $meta
378        } elseif (in_array($key, $protected, true)) {
379            // these keys, must have subkeys - a legitimate value must be an array
380            if (is_array($value)) {
381                $meta['current'][$key] = empty($meta['current'][$key]) ?
382                    $value :
383                    array_replace((array)$meta['current'][$key], $value);
384
385                if ($persistent) {
386                    $meta['persistent'][$key] = empty($meta['persistent'][$key]) ?
387                        $value :
388                        array_replace((array)$meta['persistent'][$key], $value);
389                }
390            }
391
392            // no special treatment for the rest
393        } else {
394            $meta['current'][$key] = $value;
395            if ($persistent) $meta['persistent'][$key] = $value;
396        }
397    }
398
399    // save only if metadata changed
400    if ($meta == $orig) return true;
401
402    if (isset($METADATA_RENDERERS[$id])) {
403        // set both keys individually as the renderer has references to the individual keys
404        $METADATA_RENDERERS[$id]['current'] = $meta['current'];
405        $METADATA_RENDERERS[$id]['persistent'] = $meta['persistent'];
406        return true;
407    } else {
408        return p_save_metadata($id, $meta);
409    }
410}
411
412/**
413 * Purges the non-persistant part of the meta data
414 * used on page deletion
415 *
416 * @param string $id page id
417 * @return bool  success / fail
418 * @author Michael Klier <chi@chimeric.de>
419 *
420 */
421function p_purge_metadata($id)
422{
423    $meta = p_read_metadata($id);
424    foreach ($meta['current'] as $key => $value) {
425        if (isset($meta[$key]) && is_array($meta[$key])) {
426            $meta['current'][$key] = [];
427        } else {
428            $meta['current'][$key] = '';
429        }
430    }
431    return p_save_metadata($id, $meta);
432}
433
434/**
435 * read the metadata from source/cache for $id
436 * (internal use only - called by p_get_metadata & p_set_metadata)
437 *
438 * @param string $id absolute wiki page id
439 * @param bool $cache whether or not to cache metadata in memory
440 *                             (only use for metadata likely to be accessed several times)
441 *
442 * @return   array             metadata
443 * @author   Christopher Smith <chris@jalakai.co.uk>
444 *
445 */
446function p_read_metadata($id, $cache = false)
447{
448    global $cache_metadata;
449
450    if (isset($cache_metadata[(string)$id])) return $cache_metadata[(string)$id];
451
452    $file = metaFN($id, '.meta');
453    $meta = file_exists($file) ?
454        unserialize(io_readFile($file, false)) :
455        ['current' => [], 'persistent' => []];
456
457    if ($cache) {
458        $cache_metadata[(string)$id] = $meta;
459    }
460
461    return $meta;
462}
463
464/**
465 * This is the backend function to save a metadata array to a file
466 *
467 * @param string $id absolute wiki page id
468 * @param array $meta metadata
469 *
470 * @return   bool              success / fail
471 */
472function p_save_metadata($id, $meta)
473{
474    // sync cached copies, including $INFO metadata
475    global $cache_metadata, $INFO;
476
477    if (isset($cache_metadata[$id])) $cache_metadata[$id] = $meta;
478    if (!empty($INFO) && isset($INFO['id']) && ($id == $INFO['id'])) {
479        $INFO['meta'] = $meta['current'];
480    }
481
482    return io_saveFile(metaFN($id, '.meta'), serialize($meta));
483}
484
485/**
486 * renders the metadata of a page
487 *
488 * @param string $id page id
489 * @param array $orig the original metadata
490 * @return array|null array('current'=> array,'persistent'=> array);
491 * @author Esther Brunner <esther@kaffeehaus.ch>
492 *
493 */
494function p_render_metadata($id, $orig)
495{
496    // make sure the correct ID is in global ID
497    global $ID, $METADATA_RENDERERS;
498
499    // avoid recursive rendering processes for the same id
500    if (isset($METADATA_RENDERERS[$id])) {
501        return $orig;
502    }
503
504    // store the original metadata in the global $METADATA_RENDERERS so p_set_metadata can use it
505    $METADATA_RENDERERS[$id] =& $orig;
506
507    $keep = $ID;
508    $ID = $id;
509
510    // add an extra key for the event - to tell event handlers the page whose metadata this is
511    $orig['page'] = $id;
512    $evt = new Event('PARSER_METADATA_RENDER', $orig);
513    if ($evt->advise_before()) {
514        // get instructions
515        $instructions = p_cached_instructions(wikiFN($id), false, $id);
516        if (is_null($instructions)) {
517            $ID = $keep;
518            unset($METADATA_RENDERERS[$id]);
519            return null; // something went wrong with the instructions
520        }
521
522        // set up the renderer
523        $renderer = new Doku_Renderer_metadata();
524        $renderer->meta =& $orig['current'];
525        $renderer->persistent =& $orig['persistent'];
526
527        // loop through the instructions
528        foreach ($instructions as $instruction) {
529            // execute the callback against the renderer
530            call_user_func_array([&$renderer, $instruction[0]], (array)$instruction[1]);
531        }
532
533        $evt->result = ['current' => &$renderer->meta, 'persistent' => &$renderer->persistent];
534    }
535    $evt->advise_after();
536
537    // clean up
538    $ID = $keep;
539    unset($METADATA_RENDERERS[$id]);
540    return $evt->result;
541}
542
543/**
544 * Renders a list of instruction to the specified output mode
545 *
546 * In the $info array is information from the renderer returned
547 *
548 * @param string $mode
549 * @param array|null|false $instructions
550 * @param array $info returns render info like enabled toc and cache
551 * @param string $date_at
552 * @return null|string rendered output
553 * @author Andreas Gohr <andi@splitbrain.org>
554 *
555 * @author Harry Fuecks <hfuecks@gmail.com>
556 */
557function p_render($mode, $instructions, &$info, $date_at = '')
558{
559    if (is_null($instructions)) return '';
560    if ($instructions === false) return '';
561
562    $Renderer = p_get_renderer($mode);
563    if (is_null($Renderer)) return null;
564
565    $Renderer->reset();
566
567    if ($date_at) {
568        $Renderer->date_at = $date_at;
569    }
570
571    $Renderer->smileys = getSmileys();
572    $Renderer->entities = getEntities();
573    $Renderer->acronyms = getAcronyms();
574    $Renderer->interwiki = getInterwiki();
575
576    // Loop through the instructions
577    foreach ($instructions as $instruction) {
578        // Execute the callback against the Renderer
579        if (method_exists($Renderer, $instruction[0])) {
580            call_user_func_array([&$Renderer, $instruction[0]], $instruction[1] ?: []);
581        }
582    }
583
584    //set info array
585    $info = $Renderer->info;
586
587    // Post process and return the output
588    $data = [$mode, & $Renderer->doc];
589    Event::createAndTrigger('RENDERER_CONTENT_POSTPROCESS', $data);
590    return $Renderer->doc;
591}
592
593/**
594 * Figure out the correct renderer class to use for $mode,
595 * instantiate and return it
596 *
597 * @param string $mode Mode of the renderer to get
598 * @return null|Doku_Renderer The renderer
599 *
600 * @author Christopher Smith <chris@jalakai.co.uk>
601 */
602function p_get_renderer($mode)
603{
604    /** @var PluginController $plugin_controller */
605    global $conf, $plugin_controller;
606
607    $rname = empty($conf['renderer_' . $mode]) ? $mode : $conf['renderer_' . $mode];
608    $rclass = "Doku_Renderer_$rname";
609
610    // if requested earlier or a bundled renderer
611    if (class_exists($rclass)) {
612        return new $rclass();
613    }
614
615    // not bundled, see if its an enabled renderer plugin & when $mode is 'xhtml', the renderer can supply that format.
616    /** @var Doku_Renderer $Renderer */
617    $Renderer = $plugin_controller->load('renderer', $rname);
618    if ($Renderer && is_a($Renderer, 'Doku_Renderer') && ($mode != 'xhtml' || $mode == $Renderer->getFormat())) {
619        return $Renderer;
620    }
621
622    // there is a configuration error!
623    // not bundled, not a valid enabled plugin, use $mode to try to fallback to a bundled renderer
624    $rclass = "Doku_Renderer_$mode";
625    if (class_exists($rclass)) {
626        // viewers should see renderered output, so restrict the warning to admins only
627        $msg = "No renderer '$rname' found for mode '$mode', check your plugins";
628        if ($mode == 'xhtml') {
629            $msg .= " and the 'renderer_xhtml' config setting";
630        }
631        $msg .= ".<br/>Attempting to fallback to the bundled renderer.";
632        msg($msg, -1, '', '', MSG_ADMINS_ONLY);
633
634        $Renderer = new $rclass();
635        $Renderer->nocache();     // fallback only (and may include admin alerts), don't cache
636        return $Renderer;
637    }
638
639    // fallback failed, alert the world
640    msg("No renderer '$rname' found for mode '$mode'", -1);
641    return null;
642}
643
644/**
645 * Gets the first heading from a file
646 *
647 * @param string $id dokuwiki page id
648 * @param int $render rerender if first heading not known
649 *                             default: METADATA_RENDER_USING_SIMPLE_CACHE
650 *                             Possible values: METADATA_DONT_RENDER,
651 *                                              METADATA_RENDER_USING_SIMPLE_CACHE,
652 *                                              METADATA_RENDER_USING_CACHE,
653 *                                              METADATA_RENDER_UNLIMITED
654 * @return string|null The first heading
655 *
656 * @author Andreas Gohr <andi@splitbrain.org>
657 * @author Michael Hamann <michael@content-space.de>
658 */
659function p_get_first_heading($id, $render = METADATA_RENDER_USING_SIMPLE_CACHE)
660{
661    return p_get_metadata(cleanID($id), 'title', $render);
662}
663
664/**
665 * Wrapper for GeSHi Code Highlighter, provides caching of its output
666 *
667 * @param string $code source code to be highlighted
668 * @param string $language language to provide highlighting
669 * @param string $wrapper html element to wrap the returned highlighted text
670 * @return string xhtml code
671 *
672 * @author Christopher Smith <chris@jalakai.co.uk>
673 * @author Andreas Gohr <andi@splitbrain.org>
674 */
675function p_xhtml_cached_geshi($code, $language, $wrapper = 'pre', ?array $options = null)
676{
677    global $conf, $config_cascade, $INPUT;
678    $language = strtolower($language);
679
680    // remove any leading or trailing blank lines
681    $code = preg_replace('/^\s*?\n|\s*?\n$/', '', $code);
682
683    $optionsmd5 = md5(serialize($options));
684    $cache = getCacheName($language . $code . $optionsmd5, ".code");
685    $ctime = @filemtime($cache);
686    if (
687        $ctime && !$INPUT->bool('purge') &&
688        $ctime > filemtime(DOKU_INC . 'vendor/composer/installed.json') &&  // libraries changed
689        $ctime > filemtime(reset($config_cascade['main']['default']))
690    ) { // dokuwiki changed
691        $highlighted_code = io_readFile($cache, false);
692    } else {
693        $geshi = new GeSHi($code, $language);
694        $geshi->set_encoding('utf-8');
695        $geshi->enable_classes();
696        $geshi->set_header_type(GESHI_HEADER_PRE);
697        $geshi->set_link_target($conf['target']['extern']);
698        if ($options !== null) {
699            foreach ($options as $function => $params) {
700                if (is_callable([$geshi, $function])) {
701                    $geshi->$function($params);
702                }
703            }
704        }
705
706        // remove GeSHi's wrapper element (we'll replace it with our own later)
707        // we need to use a GeSHi wrapper to avoid <BR> throughout the highlighted text
708        $highlighted_code = trim(preg_replace('!^<pre[^>]*>|</pre>$!', '', $geshi->parse_code()), "\n\r");
709        io_saveFile($cache, $highlighted_code);
710    }
711
712    // add a wrapper element if required
713    if ($wrapper) {
714        return "<$wrapper class=\"code $language\">$highlighted_code</$wrapper>";
715    } else {
716        return $highlighted_code;
717    }
718}
719