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