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