]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/InlineParser.php
Put superscript and subscript first
[SourceForge/phpwiki.git] / lib / InlineParser.php
1 <?php 
2 rcs_id('$Id$');
3 /* Copyright (C) 2002 Geoffrey T. Dairiki <dairiki@dairiki.org>
4  * Copyright (C) 2004-2008 Reini Urban
5  * Copyright (C) 2008-2009 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  *   width=n, height=n
319  */
320 function isImageLink($link) {
321     if (!$link) return false;
322     assert(defined('INLINE_IMAGES'));
323     return preg_match("/\\.(" . INLINE_IMAGES . ")$/i", $link)
324         or preg_match("/\\.(" . INLINE_IMAGES . ")\s+(size|border|align|hspace|vspace|type|data|width|height)=/i", $link);
325 }
326
327 function LinkBracketLink($bracketlink) {
328
329     // $bracketlink will start and end with brackets; in between will
330     // be either a page name, a URL or both separated by a pipe.
331     
332    $wikicreolesyntax = false;
333
334    if (string_starts_with($bracketlink, "[[")) {
335        $wikicreolesyntax = true;
336        $bracketlink = str_replace("[[", "[", $bracketlink);
337        $bracketlink = str_replace("]]", "]", $bracketlink);
338    }
339   
340     // Strip brackets and leading space
341     // bug#1904088  Some brackets links on 2 lines cause the parser to crash
342     preg_match('/(\#?) \[\s* (?: (.*?) \s* (?<!' . ESCAPE_CHAR . ')(\|) )? \s* (.+?) \s*\]/x',
343                str_replace("\n", " ", $bracketlink), $matches);
344     if (count($matches) < 4) {
345         // "[ personal\ninformation manager | PhpWiki:PersonalWiki ]"
346         trigger_error(_("Invalid [] syntax ignored").": ".$bracketlink, E_USER_WARNING);
347         return new Cached_Link;
348     }
349     list (, $hash, $label, $bar, $rawlink) = $matches;
350
351     if ($wikicreolesyntax and $label) {
352         $temp = $label;
353         $label = $rawlink;
354         $rawlink = $temp;
355     }
356
357     // Mediawiki compatibility: allow "Image:" and "File:"
358     // as synonyms of "Upload:"
359     if (string_starts_with($rawlink, "Image:")) {
360         $rawlink = str_replace("Image:", "Upload:", $rawlink);
361     }
362     if (string_starts_with($rawlink, "File:")) {
363         $rawlink = str_replace("File:", "Upload:", $rawlink);
364     }
365
366     $label = UnWikiEscape($label);
367     /*
368      * Check if the user has typed a explicit URL. This solves the
369      * problem where the URLs have a ~ character, which would be stripped away.
370      *   "[http:/server/~name/]" will work as expected
371      *   "http:/server/~name/"   will NOT work as expected, will remove the ~
372      */
373     if (   string_starts_with ($rawlink, "http://")
374         or string_starts_with ($rawlink, "https://") ) 
375     {
376         $link = $rawlink;
377         // Mozilla Browser URI Obfuscation Weakness 2004-06-14
378         //   http://www.securityfocus.com/bid/10532/
379         //   goodurl+"%2F%20%20%20."+badurl
380         if (preg_match("/%2F(%20)+\./i", $rawlink)) {
381             $rawlink = preg_replace("/%2F(%20)+\./i","%2F.",$rawlink);
382         }
383     } else
384         $link  = UnWikiEscape($rawlink);
385
386     /* Relatives links by Joel Schaubert.
387      * Recognize [../bla] or [/bla] as relative links, without needing http://
388      * but [ /link ] only if SUBPAGE_SEPERATOR is not "/". 
389      * Normally /Page links to the subpage /Page.
390      */
391     if (SUBPAGE_SEPARATOR == '/') {
392         if (preg_match('/^\.\.\//', $link)) {
393             return new Cached_ExternalLink($link, $label);
394         }
395     } else if (preg_match('/^(\.\.\/|\/)/', $link)) {
396         return new Cached_ExternalLink($link, $label);
397     }
398     // [label|link]
399     // If label looks like a url to an image or object, we want an image link.
400     if (isImageLink($label)) {
401         $imgurl = $label;
402         $intermap = getInterwikiMap();
403         if (preg_match("/^" . $intermap->getRegexp() . ":/", $label)) {
404             $imgurl = $intermap->link($label);
405             $imgurl = $imgurl->getAttr('href');
406         } elseif (! preg_match("#^(" . ALLOWED_PROTOCOLS . "):#", $imgurl)) {
407             // local theme linkname like 'images/next.gif'.
408             global $WikiTheme;
409             $imgurl = $WikiTheme->getImageURL($imgurl);
410         }
411         // for objects (non-images) the link is taken as alt tag, 
412         // which is in return taken as alternative img
413         $label = LinkImage($imgurl, $link);
414     }
415
416     if ($hash) {
417         // It's an anchor, not a link...
418         $id = MangleXmlIdentifier($link);
419         return HTML::a(array('name' => $id, 'id' => $id),
420                        $bar ? $label : $link);
421     }
422
423     if (preg_match("#^(" . ALLOWED_PROTOCOLS . "):#", $link)) {
424         // if it's an image, embed it; otherwise, it's a regular link
425         if (isImageLink($link) and empty($label)) // patch #1348996 by Robert Litwiniec
426             return LinkImage($link, $label);
427         else
428             return new Cached_ExternalLink($link, $label);
429     }
430     elseif (substr($link,0,8) == 'phpwiki:')
431         return new Cached_PhpwikiURL($link, $label);
432
433     /* Semantic relations and attributes. 
434      * Relation and attribute names must be word chars only, no space.
435      * Links and Attributes may contain everything. word, nums, units, space, groupsep, numsep, ...
436      */
437     elseif (preg_match("/^ (\w+) (:[:=]) (.*) $/x", $link) and !isImageLink($link))
438         return new Cached_SemanticLink($link, $label);
439
440     /* Do not store the link */    
441     elseif (substr($link,0,1) == ':')
442         return new Cached_WikiLink($link, $label);
443
444     /*
445      * Inline images in Interwiki urls's:
446      * [File:my_image.gif] inlines the image,
447      * File:my_image.gif shows a plain inter-wiki link,
448      * [what a pic|File:my_image.gif] shows a named inter-wiki link to the gif
449      * [File:my_image.gif|what a pic] shows a inlimed image linked to the page "what a pic"
450      *
451      * Note that for simplicity we will accept embedded object tags (non-images) 
452      * here also, and seperate them later in LinkImage()
453      */
454     elseif (strstr($link,':')
455             and ($intermap = getInterwikiMap()) 
456             and preg_match("/^" . $intermap->getRegexp() . ":/", $link)) 
457     {
458         // trigger_error("label: $label link: $link", E_USER_WARNING);
459         if (empty($label) and isImageLink($link)) {
460             // if without label => inlined image [File:xx.gif]
461             $imgurl = $intermap->link($link);
462             return LinkImage($imgurl->getAttr('href'), $link);
463         }
464         return new Cached_InterwikiLink($link, $label);
465     } else {
466         // Split anchor off end of pagename.
467         if (preg_match('/\A(.*)(?<!'.ESCAPE_CHAR.')#(.*?)\Z/', $rawlink, $m)) {
468             list(,$rawlink,$anchor) = $m;
469             $pagename = UnWikiEscape($rawlink);
470             $anchor = UnWikiEscape($anchor);
471             if (!$label)
472                 $label = $link;
473         }
474         else {
475             $pagename = $link;
476             $anchor = false;
477         }
478         return new Cached_WikiLink($pagename, $label, $anchor);
479     }
480 }
481
482 class Markup_wikicreolebracketlink  extends SimpleMarkup
483 {
484     var $_match_regexp = "\\#? \\[\\[ .*? [^]\\s] .*? \\]\\]";
485
486     function markup ($match) {
487         $link = LinkBracketLink($match);
488         assert($link->isInlineElement());
489         return $link;
490     }
491 }
492
493 class Markup_bracketlink  extends SimpleMarkup
494 {
495     var $_match_regexp = "\\#? \\[ .*? [^]\\s] .*? \\]";
496     
497     function markup ($match) {
498         $link = LinkBracketLink($match);
499         assert($link->isInlineElement());
500         return $link;
501     }
502 }
503
504 class Markup_spellcheck extends SimpleMarkup
505 {
506     function Markup_spellcheck () {
507         $this->suggestions = $GLOBALS['request']->getArg('suggestions');
508     }
509     function getMatchRegexp () {
510         if (empty($this->suggestions))
511             return "(?# false )";
512         $words = array_keys($this->suggestions);
513         return "(?<= \W ) (?:" . join('|', $words) . ") (?= \W )";
514     }
515     
516     function markup ($match) {
517         if (empty($this->suggestions) or empty($this->suggestions[$match]))
518             return $match;
519         return new Cached_SpellCheck(UnWikiEscape($match), $this->suggestions[$match]);
520     }
521 }
522
523 class Markup_searchhighlight extends SimpleMarkup
524 {
525     function Markup_searchhighlight () {
526         $result = $GLOBALS['request']->_searchhighlight;
527         require_once("lib/TextSearchQuery.php");
528         $query = new TextSearchQuery($result['query']);
529         $this->hilight_re = $query->getHighlightRegexp();
530         $this->engine = $result['engine'];
531     }
532     function getMatchRegexp () {
533         return $this->hilight_re;
534     }
535     function markup ($match) {
536         return new Cached_SearchHighlight(UnWikiEscape($match), $this->engine);
537     }
538 }
539
540 class Markup_url extends SimpleMarkup
541 {
542     function getMatchRegexp () {
543         return "(?<![[:alnum:]]) (?:" . ALLOWED_PROTOCOLS . ") : [^\s<>\"']+ (?<![ ,.?; \] \) ])";
544     }
545     
546     function markup ($match) {
547         return new Cached_ExternalLink(UnWikiEscape($match));
548     }
549 }
550
551 class Markup_interwiki extends SimpleMarkup
552 {
553     function getMatchRegexp () {
554         $map = getInterwikiMap();
555         return "(?<! [[:alnum:]])" . $map->getRegexp(). ": [^:=]\S+ (?<![ ,.?;! \] \) \" \' ])";
556     }
557
558     function markup ($match) {
559         return new Cached_InterwikiLink(UnWikiEscape($match));
560     }
561 }
562
563 class Markup_semanticlink extends SimpleMarkup
564 {
565     // No units seperated by space allowed here
566     // For :: (relations) only words, no comma,
567     // but for := (attributes) comma and dots are allowed. Units with groupsep.
568     // Ending dots or comma are not part of the link.
569     var $_match_regexp = "(?: \w+:=\S+(?<![\.,]))|(?: \w+::[\w\.]+(?<!\.))"; 
570
571     function markup ($match) {
572         return new Cached_SemanticLink(UnWikiEscape($match));
573     }
574 }
575
576 class Markup_wikiword extends SimpleMarkup
577 {
578     function getMatchRegexp () {
579         global $WikiNameRegexp;
580         if (!trim($WikiNameRegexp)) return " " . WIKI_NAME_REGEXP;
581         return " $WikiNameRegexp";
582     }
583
584     function markup ($match) {
585         if (!$match) return false;
586         if ($this->_isWikiUserPage($match))
587             return new Cached_UserLink($match); //$this->_UserLink($match);
588         else
589             return new Cached_WikiLink($match);
590     }
591
592     // FIXME: there's probably a more useful place to put these two functions    
593     function _isWikiUserPage ($page) {
594         global $request;
595         $dbi = $request->getDbh();
596         $page_handle = $dbi->getPage($page);
597         if ($page_handle and $page_handle->get('pref'))
598             return true;
599         else
600             return false;
601     }
602
603     function _UserLink($PageName) {
604         $link = HTML::a(array('href' => $PageName));
605         $link->pushContent(PossiblyGlueIconToText('wikiuser', $PageName));
606         $link->setAttr('class', 'wikiuser');
607         return $link;
608     }
609 }
610
611 class Markup_linebreak extends SimpleMarkup
612 {
613     //var $_match_regexp = "(?: (?<! %) %%% (?! %) | <(?:br|BR)> | <(?:br|BR) \/> )";
614     var $_match_regexp = "(?: (?<! %) %%% (?! %) | \\\\\\\\ | <(?:br|BR)> )";
615
616     function markup ($match) {
617         return HTML::br();
618     }
619 }
620
621 class Markup_wikicreole_italics extends BalancedMarkup
622 {
623     var $_start_regexp = "\\/\\/";
624  
625     function getEndRegexp ($match) {
626         return "\\/\\/"; 
627     }
628    
629     function markup ($match, $body) {
630         $tag = 'em';
631         return new HtmlElement($tag, $body);
632     }
633 }
634
635 class Markup_wikicreole_bold extends BalancedMarkup
636 {
637     var $_start_regexp = "\\*\\*";
638  
639     function getEndRegexp ($match) {
640         return "\\*\\*"; 
641     }
642    
643     function markup ($match, $body) {
644         $tag = 'strong';
645         return new HtmlElement($tag, $body);
646     }
647 }
648
649 class Markup_wikicreole_monospace extends BalancedMarkup
650 {
651     var $_start_regexp = "\\#\\#";
652  
653     function getEndRegexp ($match) {
654         return "\\#\\#"; 
655     }
656    
657     function markup ($match, $body) {
658         $tag = 'tt';
659         return new HtmlElement($tag, $body);
660     }
661 }
662
663 class Markup_wikicreole_superscript extends BalancedMarkup
664 {
665     var $_start_regexp = "\\^\\^";
666  
667     function getEndRegexp ($match) {
668         return "\\^\\^"; 
669     }
670    
671     function markup ($match, $body) {
672         $tag = 'sup';
673         return new HtmlElement($tag, $body);
674     }
675 }
676  
677 class Markup_wikicreole_subscript extends BalancedMarkup
678 {
679     var $_start_regexp = ",,";
680  
681     function getEndRegexp ($match) {
682         return $match; 
683     }
684    
685     function markup ($match, $body) {
686         $tag = 'sub';
687         return new HtmlElement($tag, $body);
688     }
689 }
690
691 class Markup_old_emphasis  extends BalancedMarkup
692 {
693     var $_start_regexp = "''|__";
694
695     function getEndRegexp ($match) {
696         return $match;
697     }
698     
699     function markup ($match, $body) {
700         $tag = $match == "''" ? 'em' : 'strong';
701         return new HtmlElement($tag, $body);
702     }
703 }
704
705 class Markup_nestled_emphasis extends BalancedMarkup
706 {
707     function getStartRegexp() {
708         static $start_regexp = false;
709
710         if (!$start_regexp) {
711             // The three possible delimiters
712             // (none of which can be followed by itself.)
713             $i = "_ (?! _)";
714             $b = "\\* (?! \\*)";
715             $tt = "= (?! =)";
716
717             $any = "(?: ${i}|${b}|${tt})"; // any of the three.
718
719             // Any of [_*=] is okay if preceded by space or one of [-"'/:]
720             $start[] = "(?<= \\s|^|[-\"'\\/:]) ${any}";
721
722             // _ or * is okay after = as long as not immediately followed by =
723             $start[] = "(?<= =) (?: ${i}|${b}) (?! =)";
724             // etc...
725             $start[] = "(?<= _) (?: ${b}|${tt}) (?! _)";
726             $start[] = "(?<= \\*) (?: ${i}|${tt}) (?! \\*)";
727
728
729             // any delimiter okay after an opening brace ( [{<(] )
730             // as long as it's not immediately followed by the matching closing
731             // brace.
732             $start[] = "(?<= { ) ${any} (?! } )";
733             $start[] = "(?<= < ) ${any} (?! > )";
734             $start[] = "(?<= \\( ) ${any} (?! \\) )";
735             
736             $start = "(?:" . join('|', $start) . ")";
737             
738             // Any of the above must be immediately followed by non-whitespace.
739             $start_regexp = $start . "(?= \S)";
740         }
741
742         return $start_regexp;
743     }
744
745     function getEndRegexp ($match) {
746         $chr = preg_quote($match);
747         return "(?<= \S | ^ ) (?<! $chr) $chr (?! $chr) (?= \s | [-)}>\"'\\/:.,;!? _*=] | $)";
748     }
749     
750     function markup ($match, $body) {
751         switch ($match) {
752         case '*': return new HtmlElement('b', $body);
753         case '=': return new HtmlElement('tt', $body);
754         case '_': return new HtmlElement('i', $body);
755         }
756     }
757 }
758
759 class Markup_html_emphasis extends BalancedMarkup
760 {
761     var $_start_regexp = 
762         "<(?: b|big|i|small|tt|em|strong|cite|code|dfn|kbd|samp|s|strike|del|var|sup|sub )>";
763
764     function getEndRegexp ($match) {
765         return "<\\/" . substr($match, 1);
766     }
767     
768     function markup ($match, $body) {
769         $tag = substr($match, 1, -1);
770         return new HtmlElement($tag, $body);
771     }
772 }
773
774 class Markup_html_divspan extends BalancedMarkup
775 {
776     var $_start_regexp = 
777         "<(?: div|span )(?: \s[^>]*)?>";
778
779     function getEndRegexp ($match) {
780         if (substr($match,1,4) == 'span')
781             $tag = 'span';
782         else
783             $tag = 'div';
784         return "<\\/" . $tag . '>';
785     }
786     
787     function markup ($match, $body) {
788         if (substr($match,1,4) == 'span')
789             $tag = 'span';
790         else
791             $tag = 'div';
792         $rest = substr($match,1+strlen($tag),-1);
793         if (!empty($rest)) {
794             $args = parse_attributes($rest);
795         } else {
796             $args = array();
797         }
798         return new HtmlElement($tag, $args, $body);
799     }
800 }
801
802
803 class Markup_html_abbr extends BalancedMarkup
804 {
805     //rurban: abbr|acronym need an optional title tag.
806     //sf.net bug #728595
807     // allowed attributes: title and lang
808     var $_start_regexp = "<(?: abbr|acronym )(?: [^>]*)?>"; 
809
810     function getEndRegexp ($match) {
811         if (substr($match,1,4) == 'abbr')
812             $tag = 'abbr';
813         else
814             $tag = 'acronym';
815         return "<\\/" . $tag . '>';
816     }
817     
818     function markup ($match, $body) {
819         if (substr($match,1,4) == 'abbr')
820             $tag = 'abbr';
821         else
822             $tag = 'acronym';
823         $rest = substr($match,1+strlen($tag),-1);
824         $attrs = parse_attributes($rest);
825         // Remove attributes other than title and lang
826         $allowedargs = array();
827         foreach ($attrs as $key => $value) {
828             if (in_array ($key, array("title", "lang"))) {
829                 $allowedargs[$key] = $value;
830             }
831         }
832         return new HtmlElement($tag, $allowedargs, $body);
833     }
834 }
835
836 /** ENABLE_MARKUP_COLOR
837  *  See http://www.pmwiki.org/wiki/PmWiki/WikiStyles and
838  *      http://www.flexwiki.com/default.aspx/FlexWiki/FormattingRules.html
839  */
840 class Markup_color extends BalancedMarkup {
841     // %color=blue% blue text %% and back to normal
842     var $_start_regexp = "%color=(?: [^%]*)%";
843     var $_end_regexp = "%%";
844     
845     function markup ($match, $body) {
846         $color = strtoupper(substr($match, 7, -1));
847         if (strlen($color) != 7 
848             and in_array($color, array('RED', 'BLUE', 'GRAY', 'YELLOW', 'GREEN', 'CYAN', 'BLACK'))) 
849         {   // must be a valid color name
850             return new HtmlElement('font', array('color' => $color), $body);
851         } elseif ((substr($color,0,1) == '#') 
852                   and (strspn(substr($color,1),'0123456789ABCDEF') == strlen($color)-1)) {
853             return new HtmlElement('font', array('color' => $color), $body);
854         } else {
855             trigger_error(sprintf(_("unknown color %s ignored"), substr($match, 7, -1)), E_USER_WARNING);
856         }
857                 
858     }
859 }
860
861 // Single-line HTML comment
862 // <!-- This is a comment -->
863 class Markup_html_comment extends SimpleMarkup
864 {
865     var $_match_regexp = '<!--.*?-->';
866
867     function markup ($match) {
868         return HTML::raw('');
869     }
870 }
871
872 // Special version for single-line plugins formatting, 
873 //  like: '<small>< ?plugin PopularNearby ? ></small>'
874 class Markup_plugin extends SimpleMarkup
875 {
876     var $_match_regexp = '<\?plugin(?:-form)?\s[^\n]+?\?>';
877
878     function markup ($match) {
879         return new Cached_PluginInvocation($match);
880     }
881 }
882
883 // Special version for single-line Wikicreole plugins formatting.
884 class Markup_plugin_wikicreole extends SimpleMarkup
885 {
886     var $_match_regexp = '<<[^\n]+?>>';
887
888     function markup ($match) {
889         $pi = str_replace("<<", "<?plugin ", $match);
890         $pi = str_replace(">>", " ?>", $pi);
891         return new Cached_PluginInvocation($pi);
892     }
893 }
894
895 // Special version for plugins in xml syntax 
896 // <name arg=value>body</name> or <name /> => < ? plugin pluginname arg=value body ? >
897 // PLUGIN_MARKUP_MAP = "html:RawHtml dot:GraphViz toc:CreateToc amath:AsciiMath richtable:RichTable include:IncludePage tex:TexToPng"
898 class Markup_xml_plugin extends BalancedMarkup
899 {
900     //var $_start_regexp = "<(?: ".join('|',PLUGIN_MARKUP_MAP)." )(?: \s[^>]*)>";
901
902     function getStartRegexp () {
903         global $PLUGIN_MARKUP_MAP;
904         static $_start_regexp;
905         if ($_start_regexp) return $_start_regexp;
906         if (empty($PLUGIN_MARKUP_MAP))
907             return '';
908         //"<(?: html|dot|toc|amath|richtable|include|tex )(?: \s[^>]*)>"
909         $_start_regexp = "<(?: ".join('|',array_keys($PLUGIN_MARKUP_MAP))." )(?: \s[^>]* | / )>";
910         return $_start_regexp;
911     }
912     function getEndRegexp ($match) {
913         return "<\\/" . $match . '>';
914     }
915     function markup ($match, $body) {
916         global $PLUGIN_MARKUP_MAP;
917         $name = substr($match,2,-2); 
918         $vars = '';
919         if (preg_match('/^(\S+)\|(.*)$/', $name, $_m)) {
920             $name = $_m[1];
921             $vars = $_m[2]; //str_replace(' ', '&', $_m[2]);
922         }
923         if (!isset($PLUGIN_MARKUP_MAP[$name])) {
924             trigger_error("No plugin for $name $vars defined.", E_USER_WARNING);
925             return "";
926         }
927         $plugin = $PLUGIN_MARKUP_MAP[$name];
928         return new Cached_PluginInvocation("<"."?plugin $plugin $vars $body ?".">");
929     }
930 }
931
932 /**
933  *  Wikicreole preformatted
934  *  {{{
935  *  }}}
936  */
937 class Markup_wikicreole_preformatted extends SimpleMarkup
938 {
939     var $_match_regexp = '\{\{\{.*?\}\}\}';
940
941     function markup ($match) {
942         // Remove {{{ and }}}
943         return new HtmlElement('tt', substr($match, 3, -3));
944     }
945 }
946
947 /** ENABLE_MARKUP_TEMPLATE
948  *  Template syntax similar to Mediawiki
949  *  {{template}}
950  * => < ? plugin Template page=template ? >
951  *  {{template|var1=value1|var2=value|...}}
952  * => < ? plugin Template page=template var=value ... ? >
953  */
954 class Markup_template_plugin  extends SimpleMarkup
955 {
956     // patch #1732793: allow \n, mult. {{ }} in one line, and single letters
957     var $_match_regexp = '\{\{.*?\}\}';
958     
959     function markup ($match) {
960
961         $page = substr($match,2,-2);
962         if (strpos($page, "|") === false) {
963             $imagename = $page;
964             $alt = "";
965         } else {
966             $imagename = substr($page, 0, strpos($page, "|"));
967             $alt = ltrim(strstr($page, "|"), "|");
968         }
969
970         // It's not a Mediawiki template, it's a Wikicreole image
971         if (is_image($imagename)) {
972             return LinkImage(UPLOAD_DATA_PATH . $imagename, $alt);
973         }
974
975         $page = str_replace("\n", "", $page); 
976         $vars = '';
977
978         if (preg_match('/^(\S+?)\|(.*)$/', $page, $_m)) {
979             $page = $_m[1];
980             $vars = '"' . preg_replace('/\|/', '" "', $_m[2]) . '"'; 
981             $vars = preg_replace('/"(\S+)=([^"]*)"/', '\\1="\\2"', $vars);
982         }
983  
984         // page may contain a version number
985         // {{foo?version=5}}
986         // in that case, output is "page=foo rev=5"
987         if (strstr($page, "?")) {
988             $page = str_replace("?version=", "\" rev=\"", $page);
989         }
990
991         if ($vars)
992             $s = '<'.'?plugin Template page="'.$page.'" '.$vars.' ?'.'>';
993         else
994             $s = '<'.'?plugin Template page="' . $page . '" ?'.'>';
995         return new Cached_PluginInvocation($s);
996     }
997 }
998
999 // "..." => "&#133;"  browser specific display (not cached?)
1000 // Support some HTML::Entities: (C) for copy, --- for mdash, -- for ndash
1001 // TODO: "--" => "&emdash;" browser specific display (not cached?)
1002
1003 class Markup_html_entities  extends SimpleMarkup {
1004     //var $_match_regexp = '(: \.\.\.|\-\-|\-\-\-|\(C\) )';
1005
1006     function Markup_html_entities() {
1007         $this->_entities = array('...'  => '&#133;',
1008                                  '--'   => '&ndash;',
1009                                  '---'  => '&mdash;',
1010                                  '(C)'  => '&copy;',
1011                                  '&copy;' => '&copy;',
1012                                  '&trade;'  => '&trade;',
1013                                  );
1014         $this->_match_regexp = 
1015             '(: ' . 
1016             join('|', array_map('preg_quote', array_keys($this->_entities))) . 
1017             ' )';
1018     }
1019    
1020     function markup ($match) {
1021         return HTML::Raw($this->_entities[$match]);
1022     }
1023 }
1024
1025 class Markup_isonumchars  extends SimpleMarkup {
1026     var $_match_regexp = '\&\#\d{2,5};';
1027     
1028     function markup ($match) {
1029         return HTML::Raw($match);
1030     }
1031 }
1032
1033 class Markup_isohexchars extends SimpleMarkup {
1034     // hexnums, like &#x00A4; <=> &curren;
1035     var $_match_regexp = '\&\#x[0-9a-fA-F]{2,4};';
1036     
1037     function markup ($match) {
1038         return HTML::Raw($match);
1039     }
1040 }
1041
1042 // FIXME: Do away with magic phpwiki forms.  (Maybe phpwiki: links too?)
1043 // FIXME: Do away with plugin-links.  They seem not to be used.
1044 //Plugin link
1045
1046 class InlineTransformer
1047 {
1048     var $_regexps = array();
1049     var $_markup = array();
1050     
1051     function InlineTransformer ($markup_types = false) {
1052         global $request;
1053         // We need to extend the inline parsers by certain actions, like SearchHighlight, 
1054         // SpellCheck and maybe CreateToc.
1055         if (!$markup_types) {
1056             $non_default = false;
1057             $markup_types = array
1058                 ('escape', 'wikicreolebracketlink', 'bracketlink', 'url',
1059                  'html_comment',
1060                  'interwiki',  'semanticlink', 'wikiword', 'linebreak',
1061                  'wikicreole_superscript',
1062                  'wikicreole_subscript',
1063                  'wikicreole_italics', 'wikicreole_bold',
1064                  'wikicreole_monospace', 
1065                  'old_emphasis', 'nestled_emphasis',
1066                  'html_emphasis', 'html_abbr', 'plugin', 'plugin_wikicreole',
1067                  'isonumchars', 'isohexchars', /*'html_entities'*/
1068                  );
1069             if (DISABLE_MARKUP_WIKIWORD)
1070                 $markup_types = array_remove($markup_types, 'wikiword');
1071
1072             $action = $request->getArg('action');
1073             if ($action == 'SpellCheck' and $request->getArg('suggestions'))
1074             {   // insert it after url
1075                 array_splice($markup_types, 2, 1, array('url','spellcheck'));
1076             }
1077             if (isset($request->_searchhighlight))
1078             {   // insert it after url
1079                 array_splice($markup_types, 2, 1, array('url','searchhighlight'));
1080                 //$request->setArg('searchhighlight', false);
1081             }
1082         } else {
1083             $non_default = true;
1084         }
1085         foreach ($markup_types as $mtype) {
1086             $class = "Markup_$mtype";
1087             $this->_addMarkup(new $class);
1088         }
1089         if (ENABLE_MARKUP_DIVSPAN and !$non_default)
1090             $this->_addMarkup(new Markup_html_divspan);
1091         if (ENABLE_MARKUP_COLOR and !$non_default)
1092             $this->_addMarkup(new Markup_color);
1093         // Markup_wikicreole_preformatted must be before Markup_template_plugin
1094         $this->_addMarkup(new Markup_wikicreole_preformatted);
1095         if (ENABLE_MARKUP_TEMPLATE and !$non_default)
1096             $this->_addMarkup(new Markup_template_plugin);
1097         // This does not work yet
1098         if (0 and PLUGIN_MARKUP_MAP and !$non_default)
1099             $this->_addMarkup(new Markup_xml_plugin);
1100     }
1101
1102     function _addMarkup ($markup) {
1103         if (isa($markup, 'SimpleMarkup'))
1104             $regexp = $markup->getMatchRegexp();
1105         else
1106             $regexp = $markup->getStartRegexp();
1107
1108         assert( !isset($this->_markup[$regexp]) );
1109         assert( strlen(trim($regexp)) > 0 );
1110         $this->_regexps[] = $regexp;
1111         $this->_markup[] = $markup;
1112     }
1113         
1114     function parse (&$text, $end_regexps = array('$')) {
1115         $regexps = $this->_regexps;
1116
1117         // $end_re takes precedence: "favor reduce over shift"
1118         array_unshift($regexps, $end_regexps[0]);
1119         //array_push($regexps, $end_regexps[0]);
1120         $regexps = new RegexpSet($regexps);
1121         
1122         $input = $text;
1123         $output = new XmlContent;
1124
1125         $match = $regexps->match($input);
1126         
1127         while ($match) {
1128             if ($match->regexp_ind == 0) {
1129                 // No start pattern found before end pattern.
1130                 // We're all done!
1131                 if (isset($markup) and is_object($markup) 
1132                     and isa($markup,'Markup_plugin')) 
1133                 {
1134                     $current =& $output->_content[count($output->_content)-1];
1135                     $current->setTightness(true,true);
1136                 }
1137                 $output->pushContent($match->prematch);
1138                 $text = $match->postmatch;
1139                 return $output;
1140             }
1141
1142             $markup = $this->_markup[$match->regexp_ind - 1];
1143             $body = $this->_parse_markup_body($markup, $match->match, 
1144                                               $match->postmatch, $end_regexps);
1145             if (!$body) {
1146                 // Couldn't match balanced expression.
1147                 // Ignore and look for next matching start regexp.
1148                 $match = $regexps->nextMatch($input, $match);
1149                 continue;
1150             }
1151
1152             // Matched markup.  Eat input, push output.
1153             // FIXME: combine adjacent strings.
1154             if (isa($markup, 'SimpleMarkup'))
1155                 $current = $markup->markup($match->match);
1156             else
1157                 $current = $markup->markup($match->match, $body);
1158             $input = $match->postmatch;
1159             if (isset($markup) and is_object($markup) 
1160                 and isa($markup,'Markup_plugin')) 
1161             {
1162                 $current->setTightness(true,true);
1163             }
1164             $output->pushContent($match->prematch, $current);
1165
1166             $match = $regexps->match($input);
1167         }
1168
1169         // No pattern matched, not even the end pattern.
1170         // Parse fails.
1171         return false;
1172     }
1173
1174     function _parse_markup_body ($markup, $match, &$text, $end_regexps) {
1175         if (isa($markup, 'SimpleMarkup'))
1176             return true;        // Done. SimpleMarkup is simple.
1177
1178         if (!is_object($markup)) return false; // Some error: Should assert
1179         array_unshift($end_regexps, $markup->getEndRegexp($match));
1180
1181         // Optimization: if no end pattern in text, we know the
1182         // parse will fail.  This is an important optimization,
1183         // e.g. when text is "*lots *of *start *delims *with
1184         // *no *matching *end *delims".
1185         $ends_pat = "/(?:" . join(").*(?:", $end_regexps) . ")/xs";
1186         if (!preg_match($ends_pat, $text))
1187             return false;
1188         return $this->parse($text, $end_regexps);
1189     }
1190 }
1191
1192 class LinkTransformer extends InlineTransformer
1193 {
1194     function LinkTransformer () {
1195         $this->InlineTransformer(array('escape', 'wikicreolebracketlink', 'bracketlink', 'url',
1196                                        'semanticlink', 'interwiki', 'wikiword', 
1197                                        ));
1198     }
1199 }
1200
1201 class NowikiTransformer extends InlineTransformer
1202 {
1203     function NowikiTransformer () {
1204         $this->InlineTransformer
1205             (array('linebreak',
1206                    'html_emphasis', 'html_abbr', 'plugin', 'plugin_wikicreole',
1207                    'isonumchars', 'isohexchars', /*'html_entities',*/
1208                    ));
1209     }
1210 }
1211
1212 function TransformInline($text, $markup = 2.0, $basepage=false) {
1213     static $trfm;
1214     $action = $GLOBALS['request']->getArg('action');
1215     if (empty($trfm) or $action == 'SpellCheck') {
1216         $trfm = new InlineTransformer;
1217     }
1218     
1219     if ($markup < 2.0) {
1220         $text = ConvertOldMarkup($text, 'inline');
1221     }
1222
1223     if ($basepage) {
1224         return new CacheableMarkup($trfm->parse($text), $basepage);
1225     }
1226     return $trfm->parse($text);
1227 }
1228
1229 function TransformLinks($text, $markup = 2.0, $basepage = false) {
1230     static $trfm;
1231     
1232     if (empty($trfm)) {
1233         $trfm = new LinkTransformer;
1234     }
1235
1236     if ($markup < 2.0) {
1237         $text = ConvertOldMarkup($text, 'links');
1238     }
1239     
1240     if ($basepage) {
1241         return new CacheableMarkup($trfm->parse($text), $basepage);
1242     }
1243     return $trfm->parse($text);
1244 }
1245
1246 /**
1247  * Transform only html markup and entities.
1248  */
1249 function TransformInlineNowiki($text, $markup = 2.0, $basepage=false) {
1250     static $trfm;
1251     
1252     if (empty($trfm)) {
1253         $trfm = new NowikiTransformer;
1254     }
1255     if ($basepage) {
1256         return new CacheableMarkup($trfm->parse($text), $basepage);
1257     }
1258     return $trfm->parse($text);
1259 }
1260
1261 // (c-file-style: "gnu")
1262 // Local Variables:
1263 // mode: php
1264 // tab-width: 8
1265 // c-basic-offset: 4
1266 // c-hanging-comment-ender-p: nil
1267 // indent-tabs-mode: nil
1268 // End:   
1269 ?>