]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/InlineParser.php
add strike and del to html emphasis: Patch #1542894 by Kai Krakow
[SourceForge/phpwiki.git] / lib / InlineParser.php
1 <?php 
2 rcs_id('$Id: InlineParser.php,v 1.76 2006-08-19 11:02:35 rurban Exp $');
3 /* Copyright (C) 2002 Geoffrey T. Dairiki <dairiki@dairiki.org>
4  * Copyright (C) 2004,2005 Reini Urban
5  *
6  * This file is part of PhpWiki.
7  * 
8  * PhpWiki is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; either version 2 of the License, or
11  * (at your option) any later version.
12  * 
13  * PhpWiki is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  * 
18  * You should have received a copy of the GNU General Public License
19  * along with PhpWiki; if not, write to the Free Software
20  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
21  */
22 /**
23  * This is the code which deals with the inline part of the (new-style)
24  * wiki-markup.
25  *
26  * @package Markup
27  * @author Geoffrey T. Dairiki
28  */
29 /**
30  */
31
32 /**
33  * This is the character used in wiki markup to escape characters with
34  * special meaning.
35  */
36 define('ESCAPE_CHAR', '~');
37
38 require_once(dirname(__FILE__).'/HtmlElement.php');
39 require_once('lib/CachedMarkup.php');
40 require_once(dirname(__FILE__).'/stdlib.php');
41
42
43 function WikiEscape($text) {
44     return str_replace('#', ESCAPE_CHAR . '#', $text);
45 }
46
47 function UnWikiEscape($text) {
48     return preg_replace('/' . ESCAPE_CHAR . '(.)/', '\1', $text);
49 }
50
51 /**
52  * Return type from RegexpSet::match and RegexpSet::nextMatch.
53  *
54  * @see RegexpSet
55  */
56 class RegexpSet_match {
57     /**
58      * The text leading up the the next match.
59      */
60     var $prematch;
61     /**
62      * The matched text.
63      */
64     var $match;
65     /**
66      * The text following the matched text.
67      */
68     var $postmatch;
69     /**
70      * Index of the regular expression which matched.
71      */
72     var $regexp_ind;
73 }
74
75 /**
76  * A set of regular expressions.
77  *
78  * This class is probably only useful for InlineTransformer.
79  */
80 class RegexpSet
81 {
82     /** Constructor
83      *
84      * @param array $regexps A list of regular expressions.  The
85      * regular expressions should not include any sub-pattern groups
86      * "(...)".  (Anonymous groups, like "(?:...)", as well as
87      * look-ahead and look-behind assertions are okay.)
88      */
89     function RegexpSet ($regexps) {
90         assert($regexps);
91         $this->_regexps = array_unique($regexps);
92         if (!defined('_INLINE_OPTIMIZATION')) define('_INLINE_OPTIMIZATION',0);
93     }
94
95     /**
96      * Search text for the next matching regexp from the Regexp Set.
97      *
98      * @param string $text The text to search.
99      *
100      * @return RegexpSet_match  A RegexpSet_match object, or false if no match.
101      */
102     function match ($text) {
103         return $this->_match($text, $this->_regexps, '*?');
104     }
105
106     /**
107      * Search for next matching regexp.
108      *
109      * Here, 'next' has two meanings:
110      *
111      * Match the next regexp(s) in the set, at the same position as the last match.
112      *
113      * If that fails, match the whole RegexpSet, starting after the position of the
114      * previous match.
115      *
116      * @param string $text Text to search.
117      *
118      * @param RegexpSet_match $prevMatch A RegexpSet_match object.
119      * $prevMatch should be a match object obtained by a previous
120      * match upon the same value of $text.
121      *
122      * @return RegexpSet_match A RegexpSet_match object, or false if no match.
123      */
124     function nextMatch ($text, $prevMatch) {
125         // Try to find match at same position.
126         $pos = strlen($prevMatch->prematch);
127         $regexps = array_slice($this->_regexps, $prevMatch->regexp_ind + 1);
128         if ($regexps) {
129             $repeat = sprintf('{%d}', $pos);
130             if ( ($match = $this->_match($text, $regexps, $repeat)) ) {
131                 $match->regexp_ind += $prevMatch->regexp_ind + 1;
132                 return $match;
133             }
134             
135         }
136         
137         // Failed.  Look for match after current position.
138         $repeat = sprintf('{%d,}?', $pos + 1);
139         return $this->_match($text, $this->_regexps, $repeat);
140     }
141
142     // Syntax: http://www.pcre.org/pcre.txt
143     //   x - EXTENDED, ignore whitespace
144     //   s - DOTALL
145     //   A - ANCHORED
146     //   S - STUDY
147     function _match ($text, $regexps, $repeat) {
148         // If one of the regexps is an empty string, php will crash here: 
149         // sf.net: Fatal error: Allowed memory size of 8388608 bytes exhausted 
150         //         (tried to allocate 634 bytes)
151         if (_INLINE_OPTIMIZATION) { // disabled, wrong
152         // So we try to minize memory usage, by looping explicitly,
153         // and storing only those regexp which actually match. 
154         // There may be more than one, so we have to find the longest, 
155         // and match inside until the shortest is empty.
156         $matched = array(); $matched_ind = array();
157         for ($i=0; $i<count($regexps); $i++) {
158             if (!trim($regexps[$i])) {
159                 trigger_error("empty regexp $i", E_USER_WARNING);
160                 continue;
161             }
162             $pat= "/ ( . $repeat ) ( " . $regexps[$i] . " ) /x";
163             if (preg_match($pat, $text, $_m)) {
164                 $m = $_m; // FIXME: prematch, postmatch is wrong
165                 $matched[] = $regexps[$i];
166                 $matched_ind[] = $i;
167                 $regexp_ind = $i;
168             }
169         }
170         // To overcome ANCHORED:
171         // We could sort by longest match and iterate over these.
172         if (empty($matched)) return false;
173         }
174         $match = new RegexpSet_match;
175         
176         // Optimization: if the matches are only "$" and another, then omit "$"
177         if (! _INLINE_OPTIMIZATION or count($matched) > 2) {
178             assert(!empty($repeat));
179             assert(!empty($regexps));
180             for ($i=0; $i<count($regexps); $i++) {
181                 if (!trim($regexps[$i])) {
182                     trigger_error("empty regexp $i", E_USER_WARNING);
183                     $regexps[$i] = '\Wxxxx\w\W\w\W\w\W\w\W\w\W\w'; // some placeholder
184                 }
185             }
186             // We could do much better, if we would know the matching markup for the 
187             // longest regexp match:
188             $hugepat= "/ ( . $repeat ) ( (" . join(')|(', $regexps) . ") ) /Asx";
189             // Proposed premature optimization 1:
190             //$hugepat= "/ ( . $repeat ) ( (" . join(')|(', array_values($matched)) . ") ) /Asx";
191             if (! preg_match($hugepat, $text, $m)) {
192                 return false;
193             }
194             // Proposed premature optimization 1:
195             //$match->regexp_ind = $matched_ind[count($m) - 4];
196             $match->regexp_ind = count($m) - 4;
197         } else {
198             $match->regexp_ind = $regexp_ind;
199         }
200         
201         $match->postmatch = substr($text, strlen($m[0]));
202         $match->prematch = $m[1];
203         $match->match = $m[2];
204
205         /* DEBUGGING */
206         /*
207         if (DEBUG & 4) {
208           var_dump($regexps); var_dump($matched); var_dump($matched_inc); 
209         PrintXML(HTML::dl(HTML::dt("input"),
210                           HTML::dd(HTML::pre($text)),
211                           HTML::dt("regexp"),
212                           HTML::dd(HTML::pre($match->regexp_ind, ":", $regexps[$match->regexp_ind])),
213                           HTML::dt("prematch"),
214                           HTML::dd(HTML::pre($match->prematch)),
215                           HTML::dt("match"),
216                           HTML::dd(HTML::pre($match->match)),
217                           HTML::dt("postmatch"),
218                           HTML::dd(HTML::pre($match->postmatch))
219                           ));
220         }
221         */
222         return $match;
223     }
224 }
225
226
227
228 /**
229  * A simple markup rule (i.e. terminal token).
230  *
231  * These are defined by a regexp.
232  *
233  * When a match is found for the regexp, the matching text is replaced.
234  * The replacement content is obtained by calling the SimpleMarkup::markup method.
235  */ 
236 class SimpleMarkup
237 {
238     var $_match_regexp;
239
240     /** Get regexp.
241      *
242      * @return string Regexp which matches this token.
243      */
244     function getMatchRegexp () {
245         return $this->_match_regexp;
246     }
247
248     /** Markup matching text.
249      *
250      * @param string $match The text which matched the regexp
251      * (obtained from getMatchRegexp).
252      *
253      * @return mixed The expansion of the matched text.
254      */
255     function markup ($match /*, $body */) {
256         trigger_error("pure virtual", E_USER_ERROR);
257     }
258 }
259
260 /**
261  * A balanced markup rule.
262  *
263  * These are defined by a start regexp, and an end regexp.
264  */ 
265 class BalancedMarkup
266 {
267     var $_start_regexp;
268
269     /** Get the starting regexp for this rule.
270      *
271      * @return string The starting regexp.
272      */
273     function getStartRegexp () {
274         return $this->_start_regexp;
275     }
276     
277     /** Get the ending regexp for this rule.
278      *
279      * @param string $match The text which matched the starting regexp.
280      *
281      * @return string The ending regexp.
282      */
283     function getEndRegexp ($match) {
284         return $this->_end_regexp;
285     }
286
287     /** Get expansion for matching input.
288      *
289      * @param string $match The text which matched the starting regexp.
290      *
291      * @param mixed $body Transformed text found between the starting
292      * and ending regexps.
293      *
294      * @return mixed The expansion of the matched text.
295      */
296     function markup ($match, $body) {
297         trigger_error("pure virtual", E_USER_ERROR);
298     }
299 }
300
301 class Markup_escape  extends SimpleMarkup
302 {
303     function getMatchRegexp () {
304         return ESCAPE_CHAR . '(?: [[:alnum:]]+ | .)';
305     }
306     
307     function markup ($match) {
308         assert(strlen($match) >= 2);
309         return substr($match, 1);
310     }
311 }
312
313 /**
314  * [image.jpg size=50% border=5], [image.jpg size=50x30]
315  * Support for the following attributes: see stdlib.php:LinkImage()
316  *   size=<precent>%, size=<width>x<height>
317  *   border=n, align=\w+, hspace=n, vspace=n
318  */
319 function isImageLink($link) {
320     if (!$link) return false;
321     assert(defined('INLINE_IMAGES'));
322     return preg_match("/\\.(" . INLINE_IMAGES . ")$/i", $link)
323         or preg_match("/\\.(" . INLINE_IMAGES . ")\s+(size|border|align|hspace|vspace)=/i", $link);
324 }
325
326 function LinkBracketLink($bracketlink) {
327
328     // $bracketlink will start and end with brackets; in between will
329     // be either a page name, a URL or both separated by a pipe.
330     
331     // strip brackets and leading space
332     // FIXME: \n inside [] will lead to errors
333     preg_match('/(\#?) \[\s* (?: (.*?) \s* (?<!' . ESCAPE_CHAR . ')(\|) )? \s* (.+?) \s*\]/x',
334                $bracketlink, $matches);
335     if (count($matches) < 4) {
336         trigger_error(_("Invalid [] syntax ignored").": ".$bracketlink, E_USER_WARNING);
337         return new Cached_Link;
338     }
339     list (, $hash, $label, $bar, $rawlink) = $matches;
340
341     $label = UnWikiEscape($label);
342     /*
343      * Check if the user has typed a explicit URL. This solves the
344      * problem where the URLs have a ~ character, which would be stripped away.
345      *   "[http:/server/~name/]" will work as expected
346      *   "http:/server/~name/"   will NOT work as expected, will remove the ~
347      */
348     if (strstr($rawlink, "http://") or strstr($rawlink, "https://")) {
349         $link = $rawlink;
350         // Mozilla Browser URI Obfuscation Weakness 2004-06-14
351         //   http://www.securityfocus.com/bid/10532/
352         //   goodurl+"%2F%20%20%20."+badurl
353         if (preg_match("/%2F(%20)+\./i", $rawlink)) {
354             $rawlink = preg_replace("/%2F(%20)+\./i","%2F.",$rawlink);
355         }
356     } else
357         $link  = UnWikiEscape($rawlink);
358
359     /* Relatives links by Joel Schaubert.
360      * Recognize [../bla] or [/bla] as relative links, without needing http://
361      * but {/link] only if SUBPAG_SEPERATOR is not /
362      */
363     if (SUBPAGE_SEPARATOR == '/') {
364         if (preg_match('/^\.\.\//', $link)) {
365             return new Cached_ExternalLink($link, $label);
366         }
367     } else if (preg_match('/^(\.\.\/|\/)/', $link)) {
368         return new Cached_ExternalLink($link, $label);
369     }
370     // [label|link]
371     // if label looks like a url to an image, we want an image link.
372     if (isImageLink($label)) {
373         $imgurl = $label;
374         $intermap = getInterwikiMap();
375         if (preg_match("/^" . $intermap->getRegexp() . ":/", $label)) {
376             $imgurl = $intermap->link($label);
377             $imgurl = $imgurl->getAttr('href');
378         } elseif (! preg_match("#^(" . ALLOWED_PROTOCOLS . "):#", $imgurl)) {
379             // local theme linkname like 'images/next.gif'.
380             global $WikiTheme;
381             $imgurl = $WikiTheme->getImageURL($imgurl);
382         }
383         $label = LinkImage($imgurl, $link);
384     }
385
386     if ($hash) {
387         // It's an anchor, not a link...
388         $id = MangleXmlIdentifier($link);
389         return HTML::a(array('name' => $id, 'id' => $id),
390                        $bar ? $label : $link);
391     }
392
393     if (preg_match("#^(" . ALLOWED_PROTOCOLS . "):#", $link)) {
394         // if it's an image, embed it; otherwise, it's a regular link
395         if (isImageLink($link))
396             return LinkImage($link, $label);
397         else
398             return new Cached_ExternalLink($link, $label);
399     }
400     elseif (preg_match("/^phpwiki:/", $link))
401         return new Cached_PhpwikiURL($link, $label);
402     /* Semantic relations and attributes */
403     elseif (preg_match("/:[:-]/", $link) and !isImageLink($link))
404         return new Cached_SemanticLink($link, $label);
405     /*
406      * Inline images in Interwiki urls's:
407      * [File:my_image.gif] inlines the image,
408      * File:my_image.gif shows a plain inter-wiki link,
409      * [what a pic|File:my_image.gif] shows a named inter-wiki link to the gif
410      * [File:my_image.gif|what a pic] shows a inlimed image linked to the page "what a pic"
411      *
412      * Note that for simplicity we will accept embedded object tags (non-images) 
413      * here also, and seperate them later in LinkImage()
414      */
415     elseif (strstr($link,':')
416             and ($intermap = getInterwikiMap()) 
417             and preg_match("/^" . $intermap->getRegexp() . ":/", $link)) 
418     {
419         // trigger_error("label: $label link: $link", E_USER_WARNING);
420         if (empty($label) and isImageLink($link)) {
421             // if without label => inlined image [File:xx.gif]
422             $imgurl = $intermap->link($link);
423             return LinkImage($imgurl->getAttr('href'), $label);
424         }
425         return new Cached_InterwikiLink($link, $label);
426     } else {
427         // Split anchor off end of pagename.
428         if (preg_match('/\A(.*)(?<!'.ESCAPE_CHAR.')#(.*?)\Z/', $rawlink, $m)) {
429             list(,$rawlink,$anchor) = $m;
430             $pagename = UnWikiEscape($rawlink);
431             $anchor = UnWikiEscape($anchor);
432             if (!$label)
433                 $label = $link;
434         }
435         else {
436             $pagename = $link;
437             $anchor = false;
438         }
439         return new Cached_WikiLink($pagename, $label, $anchor);
440     }
441 }
442
443 class Markup_bracketlink  extends SimpleMarkup
444 {
445     var $_match_regexp = "\\#? \\[ .*? [^]\\s] .*? \\]";
446     
447     function markup ($match) {
448         $link = LinkBracketLink($match);
449         assert($link->isInlineElement());
450         return $link;
451     }
452 }
453
454 class Markup_url extends SimpleMarkup
455 {
456     function getMatchRegexp () {
457         return "(?<![[:alnum:]]) (?:" . ALLOWED_PROTOCOLS . ") : [^\s<>\"']+ (?<![ ,.?; \] \) ])";
458     }
459     
460     function markup ($match) {
461         return new Cached_ExternalLink(UnWikiEscape($match));
462     }
463 }
464
465
466 class Markup_interwiki extends SimpleMarkup
467 {
468     function getMatchRegexp () {
469         global $request;
470         $map = getInterwikiMap();
471         return "(?<! [[:alnum:]])" . $map->getRegexp(). ": \S+ (?<![ ,.?;! \] \) \" \' ])";
472     }
473
474     function markup ($match) {
475         //$map = getInterwikiMap();
476         return new Cached_InterwikiLink(UnWikiEscape($match));
477     }
478 }
479
480 class Markup_wikiword extends SimpleMarkup
481 {
482     function getMatchRegexp () {
483         global $WikiNameRegexp;
484         if (!trim($WikiNameRegexp)) return " " . WIKI_NAME_REGEXP;
485         return " $WikiNameRegexp";
486     }
487
488     function markup ($match) {
489         if (!$match) return false;
490         if ($this->_isWikiUserPage($match))
491             return new Cached_UserLink($match); //$this->_UserLink($match);
492         else
493             return new Cached_WikiLink($match);
494     }
495
496     // FIXME: there's probably a more useful place to put these two functions    
497     function _isWikiUserPage ($page) {
498         global $request;
499         $dbi = $request->getDbh();
500         $page_handle = $dbi->getPage($page);
501         if ($page_handle and $page_handle->get('pref'))
502             return true;
503         else
504             return false;
505     }
506
507     function _UserLink($PageName) {
508         $link = HTML::a(array('href' => $PageName));
509         $link->pushContent(PossiblyGlueIconToText('wikiuser', $PageName));
510         $link->setAttr('class', 'wikiuser');
511         return $link;
512     }
513 }
514
515 class Markup_linebreak extends SimpleMarkup
516 {
517     //var $_match_regexp = "(?: (?<! %) %%% (?! %) | <(?:br|BR)> | <(?:br|BR) \/> )";
518     var $_match_regexp = "(?: (?<! %) %%% (?! %) | <(?:br|BR)> )";
519
520     function markup ($match) {
521         return HTML::br();
522     }
523 }
524
525 class Markup_old_emphasis  extends BalancedMarkup
526 {
527     var $_start_regexp = "''|__";
528
529     function getEndRegexp ($match) {
530         return $match;
531     }
532     
533     function markup ($match, $body) {
534         $tag = $match == "''" ? 'em' : 'strong';
535         return new HtmlElement($tag, $body);
536     }
537 }
538
539 class Markup_nestled_emphasis extends BalancedMarkup
540 {
541     function getStartRegexp() {
542         static $start_regexp = false;
543
544         if (!$start_regexp) {
545             // The three possible delimiters
546             // (none of which can be followed by itself.)
547             $i = "_ (?! _)";
548             $b = "\\* (?! \\*)";
549             $tt = "= (?! =)";
550
551             $any = "(?: ${i}|${b}|${tt})"; // any of the three.
552
553             // Any of [_*=] is okay if preceded by space or one of [-"'/:]
554             $start[] = "(?<= \\s|^|[-\"'\\/:]) ${any}";
555
556             // _ or * is okay after = as long as not immediately followed by =
557             $start[] = "(?<= =) (?: ${i}|${b}) (?! =)";
558             // etc...
559             $start[] = "(?<= _) (?: ${b}|${tt}) (?! _)";
560             $start[] = "(?<= \\*) (?: ${i}|${tt}) (?! \\*)";
561
562
563             // any delimiter okay after an opening brace ( [{<(] )
564             // as long as it's not immediately followed by the matching closing
565             // brace.
566             $start[] = "(?<= { ) ${any} (?! } )";
567             $start[] = "(?<= < ) ${any} (?! > )";
568             $start[] = "(?<= \\( ) ${any} (?! \\) )";
569             
570             $start = "(?:" . join('|', $start) . ")";
571             
572             // Any of the above must be immediately followed by non-whitespace.
573             $start_regexp = $start . "(?= \S)";
574         }
575
576         return $start_regexp;
577     }
578
579     function getEndRegexp ($match) {
580         $chr = preg_quote($match);
581         return "(?<= \S | ^ ) (?<! $chr) $chr (?! $chr) (?= \s | [-)}>\"'\\/:.,;!? _*=] | $)";
582     }
583     
584     function markup ($match, $body) {
585         switch ($match) {
586         case '*': return new HtmlElement('b', $body);
587         case '=': return new HtmlElement('tt', $body);
588         case '_': return new HtmlElement('i', $body);
589         }
590     }
591 }
592
593 class Markup_html_emphasis extends BalancedMarkup
594 {
595     var $_start_regexp = 
596         "<(?: b|big|i|small|tt|em|strong|cite|code|dfn|kbd|samp|strike|del|var|sup|sub )>";
597
598     function getEndRegexp ($match) {
599         return "<\\/" . substr($match, 1);
600     }
601     
602     function markup ($match, $body) {
603         $tag = substr($match, 1, -1);
604         return new HtmlElement($tag, $body);
605     }
606 }
607
608 class Markup_html_abbr extends BalancedMarkup
609 {
610     //rurban: abbr|acronym need an optional title tag.
611     //sf.net bug #728595
612     var $_start_regexp = "<(?: abbr|acronym )(?: \stitle=[^>]*)?>";
613
614     function getEndRegexp ($match) {
615         if (substr($match,1,4) == 'abbr')
616             $tag = 'abbr';
617         else
618             $tag = 'acronym';
619         return "<\\/" . $tag . '>';
620     }
621     
622     function markup ($match, $body) {
623         if (substr($match,1,4) == 'abbr')
624             $tag = 'abbr';
625         else
626             $tag = 'acronym';
627         $rest = substr($match,1+strlen($tag),-1);
628         if (!empty($rest)) {
629             list($key,$val) = explode("=",$rest);
630             $args = array($key => $val);
631         } else $args = array();
632         return new HtmlElement($tag, $args, $body);
633     }
634 }
635
636 /** ENABLE_MARKUP_COLOR
637  *  See http://www.pmwiki.org/wiki/PmWiki/WikiStyles and
638  *      http://www.flexwiki.com/default.aspx/FlexWiki/FormattingRules.html
639  */
640 class Markup_color extends BalancedMarkup {
641     // %color=blue% blue text %% and back to normal
642     var $_start_regexp = "%color=(?: [^%]*)%";
643     var $_end_regexp = "%%";
644     
645     function markup ($match, $body) {
646         $color = substr($match, 7, -1);
647         if (strlen($color) != 7 
648             and in_array($color, array('red', 'blue', 'grey', 'black'))) {
649             // must be a name
650             return new HtmlElement('font', array('color' => $color), $body);
651         } elseif ((substr($color,0,1) == '#') 
652                   and (strspn(substr($color,1),'0123456789ABCDEFabcdef') == strlen($color)-1)) {
653             return new HtmlElement('font', array('color' => $color), $body);
654         } else {
655             trigger_error(sprintf(_("unknown color %s ignored"), $color), E_USER_WARNING);
656         }
657                 
658     }
659 }
660
661 // Special version for single-line plugins formatting, 
662 //  like: '<small>< ?plugin PopularNearby ? ></small>'
663 class Markup_plugin extends SimpleMarkup
664 {
665     var $_match_regexp = '<\?plugin(?:-form)?\s[^\n]+?\?>';
666
667     function markup ($match) {
668         //$xml = new Cached_PluginInvocation($match);
669         //$xml->setTightness(true,true);
670         return new Cached_PluginInvocation($match);
671     }
672 }
673
674 // Special version for plugins in xml syntax 
675 // <name arg=value>body</name> or <name /> => < ? plugin pluginname arg=value body ? >
676 // PLUGIN_MARKUP_MAP = "html:RawHtml dot:GraphViz toc:CreateToc amath:AsciiMath richtable:RichTable include:IncludePage tex:TexToPng"
677 class Markup_xml_plugin extends BalancedMarkup
678 {
679     //var $_start_regexp = "<(?: ".join('|',PLUGIN_MARKUP_MAP)." )(?: \s[^>]*)>";
680
681     function getStartRegexp ($match) {
682         static $_start_regexp;
683         if ($_start_regexp) return $_start_regexp;
684         if (!defined('PLUGIN_MARKUP_MAP'))
685             return '';
686         $pairs = split(' ', PLUGIN_MARKUP_MAP);
687         $this->_map = array();
688         foreach ($pairs as $pair) {
689             list($xml,$plugin) = split(':',$pair);
690             $this->_map[$xml] = $plugin;
691         }
692         //"<(?: html|dot|toc|amath|richtable|include|tex )(?: \s[^>]*)>"
693         return "<(?: ".join('|',array_keys($this->_map))." )(?:(?:\s[^>]*|/))>";;
694     }
695     function getEndRegexp ($match) {
696         return "<\\/" . $match . '>';
697     }
698     function markup ($match, $body) {
699         $name = substr($match,2,-2); $vars = '';
700         if (preg_match('/^(\S+)\|(.*)$/', $name, $_m)) {
701             $name = $_m[1];
702             $vars = $_m[2]; //str_replace(' ', '&', $_m[2]);
703         }
704         if (!isset($this->_map[$name])) {
705             trigger_error("No plugin for $ name $ vars defined.", E_USER_WARNING);
706             return "";
707         }
708         $plugin = $this->_map[$name];
709         return new Cached_PluginInvocation("<"."?plugin $plugin $vars $body ?".">");
710     }
711 }
712
713 /** ENABLE_MARKUP_TEMPLATE
714  *  Template syntax similar to mediawiki
715  *  {{template}}
716  * => < ? plugin Template page=template ? >
717  *  {{template|var=value|...}}
718  * => < ? plugin Template page=template vars="var=value&..." ? >
719  */
720 class Markup_template_plugin  extends SimpleMarkup
721 {
722     var $_match_regexp = '\{\{\w[^\n]+\}\}';
723     
724     function markup ($match) {
725         $page = substr($match,2,-2); $vars = '';
726         if (preg_match('/^(\S+)\|(.*)$/', $page, $_m)) {
727             $page = $_m[1];
728             $vars = str_replace('|', '&', $_m[2]);
729         }
730         if ($vars)
731             $s = '<'.'?plugin Template page=' . $page . ' vars="' . $vars . '"?'.'>';
732         else
733             $s = '<'.'?plugin Template page=' . $page . '?'.'>';
734         return new Cached_PluginInvocation($s);
735     }
736 }
737
738 // "..." => "&#133;"  browser specific display (not cached?)
739 // Support some HTML::Entities: (C) for copy, --- for mdash, -- for ndash
740 // TODO: "--" => "&emdash;" browser specific display (not cached?)
741
742 class Markup_html_entities  extends SimpleMarkup {
743     //var $_match_regexp = '(: \.\.\.|\-\-|\-\-\-|\(C\) )';
744
745     function Markup_html_entities() {
746         $this->_entities = array('...'  => '&#133;',
747                                  '--'   => '&ndash;',
748                                  '---'  => '&mdash;',
749                                  '(C)'  => '&copy;',
750                                  '&copy;' => '&copy;',
751                                  '&trade;'  => '&trade;',
752                                  );
753         $this->_match_regexp = 
754             '(: ' . 
755             join('|', array_map('preg_quote', array_keys($this->_entities))) . 
756             ' )';
757     }
758    
759     function markup ($match) {
760         return HTML::Raw($this->_entities[$match]);
761     }
762 }
763
764 class Markup_isonumchars  extends SimpleMarkup {
765     var $_match_regexp = '\&\#\d{2,5};';
766     
767     function markup ($match) {
768         return HTML::Raw($match);
769     }
770 }
771
772 class Markup_isohexchars extends SimpleMarkup {
773     // hexnums, like &#x00A4; <=> &curren;
774     var $_match_regexp = '\&\#x[0-9a-fA-F]{2,4};';
775     
776     function markup ($match) {
777         return HTML::Raw($match);
778     }
779 }
780
781 // FIXME: Do away with magic phpwiki forms.  (Maybe phpwiki: links too?)
782 // FIXME: Do away with plugin-links.  They seem not to be used.
783 //Plugin link
784
785 class InlineTransformer
786 {
787     var $_regexps = array();
788     var $_markup = array();
789     
790     function InlineTransformer ($markup_types = false) {
791         if (!$markup_types) {
792             $non_default = false;
793             if (DISABLE_MARKUP_WIKIWORD)
794                 $markup_types = array
795                     ('escape', 'bracketlink', 'url',
796                      'interwiki', /* 'wikiword', */ 'linebreak',
797                      'old_emphasis', 'nestled_emphasis',
798                      'html_emphasis', 'html_abbr', 'plugin',
799                      'isonumchars', 'isohexchars', 'html_entities'
800                      );
801             else
802                 $markup_types = array
803                     ('escape', 'bracketlink', 'url',
804                      'interwiki', 'wikiword', 'linebreak',
805                      'old_emphasis', 'nestled_emphasis',
806                      'html_emphasis', 'html_abbr', 'plugin',
807                      'isonumchars', 'isohexchars', /*'html_entities'*/
808                      );
809         } else {
810             $non_default = true;
811         }
812         foreach ($markup_types as $mtype) {
813             $class = "Markup_$mtype";
814             $this->_addMarkup(new $class);
815         }
816         if (ENABLE_MARKUP_COLOR and !$non_default)
817             $this->_addMarkup(new Markup_color);
818         if (ENABLE_MARKUP_TEMPLATE and !$non_default)
819             $this->_addMarkup(new Markup_template_plugin);
820     }
821
822     function _addMarkup ($markup) {
823         if (isa($markup, 'SimpleMarkup'))
824             $regexp = $markup->getMatchRegexp();
825         else
826             $regexp = $markup->getStartRegexp();
827
828         assert(!isset($this->_markup[$regexp]));
829         $this->_regexps[] = $regexp;
830         $this->_markup[] = $markup;
831     }
832         
833     function parse (&$text, $end_regexps = array('$')) {
834         $regexps = $this->_regexps;
835
836         // $end_re takes precedence: "favor reduce over shift"
837         array_unshift($regexps, $end_regexps[0]);
838         //array_push($regexps, $end_regexps[0]);
839         $regexps = new RegexpSet($regexps);
840         
841         $input = $text;
842         $output = new XmlContent;
843
844         $match = $regexps->match($input);
845         
846         while ($match) {
847             if ($match->regexp_ind == 0) {
848                 // No start pattern found before end pattern.
849                 // We're all done!
850                 if (isset($markup) and is_object($markup) 
851                     and isa($markup,'Markup_plugin')) 
852                 {
853                     $current =& $output->_content[count($output->_content)-1];
854                     $current->setTightness(true,true);
855                 }
856                 $output->pushContent($match->prematch);
857                 $text = $match->postmatch;
858                 return $output;
859             }
860
861             $markup = $this->_markup[$match->regexp_ind - 1];
862             $body = $this->_parse_markup_body($markup, $match->match, 
863                                               $match->postmatch, $end_regexps);
864             if (!$body) {
865                 // Couldn't match balanced expression.
866                 // Ignore and look for next matching start regexp.
867                 $match = $regexps->nextMatch($input, $match);
868                 continue;
869             }
870
871             // Matched markup.  Eat input, push output.
872             // FIXME: combine adjacent strings.
873             if (isa($markup, 'SimpleMarkup'))
874                 $current = $markup->markup($match->match);
875             else
876                 $current = $markup->markup($match->match, $body);
877             $input = $match->postmatch;
878             if (isset($markup) and is_object($markup) 
879                 and isa($markup,'Markup_plugin')) 
880             {
881                 $current->setTightness(true,true);
882             }
883             $output->pushContent($match->prematch, $current);
884
885             $match = $regexps->match($input);
886         }
887
888         // No pattern matched, not even the end pattern.
889         // Parse fails.
890         return false;
891     }
892
893     function _parse_markup_body ($markup, $match, &$text, $end_regexps) {
894         if (isa($markup, 'SimpleMarkup'))
895             return true;        // Done. SimpleMarkup is simple.
896
897         if (!is_object($markup)) return false; // Some error: Should assert
898         array_unshift($end_regexps, $markup->getEndRegexp($match));
899
900         // Optimization: if no end pattern in text, we know the
901         // parse will fail.  This is an important optimization,
902         // e.g. when text is "*lots *of *start *delims *with
903         // *no *matching *end *delims".
904         $ends_pat = "/(?:" . join(").*(?:", $end_regexps) . ")/xs";
905         if (!preg_match($ends_pat, $text))
906             return false;
907         return $this->parse($text, $end_regexps);
908     }
909 }
910
911 class LinkTransformer extends InlineTransformer
912 {
913     function LinkTransformer () {
914         $this->InlineTransformer(array('escape', 'bracketlink', 'url',
915                                        'interwiki', 'wikiword'));
916     }
917 }
918
919 class NowikiTransformer extends InlineTransformer
920 {
921     function NowikiTransformer () {
922         $this->InlineTransformer
923             (array('linebreak',
924                    'html_emphasis', 'html_abbr', 'plugin',
925                    'isonumchars', 'isohexchars', /*'html_entities',*/
926                    ));
927     }
928 }
929
930 function TransformInline($text, $markup = 2.0, $basepage=false) {
931     static $trfm;
932     
933     if (empty($trfm)) {
934         $trfm = new InlineTransformer;
935     }
936     
937     if ($markup < 2.0) {
938         $text = ConvertOldMarkup($text, 'inline');
939     }
940
941     if ($basepage) {
942         return new CacheableMarkup($trfm->parse($text), $basepage);
943     }
944     return $trfm->parse($text);
945 }
946
947 function TransformLinks($text, $markup = 2.0, $basepage = false) {
948     static $trfm;
949     
950     if (empty($trfm)) {
951         $trfm = new LinkTransformer;
952     }
953
954     if ($markup < 2.0) {
955         $text = ConvertOldMarkup($text, 'links');
956     }
957     
958     if ($basepage) {
959         return new CacheableMarkup($trfm->parse($text), $basepage);
960     }
961     return $trfm->parse($text);
962 }
963
964 /**
965  * Transform only html markup and entities.
966  */
967 function TransformInlineNowiki($text, $markup = 2.0, $basepage=false) {
968     static $trfm;
969     
970     if (empty($trfm)) {
971         $trfm = new NowikiTransformer;
972     }
973     if ($basepage) {
974         return new CacheableMarkup($trfm->parse($text), $basepage);
975     }
976     return $trfm->parse($text);
977 }
978
979
980 // $Log: not supported by cvs2svn $
981 // Revision 1.75  2006/08/15 13:43:10  rurban
982 // add Markup_xml_plugin (untested) and fix Markup_template_plugin
983 //
984 // Revision 1.74  2006/07/23 14:03:18  rurban
985 // add new feature: DISABLE_MARKUP_WIKIWORD
986 //
987 // Revision 1.73  2006/04/15 12:20:36  rurban
988 // fix relatives links patch by Joel Schaubert for [/
989 //
990 // Revision 1.72  2006/03/07 20:43:29  rurban
991 // relative external link, if no internal subpage. by joel Schaubert
992 //
993 // Revision 1.71  2005/11/14 22:31:12  rurban
994 // add SemanticWeb support
995 //
996 // Revision 1.70  2005/10/31 16:45:23  rurban
997 // added cfg-able markups only for default TextTransformation, not for links and others
998 //
999 // Revision 1.69  2005/09/14 05:57:19  rurban
1000 // make ENABLE_MARKUP_TEMPLATE optional
1001 //
1002 // Revision 1.68  2005/09/10 21:24:32  rurban
1003 // optionally support {{Template|vars}} syntax
1004 //
1005 // Revision 1.67  2005/06/06 17:41:20  rurban
1006 // support new ENABLE_MARKUP_COLOR
1007 //
1008 // Revision 1.66  2005/04/23 11:15:49  rurban
1009 // handle allowed inlined objects within INLINE_IMAGES
1010 //
1011 // Revision 1.65  2005/03/27 18:24:17  rurban
1012 // add Log
1013 //
1014
1015 // (c-file-style: "gnu")
1016 // Local Variables:
1017 // mode: php
1018 // tab-width: 8
1019 // c-basic-offset: 4
1020 // c-hanging-comment-ender-p: nil
1021 // indent-tabs-mode: nil
1022 // End:   
1023 ?>