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