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