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