xref: /dokuwiki/inc/parserutils.php (revision 4c3263af6652b0a479e2c742914eb67a7929b9b9)
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,$date_at=''){
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 || $date_at){
69        if(@file_exists($file)){
70            $ret = p_render('xhtml',p_get_instructions(io_readWikiPage($file,$id,$rev)),$info,max($rev,$date_at)); //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 */
162function p_get_instructions($text){
163
164    $modes = p_get_parsermodes();
165
166    // Create the parser
167    $Parser = new Doku_Parser();
168
169    // Add the Handler
170    $Parser->Handler = new Doku_Handler();
171
172    //add modes to parser
173    foreach($modes as $mode){
174        $Parser->addMode($mode['mode'],$mode['obj']);
175    }
176
177    // Do the parsing
178    trigger_event('PARSER_WIKITEXT_PREPROCESS', $text);
179    $p = $Parser->parse($text);
180    //  dbg($p);
181    return $p;
182}
183
184/**
185 * returns the metadata of a page
186 *
187 * @param string $id The id of the page the metadata should be returned from
188 * @param string $key The key of the metdata value that shall be read (by default everything) - separate hierarchies by " " like "date created"
189 * @param int $render If the page should be rendererd - possible values:
190 *     METADATA_DONT_RENDER, METADATA_RENDER_USING_SIMPLE_CACHE, METADATA_RENDER_USING_CACHE
191 *     METADATA_RENDER_UNLIMITED (also combined with the previous two options),
192 *     default: METADATA_RENDER_USING_CACHE
193 * @return mixed The requested metadata fields
194 *
195 * @author Esther Brunner <esther@kaffeehaus.ch>
196 * @author Michael Hamann <michael@content-space.de>
197 */
198function p_get_metadata($id, $key='', $render=METADATA_RENDER_USING_CACHE){
199    global $ID;
200    static $render_count = 0;
201    // track pages that have already been rendered in order to avoid rendering the same page
202    // again
203    static $rendered_pages = array();
204
205    // cache the current page
206    // Benchmarking shows the current page's metadata is generally the only page metadata
207    // accessed several times. This may catch a few other pages, but that shouldn't be an issue.
208    $cache = ($ID == $id);
209    $meta = p_read_metadata($id, $cache);
210
211    if (!is_numeric($render)) {
212        if ($render) {
213            $render = METADATA_RENDER_USING_SIMPLE_CACHE;
214        } else {
215            $render = METADATA_DONT_RENDER;
216        }
217    }
218
219    // prevent recursive calls in the cache
220    static $recursion = false;
221    if (!$recursion && $render != METADATA_DONT_RENDER && !isset($rendered_pages[$id])&& page_exists($id)){
222        $recursion = true;
223
224        $cachefile = new cache_renderer($id, wikiFN($id), 'metadata');
225
226        $do_render = false;
227        if ($render & METADATA_RENDER_UNLIMITED || $render_count < P_GET_METADATA_RENDER_LIMIT) {
228            if ($render & METADATA_RENDER_USING_SIMPLE_CACHE) {
229                $pagefn = wikiFN($id);
230                $metafn = metaFN($id, '.meta');
231                if (!@file_exists($metafn) || @filemtime($pagefn) > @filemtime($cachefile->cache)) {
232                    $do_render = true;
233                }
234            } elseif (!$cachefile->useCache()){
235                $do_render = true;
236            }
237        }
238        if ($do_render) {
239            if (!defined('DOKU_UNITTEST')) {
240                ++$render_count;
241                $rendered_pages[$id] = true;
242            }
243            $old_meta = $meta;
244            $meta = p_render_metadata($id, $meta);
245            // only update the file when the metadata has been changed
246            if ($meta == $old_meta || p_save_metadata($id, $meta)) {
247                // store a timestamp in order to make sure that the cachefile is touched
248                // this timestamp is also stored when the meta data is still the same
249                $cachefile->storeCache(time());
250            } else {
251                msg('Unable to save metadata file. Hint: disk full; file permissions; safe_mode setting.',-1);
252            }
253        }
254
255        $recursion = false;
256    }
257
258    $val = $meta['current'];
259
260    // filter by $key
261    foreach(preg_split('/\s+/', $key, 2, PREG_SPLIT_NO_EMPTY) as $cur_key) {
262        if (!isset($val[$cur_key])) {
263            return null;
264        }
265        $val = $val[$cur_key];
266    }
267    return $val;
268}
269
270/**
271 * sets metadata elements of a page
272 *
273 * @see http://www.dokuwiki.org/devel:metadata#functions_to_get_and_set_metadata
274 *
275 * @param String  $id         is the ID of a wiki page
276 * @param Array   $data       is an array with key ⇒ value pairs to be set in the metadata
277 * @param Boolean $render     whether or not the page metadata should be generated with the renderer
278 * @param Boolean $persistent indicates whether or not the particular metadata value will persist through
279 *                            the next metadata rendering.
280 * @return boolean true on success
281 *
282 * @author Esther Brunner <esther@kaffeehaus.ch>
283 * @author Michael Hamann <michael@content-space.de>
284 */
285function p_set_metadata($id, $data, $render=false, $persistent=true){
286    if (!is_array($data)) return false;
287
288    global $ID, $METADATA_RENDERERS;
289
290    // if there is currently a renderer change the data in the renderer instead
291    if (isset($METADATA_RENDERERS[$id])) {
292        $orig =& $METADATA_RENDERERS[$id];
293        $meta = $orig;
294    } else {
295        // cache the current page
296        $cache = ($ID == $id);
297        $orig = p_read_metadata($id, $cache);
298
299        // render metadata first?
300        $meta = $render ? p_render_metadata($id, $orig) : $orig;
301    }
302
303    // now add the passed metadata
304    $protected = array('description', 'date', 'contributor');
305    foreach ($data as $key => $value){
306
307        // be careful with sub-arrays of $meta['relation']
308        if ($key == 'relation'){
309
310            foreach ($value as $subkey => $subvalue){
311                if(isset($meta['current'][$key][$subkey]) && is_array($meta['current'][$key][$subkey])) {
312                    $meta['current'][$key][$subkey] = array_merge($meta['current'][$key][$subkey], (array)$subvalue);
313                } else {
314                    $meta['current'][$key][$subkey] = $subvalue;
315                }
316                if($persistent) {
317                    if(isset($meta['persistent'][$key][$subkey]) && is_array($meta['persistent'][$key][$subkey])) {
318                        $meta['persistent'][$key][$subkey] = array_merge($meta['persistent'][$key][$subkey], (array)$subvalue);
319                    } else {
320                        $meta['persistent'][$key][$subkey] = $subvalue;
321                    }
322                }
323            }
324
325            // be careful with some senisitive arrays of $meta
326        } elseif (in_array($key, $protected)){
327
328            // these keys, must have subkeys - a legitimate value must be an array
329            if (is_array($value)) {
330                $meta['current'][$key] = !empty($meta['current'][$key]) ? array_merge((array)$meta['current'][$key],$value) : $value;
331
332                if ($persistent) {
333                    $meta['persistent'][$key] = !empty($meta['persistent'][$key]) ? array_merge((array)$meta['persistent'][$key],$value) : $value;
334                }
335            }
336
337            // no special treatment for the rest
338        } else {
339            $meta['current'][$key] = $value;
340            if ($persistent) $meta['persistent'][$key] = $value;
341        }
342    }
343
344    // save only if metadata changed
345    if ($meta == $orig) return true;
346
347    if (isset($METADATA_RENDERERS[$id])) {
348        // set both keys individually as the renderer has references to the individual keys
349        $METADATA_RENDERERS[$id]['current']    = $meta['current'];
350        $METADATA_RENDERERS[$id]['persistent'] = $meta['persistent'];
351        return true;
352    } else {
353        return p_save_metadata($id, $meta);
354    }
355}
356
357/**
358 * Purges the non-persistant part of the meta data
359 * used on page deletion
360 *
361 * @author Michael Klier <chi@chimeric.de>
362 */
363function p_purge_metadata($id) {
364    $meta = p_read_metadata($id);
365    foreach($meta['current'] as $key => $value) {
366        if(is_array($meta[$key])) {
367            $meta['current'][$key] = array();
368        } else {
369            $meta['current'][$key] = '';
370        }
371
372    }
373    return p_save_metadata($id, $meta);
374}
375
376/**
377 * read the metadata from source/cache for $id
378 * (internal use only - called by p_get_metadata & p_set_metadata)
379 *
380 * @author   Christopher Smith <chris@jalakai.co.uk>
381 *
382 * @param    string   $id      absolute wiki page id
383 * @param    bool     $cache   whether or not to cache metadata in memory
384 *                             (only use for metadata likely to be accessed several times)
385 *
386 * @return   array             metadata
387 */
388function p_read_metadata($id,$cache=false) {
389    global $cache_metadata;
390
391    if (isset($cache_metadata[(string)$id])) return $cache_metadata[(string)$id];
392
393    $file = metaFN($id, '.meta');
394    $meta = @file_exists($file) ? unserialize(io_readFile($file, false)) : array('current'=>array(),'persistent'=>array());
395
396    if ($cache) {
397        $cache_metadata[(string)$id] = $meta;
398    }
399
400    return $meta;
401}
402
403/**
404 * This is the backend function to save a metadata array to a file
405 *
406 * @param    string   $id      absolute wiki page id
407 * @param    array    $meta    metadata
408 *
409 * @return   bool              success / fail
410 */
411function p_save_metadata($id, $meta) {
412    // sync cached copies, including $INFO metadata
413    global $cache_metadata, $INFO;
414
415    if (isset($cache_metadata[$id])) $cache_metadata[$id] = $meta;
416    if (!empty($INFO) && ($id == $INFO['id'])) { $INFO['meta'] = $meta['current']; }
417
418    return io_saveFile(metaFN($id, '.meta'), serialize($meta));
419}
420
421/**
422 * renders the metadata of a page
423 *
424 * @author Esther Brunner <esther@kaffeehaus.ch>
425 */
426function p_render_metadata($id, $orig){
427    // make sure the correct ID is in global ID
428    global $ID, $METADATA_RENDERERS;
429
430    // avoid recursive rendering processes for the same id
431    if (isset($METADATA_RENDERERS[$id]))
432        return $orig;
433
434    // store the original metadata in the global $METADATA_RENDERERS so p_set_metadata can use it
435    $METADATA_RENDERERS[$id] =& $orig;
436
437    $keep = $ID;
438    $ID   = $id;
439
440    // add an extra key for the event - to tell event handlers the page whose metadata this is
441    $orig['page'] = $id;
442    $evt = new Doku_Event('PARSER_METADATA_RENDER', $orig);
443    if ($evt->advise_before()) {
444
445        require_once DOKU_INC."inc/parser/metadata.php";
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,$date_at=''){
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    if($date_at) {
595        $Renderer->date_at = $date_at;
596    }
597
598    $Renderer->smileys = getSmileys();
599    $Renderer->entities = getEntities();
600    $Renderer->acronyms = getAcronyms();
601    $Renderer->interwiki = getInterwiki();
602
603    // Loop through the instructions
604    foreach ( $instructions as $instruction ) {
605        // Execute the callback against the Renderer
606        if(method_exists($Renderer, $instruction[0])){
607            call_user_func_array(array(&$Renderer, $instruction[0]), $instruction[1] ? $instruction[1] : array());
608        }
609    }
610
611    //set info array
612    $info = $Renderer->info;
613
614    // Post process and return the output
615    $data = array($mode,& $Renderer->doc);
616    trigger_event('RENDERER_CONTENT_POSTPROCESS',$data);
617    return $Renderer->doc;
618}
619
620/**
621 * @param $mode string Mode of the renderer to get
622 * @return null|Doku_Renderer The renderer
623 */
624function & p_get_renderer($mode) {
625    /** @var Doku_Plugin_Controller $plugin_controller */
626    global $conf, $plugin_controller;
627
628    $rname = !empty($conf['renderer_'.$mode]) ? $conf['renderer_'.$mode] : $mode;
629    $rclass = "Doku_Renderer_$rname";
630
631    if( class_exists($rclass) ) {
632        $Renderer = new $rclass();
633        return $Renderer;
634    }
635
636    // try default renderer first:
637    $file = DOKU_INC."inc/parser/$rname.php";
638    if(@file_exists($file)){
639        require_once $file;
640
641        if ( !class_exists($rclass) ) {
642            trigger_error("Unable to resolve render class $rclass",E_USER_WARNING);
643            msg("Renderer '$rname' for $mode not valid",-1);
644            return null;
645        }
646        $Renderer = new $rclass();
647    }else{
648        // Maybe a plugin/component is available?
649        $Renderer = $plugin_controller->load('renderer',$rname);
650
651        if(!isset($Renderer) || is_null($Renderer)){
652            msg("No renderer '$rname' found for mode '$mode'",-1);
653            return null;
654        }
655    }
656
657    return $Renderer;
658}
659
660/**
661 * Gets the first heading from a file
662 *
663 * @param   string   $id       dokuwiki page id
664 * @param   int      $render   rerender if first heading not known
665 *                             default: METADATA_RENDER_USING_SIMPLE_CACHE
666 *                             Possible values: METADATA_DONT_RENDER,
667 *                                              METADATA_RENDER_USING_SIMPLE_CACHE,
668 *                                              METADATA_RENDER_USING_CACHE,
669 *                                              METADATA_RENDER_UNLIMITED
670 *
671 * @return string|null The first heading
672 * @author Andreas Gohr <andi@splitbrain.org>
673 * @author Michael Hamann <michael@content-space.de>
674 */
675function p_get_first_heading($id, $render=METADATA_RENDER_USING_SIMPLE_CACHE){
676    return p_get_metadata(cleanID($id),'title',$render);
677}
678
679/**
680 * Wrapper for GeSHi Code Highlighter, provides caching of its output
681 *
682 * @param  string   $code       source code to be highlighted
683 * @param  string   $language   language to provide highlighting
684 * @param  string   $wrapper    html element to wrap the returned highlighted text
685 *
686 * @return string xhtml code
687 * @author Christopher Smith <chris@jalakai.co.uk>
688 * @author Andreas Gohr <andi@splitbrain.org>
689 */
690function p_xhtml_cached_geshi($code, $language, $wrapper='pre') {
691    global $conf, $config_cascade, $INPUT;
692    $language = strtolower($language);
693
694    // remove any leading or trailing blank lines
695    $code = preg_replace('/^\s*?\n|\s*?\n$/','',$code);
696
697    $cache = getCacheName($language.$code,".code");
698    $ctime = @filemtime($cache);
699    if($ctime && !$INPUT->bool('purge') &&
700            $ctime > filemtime(DOKU_INC.'inc/geshi.php') &&                 // geshi changed
701            $ctime > @filemtime(DOKU_INC.'inc/geshi/'.$language.'.php') &&  // language syntax definition changed
702            $ctime > filemtime(reset($config_cascade['main']['default']))){ // dokuwiki changed
703        $highlighted_code = io_readFile($cache, false);
704
705    } else {
706
707        $geshi = new GeSHi($code, $language, DOKU_INC . 'inc/geshi');
708        $geshi->set_encoding('utf-8');
709        $geshi->enable_classes();
710        $geshi->set_header_type(GESHI_HEADER_PRE);
711        $geshi->set_link_target($conf['target']['extern']);
712
713        // remove GeSHi's wrapper element (we'll replace it with our own later)
714        // we need to use a GeSHi wrapper to avoid <BR> throughout the highlighted text
715        $highlighted_code = trim(preg_replace('!^<pre[^>]*>|</pre>$!','',$geshi->parse_code()),"\n\r");
716        io_saveFile($cache,$highlighted_code);
717    }
718
719    // add a wrapper element if required
720    if ($wrapper) {
721        return "<$wrapper class=\"code $language\">$highlighted_code</$wrapper>";
722    } else {
723        return $highlighted_code;
724    }
725}
726
727