]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/InlineParser.php
Implemented Wikicreole syntax for preformatted text
[SourceForge/phpwiki.git] / lib / InlineParser.php
1 <?php 
2 rcs_id('$Id: InlineParser.php,v 1.105 2008-08-19 18:05:40 vargenau Exp $');
3 /* Copyright (C) 2002 Geoffrey T. Dairiki <dairiki@dairiki.org>
4  * Copyright (C) 2004-2008 Reini Urban
5  * Copyright (C) 2008 Marc-Etienne Vargenau, Alcatel-Lucent
6  *
7  * This file is part of PhpWiki.
8  * 
9  * PhpWiki is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License as published by
11  * the Free Software Foundation; either version 2 of the License, or
12  * (at your option) any later version.
13  * 
14  * PhpWiki is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU General Public License for more details.
18  * 
19  * You should have received a copy of the GNU General Public License
20  * along with PhpWiki; if not, write to the Free Software
21  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
22  */
23 /**
24  * This is the code which deals with the inline part of the (new-style)
25  * wiki-markup.
26  *
27  * @package Markup
28  * @author Geoffrey T. Dairiki, Reini Urban
29  */
30 /**
31  */
32
33 /**
34  * This is the character used in wiki markup to escape characters with
35  * special meaning.
36  */
37 define('ESCAPE_CHAR', '~');
38
39 require_once(dirname(__FILE__).'/HtmlElement.php');
40 require_once('lib/CachedMarkup.php');
41 require_once(dirname(__FILE__).'/stdlib.php');
42
43
44 function WikiEscape($text) {
45     return str_replace('#', ESCAPE_CHAR . '#', $text);
46 }
47
48 function UnWikiEscape($text) {
49     return preg_replace('/' . ESCAPE_CHAR . '(.)/', '\1', $text);
50 }
51
52 /**
53  * Return type from RegexpSet::match and RegexpSet::nextMatch.
54  *
55  * @see RegexpSet
56  */
57 class RegexpSet_match {
58     /**
59      * The text leading up the the next match.
60      */
61     var $prematch;
62     /**
63      * The matched text.
64      */
65     var $match;
66     /**
67      * The text following the matched text.
68      */
69     var $postmatch;
70     /**
71      * Index of the regular expression which matched.
72      */
73     var $regexp_ind;
74 }
75
76 /**
77  * A set of regular expressions.
78  *
79  * This class is probably only useful for InlineTransformer.
80  */
81 class RegexpSet
82 {
83     /** Constructor
84      *
85      * @param array $regexps A list of regular expressions.  The
86      * regular expressions should not include any sub-pattern groups
87      * "(...)".  (Anonymous groups, like "(?:...)", as well as
88      * look-ahead and look-behind assertions are okay.)
89      */
90     function RegexpSet ($regexps) {
91         assert($regexps);
92         $this->_regexps = array_unique($regexps);
93         if (!defined('_INLINE_OPTIMIZATION')) define('_INLINE_OPTIMIZATION',0);
94     }
95
96     /**
97      * Search text for the next matching regexp from the Regexp Set.
98      *
99      * @param string $text The text to search.
100      *
101      * @return RegexpSet_match  A RegexpSet_match object, or false if no match.
102      */
103     function match ($text) {
104         return $this->_match($text, $this->_regexps, '*?');
105     }
106
107     /**
108      * Search for next matching regexp.
109      *
110      * Here, 'next' has two meanings:
111      *
112      * Match the next regexp(s) in the set, at the same position as the last match.
113      *
114      * If that fails, match the whole RegexpSet, starting after the position of the
115      * previous match.
116      *
117      * @param string $text Text to search.
118      *
119      * @param RegexpSet_match $prevMatch A RegexpSet_match object.
120      * $prevMatch should be a match object obtained by a previous
121      * match upon the same value of $text.
122      *
123      * @return RegexpSet_match A RegexpSet_match object, or false if no match.
124      */
125     function nextMatch ($text, $prevMatch) {
126         // Try to find match at same position.
127         $pos = strlen($prevMatch->prematch);
128         $regexps = array_slice($this->_regexps, $prevMatch->regexp_ind + 1);
129         if ($regexps) {
130             $repeat = sprintf('{%d}', $pos);
131             if ( ($match = $this->_match($text, $regexps, $repeat)) ) {
132                 $match->regexp_ind += $prevMatch->regexp_ind + 1;
133                 return $match;
134             }
135             
136         }
137         
138         // Failed.  Look for match after current position.
139         $repeat = sprintf('{%d,}?', $pos + 1);
140         return $this->_match($text, $this->_regexps, $repeat);
141     }
142
143     // Syntax: http://www.pcre.org/pcre.txt
144     //   x - EXTENDED, ignore whitespace
145     //   s - DOTALL
146     //   A - ANCHORED
147     //   S - STUDY
148     function _match ($text, $regexps, $repeat) {
149         // If one of the regexps is an empty string, php will crash here: 
150         // sf.net: Fatal error: Allowed memory size of 8388608 bytes exhausted 
151         //         (tried to allocate 634 bytes)
152         if (_INLINE_OPTIMIZATION) { // disabled, wrong
153             // So we try to minize memory usage, by looping explicitly,
154             // and storing only those regexp which actually match. 
155             // There may be more than one, so we have to find the longest, 
156             // and match inside until the shortest is empty.
157             $matched = array(); $matched_ind = array();
158             for ($i=0; $i<count($regexps); $i++) {
159                 if (!trim($regexps[$i])) {
160                     trigger_error("empty regexp $i", E_USER_WARNING);
161                     continue;
162                 }
163                 $pat= "/ ( . $repeat ) ( " . $regexps[$i] . " ) /x";
164                 if (preg_match($pat, $text, $_m)) {
165                     $m = $_m; // FIXME: prematch, postmatch is wrong
166                     $matched[] = $regexps[$i];
167                     $matched_ind[] = $i;
168                     $regexp_ind = $i;
169                 }
170             }
171             // To overcome ANCHORED:
172             // We could sort by longest match and iterate over these.
173             if (empty($matched)) return false;
174         }
175         $match = new RegexpSet_match;
176         
177         // Optimization: if the matches are only "$" and another, then omit "$"
178         if (! _INLINE_OPTIMIZATION or count($matched) > 2) {
179             assert(!empty($repeat));
180             assert(!empty($regexps));
181             // We could do much better, if we would know the matching markup for the 
182             // longest regexp match:
183             $hugepat= "/ ( . $repeat ) ( (" . join(')|(', $regexps) . ") ) /Asx";
184             // Proposed premature optimization 1:
185             //$hugepat= "/ ( . $repeat ) ( (" . join(')|(', array_values($matched)) . ") ) /Asx";
186             if (! preg_match($hugepat, $text, $m)) {
187                 return false;
188             }
189             // Proposed premature optimization 1:
190             //$match->regexp_ind = $matched_ind[count($m) - 4];
191             $match->regexp_ind = count($m) - 4;
192         } else {
193             $match->regexp_ind = $regexp_ind;
194         }
195         
196         $match->postmatch = substr($text, strlen($m[0]));
197         $match->prematch = $m[1];
198         $match->match = $m[2];
199
200         /* DEBUGGING */
201         if (DEBUG & _DEBUG_PARSER) {
202           static $_already_dumped = 0;
203           if (!$_already_dumped) {
204             var_dump($regexps); 
205             if (_INLINE_OPTIMIZATION)
206                 var_dump($matched);
207             var_dump($matched_inc); 
208           }
209           $_already_dumped = 1;
210           PrintXML(HTML::dl(HTML::dt("input"),
211                           HTML::dd(HTML::pre($text)),
212                           HTML::dt("regexp"),
213                           HTML::dd(HTML::pre($match->regexp_ind, ":", $regexps[$match->regexp_ind])),
214                           HTML::dt("prematch"),
215                           HTML::dd(HTML::pre($match->prematch)),
216                           HTML::dt("match"),
217                           HTML::dd(HTML::pre($match->match)),
218                           HTML::dt("postmatch"),
219                           HTML::dd(HTML::pre($match->postmatch))
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|type|data|width|height)=/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    $wikicreolesyntax = false;
332
333    if (string_starts_with($bracketlink, "[[")) {
334        $wikicreolesyntax = true;
335        $bracketlink = str_replace("[[", "[", $bracketlink);
336        $bracketlink = str_replace("]]", "]", $bracketlink);
337    }
338   
339     // Strip brackets and leading space
340     // bug#1904088  Some brackets links on 2 lines cause the parser to crash
341     preg_match('/(\#?) \[\s* (?: (.*?) \s* (?<!' . ESCAPE_CHAR . ')(\|) )? \s* (.+?) \s*\]/x',
342                str_replace("\n", " ", $bracketlink), $matches);
343     if (count($matches) < 4) {
344         // "[ personal\ninformation manager | PhpWiki:PersonalWiki ]"
345         trigger_error(_("Invalid [] syntax ignored").": ".$bracketlink, E_USER_WARNING);
346         return new Cached_Link;
347     }
348     list (, $hash, $label, $bar, $rawlink) = $matches;
349
350     if ($wikicreolesyntax and $label) {
351         $temp = $label;
352         $label = $rawlink;
353         $rawlink = $temp;
354     }
355
356     $label = UnWikiEscape($label);
357     /*
358      * Check if the user has typed a explicit URL. This solves the
359      * problem where the URLs have a ~ character, which would be stripped away.
360      *   "[http:/server/~name/]" will work as expected
361      *   "http:/server/~name/"   will NOT work as expected, will remove the ~
362      */
363     if (   string_starts_with ($rawlink, "http://")
364         or string_starts_with ($rawlink, "https://") ) 
365     {
366         $link = $rawlink;
367         // Mozilla Browser URI Obfuscation Weakness 2004-06-14
368         //   http://www.securityfocus.com/bid/10532/
369         //   goodurl+"%2F%20%20%20."+badurl
370         if (preg_match("/%2F(%20)+\./i", $rawlink)) {
371             $rawlink = preg_replace("/%2F(%20)+\./i","%2F.",$rawlink);
372         }
373     } else
374         $link  = UnWikiEscape($rawlink);
375
376     /* Relatives links by Joel Schaubert.
377      * Recognize [../bla] or [/bla] as relative links, without needing http://
378      * but [ /link ] only if SUBPAGE_SEPERATOR is not "/". 
379      * Normally /Page links to the subpage /Page.
380      */
381     if (SUBPAGE_SEPARATOR == '/') {
382         if (preg_match('/^\.\.\//', $link)) {
383             return new Cached_ExternalLink($link, $label);
384         }
385     } else if (preg_match('/^(\.\.\/|\/)/', $link)) {
386         return new Cached_ExternalLink($link, $label);
387     }
388     // [label|link]
389     // If label looks like a url to an image or object, we want an image link.
390     if (isImageLink($label)) {
391         $imgurl = $label;
392         $intermap = getInterwikiMap();
393         if (preg_match("/^" . $intermap->getRegexp() . ":/", $label)) {
394             $imgurl = $intermap->link($label);
395             $imgurl = $imgurl->getAttr('href');
396         } elseif (! preg_match("#^(" . ALLOWED_PROTOCOLS . "):#", $imgurl)) {
397             // local theme linkname like 'images/next.gif'.
398             global $WikiTheme;
399             $imgurl = $WikiTheme->getImageURL($imgurl);
400         }
401         // for objects (non-images) the link is taken as alt tag, 
402         // which is in return taken as alternative img
403         $label = LinkImage($imgurl, $link);
404     }
405
406     if ($hash) {
407         // It's an anchor, not a link...
408         $id = MangleXmlIdentifier($link);
409         return HTML::a(array('name' => $id, 'id' => $id),
410                        $bar ? $label : $link);
411     }
412
413     if (preg_match("#^(" . ALLOWED_PROTOCOLS . "):#", $link)) {
414         // if it's an image, embed it; otherwise, it's a regular link
415         if (isImageLink($link) and empty($label)) // patch #1348996 by Robert Litwiniec
416             return LinkImage($link, $label);
417         else
418             return new Cached_ExternalLink($link, $label);
419     }
420     elseif (substr($link,0,8) == 'phpwiki:')
421         return new Cached_PhpwikiURL($link, $label);
422
423     /* Semantic relations and attributes. 
424      * Relation and attribute names must be word chars only, no space.
425      * Links and Attributes may contain everything. word, nums, units, space, groupsep, numsep, ...
426      */
427     elseif (preg_match("/^ (\w+) (:[:=]) (.*) $/x", $link) and !isImageLink($link))
428         return new Cached_SemanticLink($link, $label);
429
430     /* Do not store the link */    
431     elseif (substr($link,0,1) == ':')
432         return new Cached_WikiLink($link, $label);
433
434     /*
435      * Inline images in Interwiki urls's:
436      * [File:my_image.gif] inlines the image,
437      * File:my_image.gif shows a plain inter-wiki link,
438      * [what a pic|File:my_image.gif] shows a named inter-wiki link to the gif
439      * [File:my_image.gif|what a pic] shows a inlimed image linked to the page "what a pic"
440      *
441      * Note that for simplicity we will accept embedded object tags (non-images) 
442      * here also, and seperate them later in LinkImage()
443      */
444     elseif (strstr($link,':')
445             and ($intermap = getInterwikiMap()) 
446             and preg_match("/^" . $intermap->getRegexp() . ":/", $link)) 
447     {
448         // trigger_error("label: $label link: $link", E_USER_WARNING);
449         if (empty($label) and isImageLink($link)) {
450             // if without label => inlined image [File:xx.gif]
451             $imgurl = $intermap->link($link);
452             return LinkImage($imgurl->getAttr('href'), $link);
453         }
454         return new Cached_InterwikiLink($link, $label);
455     } else {
456         // Split anchor off end of pagename.
457         if (preg_match('/\A(.*)(?<!'.ESCAPE_CHAR.')#(.*?)\Z/', $rawlink, $m)) {
458             list(,$rawlink,$anchor) = $m;
459             $pagename = UnWikiEscape($rawlink);
460             $anchor = UnWikiEscape($anchor);
461             if (!$label)
462                 $label = $link;
463         }
464         else {
465             $pagename = $link;
466             $anchor = false;
467         }
468         return new Cached_WikiLink($pagename, $label, $anchor);
469     }
470 }
471
472 class Markup_bracketlink  extends SimpleMarkup
473 {
474     var $_match_regexp = "\\#? \\[ .*? [^]\\s] .*? \\]";
475     // TODO: include second ] in regexp
476     
477     function markup ($match) {
478         $link = LinkBracketLink($match);
479         assert($link->isInlineElement());
480         return $link;
481     }
482 }
483
484 class Markup_spellcheck extends SimpleMarkup
485 {
486     function Markup_spellcheck () {
487         $this->suggestions = $GLOBALS['request']->getArg('suggestions');
488     }
489     function getMatchRegexp () {
490         if (empty($this->suggestions))
491             return "(?# false )";
492         $words = array_keys($this->suggestions);
493         return "(?<= \W ) (?:" . join('|', $words) . ") (?= \W )";
494     }
495     
496     function markup ($match) {
497         if (empty($this->suggestions) or empty($this->suggestions[$match]))
498             return $match;
499         return new Cached_SpellCheck(UnWikiEscape($match), $this->suggestions[$match]);
500     }
501 }
502
503 class Markup_searchhighlight extends SimpleMarkup
504 {
505     function Markup_searchhighlight () {
506         $result = $GLOBALS['request']->_searchhighlight;
507         require_once("lib/TextSearchQuery.php");
508         $query = new TextSearchQuery($result['query']);
509         $this->hilight_re = $query->getHighlightRegexp();
510         $this->engine = $result['engine'];
511     }
512     function getMatchRegexp () {
513         return $this->hilight_re;
514     }
515     function markup ($match) {
516         return new Cached_SearchHighlight(UnWikiEscape($match), $this->engine);
517     }
518 }
519
520 class Markup_url extends SimpleMarkup
521 {
522     function getMatchRegexp () {
523         return "(?<![[:alnum:]]) (?:" . ALLOWED_PROTOCOLS . ") : [^\s<>\"']+ (?<![ ,.?; \] \) ])";
524     }
525     
526     function markup ($match) {
527         return new Cached_ExternalLink(UnWikiEscape($match));
528     }
529 }
530
531 class Markup_interwiki extends SimpleMarkup
532 {
533     function getMatchRegexp () {
534         $map = getInterwikiMap();
535         return "(?<! [[:alnum:]])" . $map->getRegexp(). ": [^:=]\S+ (?<![ ,.?;! \] \) \" \' ])";
536     }
537
538     function markup ($match) {
539         return new Cached_InterwikiLink(UnWikiEscape($match));
540     }
541 }
542
543 class Markup_semanticlink extends SimpleMarkup
544 {
545     // No units seperated by space allowed here
546     // For :: (relations) only words, no comma,
547     // but for := (attributes) comma and dots are allowed. Units with groupsep.
548     // Ending dots or comma are not part of the link.
549     var $_match_regexp = "(?: \w+:=\S+(?<![\.,]))|(?: \w+::[\w\.]+(?<!\.))"; 
550
551     function markup ($match) {
552         return new Cached_SemanticLink(UnWikiEscape($match));
553     }
554 }
555
556 class Markup_wikiword extends SimpleMarkup
557 {
558     function getMatchRegexp () {
559         global $WikiNameRegexp;
560         if (!trim($WikiNameRegexp)) return " " . WIKI_NAME_REGEXP;
561         return " $WikiNameRegexp";
562     }
563
564     function markup ($match) {
565         if (!$match) return false;
566         if ($this->_isWikiUserPage($match))
567             return new Cached_UserLink($match); //$this->_UserLink($match);
568         else
569             return new Cached_WikiLink($match);
570     }
571
572     // FIXME: there's probably a more useful place to put these two functions    
573     function _isWikiUserPage ($page) {
574         global $request;
575         $dbi = $request->getDbh();
576         $page_handle = $dbi->getPage($page);
577         if ($page_handle and $page_handle->get('pref'))
578             return true;
579         else
580             return false;
581     }
582
583     function _UserLink($PageName) {
584         $link = HTML::a(array('href' => $PageName));
585         $link->pushContent(PossiblyGlueIconToText('wikiuser', $PageName));
586         $link->setAttr('class', 'wikiuser');
587         return $link;
588     }
589 }
590
591 class Markup_linebreak extends SimpleMarkup
592 {
593     //var $_match_regexp = "(?: (?<! %) %%% (?! %) | <(?:br|BR)> | <(?:br|BR) \/> )";
594     var $_match_regexp = "(?: (?<! %) %%% (?! %) | \\\\\\\\ | <(?:br|BR)> )";
595
596     function markup ($match) {
597         return HTML::br();
598     }
599 }
600
601 class Markup_wikicreole_subscript extends BalancedMarkup
602 {
603     var $_start_regexp = ",,";
604  
605     function getEndRegexp ($match) {
606         return $match; 
607     }
608    
609     function markup ($match, $body) {
610         $tag = 'sub';
611         return new HtmlElement($tag, $body);
612     }
613 }
614
615 class Markup_old_emphasis  extends BalancedMarkup
616 {
617     var $_start_regexp = "''|__";
618
619     function getEndRegexp ($match) {
620         return $match;
621     }
622     
623     function markup ($match, $body) {
624         $tag = $match == "''" ? 'em' : 'strong';
625         return new HtmlElement($tag, $body);
626     }
627 }
628
629 class Markup_nestled_emphasis extends BalancedMarkup
630 {
631     function getStartRegexp() {
632         static $start_regexp = false;
633
634         if (!$start_regexp) {
635             // The three possible delimiters
636             // (none of which can be followed by itself.)
637             $i = "_ (?! _)";
638             $b = "\\* (?! \\*)";
639             $tt = "= (?! =)";
640
641             $any = "(?: ${i}|${b}|${tt})"; // any of the three.
642
643             // Any of [_*=] is okay if preceded by space or one of [-"'/:]
644             $start[] = "(?<= \\s|^|[-\"'\\/:]) ${any}";
645
646             // _ or * is okay after = as long as not immediately followed by =
647             $start[] = "(?<= =) (?: ${i}|${b}) (?! =)";
648             // etc...
649             $start[] = "(?<= _) (?: ${b}|${tt}) (?! _)";
650             $start[] = "(?<= \\*) (?: ${i}|${tt}) (?! \\*)";
651
652
653             // any delimiter okay after an opening brace ( [{<(] )
654             // as long as it's not immediately followed by the matching closing
655             // brace.
656             $start[] = "(?<= { ) ${any} (?! } )";
657             $start[] = "(?<= < ) ${any} (?! > )";
658             $start[] = "(?<= \\( ) ${any} (?! \\) )";
659             
660             $start = "(?:" . join('|', $start) . ")";
661             
662             // Any of the above must be immediately followed by non-whitespace.
663             $start_regexp = $start . "(?= \S)";
664         }
665
666         return $start_regexp;
667     }
668
669     function getEndRegexp ($match) {
670         $chr = preg_quote($match);
671         return "(?<= \S | ^ ) (?<! $chr) $chr (?! $chr) (?= \s | [-)}>\"'\\/:.,;!? _*=] | $)";
672     }
673     
674     function markup ($match, $body) {
675         switch ($match) {
676         case '*': return new HtmlElement('b', $body);
677         case '=': return new HtmlElement('tt', $body);
678         case '_': return new HtmlElement('i', $body);
679         }
680     }
681 }
682
683 class Markup_html_emphasis extends BalancedMarkup
684 {
685     var $_start_regexp = 
686         "<(?: b|big|i|small|tt|em|strong|cite|code|dfn|kbd|samp|s|strike|del|var|sup|sub )>";
687
688     function getEndRegexp ($match) {
689         return "<\\/" . substr($match, 1);
690     }
691     
692     function markup ($match, $body) {
693         $tag = substr($match, 1, -1);
694         return new HtmlElement($tag, $body);
695     }
696 }
697
698 class Markup_html_divspan extends BalancedMarkup
699 {
700     var $_start_regexp = 
701         "<(?: div|span )(?: \s[^>]*)?>";
702
703     function getEndRegexp ($match) {
704         if (substr($match,1,4) == 'span')
705             $tag = 'span';
706         else
707             $tag = 'div';
708         return "<\\/" . $tag . '>';
709     }
710     
711     function markup ($match, $body) {
712         if (substr($match,1,4) == 'span')
713             $tag = 'span';
714         else
715             $tag = 'div';
716         $rest = substr($match,1+strlen($tag),-1);
717         if (!empty($rest)) {
718             list($key,$val) = explode("=",$rest);
719             $args = array($key => $val);
720         } else $args = array();
721         return new HtmlElement($tag, $args, $body);
722     }
723 }
724
725
726 class Markup_html_abbr extends BalancedMarkup
727 {
728     //rurban: abbr|acronym need an optional title tag.
729     //sf.net bug #728595
730     var $_start_regexp = "<(?: abbr|acronym )(?: \stitle=[^>]*)?>";
731
732     function getEndRegexp ($match) {
733         if (substr($match,1,4) == 'abbr')
734             $tag = 'abbr';
735         else
736             $tag = 'acronym';
737         return "<\\/" . $tag . '>';
738     }
739     
740     function markup ($match, $body) {
741         if (substr($match,1,4) == 'abbr')
742             $tag = 'abbr';
743         else
744             $tag = 'acronym';
745         $rest = substr($match,1+strlen($tag),-1);
746         if (!empty($rest)) {
747             list($key,$val) = explode("=",$rest);
748             $args = array($key => $val);
749         } else $args = array();
750         return new HtmlElement($tag, $args, $body);
751     }
752 }
753
754 /** ENABLE_MARKUP_COLOR
755  *  See http://www.pmwiki.org/wiki/PmWiki/WikiStyles and
756  *      http://www.flexwiki.com/default.aspx/FlexWiki/FormattingRules.html
757  */
758 class Markup_color extends BalancedMarkup {
759     // %color=blue% blue text %% and back to normal
760     var $_start_regexp = "%color=(?: [^%]*)%";
761     var $_end_regexp = "%%";
762     
763     function markup ($match, $body) {
764         $color = strtoupper(substr($match, 7, -1));
765         if (strlen($color) != 7 
766             and in_array($color, array('RED', 'BLUE', 'GRAY', 'YELLOW', 'GREEN', 'CYAN', 'BLACK'))) 
767         {   // must be a valid color name
768             return new HtmlElement('font', array('color' => $color), $body);
769         } elseif ((substr($color,0,1) == '#') 
770                   and (strspn(substr($color,1),'0123456789ABCDEF') == strlen($color)-1)) {
771             return new HtmlElement('font', array('color' => $color), $body);
772         } else {
773             trigger_error(sprintf(_("unknown color %s ignored"), substr($match, 7, -1)), E_USER_WARNING);
774         }
775                 
776     }
777 }
778
779 // Special version for single-line plugins formatting, 
780 //  like: '<small>< ?plugin PopularNearby ? ></small>'
781 class Markup_plugin extends SimpleMarkup
782 {
783     var $_match_regexp = '<\?plugin(?:-form)?\s[^\n]+?\?>';
784
785     function markup ($match) {
786         //$xml = new Cached_PluginInvocation($match);
787         //$xml->setTightness(true,true);
788         return new Cached_PluginInvocation($match);
789     }
790 }
791
792 // Special version for plugins in xml syntax 
793 // <name arg=value>body</name> or <name /> => < ? plugin pluginname arg=value body ? >
794 // PLUGIN_MARKUP_MAP = "html:RawHtml dot:GraphViz toc:CreateToc amath:AsciiMath richtable:RichTable include:IncludePage tex:TexToPng"
795 class Markup_xml_plugin extends BalancedMarkup
796 {
797     //var $_start_regexp = "<(?: ".join('|',PLUGIN_MARKUP_MAP)." )(?: \s[^>]*)>";
798
799     function getStartRegexp () {
800         global $PLUGIN_MARKUP_MAP;
801         static $_start_regexp;
802         if ($_start_regexp) return $_start_regexp;
803         if (empty($PLUGIN_MARKUP_MAP))
804             return '';
805         //"<(?: html|dot|toc|amath|richtable|include|tex )(?: \s[^>]*)>"
806         $_start_regexp = "<(?: ".join('|',array_keys($PLUGIN_MARKUP_MAP))." )(?: \s[^>]* | / )>";
807         return $_start_regexp;
808     }
809     function getEndRegexp ($match) {
810         return "<\\/" . $match . '>';
811     }
812     function markup ($match, $body) {
813         global $PLUGIN_MARKUP_MAP;
814         $name = substr($match,2,-2); 
815         $vars = '';
816         if (preg_match('/^(\S+)\|(.*)$/', $name, $_m)) {
817             $name = $_m[1];
818             $vars = $_m[2]; //str_replace(' ', '&', $_m[2]);
819         }
820         if (!isset($PLUGIN_MARKUP_MAP[$name])) {
821             trigger_error("No plugin for $name $vars defined.", E_USER_WARNING);
822             return "";
823         }
824         $plugin = $PLUGIN_MARKUP_MAP[$name];
825         return new Cached_PluginInvocation("<"."?plugin $plugin $vars $body ?".">");
826     }
827 }
828
829 /**
830  *  Wikicreole preformatted
831  *  {{{
832  *  }}}
833  */
834 class Markup_wikicreole_preformatted extends SimpleMarkup
835 {
836     var $_match_regexp = '\{\{\{.*?\}\}\}';
837
838     function markup ($match) {
839         // Remove {{{ and }}}
840         return new HtmlElement('pre', substr($match, 3, -3));
841     }
842 }
843
844 /** ENABLE_MARKUP_TEMPLATE
845  *  Template syntax similar to mediawiki
846  *  {{template}}
847  * => < ? plugin Template page=template ? >
848  *  {{template|var1=value1|var2=value|...}}
849  * => < ? plugin Template page=template var=value ... ? >
850  */
851 class Markup_template_plugin  extends SimpleMarkup
852 {
853     // patch #1732793: allow \n, mult. {{ }} in one line, and single letters
854     var $_match_regexp = '\{\{.*?\}\}';
855     
856     function markup ($match) {
857         $page = substr(str_replace("\n", "", $match),2,-2); $vars = '';
858         if (preg_match('/^(\S+?)\|(.*)$/', $page, $_m)) {
859             $page = $_m[1];
860             $vars = '"' . preg_replace('/\|/', '" "', $_m[2]) . '"'; 
861             $vars = preg_replace('/"(\S+)=([^"]*)"/', '\\1="\\2"', $vars);
862         }
863  
864         // page may contain a version number
865         // {{foo?version=5}}
866         // in that case, output is "page=foo rev=5"
867         if (strstr($page, "?")) {
868             $page = str_replace("?version=", "\" rev=\"", $page);
869         }
870
871         if ($vars)
872             $s = '<'.'?plugin Template page="'.$page.'" '.$vars.' ?'.'>';
873         else
874             $s = '<'.'?plugin Template page="' . $page . '" ?'.'>';
875         return new Cached_PluginInvocation($s);
876     }
877 }
878
879 /** ENABLE_MARKUP_MEDIAWIKI_TABLE
880  *  Table syntax similar to Mediawiki
881  *  {|
882  * => <?plugin MediawikiTable
883  *  |}
884  * => ?>
885  */
886 class Markup_mediawikitable_plugin extends SimpleMarkup
887 {
888     var $_match_regexp = '\{\|.*?\|\}';
889
890     function markup ($match) {
891       $s = '<'.'?plugin MediawikiTable ' . $match . '?'.'>';
892       return new Cached_PluginInvocation($s);
893     }
894 }
895
896 // "..." => "&#133;"  browser specific display (not cached?)
897 // Support some HTML::Entities: (C) for copy, --- for mdash, -- for ndash
898 // TODO: "--" => "&emdash;" browser specific display (not cached?)
899
900 class Markup_html_entities  extends SimpleMarkup {
901     //var $_match_regexp = '(: \.\.\.|\-\-|\-\-\-|\(C\) )';
902
903     function Markup_html_entities() {
904         $this->_entities = array('...'  => '&#133;',
905                                  '--'   => '&ndash;',
906                                  '---'  => '&mdash;',
907                                  '(C)'  => '&copy;',
908                                  '&copy;' => '&copy;',
909                                  '&trade;'  => '&trade;',
910                                  );
911         $this->_match_regexp = 
912             '(: ' . 
913             join('|', array_map('preg_quote', array_keys($this->_entities))) . 
914             ' )';
915     }
916    
917     function markup ($match) {
918         return HTML::Raw($this->_entities[$match]);
919     }
920 }
921
922 class Markup_isonumchars  extends SimpleMarkup {
923     var $_match_regexp = '\&\#\d{2,5};';
924     
925     function markup ($match) {
926         return HTML::Raw($match);
927     }
928 }
929
930 class Markup_isohexchars extends SimpleMarkup {
931     // hexnums, like &#x00A4; <=> &curren;
932     var $_match_regexp = '\&\#x[0-9a-fA-F]{2,4};';
933     
934     function markup ($match) {
935         return HTML::Raw($match);
936     }
937 }
938
939 // FIXME: Do away with magic phpwiki forms.  (Maybe phpwiki: links too?)
940 // FIXME: Do away with plugin-links.  They seem not to be used.
941 //Plugin link
942
943 class InlineTransformer
944 {
945     var $_regexps = array();
946     var $_markup = array();
947     
948     function InlineTransformer ($markup_types = false) {
949         global $request;
950         // We need to extend the inline parsers by certain actions, like SearchHighlight, 
951         // SpellCheck and maybe CreateToc.
952         if (!$markup_types) {
953             $non_default = false;
954             $markup_types = array
955                 ('escape', 'bracketlink', 'url',
956                  'interwiki',  'semanticlink', 'wikiword', 'linebreak',
957                  'wikicreole_subscript', 'old_emphasis', 'nestled_emphasis',
958                  'html_emphasis', 'html_abbr', 'plugin',
959                  'isonumchars', 'isohexchars', /*'html_entities'*/
960                  );
961             if (DISABLE_MARKUP_WIKIWORD)
962                 $markup_types = array_remove($markup_types, 'wikiword');
963
964             $action = $request->getArg('action');
965             if ($action == 'SpellCheck' and $request->getArg('suggestions'))
966             {   // insert it after url
967                 array_splice($markup_types, 2, 1, array('url','spellcheck'));
968             }
969             if (isset($request->_searchhighlight))
970             {   // insert it after url
971                 array_splice($markup_types, 2, 1, array('url','searchhighlight'));
972                 //$request->setArg('searchhighlight', false);
973             }
974         } else {
975             $non_default = true;
976         }
977         foreach ($markup_types as $mtype) {
978             $class = "Markup_$mtype";
979             $this->_addMarkup(new $class);
980         }
981         if (ENABLE_MARKUP_DIVSPAN and !$non_default)
982             $this->_addMarkup(new Markup_html_divspan);
983         if (ENABLE_MARKUP_COLOR and !$non_default)
984             $this->_addMarkup(new Markup_color);
985         // Markup_wikicreole_preformatted must be before Markup_template_plugin
986         $this->_addMarkup(new Markup_wikicreole_preformatted);
987         if (ENABLE_MARKUP_TEMPLATE and !$non_default)
988             $this->_addMarkup(new Markup_template_plugin);
989         if (ENABLE_MARKUP_MEDIAWIKI_TABLE)
990             $this->_addMarkup(new Markup_mediawikitable_plugin);
991         // This does not work yet
992         if (0 and PLUGIN_MARKUP_MAP and !$non_default)
993             $this->_addMarkup(new Markup_xml_plugin);
994     }
995
996     function _addMarkup ($markup) {
997         if (isa($markup, 'SimpleMarkup'))
998             $regexp = $markup->getMatchRegexp();
999         else
1000             $regexp = $markup->getStartRegexp();
1001
1002         assert( !isset($this->_markup[$regexp]) );
1003         assert( strlen(trim($regexp)) > 0 );
1004         $this->_regexps[] = $regexp;
1005         $this->_markup[] = $markup;
1006     }
1007         
1008     function parse (&$text, $end_regexps = array('$')) {
1009         $regexps = $this->_regexps;
1010
1011         // $end_re takes precedence: "favor reduce over shift"
1012         array_unshift($regexps, $end_regexps[0]);
1013         //array_push($regexps, $end_regexps[0]);
1014         $regexps = new RegexpSet($regexps);
1015         
1016         $input = $text;
1017         $output = new XmlContent;
1018
1019         $match = $regexps->match($input);
1020         
1021         while ($match) {
1022             if ($match->regexp_ind == 0) {
1023                 // No start pattern found before end pattern.
1024                 // We're all done!
1025                 if (isset($markup) and is_object($markup) 
1026                     and isa($markup,'Markup_plugin')) 
1027                 {
1028                     $current =& $output->_content[count($output->_content)-1];
1029                     $current->setTightness(true,true);
1030                 }
1031                 $output->pushContent($match->prematch);
1032                 $text = $match->postmatch;
1033                 return $output;
1034             }
1035
1036             $markup = $this->_markup[$match->regexp_ind - 1];
1037             $body = $this->_parse_markup_body($markup, $match->match, 
1038                                               $match->postmatch, $end_regexps);
1039             if (!$body) {
1040                 // Couldn't match balanced expression.
1041                 // Ignore and look for next matching start regexp.
1042                 $match = $regexps->nextMatch($input, $match);
1043                 continue;
1044             }
1045
1046             // Matched markup.  Eat input, push output.
1047             // FIXME: combine adjacent strings.
1048             if (isa($markup, 'SimpleMarkup'))
1049                 $current = $markup->markup($match->match);
1050             else
1051                 $current = $markup->markup($match->match, $body);
1052             $input = $match->postmatch;
1053             if (isset($markup) and is_object($markup) 
1054                 and isa($markup,'Markup_plugin')) 
1055             {
1056                 $current->setTightness(true,true);
1057             }
1058             $output->pushContent($match->prematch, $current);
1059
1060             $match = $regexps->match($input);
1061         }
1062
1063         // No pattern matched, not even the end pattern.
1064         // Parse fails.
1065         return false;
1066     }
1067
1068     function _parse_markup_body ($markup, $match, &$text, $end_regexps) {
1069         if (isa($markup, 'SimpleMarkup'))
1070             return true;        // Done. SimpleMarkup is simple.
1071
1072         if (!is_object($markup)) return false; // Some error: Should assert
1073         array_unshift($end_regexps, $markup->getEndRegexp($match));
1074
1075         // Optimization: if no end pattern in text, we know the
1076         // parse will fail.  This is an important optimization,
1077         // e.g. when text is "*lots *of *start *delims *with
1078         // *no *matching *end *delims".
1079         $ends_pat = "/(?:" . join(").*(?:", $end_regexps) . ")/xs";
1080         if (!preg_match($ends_pat, $text))
1081             return false;
1082         return $this->parse($text, $end_regexps);
1083     }
1084 }
1085
1086 class LinkTransformer extends InlineTransformer
1087 {
1088     function LinkTransformer () {
1089         $this->InlineTransformer(array('escape', 'bracketlink', 'url',
1090                                        'semanticlink', 'interwiki', 'wikiword', 
1091                                        ));
1092     }
1093 }
1094
1095 class NowikiTransformer extends InlineTransformer
1096 {
1097     function NowikiTransformer () {
1098         $this->InlineTransformer
1099             (array('linebreak',
1100                    'html_emphasis', 'html_abbr', 'plugin',
1101                    'isonumchars', 'isohexchars', /*'html_entities',*/
1102                    ));
1103     }
1104 }
1105
1106 function TransformInline($text, $markup = 2.0, $basepage=false) {
1107     static $trfm;
1108     $action = $GLOBALS['request']->getArg('action');
1109     if (empty($trfm) or $action == 'SpellCheck') {
1110         $trfm = new InlineTransformer;
1111     }
1112     
1113     if ($markup < 2.0) {
1114         $text = ConvertOldMarkup($text, 'inline');
1115     }
1116
1117     if ($basepage) {
1118         return new CacheableMarkup($trfm->parse($text), $basepage);
1119     }
1120     return $trfm->parse($text);
1121 }
1122
1123 function TransformLinks($text, $markup = 2.0, $basepage = false) {
1124     static $trfm;
1125     
1126     if (empty($trfm)) {
1127         $trfm = new LinkTransformer;
1128     }
1129
1130     if ($markup < 2.0) {
1131         $text = ConvertOldMarkup($text, 'links');
1132     }
1133     
1134     if ($basepage) {
1135         return new CacheableMarkup($trfm->parse($text), $basepage);
1136     }
1137     return $trfm->parse($text);
1138 }
1139
1140 /**
1141  * Transform only html markup and entities.
1142  */
1143 function TransformInlineNowiki($text, $markup = 2.0, $basepage=false) {
1144     static $trfm;
1145     
1146     if (empty($trfm)) {
1147         $trfm = new NowikiTransformer;
1148     }
1149     if ($basepage) {
1150         return new CacheableMarkup($trfm->parse($text), $basepage);
1151     }
1152     return $trfm->parse($text);
1153 }
1154
1155
1156 // $Log: not supported by cvs2svn $
1157 // Revision 1.104  2008/08/06 09:28:41  vargenau
1158 // Allow header syntax in Mediawiki tables
1159 //
1160 // Revision 1.103  2008/08/03 16:18:35  vargenau
1161 // Implement "{{foo?version=5}}" syntax for templates
1162 //
1163 // Revision 1.102  2008/08/03 16:03:47  vargenau
1164 // Implement Wikicreole syntax for links
1165 //
1166 // Revision 1.101  2008/08/03 15:56:20  vargenau
1167 // Implement Wikicreole syntax for line break
1168 //
1169 // Revision 1.100  2008/08/03 15:52:31  vargenau
1170 // Implement Wikicreole syntax for subscript
1171 //
1172 // Revision 1.99  2008/05/06 19:23:17  rurban
1173 // update (c)
1174 //
1175 // Revision 1.98  2008/03/21 20:35:52  rurban
1176 // Improve upon embedded ImgObject, such as [ *.mp3 ], objects.
1177 // Object tags now render as label correctly and param tags are also added.
1178 //
1179 // Revision 1.97  2008/03/18 20:25:49  rurban
1180 // Fixed "\n" => " " in [ link parsing ] by suggestion of Marc-Etienne
1181 //
1182 // Revision 1.96  2008/03/17 19:06:39  rurban
1183 // fix bug#1904088  Some brackets links with \n cause the parser to crash
1184 //
1185 // Revision 1.95  2008/02/15 20:02:49  vargenau
1186 // Allow <s> to strike; update Help for <s> and <strike>
1187 //
1188 // Revision 1.94  2008/01/31 20:40:10  vargenau
1189 // Implemented Mediawiki-like syntax for tables
1190 //
1191 // Revision 1.93  2007/09/26 16:54:34  rurban
1192 // Fix Bug#1802827 Template does not get expanded with {{ }} syntax.
1193 // by vargenau
1194 //
1195 // Revision 1.92  2007/08/10 21:58:01  rurban
1196 // Improve SemanticLink parsings:
1197 //   No units seperated by space allowed without []
1198 //   For :: (relations) only words, no comma,
1199 //   but for := (attributes) comma and dots are allowed. Units with groupsep.
1200 //   Ending dots or comma are not part of the link.
1201 //
1202 // Revision 1.91  2007/06/07 18:56:57  rurban
1203 // patch #1732793: allow \n, mult. {{ }} in one line, and single
1204 // letters (slightly improved) by AlJeux and ReiniUrban
1205 //
1206 // Revision 1.90  2007/03/18 17:35:14  rurban
1207 // Fix :DontStoreLink
1208 //
1209 // Revision 1.89  2007/02/17 14:16:28  rurban
1210 // fix color GREY to GRAY
1211 //
1212 // Revision 1.88  2007/01/21 13:15:50  rurban
1213 // Support spaces in attributes and relation links
1214 //
1215 // Revision 1.87  2007/01/20 15:53:51  rurban
1216 // Rewrite of SearchHighlight: through ActionPage and InlineParser
1217 //
1218 // Revision 1.86  2007/01/20 11:25:07  rurban
1219 // add SpellCheck support
1220 //
1221 // Revision 1.85  2007/01/07 18:42:49  rurban
1222 // Add support for non-bracket semantic relation parsing. Assert empty regex (interwikimap?) earlier. Change {{Template||}} vars handling to new style. Stricter interwikimap matching not to find semantic links
1223 //
1224 // Revision 1.84  2007/01/02 13:18:07  rurban
1225 // fix semantic attributes syntax :=, not :-, disable DIVSPAN and PLUGIN_MARKUP_MAP
1226 //
1227 // Revision 1.83  2006/12/22 00:23:24  rurban
1228 // Fix Bug #1540007 "hardened-php issue, crawlers related"
1229 // Broken str_replace with strings > 200 chars
1230 //
1231 // Revision 1.82  2006/12/02 19:53:05  rurban
1232 // Simplify DISABLE_MARKUP_WIKIWORD handling by adding the new function
1233 // stdlib: array_remove(). Hopefully PHP will not add this natively sooner
1234 // or later.
1235 //
1236 // Revision 1.81  2006/11/19 13:52:52  rurban
1237 // improve debug output: regex only once
1238 //
1239 // Revision 1.80  2006/10/12 06:32:30  rurban
1240 // Optionally support new tags <div>, <span> with ENABLE_MARKUP_DIVSPAN (in work)
1241 //
1242 // Revision 1.79  2006/10/08 12:38:11  rurban
1243 // New special interwiki link markup [:LinkTo] without storing the backlink
1244 //
1245 // Revision 1.78  2006/09/03 09:53:52  rurban
1246 // more colors, case-insensitive color names
1247 //
1248 // Revision 1.77  2006/08/25 19:02:02  rurban
1249 // patch #1348996 by Robert Litwiniec: fix show image semantics if label is given
1250 //
1251 // Revision 1.76  2006/08/19 11:02:35  rurban
1252 // add strike and del to html emphasis: Patch #1542894 by Kai Krakow
1253 //
1254 // Revision 1.75  2006/08/15 13:43:10  rurban
1255 // add Markup_xml_plugin (untested) and fix Markup_template_plugin
1256 //
1257 // Revision 1.74  2006/07/23 14:03:18  rurban
1258 // add new feature: DISABLE_MARKUP_WIKIWORD
1259 //
1260 // Revision 1.73  2006/04/15 12:20:36  rurban
1261 // fix relatives links patch by Joel Schaubert for [/
1262 //
1263 // Revision 1.72  2006/03/07 20:43:29  rurban
1264 // relative external link, if no internal subpage. by joel Schaubert
1265 //
1266 // Revision 1.71  2005/11/14 22:31:12  rurban
1267 // add SemanticWeb support
1268 //
1269 // Revision 1.70  2005/10/31 16:45:23  rurban
1270 // added cfg-able markups only for default TextTransformation, not for links and others
1271 //
1272 // Revision 1.69  2005/09/14 05:57:19  rurban
1273 // make ENABLE_MARKUP_TEMPLATE optional
1274 //
1275 // Revision 1.68  2005/09/10 21:24:32  rurban
1276 // optionally support {{Template|vars}} syntax
1277 //
1278 // Revision 1.67  2005/06/06 17:41:20  rurban
1279 // support new ENABLE_MARKUP_COLOR
1280 //
1281 // Revision 1.66  2005/04/23 11:15:49  rurban
1282 // handle allowed inlined objects within INLINE_IMAGES
1283 //
1284 // Revision 1.65  2005/03/27 18:24:17  rurban
1285 // add Log
1286 //
1287
1288 // (c-file-style: "gnu")
1289 // Local Variables:
1290 // mode: php
1291 // tab-width: 8
1292 // c-basic-offset: 4
1293 // c-hanging-comment-ender-p: nil
1294 // indent-tabs-mode: nil
1295 // End:   
1296 ?>