xref: /dokuwiki/inc/parserutils.php (revision ce6b63d97068e71369bad95e7959d0110717bbfd)
1<?php
2/**
3 * Utilities for collecting data from config files
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
10  if(!defined('DOKU_INC')) define('DOKU_INC',realpath(dirname(__FILE__).'/../').'/');
11
12  require_once(DOKU_INC.'inc/confutils.php');
13  require_once(DOKU_INC.'inc/pageutils.php');
14  require_once(DOKU_INC.'inc/pluginutils.php');
15  require_once(DOKU_INC.'inc/cache.php');
16
17/**
18 * Returns the parsed Wikitext in XHTML for the given id and revision.
19 *
20 * If $excuse is true an explanation is returned if the file
21 * wasn't found
22 *
23 * @author Andreas Gohr <andi@splitbrain.org>
24 */
25function p_wiki_xhtml($id, $rev='', $excuse=true){
26  $file = wikiFN($id,$rev);
27  $ret  = '';
28
29  //ensure $id is in global $ID (needed for parsing)
30  global $ID;
31  $keep = $ID;
32  $ID   = $id;
33
34  if($rev){
35    if(@file_exists($file)){
36      $ret = p_render('xhtml',p_get_instructions(io_readfile($file)),$info); //no caching on old revisions
37    }elseif($excuse){
38      $ret = p_locale_xhtml('norev');
39    }
40  }else{
41    if(@file_exists($file)){
42      $ret = p_cached_output($file,'xhtml',$id);
43    }elseif($excuse){
44      $ret = p_locale_xhtml('newpage');
45    }
46  }
47
48  //restore ID (just in case)
49  $ID = $keep;
50
51  return $ret;
52}
53
54/**
55 * Returns starting summary for a page (e.g. the first few
56 * paragraphs), marked up in XHTML.
57 *
58 * If $excuse is true an explanation is returned if the file
59 * wasn't found
60 *
61 * @param string wiki page id
62 * @param reference populated with page title from heading or page id
63 * @deprecated
64 * @author Harry Fuecks <hfuecks@gmail.com>
65 */
66function p_wiki_xhtml_summary($id, &$title, $rev='', $excuse=true){
67  $file = wikiFN($id,$rev);
68  $ret  = '';
69
70  //ensure $id is in global $ID (needed for parsing)
71  global $ID;
72  $keep = $ID;
73  $ID   = $id;
74
75  if($rev){
76    if(@file_exists($file)){
77      //no caching on old revisions
78      $ins = p_get_instructions(io_readfile($file));
79    }elseif($excuse){
80      $ret = p_locale_xhtml('norev');
81      //restore ID (just in case)
82      $ID = $keep;
83      return $ret;
84    }
85
86  }else{
87
88    if(@file_exists($file)){
89      // The XHTML for a summary is not cached so use the instruction cache
90      $ins = p_cached_instructions($file);
91    }elseif($excuse){
92      $ret = p_locale_xhtml('newpage');
93      //restore ID (just in case)
94      $ID = $keep;
95      return $ret;
96    }
97  }
98
99  $ret = p_render('xhtmlsummary',$ins,$info);
100
101  if ( $info['sum_pagetitle'] ) {
102    $title = $info['sum_pagetitle'];
103  } else {
104    $title = $id;
105  }
106
107  $ID = $keep;
108  return $ret;
109}
110
111/**
112 * Returns the specified local text in parsed format
113 *
114 * @author Andreas Gohr <andi@splitbrain.org>
115 */
116function p_locale_xhtml($id){
117  //fetch parsed locale
118  $html = p_cached_output(localeFN($id));
119  return $html;
120}
121
122/**
123 *     *** DEPRECATED ***
124 *
125 * use p_cached_output()
126 *
127 * Returns the given file parsed to XHTML
128 *
129 * Uses and creates a cachefile
130 *
131 * @deprecated
132 * @author Andreas Gohr <andi@splitbrain.org>
133 * @todo   rewrite to use mode instead of hardcoded XHTML
134 */
135function p_cached_xhtml($file){
136  return p_cached_output($file);
137}
138
139/**
140 * Returns the given file parsed into the requested output format
141 *
142 * @author Andreas Gohr <andi@splitbrain.org>
143 * @author Chris Smith <chris@jalakai.co.uk>
144 */
145function p_cached_output($file, $format='xhtml', $id='') {
146  global $conf;
147
148  $cache = new cache_renderer($id, $file, $format);
149  if ($cache->useCache()) {
150    $parsed = $cache->retrieveCache();
151    if($conf['allowdebug']) $parsed .= "\n<!-- cachefile {$cache->cache} used -->\n";
152  } else {
153    $parsed = p_render($format, p_cached_instructions($file,false,$id), $info);
154
155    if ($info['cache']) {
156      $cache->storeCache($parsed);               //save cachefile
157      if($conf['allowdebug']) $parsed .= "\n<!-- no cachefile used, but created -->\n";
158    }else{
159      $cache->removeCache();                     //try to delete cachefile
160      if($conf['allowdebug']) $parsed .= "\n<!-- no cachefile used, caching forbidden -->\n";
161    }
162  }
163
164  return $parsed;
165}
166
167/**
168 * Returns the render instructions for a file
169 *
170 * Uses and creates a serialized cache file
171 *
172 * @author Andreas Gohr <andi@splitbrain.org>
173 */
174function p_cached_instructions($file,$cacheonly=false,$id='') {
175  global $conf;
176
177  $cache = new cache_instructions($id, $file);
178
179  if ($cacheonly || $cache->useCache()) {
180    return $cache->retrieveCache();
181  } else if (@file_exists($file)) {
182    // no cache - do some work
183    $ins = p_get_instructions(io_readfile($file));
184    $cache->storeCache($ins);
185    return $ins;
186  }
187
188  return NULL;
189}
190
191/**
192 * turns a page into a list of instructions
193 *
194 * @author Harry Fuecks <hfuecks@gmail.com>
195 * @author Andreas Gohr <andi@splitbrain.org>
196 */
197function p_get_instructions($text){
198
199  $modes = p_get_parsermodes();
200
201  // Create the parser
202  $Parser = & new Doku_Parser();
203
204  // Add the Handler
205  $Parser->Handler = & new Doku_Handler();
206
207  //add modes to parser
208  foreach($modes as $mode){
209    $Parser->addMode($mode['mode'],$mode['obj']);
210  }
211
212  // Do the parsing
213  trigger_event('PARSER_WIKITEXT_PREPROCESS', $text);
214  $p = $Parser->parse($text);
215//  dbg($p);
216  return $p;
217}
218
219/**
220 * returns the metadata of a page
221 *
222 * @author Esther Brunner <esther@kaffeehaus.ch>
223 */
224function p_get_metadata($id, $key=false, $render=false){
225  $file = metaFN($id, '.meta');
226
227  if (@file_exists($file)) $meta = unserialize(io_readFile($file, false));
228  else $meta = array();
229
230  // metadata has never been rendered before - do it!
231  if ($render && !$meta['description']['abstract']){
232    $meta = p_render_metadata($id, $meta);
233    io_saveFile($file, serialize($meta));
234  }
235
236  // filter by $key
237  if ($key){
238    list($key, $subkey) = explode(' ', $key, 2);
239    if (trim($subkey)) return $meta[$key][$subkey];
240    else return $meta[$key];
241  }
242
243  return $meta;
244}
245
246/**
247 * sets metadata elements of a page
248 *
249 * @author Esther Brunner <esther@kaffeehaus.ch>
250 */
251function p_set_metadata($id, $data, $render=false){
252  if (!is_array($data)) return false;
253
254  $orig = p_get_metadata($id);
255
256  // render metadata first?
257  if ($render) $meta = p_render_metadata($id, $orig);
258  else $meta = $orig;
259
260  // now add the passed metadata
261  $protected = array('description', 'date', 'contributor');
262  foreach ($data as $key => $value){
263
264    // be careful with sub-arrays of $meta['relation']
265    if ($key == 'relation'){
266      foreach ($value as $subkey => $subvalue){
267        $meta[$key][$subkey] = array_merge($meta[$key][$subkey], $subvalue);
268      }
269
270    // be careful with some senisitive arrays of $meta
271    } elseif (in_array($key, $protected)){
272      if (is_array($value)){
273        #FIXME not sure if this is the intended thing:
274        if(!is_array($meta[$key])) $meta[$key] = array($meta[$key]);
275        $meta[$key] = array_merge($meta[$key], $value);
276      }
277
278    // no special treatment for the rest
279    } else {
280      $meta[$key] = $value;
281    }
282  }
283
284  // save only if metadata changed
285  if ($meta == $orig) return true;
286  return io_saveFile(metaFN($id, '.meta'), serialize($meta));
287}
288
289/**
290 * renders the metadata of a page
291 *
292 * @author Esther Brunner <esther@kaffeehaus.ch>
293 */
294function p_render_metadata($id, $orig){
295  require_once DOKU_INC."inc/parser/metadata.php";
296
297  // get instructions
298  $instructions = p_cached_instructions(wikiFN($id),false,$id);
299
300  // set up the renderer
301  $renderer = & new Doku_Renderer_metadata();
302  $renderer->meta = $orig;
303
304  // loop through the instructions
305  foreach ($instructions as $instruction){
306    // execute the callback against the renderer
307    call_user_func_array(array(&$renderer, $instruction[0]), $instruction[1]);
308  }
309
310  return $renderer->meta;
311}
312
313/**
314 * returns all available parser syntax modes in correct order
315 *
316 * @author Andreas Gohr <andi@splitbrain.org>
317 */
318function p_get_parsermodes(){
319  global $conf;
320
321  //reuse old data
322  static $modes = null;
323  if($modes != null){
324    return $modes;
325  }
326
327  //import parser classes and mode definitions
328  require_once DOKU_INC . 'inc/parser/parser.php';
329
330  // we now collect all syntax modes and their objects, then they will
331  // be sorted and added to the parser in correct order
332  $modes = array();
333
334  // add syntax plugins
335  $pluginlist = plugin_list('syntax');
336  if(count($pluginlist)){
337    global $PARSER_MODES;
338    $obj = null;
339    foreach($pluginlist as $p){
340      if(!$obj =& plugin_load('syntax',$p)) continue; //attempt to load plugin into $obj
341      $PARSER_MODES[$obj->getType()][] = "plugin_$p"; //register mode type
342      //add to modes
343      $modes[] = array(
344                   'sort' => $obj->getSort(),
345                   'mode' => "plugin_$p",
346                   'obj'  => $obj,
347                 );
348      unset($obj); //remove the reference
349    }
350  }
351
352  // add default modes
353  $std_modes = array('listblock','preformatted','notoc','nocache',
354                     'header','table','linebreak','footnote','hr',
355                     'unformatted','php','html','code','file','quote',
356                     'internallink','rss','media','externallink',
357                     'emaillink','windowssharelink','eol');
358  if($conf['typography']){
359    $std_modes[] = 'quotes';
360    $std_modes[] = 'multiplyentity';
361  }
362  foreach($std_modes as $m){
363    $class = "Doku_Parser_Mode_$m";
364    $obj   = new $class();
365    $modes[] = array(
366                 'sort' => $obj->getSort(),
367                 'mode' => $m,
368                 'obj'  => $obj
369               );
370  }
371
372  // add formatting modes
373  $fmt_modes = array('strong','emphasis','underline','monospace',
374                     'subscript','superscript','deleted');
375  foreach($fmt_modes as $m){
376    $obj   = new Doku_Parser_Mode_formatting($m);
377    $modes[] = array(
378                 'sort' => $obj->getSort(),
379                 'mode' => $m,
380                 'obj'  => $obj
381               );
382  }
383
384  // add modes which need files
385  $obj     = new Doku_Parser_Mode_smiley(array_keys(getSmileys()));
386  $modes[] = array('sort' => $obj->getSort(), 'mode' => 'smiley','obj'  => $obj );
387  $obj     = new Doku_Parser_Mode_acronym(array_keys(getAcronyms()));
388  $modes[] = array('sort' => $obj->getSort(), 'mode' => 'acronym','obj'  => $obj );
389  $obj     = new Doku_Parser_Mode_entity(array_keys(getEntities()));
390  $modes[] = array('sort' => $obj->getSort(), 'mode' => 'entity','obj'  => $obj );
391
392
393  // add optional camelcase mode
394  if($conf['camelcase']){
395    $obj     = new Doku_Parser_Mode_camelcaselink();
396    $modes[] = array('sort' => $obj->getSort(), 'mode' => 'camelcaselink','obj'  => $obj );
397  }
398
399  //sort modes
400  usort($modes,'p_sort_modes');
401
402  return $modes;
403}
404
405/**
406 * Callback function for usort
407 *
408 * @author Andreas Gohr <andi@splitbrain.org>
409 */
410function p_sort_modes($a, $b){
411  if($a['sort'] == $b['sort']) return 0;
412  return ($a['sort'] < $b['sort']) ? -1 : 1;
413}
414
415/**
416 * Renders a list of instruction to the specified output mode
417 *
418 * In the $info array are informations from the renderer returned
419 *
420 * @author Harry Fuecks <hfuecks@gmail.com>
421 * @author Andreas Gohr <andi@splitbrain.org>
422 */
423function p_render($mode,$instructions,& $info){
424  if(is_null($instructions)) return '';
425
426  if ($mode=='wiki') { msg("Renderer for $mode not valid",-1); return null; } //FIXME!! remove this line when inc/parser/wiki.php works.
427
428  // Create the renderer
429  if(!@file_exists(DOKU_INC."inc/parser/$mode.php")){
430    msg("No renderer for $mode found",-1);
431    return null;
432  }
433
434  require_once DOKU_INC."inc/parser/$mode.php";
435  $rclass = "Doku_Renderer_$mode";
436  if ( !class_exists($rclass) ) {
437    trigger_error("Unable to resolve render class $rclass",E_USER_WARNING);
438    msg("Renderer for $mode not valid",-1);
439    return null;
440  }
441  $Renderer = & new $rclass(); #FIXME any way to check for class existance?
442
443  $Renderer->smileys = getSmileys();
444  $Renderer->entities = getEntities();
445  $Renderer->acronyms = getAcronyms();
446  $Renderer->interwiki = getInterwiki();
447  #$Renderer->badwords = getBadWords();
448
449  // Loop through the instructions
450  foreach ( $instructions as $instruction ) {
451      // Execute the callback against the Renderer
452      call_user_func_array(array(&$Renderer, $instruction[0]),$instruction[1]);
453  }
454
455  //set info array
456  $info = $Renderer->info;
457
458  // Post process and return the output
459  $data = array($mode,& $Renderer->doc);
460  trigger_event('RENDERER_CONTENT_POSTPROCESS',$data);
461  return $Renderer->doc;
462}
463
464/**
465 * Gets the first heading from a file
466 *
467 * @author Andreas Gohr <andi@splitbrain.org>
468 */
469function p_get_first_heading($id){
470  global $conf;
471  return $conf['useheading'] ? p_get_metadata($id,'title') : null;
472}
473
474/**
475 * Wrapper for GeSHi Code Highlighter, provides caching of its output
476 *
477 * @author Christopher Smith <chris@jalakai.co.uk>
478 */
479function p_xhtml_cached_geshi($code, $language) {
480  $cache = getCacheName($language.$code,".code");
481
482  if (@file_exists($cache) && !$_REQUEST['purge']) {
483
484    $highlighted_code = io_readFile($cache, false);
485    @touch($cache);
486
487  } else {
488
489    require_once(DOKU_INC . 'inc/geshi.php');
490
491    $geshi = new GeSHi($code, strtolower($language), DOKU_INC . 'inc/geshi');
492    $geshi->set_encoding('utf-8');
493    $geshi->enable_classes();
494    $geshi->set_header_type(GESHI_HEADER_PRE);
495    $geshi->set_overall_class("code $language");
496    $geshi->set_link_target($conf['target']['extern']);
497
498    $highlighted_code = $geshi->parse_code();
499
500    io_saveFile($cache,$highlighted_code);
501  }
502
503  return $highlighted_code;
504}
505
506//Setup VIM: ex: et ts=2 enc=utf-8 :
507