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