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