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