]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/InlineParser.php
comment
[SourceForge/phpwiki.git] / lib / InlineParser.php
1 <?php 
2 rcs_id('$Id: InlineParser.php,v 1.62 2005-02-05 15:35:37 rurban Exp $');
3 /* Copyright (C) 2002 Geoffrey T. Dairiki <dairiki@dairiki.org>
4  * Copyright (C) 2004 Reini Urban
5  *
6  * This file is part of PhpWiki.
7  * 
8  * PhpWiki is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; either version 2 of the License, or
11  * (at your option) any later version.
12  * 
13  * PhpWiki is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  * 
18  * You should have received a copy of the GNU General Public License
19  * along with PhpWiki; if not, write to the Free Software
20  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
21  */
22 /**
23  * This is the code which deals with the inline part of the (new-style)
24  * wiki-markup.
25  *
26  * @package Markup
27  * @author Geoffrey T. Dairiki
28  */
29 /**
30  */
31
32 /**
33  * This is the character used in wiki markup to escape characters with
34  * special meaning.
35  */
36 define('ESCAPE_CHAR', '~');
37
38 require_once(dirname(__FILE__).'/HtmlElement.php');
39 require_once('lib/CachedMarkup.php');
40 require_once(dirname(__FILE__).'/stdlib.php');
41
42
43 function WikiEscape($text) {
44     return str_replace('#', ESCAPE_CHAR . '#', $text);
45 }
46
47 function UnWikiEscape($text) {
48     return preg_replace('/' . ESCAPE_CHAR . '(.)/', '\1', $text);
49 }
50
51 /**
52  * Return type from RegexpSet::match and RegexpSet::nextMatch.
53  *
54  * @see RegexpSet
55  */
56 class RegexpSet_match {
57     /**
58      * The text leading up the the next match.
59      */
60     var $prematch;
61     /**
62      * The matched text.
63      */
64     var $match;
65     /**
66      * The text following the matched text.
67      */
68     var $postmatch;
69     /**
70      * Index of the regular expression which matched.
71      */
72     var $regexp_ind;
73 }
74
75 /**
76  * A set of regular expressions.
77  *
78  * This class is probably only useful for InlineTransformer.
79  */
80 class RegexpSet
81 {
82     /** Constructor
83      *
84      * @param array $regexps A list of regular expressions.  The
85      * regular expressions should not include any sub-pattern groups
86      * "(...)".  (Anonymous groups, like "(?:...)", as well as
87      * look-ahead and look-behind assertions are okay.)
88      */
89     function RegexpSet ($regexps) {
90         assert($regexps);
91         $this->_regexps = array_unique($regexps);
92         if (!defined('_INLINE_OPTIMIZATION')) define('_INLINE_OPTIMIZATION',0);
93     }
94
95     /**
96      * Search text for the next matching regexp from the Regexp Set.
97      *
98      * @param string $text The text to search.
99      *
100      * @return RegexpSet_match  A RegexpSet_match object, or false if no match.
101      */
102     function match ($text) {
103         return $this->_match($text, $this->_regexps, '*?');
104     }
105
106     /**
107      * Search for next matching regexp.
108      *
109      * Here, 'next' has two meanings:
110      *
111      * Match the next regexp(s) in the set, at the same position as the last match.
112      *
113      * If that fails, match the whole RegexpSet, starting after the position of the
114      * previous match.
115      *
116      * @param string $text Text to search.
117      *
118      * @param RegexpSet_match $prevMatch A RegexpSet_match object.
119      * $prevMatch should be a match object obtained by a previous
120      * match upon the same value of $text.
121      *
122      * @return RegexpSet_match A RegexpSet_match object, or false if no match.
123      */
124     function nextMatch ($text, $prevMatch) {
125         // Try to find match at same position.
126         $pos = strlen($prevMatch->prematch);
127         $regexps = array_slice($this->_regexps, $prevMatch->regexp_ind + 1);
128         if ($regexps) {
129             $repeat = sprintf('{%d}', $pos);
130             if ( ($match = $this->_match($text, $regexps, $repeat)) ) {
131                 $match->regexp_ind += $prevMatch->regexp_ind + 1;
132                 return $match;
133             }
134             
135         }
136         
137         // Failed.  Look for match after current position.
138         $repeat = sprintf('{%d,}?', $pos + 1);
139         return $this->_match($text, $this->_regexps, $repeat);
140     }
141
142     // Syntax: http://www.pcre.org/pcre.txt
143     //   x - EXTENDED, ignore whitespace
144     //   s - DOTALL
145     //   A - ANCHORED
146     //   S - STUDY
147     function _match ($text, $regexps, $repeat) {
148         // If one of the regexps is an empty string, php will crash here: 
149         // sf.net: Fatal error: Allowed memory size of 8388608 bytes exhausted 
150         //         (tried to allocate 634 bytes)
151         if (_INLINE_OPTIMIZATION) { // disabled, wrong
152         // So we try to minize memory usage, by looping explicitly,
153         // and storing only those regexp which actually match. 
154         // There may be more than one, so we have to find the longest, 
155         // and match inside until the shortest is empty.
156         $matched = array(); $matched_ind = array();
157         for ($i=0; $i<count($regexps); $i++) {
158             if (!trim($regexps[$i])) {
159                 trigger_error("empty regexp $i", E_USER_WARNING);
160                 continue;
161             }
162             $pat= "/ ( . $repeat ) ( " . $regexps[$i] . " ) /x";
163             if (preg_match($pat, $text, $_m)) {
164                 $m = $_m; // FIXME: prematch, postmatch is wrong
165                 $matched[] = $regexps[$i];
166                 $matched_ind[] = $i;
167                 $regexp_ind = $i;
168             }
169         }
170         // To overcome ANCHORED:
171         // We could sort by longest match and iterate over these.
172         if (empty($matched)) return false;
173         }
174         $match = new RegexpSet_match;
175         
176         // Optimization: if the matches are only "$" and another, then omit "$"
177         if (! _INLINE_OPTIMIZATION or count($matched) > 2) {
178             assert(!empty($repeat));
179             assert(!empty($regexps));
180             for ($i=0; $i<count($regexps); $i++) {
181                 if (!trim($regexps[$i])) {
182                     trigger_error("empty regexp $i", E_USER_WARNING);
183                     $regexps[$i] = '\Wxxxx\w\W\w\W\w\W\w\W\w\W\w'; // some placeholder
184                 }
185             }
186             // We could do much better, if we would know the matching markup for the 
187             // longest regexp match:
188             $hugepat= "/ ( . $repeat ) ( (" . join(')|(', $regexps) . ") ) /Asx";
189             // Proposed premature optimization 1:
190             //$hugepat= "/ ( . $repeat ) ( (" . join(')|(', array_values($matched)) . ") ) /Asx";
191 /* currently:
192   '/ ( . *? ) ( ($)|(~(?: [[:alnum:]]+ | .))|(&#\d{2,5};)|(\#? \[ .*? [^]\s] .*? \])|((?<![[:alnum:]]) (?:http|https|mailto|ftp|news|nntp|ssh|gopher) : [^\s<>"']+ (?<![ ,.?; \] \) ]))|((?<! [[:alnum:]])(?:AbbeNormal|AcadWiki|Acronym|Advogato|AIWiki|ALife|Annotation|AnnotationWiki|AwarenessWiki|BcWireless|BenefitsWiki|BridgesWiki|bsdWiki|C2find|Cache|Category|CLiki|CmWiki|CreationMatters|DejaNews|DeWikiPedia|Dict|Dictionary|DiveIntoOsx|DocBook|DolphinWiki|DseWiki|EfnetCeeWiki|EfnetCppWiki|EfnetPythonWiki|EfnetXmlWiki|EljWiki|EmacsWiki|FinalEmpire|Foldoc|FoxWiki|FreeBSDman|FreeNetworks|FreshMeat|Google|GoogleGroups|GreenCheese|HammondWiki|Haribeau|IAWiki|MRQE|IMDB|ISBN|JargonFile|JiniWiki|JspWiki|KmWiki|KnowHow|LanifexWiki|LegoWiki|LinuxWiki|LugKR|MathSongsWiki|MbTest|MeatBall|MetaWiki|MetaWikiPedia|MoinMoin|MuWeb|NetVillage|OpenWiki|OrgPatterns|PangalacticOrg|PersonalTelco|php-function|php-lookup|PhpWiki|PhpWikiCvs|PhpWikiDemo|Pikie|PolitizenWiki|PPR|PurlNet|PythonInfo|PythonWiki|PyWiki|RFC|SeaPig|SeattleWireless|SenseisLibrary|Shakti|SourceForge|Squeak|StrikiWiki|SVGWiki|Tavi|Thesaurus|Thinki|TmNet|TMwiki|TWiki|TwistedWiki|Unreal|UseMod|VisualWorks|WebDevWikiNL|WebSeitzWiki|Why|Wiki|WikiPedia|WikiWorld|YpsiEyeball|ZWiki|Upload): \S+ (?<![ ,.?;! \] \) " \' ]))|( (?<![[:alnum:]])(?:[[:upper:]][[:lower:]]+){2,}(?![[:alnum:]]))|((?: (?<! %) %%% (?! %) | <(?:br|BR)> ))|(''|__)|((?:(?<= \s|^|[-"'\/:]) (?: _ (?! _)|\* (?! \*)|= (?! =))|(?<= =) (?: _ (?! _)|\* (?! \*)) (?! =)|(?<= _) (?: \* (?! \*)|= (?! =)) (?! _)|(?<= \*) (?: _ (?! _)|= (?! =)) (?! \*)|(?<= { ) (?: _ (?! _)|\* (?! \*)|= (?! =)) (?! } )|(?<= < ) (?: _ (?! _)|\* (?! \*)|= (?! =)) (?! > )|(?<= \( ) (?: _ (?! _)|\* (?! \*)|= (?! =)) (?! \) ))(?= \S))|(<(?: b|big|i|small|tt|em|strong|cite|code|dfn|kbd|samp|var|sup|sub )>)|(<(?: abbr|acronym )(?: \stitle=[^>]*)?>)|(<\?plugin(?:-form)?\s[^\n]+?\?>) ) /Asx'
193 */
194             if (! preg_match($hugepat, $text, $m)) {
195                 return false;
196             }
197             // Proposed premature optimization 1:
198             //$match->regexp_ind = $matched_ind[count($m) - 4];
199             $match->regexp_ind = count($m) - 4;
200         } else {
201             $match->regexp_ind = $regexp_ind;
202         }
203         
204         $match->postmatch = substr($text, strlen($m[0]));
205         $match->prematch = $m[1];
206         $match->match = $m[2];
207
208         /* DEBUGGING */
209         /*
210         if (DEBUG & 4) {
211           var_dump($regexps); var_dump($matched); var_dump($matched_inc); 
212         PrintXML(HTML::dl(HTML::dt("input"),
213                           HTML::dd(HTML::pre($text)),
214                           HTML::dt("regexp"),
215                           HTML::dd(HTML::pre($match->regexp_ind, ":", $regexps[$match->regexp_ind])),
216                           HTML::dt("prematch"),
217                           HTML::dd(HTML::pre($match->prematch)),
218                           HTML::dt("match"),
219                           HTML::dd(HTML::pre($match->match)),
220                           HTML::dt("postmatch"),
221                           HTML::dd(HTML::pre($match->postmatch))
222                           ));
223         }
224         */
225         return $match;
226     }
227 }
228
229
230
231 /**
232  * A simple markup rule (i.e. terminal token).
233  *
234  * These are defined by a regexp.
235  *
236  * When a match is found for the regexp, the matching text is replaced.
237  * The replacement content is obtained by calling the SimpleMarkup::markup method.
238  */ 
239 class SimpleMarkup
240 {
241     var $_match_regexp;
242
243     /** Get regexp.
244      *
245      * @return string Regexp which matches this token.
246      */
247     function getMatchRegexp () {
248         return $this->_match_regexp;
249     }
250
251     /** Markup matching text.
252      *
253      * @param string $match The text which matched the regexp
254      * (obtained from getMatchRegexp).
255      *
256      * @return mixed The expansion of the matched text.
257      */
258     function markup ($match /*, $body */) {
259         trigger_error("pure virtual", E_USER_ERROR);
260     }
261 }
262
263 /**
264  * A balanced markup rule.
265  *
266  * These are defined by a start regexp, and an end regexp.
267  */ 
268 class BalancedMarkup
269 {
270     var $_start_regexp;
271
272     /** Get the starting regexp for this rule.
273      *
274      * @return string The starting regexp.
275      */
276     function getStartRegexp () {
277         return $this->_start_regexp;
278     }
279     
280     /** Get the ending regexp for this rule.
281      *
282      * @param string $match The text which matched the starting regexp.
283      *
284      * @return string The ending regexp.
285      */
286     function getEndRegexp ($match) {
287         return $this->_end_regexp;
288     }
289
290     /** Get expansion for matching input.
291      *
292      * @param string $match The text which matched the starting regexp.
293      *
294      * @param mixed $body Transformed text found between the starting
295      * and ending regexps.
296      *
297      * @return mixed The expansion of the matched text.
298      */
299     function markup ($match, $body) {
300         trigger_error("pure virtual", E_USER_ERROR);
301     }
302 }
303
304 class Markup_escape  extends SimpleMarkup
305 {
306     function getMatchRegexp () {
307         return ESCAPE_CHAR . '(?: [[:alnum:]]+ | .)';
308     }
309     
310     function markup ($match) {
311         assert(strlen($match) >= 2);
312         return substr($match, 1);
313     }
314 }
315
316 /**
317  * [image.jpg size=50% border=5], [image.jpg size=50x30]
318  * Support for the following attributes: see stdlib.php:LinkImage()
319  *   size=<precent>%, size=<width>x<height>
320  *   border=n, align=\w+, hspace=n, vspace=n
321  */
322 function isImageLink($link) {
323     if (!$link) return false;
324     assert(defined('INLINE_IMAGES'));
325     return preg_match("/\\.(" . INLINE_IMAGES . ")$/i", $link)
326         or preg_match("/\\.(" . INLINE_IMAGES . ")\s+(size|border|align|hspace|vspace)=/i", $link);
327 }
328
329 function LinkBracketLink($bracketlink) {
330
331     // $bracketlink will start and end with brackets; in between will
332     // be either a page name, a URL or both separated by a pipe.
333     
334     // strip brackets and leading space
335     // FIXME: \n inside [] will lead to errors
336     preg_match('/(\#?) \[\s* (?: (.*?) \s* (?<!' . ESCAPE_CHAR . ')(\|) )? \s* (.+?) \s*\]/x',
337                $bracketlink, $matches);
338     if (count($matches) < 4) {
339         trigger_error(_("Invalid [] syntax ignored").": ".$bracketlink, E_USER_NOTICE);
340         return new Cached_Link;
341     }
342     list (, $hash, $label, $bar, $rawlink) = $matches;
343
344     $label = UnWikiEscape($label);
345     /*
346      * Check if the user has typed a explicit URL. This solves the
347      * problem where the URLs have a ~ character, which would be stripped away.
348      *   "[http:/server/~name/]" will work as expected
349      *   "http:/server/~name/"   will NOT work as expected, will remove the ~
350      */
351     if (strstr($rawlink, "http://") or strstr($rawlink, "https://")) {
352         $link = $rawlink;
353         // Mozilla Browser URI Obfuscation Weakness 2004-06-14
354         //   http://www.securityfocus.com/bid/10532/
355         //   goodurl+"%2F%20%20%20."+badurl
356         if (preg_match("/%2F(%20)+\./i", $rawlink)) {
357             $rawlink = preg_replace("/%2F(%20)+\./i","%2F.",$rawlink);
358         }
359     } else
360         $link  = UnWikiEscape($rawlink);
361
362     // [label|link]
363     // if label looks like a url to an image, we want an image link.
364     if (isImageLink($label)) {
365         $imgurl = $label;
366         $intermap = getInterwikiMap();
367         if (preg_match("/^" . $intermap->getRegexp() . ":/", $label)) {
368             $imgurl = $intermap->link($label);
369             $imgurl = $imgurl->getAttr('href');
370         } elseif (! preg_match("#^(" . ALLOWED_PROTOCOLS . "):#", $imgurl)) {
371             // local theme linkname like 'images/next.gif'.
372             global $WikiTheme;
373             $imgurl = $WikiTheme->getImageURL($imgurl);
374         }
375         $label = LinkImage($imgurl, $link);
376     }
377
378     if ($hash) {
379         // It's an anchor, not a link...
380         $id = MangleXmlIdentifier($link);
381         return HTML::a(array('name' => $id, 'id' => $id),
382                        $bar ? $label : $link);
383     }
384
385     if (preg_match("#^(" . ALLOWED_PROTOCOLS . "):#", $link)) {
386         // if it's an image, embed it; otherwise, it's a regular link
387         if (isImageLink($link))
388             return LinkImage($link, $label);
389         else
390             return new Cached_ExternalLink($link, $label);
391     }
392     elseif (preg_match("/^phpwiki:/", $link))
393         return new Cached_PhpwikiURL($link, $label);
394     /*
395      * Inline images in Interwiki urls's:
396      * [File:my_image.gif] inlines the image,
397      * File:my_image.gif shows a plain inter-wiki link,
398      * [what a pic|File:my_image.gif] shows a named inter-wiki link to the gif
399      * [File:my_image.gif|what a pic] shows a inlimed image linked to the page "what a pic"
400      */
401     elseif (strstr($link,':') and 
402             ($intermap = getInterwikiMap()) and 
403             preg_match("/^" . $intermap->getRegexp() . ":/", $link)) {
404         if (empty($label) && isImageLink($link)) {
405             // if without label => inlined image [File:xx.gif]
406             $imgurl = $intermap->link($link);
407             return LinkImage($imgurl->getAttr('href'), $label);
408         }
409         return new Cached_InterwikiLink($link, $label);
410     } else {
411         // Split anchor off end of pagename.
412         if (preg_match('/\A(.*)(?<!'.ESCAPE_CHAR.')#(.*?)\Z/', $rawlink, $m)) {
413             list(,$rawlink,$anchor) = $m;
414             $pagename = UnWikiEscape($rawlink);
415             $anchor = UnWikiEscape($anchor);
416             if (!$label)
417                 $label = $link;
418         }
419         else {
420             $pagename = $link;
421             $anchor = false;
422         }
423         return new Cached_WikiLink($pagename, $label, $anchor);
424     }
425 }
426
427 class Markup_bracketlink  extends SimpleMarkup
428 {
429     var $_match_regexp = "\\#? \\[ .*? [^]\\s] .*? \\]";
430     
431     function markup ($match) {
432         $link = LinkBracketLink($match);
433         assert($link->isInlineElement());
434         return $link;
435     }
436 }
437
438 class Markup_url extends SimpleMarkup
439 {
440     function getMatchRegexp () {
441         return "(?<![[:alnum:]]) (?:" . ALLOWED_PROTOCOLS . ") : [^\s<>\"']+ (?<![ ,.?; \] \) ])";
442     }
443     
444     function markup ($match) {
445         return new Cached_ExternalLink(UnWikiEscape($match));
446     }
447 }
448
449
450 class Markup_interwiki extends SimpleMarkup
451 {
452     function getMatchRegexp () {
453         global $request;
454         $map = getInterwikiMap();
455         return "(?<! [[:alnum:]])" . $map->getRegexp(). ": \S+ (?<![ ,.?;! \] \) \" \' ])";
456     }
457
458     function markup ($match) {
459         //$map = getInterwikiMap();
460         return new Cached_InterwikiLink(UnWikiEscape($match));
461     }
462 }
463
464 class Markup_wikiword extends SimpleMarkup
465 {
466     function getMatchRegexp () {
467         global $WikiNameRegexp;
468         if (!trim($WikiNameRegexp)) return " " . WIKI_NAME_REGEXP;
469         return " $WikiNameRegexp";
470     }
471
472     function markup ($match) {
473         if (!$match) return false;
474         if ($this->_isWikiUserPage($match))
475             return new Cached_UserLink($match); //$this->_UserLink($match);
476         else
477             return new Cached_WikiLink($match);
478     }
479
480     // FIXME: there's probably a more useful place to put these two functions    
481     function _isWikiUserPage ($page) {
482         global $request;
483         $dbi = $request->getDbh();
484         $page_handle = $dbi->getPage($page);
485         if ($page_handle and $page_handle->get('pref'))
486             return true;
487         else
488             return false;
489     }
490
491     function _UserLink($PageName) {
492         $link = HTML::a(array('href' => $PageName));
493         $link->pushContent(PossiblyGlueIconToText('wikiuser', $PageName));
494         $link->setAttr('class', 'wikiuser');
495         return $link;
496     }
497 }
498
499 class Markup_linebreak extends SimpleMarkup
500 {
501     //var $_match_regexp = "(?: (?<! %) %%% (?! %) | <(?:br|BR)> | <(?:br|BR) \/> )";
502     var $_match_regexp = "(?: (?<! %) %%% (?! %) | <(?:br|BR)> )";
503
504     function markup ($match) {
505         return HTML::br();
506     }
507 }
508
509 class Markup_old_emphasis  extends BalancedMarkup
510 {
511     var $_start_regexp = "''|__";
512
513     function getEndRegexp ($match) {
514         return $match;
515     }
516     
517     function markup ($match, $body) {
518         $tag = $match == "''" ? 'em' : 'strong';
519         return new HtmlElement($tag, $body);
520     }
521 }
522
523 class Markup_nestled_emphasis extends BalancedMarkup
524 {
525     function getStartRegexp() {
526         static $start_regexp = false;
527
528         if (!$start_regexp) {
529             // The three possible delimiters
530             // (none of which can be followed by itself.)
531             $i = "_ (?! _)";
532             $b = "\\* (?! \\*)";
533             $tt = "= (?! =)";
534
535             $any = "(?: ${i}|${b}|${tt})"; // any of the three.
536
537             // Any of [_*=] is okay if preceded by space or one of [-"'/:]
538             $start[] = "(?<= \\s|^|[-\"'\\/:]) ${any}";
539
540             // _ or * is okay after = as long as not immediately followed by =
541             $start[] = "(?<= =) (?: ${i}|${b}) (?! =)";
542             // etc...
543             $start[] = "(?<= _) (?: ${b}|${tt}) (?! _)";
544             $start[] = "(?<= \\*) (?: ${i}|${tt}) (?! \\*)";
545
546
547             // any delimiter okay after an opening brace ( [{<(] )
548             // as long as it's not immediately followed by the matching closing
549             // brace.
550             $start[] = "(?<= { ) ${any} (?! } )";
551             $start[] = "(?<= < ) ${any} (?! > )";
552             $start[] = "(?<= \\( ) ${any} (?! \\) )";
553             
554             $start = "(?:" . join('|', $start) . ")";
555             
556             // Any of the above must be immediately followed by non-whitespace.
557             $start_regexp = $start . "(?= \S)";
558         }
559
560         return $start_regexp;
561     }
562
563     function getEndRegexp ($match) {
564         $chr = preg_quote($match);
565         return "(?<= \S | ^ ) (?<! $chr) $chr (?! $chr) (?= \s | [-)}>\"'\\/:.,;!? _*=] | $)";
566     }
567     
568     function markup ($match, $body) {
569         switch ($match) {
570         case '*': return new HtmlElement('b', $body);
571         case '=': return new HtmlElement('tt', $body);
572         case '_': return new HtmlElement('i', $body);
573         }
574     }
575 }
576
577 class Markup_html_emphasis extends BalancedMarkup
578 {
579     var $_start_regexp = 
580         "<(?: b|big|i|small|tt|em|strong|cite|code|dfn|kbd|samp|var|sup|sub )>";
581
582     function getEndRegexp ($match) {
583         return "<\\/" . substr($match, 1);
584     }
585     
586     function markup ($match, $body) {
587         $tag = substr($match, 1, -1);
588         return new HtmlElement($tag, $body);
589     }
590 }
591
592 class Markup_html_abbr extends BalancedMarkup
593 {
594     //rurban: abbr|acronym need an optional title tag.
595     //sf.net bug #728595
596     var $_start_regexp = "<(?: abbr|acronym )(?: \stitle=[^>]*)?>";
597
598     function getEndRegexp ($match) {
599         if (substr($match,1,4) == 'abbr')
600             $tag = 'abbr';
601         else
602             $tag = 'acronym';
603         return "<\\/" . $tag . '>';
604     }
605     
606     function markup ($match, $body) {
607         if (substr($match,1,4) == 'abbr')
608             $tag = 'abbr';
609         else
610             $tag = 'acronym';
611         $rest = substr($match,1+strlen($tag),-1);
612         if (!empty($rest)) {
613             list($key,$val) = explode("=",$rest);
614             $args = array($key => $val);
615         } else $args = array();
616         return new HtmlElement($tag, $args, $body);
617     }
618 }
619
620 // Special version for single-line plugins formatting, 
621 //  like: '<small>< ?plugin PopularNearby ? ></small>'
622 class Markup_plugin extends SimpleMarkup
623 {
624     var $_match_regexp = '<\?plugin(?:-form)?\s[^\n]+?\?>';
625
626     function markup ($match) {
627         //$xml = new Cached_PluginInvocation($match);
628         //$xml->setTightness(true,true);
629         return new Cached_PluginInvocation($match);
630     }
631 }
632
633
634 // TODO: "..." => "&#133;"  browser specific display (not cached?)
635 // TODO: "--" => "&emdash;" browser specific display (not cached?)
636
637 // FIXME: escape '&' somehow.
638 class Markup_isonumchars  extends SimpleMarkup {
639     // var $_match_regexp = '<\?plugin(?:-form)?\s[^\n]+?\? >';
640     // no hexnums yet, like &#x00A4; <=> &curren;
641     var $_match_regexp = '\&\#\d{2,5};';
642     
643     function markup ($match) {
644         return $match;
645     }
646 }
647
648 // FIXME: escape '&' somehow.
649 class Markup_isohexchars extends SimpleMarkup {
650     var $_match_regexp = '\&\#x[0-9a-fA-F]{2,4};';
651     
652     function markup ($match) {
653         return $match;
654     }
655 }
656
657 // FIXME: Do away with magic phpwiki forms.  (Maybe phpwiki: links too?)
658 // FIXME: Do away with plugin-links.  They seem not to be used.
659 //Plugin link
660
661
662 class InlineTransformer
663 {
664     var $_regexps = array();
665     var $_markup = array();
666     
667     function InlineTransformer ($markup_types = false) {
668         if (!$markup_types)
669             $markup_types = array('escape', /*'isonumchars', 'isohexchars',*/
670                                   'bracketlink', 'url',
671                                   'interwiki', 'wikiword', 'linebreak',
672                                   'old_emphasis', 'nestled_emphasis',
673                                   'html_emphasis', 'html_abbr', 'plugin');
674         foreach ($markup_types as $mtype) {
675             $class = "Markup_$mtype";
676             $this->_addMarkup(new $class);
677         }
678     }
679
680     function _addMarkup ($markup) {
681         if (isa($markup, 'SimpleMarkup'))
682             $regexp = $markup->getMatchRegexp();
683         else
684             $regexp = $markup->getStartRegexp();
685
686         assert(!isset($this->_markup[$regexp]));
687         $this->_regexps[] = $regexp;
688         $this->_markup[] = $markup;
689     }
690         
691     function parse (&$text, $end_regexps = array('$')) {
692         $regexps = $this->_regexps;
693
694         // $end_re takes precedence: "favor reduce over shift"
695         array_unshift($regexps, $end_regexps[0]);
696         //array_push($regexps, $end_regexps[0]);
697         $regexps = new RegexpSet($regexps);
698         
699         $input = $text;
700         $output = new XmlContent;
701
702         $match = $regexps->match($input);
703         
704         while ($match) {
705             if ($match->regexp_ind == 0) {
706                 // No start pattern found before end pattern.
707                 // We're all done!
708                 if (isset($markup) and is_object($markup) and isa($markup,'Markup_plugin')) {
709                     $current =& $output->_content[count($output->_content)-1];
710                     $current->setTightness(true,true);
711                 }
712                 $output->pushContent($match->prematch);
713                 $text = $match->postmatch;
714                 return $output;
715             }
716
717             $markup = $this->_markup[$match->regexp_ind - 1];
718             $body = $this->_parse_markup_body($markup, $match->match, $match->postmatch, $end_regexps);
719             if (!$body) {
720                 // Couldn't match balanced expression.
721                 // Ignore and look for next matching start regexp.
722                 $match = $regexps->nextMatch($input, $match);
723                 continue;
724             }
725
726             // Matched markup.  Eat input, push output.
727             // FIXME: combine adjacent strings.
728             if (isa($markup, 'SimpleMarkup'))
729                 $current = $markup->markup($match->match);
730             else
731                 $current = $markup->markup($match->match, $body);
732             $input = $match->postmatch;
733             if (isset($markup) and is_object($markup) and isa($markup,'Markup_plugin')) {
734                 $current->setTightness(true,true);
735             }
736             $output->pushContent($match->prematch, $current);
737
738             $match = $regexps->match($input);
739         }
740
741         // No pattern matched, not even the end pattern.
742         // Parse fails.
743         return false;
744     }
745
746     function _parse_markup_body ($markup, $match, &$text, $end_regexps) {
747         if (isa($markup, 'SimpleMarkup'))
748             return true;        // Done. SimpleMarkup is simple.
749
750         if (!is_object($markup)) return false; // Some error: Should assert
751         array_unshift($end_regexps, $markup->getEndRegexp($match));
752
753         // Optimization: if no end pattern in text, we know the
754         // parse will fail.  This is an important optimization,
755         // e.g. when text is "*lots *of *start *delims *with
756         // *no *matching *end *delims".
757         $ends_pat = "/(?:" . join(").*(?:", $end_regexps) . ")/xs";
758         if (!preg_match($ends_pat, $text))
759             return false;
760         return $this->parse($text, $end_regexps);
761     }
762 }
763
764 class LinkTransformer extends InlineTransformer
765 {
766     function LinkTransformer () {
767         $this->InlineTransformer(array('escape', 'bracketlink', 'url',
768                                        'interwiki', 'wikiword'));
769     }
770 }
771
772 function TransformInline($text, $markup = 2.0, $basepage=false) {
773     static $trfm;
774     
775     if (empty($trfm)) {
776         $trfm = new InlineTransformer;
777     }
778     
779     if ($markup < 2.0) {
780         $text = ConvertOldMarkup($text, 'inline');
781     }
782
783     if ($basepage) {
784         return new CacheableMarkup($trfm->parse($text), $basepage);
785     }
786     return $trfm->parse($text);
787 }
788
789 function TransformLinks($text, $markup = 2.0, $basepage = false) {
790     static $trfm;
791     
792     if (empty($trfm)) {
793         $trfm = new LinkTransformer;
794     }
795
796     if ($markup < 2.0) {
797         $text = ConvertOldMarkup($text, 'links');
798     }
799     
800     if ($basepage) {
801         return new CacheableMarkup($trfm->parse($text), $basepage);
802     }
803     return $trfm->parse($text);
804 }
805
806 // (c-file-style: "gnu")
807 // Local Variables:
808 // mode: php
809 // tab-width: 8
810 // c-basic-offset: 4
811 // c-hanging-comment-ender-p: nil
812 // indent-tabs-mode: nil
813 // End:   
814 ?>