]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/InlineParser.php
http://www.securityfocus.com/bid/10532/
[SourceForge/phpwiki.git] / lib / InlineParser.php
1 <?php 
2 rcs_id('$Id: InlineParser.php,v 1.57 2004-06-20 15:26:29 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             // We could do much better, if we would know the matching markup for the 
179             // longest regexp match:
180             $hugepat= "/ ( . $repeat ) ( (" . join(')|(', $regexps) . ") ) /Asx";
181             // Proposed premature optimization 1:
182             //$hugepat= "/ ( . $repeat ) ( (" . join(')|(', array_values($matched)) . ") ) /Asx";
183 /* currently:
184   '/ ( . *? ) ( ($)|(~(?: [[:alnum:]]+ | .))|(&#\d{2,5};)|(\#? \[ .*? [^]\s] .*? \])|((?<![[:alnum:]]) (?:http|https|mailto|ftp|news|nntp|ssh|gopher) : [^\s<>"']+ (?<![ ,.?; \] \) ]))|((?<! [[:alnum:]])(?:AbbeNormal|AcadWiki|Acronym|Advogato|AIWiki|ALife|AndStuff|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'
185 */
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         /*
202         if (DEBUG == 4) {
203           var_dump($regexps); var_dump($matched); var_dump($matched_inc); 
204         PrintXML(HTML::dl(HTML::dt("input"),
205                           HTML::dd(HTML::pre($text)),
206                           HTML::dt("regexp"),
207                           HTML::dd(HTML::pre($match->regexp_ind, ":", $regexps[$match->regexp_ind])),
208                           HTML::dt("prematch"),
209                           HTML::dd(HTML::pre($match->prematch)),
210                           HTML::dt("match"),
211                           HTML::dd(HTML::pre($match->match)),
212                           HTML::dt("postmatch"),
213                           HTML::dd(HTML::pre($match->postmatch))
214                           ));
215         }
216         */
217         return $match;
218     }
219 }
220
221
222
223 /**
224  * A simple markup rule (i.e. terminal token).
225  *
226  * These are defined by a regexp.
227  *
228  * When a match is found for the regexp, the matching text is replaced.
229  * The replacement content is obtained by calling the SimpleMarkup::markup method.
230  */ 
231 class SimpleMarkup
232 {
233     var $_match_regexp;
234
235     /** Get regexp.
236      *
237      * @return string Regexp which matches this token.
238      */
239     function getMatchRegexp () {
240         return $this->_match_regexp;
241     }
242
243     /** Markup matching text.
244      *
245      * @param string $match The text which matched the regexp
246      * (obtained from getMatchRegexp).
247      *
248      * @return mixed The expansion of the matched text.
249      */
250     function markup ($match /*, $body */) {
251         trigger_error("pure virtual", E_USER_ERROR);
252     }
253 }
254
255 /**
256  * A balanced markup rule.
257  *
258  * These are defined by a start regexp, and an end regexp.
259  */ 
260 class BalancedMarkup
261 {
262     var $_start_regexp;
263
264     /** Get the starting regexp for this rule.
265      *
266      * @return string The starting regexp.
267      */
268     function getStartRegexp () {
269         return $this->_start_regexp;
270     }
271     
272     /** Get the ending regexp for this rule.
273      *
274      * @param string $match The text which matched the starting regexp.
275      *
276      * @return string The ending regexp.
277      */
278     function getEndRegexp ($match) {
279         return $this->_end_regexp;
280     }
281
282     /** Get expansion for matching input.
283      *
284      * @param string $match The text which matched the starting regexp.
285      *
286      * @param mixed $body Transformed text found between the starting
287      * and ending regexps.
288      *
289      * @return mixed The expansion of the matched text.
290      */
291     function markup ($match, $body) {
292         trigger_error("pure virtual", E_USER_ERROR);
293     }
294 }
295
296 class Markup_escape  extends SimpleMarkup
297 {
298     function getMatchRegexp () {
299         return ESCAPE_CHAR . '(?: [[:alnum:]]+ | .)';
300     }
301     
302     function markup ($match) {
303         assert(strlen($match) >= 2);
304         return substr($match, 1);
305     }
306 }
307
308 /**
309  * [image.jpg size=50% border=5], [image.jpg size=50x30]
310  * Support for the following attributes: see stdlib.php:LinkImage()
311  *   size=<precent>%, size=<width>x<height>
312  *   border=n, align=\w+, hspace=n, vspace=n
313  */
314 function isImageLink($link) {
315     if (!$link) return false;
316     return preg_match("/\\.(" . INLINE_IMAGES . ")$/i", $link)
317         or preg_match("/\\.(" . INLINE_IMAGES . ")\s+(size|border|align|hspace|vspace)=/i", $link);
318 }
319
320 function LinkBracketLink($bracketlink) {
321
322     // $bracketlink will start and end with brackets; in between will
323     // be either a page name, a URL or both separated by a pipe.
324     
325     // strip brackets and leading space
326     preg_match('/(\#?) \[\s* (?: (.*?) \s* (?<!' . ESCAPE_CHAR . ')(\|) )? \s* (.+?) \s*\]/x',
327                $bracketlink, $matches);
328     if (count($matches) < 4) {
329         trigger_error(_("Invalid [] syntax ignored").": ".$bracketlink, E_USER_NOTICE);
330         return new Cached_Link;
331     }
332     list (, $hash, $label, $bar, $rawlink) = $matches;
333
334     $label = UnWikiEscape($label);
335     /*
336      * Check if the user has typed a explicit URL. This solves the
337      * problem where the URLs have a ~ character, which would be stripped away.
338      *   "[http:/server/~name/]" will work as expected
339      *   "http:/server/~name/"   will NOT work as expected, will remove the ~
340      */
341     if (strstr($rawlink, "http://") or strstr($rawlink, "https://")) {
342         $link = $rawlink;
343         // Mozilla Browser URI Obfuscation Weakness 2004-06-14
344         //   http://www.securityfocus.com/bid/10532/
345         //   goodurl+"%2F%20%20%20."+badurl
346         if (preg_match("/%2F(%20)+\./i", $rawlink)) {
347             $rawlink = preg_replace("/%2F(%20)+\./i","%2F.",$rawlink);
348         }
349     } else
350         $link  = UnWikiEscape($rawlink);
351
352     // [label|link]
353     // if label looks like a url to an image, we want an image link.
354     if (isImageLink($label)) {
355         $imgurl = $label;
356         $intermap = getInterwikiMap();
357         if (preg_match("/^" . $intermap->getRegexp() . ":/", $label)) {
358             $imgurl = $intermap->link($label);
359             $imgurl = $imgurl->getAttr('href');
360         } elseif (! preg_match("#^(" . ALLOWED_PROTOCOLS . "):#", $imgurl)) {
361             // local theme linkname like 'images/next.gif'.
362             global $WikiTheme;
363             $imgurl = $WikiTheme->getImageURL($imgurl);
364         }
365         $label = LinkImage($imgurl, $link);
366     }
367
368     if ($hash) {
369         // It's an anchor, not a link...
370         $id = MangleXmlIdentifier($link);
371         return HTML::a(array('name' => $id, 'id' => $id),
372                        $bar ? $label : $link);
373     }
374
375     if (preg_match("#^(" . ALLOWED_PROTOCOLS . "):#", $link)) {
376         // if it's an image, embed it; otherwise, it's a regular link
377         if (isImageLink($link))
378             return LinkImage($link, $label);
379         else
380             return new Cached_ExternalLink($link, $label);
381     }
382     elseif (preg_match("/^phpwiki:/", $link))
383         return new Cached_PhpwikiURL($link, $label);
384     /*
385      * Inline images in Interwiki urls's:
386      * [File:my_image.gif] inlines the image,
387      * File:my_image.gif shows a plain inter-wiki link,
388      * [what a pic|File:my_image.gif] shows a named inter-wiki link to the gif
389      * [File:my_image.gif|what a pic] shows a inlimed image linked to the page "what a pic"
390      */
391     elseif (strstr($link,':') and 
392             ($intermap = getInterwikiMap()) and 
393             preg_match("/^" . $intermap->getRegexp() . ":/", $link)) {
394         if (empty($label) && isImageLink($link)) {
395             // if without label => inlined image [File:xx.gif]
396             $imgurl = $intermap->link($link);
397             return LinkImage($imgurl->getAttr('href'), $label);
398         }
399         return new Cached_InterwikiLink($link, $label);
400     } else {
401         // Split anchor off end of pagename.
402         if (preg_match('/\A(.*)(?<!'.ESCAPE_CHAR.')#(.*?)\Z/', $rawlink, $m)) {
403             list(,$rawlink,$anchor) = $m;
404             $pagename = UnWikiEscape($rawlink);
405             $anchor = UnWikiEscape($anchor);
406             if (!$label)
407                 $label = $link;
408         }
409         else {
410             $pagename = $link;
411             $anchor = false;
412         }
413         return new Cached_WikiLink($pagename, $label, $anchor);
414     }
415 }
416
417 class Markup_bracketlink  extends SimpleMarkup
418 {
419     var $_match_regexp = "\\#? \\[ .*? [^]\\s] .*? \\]";
420     
421     function markup ($match) {
422         $link = LinkBracketLink($match);
423         assert($link->isInlineElement());
424         return $link;
425     }
426 }
427
428 class Markup_url extends SimpleMarkup
429 {
430     function getMatchRegexp () {
431         return "(?<![[:alnum:]]) (?:" . ALLOWED_PROTOCOLS . ") : [^\s<>\"']+ (?<![ ,.?; \] \) ])";
432     }
433     
434     function markup ($match) {
435         return new Cached_ExternalLink(UnWikiEscape($match));
436     }
437 }
438
439
440 class Markup_interwiki extends SimpleMarkup
441 {
442     function getMatchRegexp () {
443         global $request;
444         $map = getInterwikiMap();
445         return "(?<! [[:alnum:]])" . $map->getRegexp(). ": \S+ (?<![ ,.?;! \] \) \" \' ])";
446     }
447
448     function markup ($match) {
449         //$map = getInterwikiMap();
450         return new Cached_InterwikiLink(UnWikiEscape($match));
451     }
452 }
453
454 class Markup_wikiword extends SimpleMarkup
455 {
456     function getMatchRegexp () {
457         global $WikiNameRegexp;
458         if (!trim($WikiNameRegexp)) return " " . WIKI_NAME_REGEXP;
459         return " $WikiNameRegexp";
460     }
461
462     function markup ($match) {
463         if (!$match) return false;
464         if ($this->_isWikiUserPage($match))
465             return new Cached_UserLink($match); //$this->_UserLink($match);
466         else
467             return new Cached_WikiLink($match);
468     }
469
470     // FIXME: there's probably a more useful place to put these two functions    
471     function _isWikiUserPage ($page) {
472         global $request;
473         $dbi = $request->getDbh();
474         $page_handle = $dbi->getPage($page);
475         if ($page_handle and $page_handle->get('pref'))
476             return true;
477         else
478             return false;
479     }
480
481     function _UserLink($PageName) {
482         $link = HTML::a(array('href' => $PageName));
483         $link->pushContent(PossiblyGlueIconToText('wikiuser', $PageName));
484         $link->setAttr('class', 'wikiuser');
485         return $link;
486     }
487 }
488
489 class Markup_linebreak extends SimpleMarkup
490 {
491     //var $_match_regexp = "(?: (?<! %) %%% (?! %) | <(?:br|BR)> | <(?:br|BR) \/> )";
492     var $_match_regexp = "(?: (?<! %) %%% (?! %) | <(?:br|BR)> )";
493
494     function markup ($match) {
495         return HTML::br();
496     }
497 }
498
499 class Markup_old_emphasis  extends BalancedMarkup
500 {
501     var $_start_regexp = "''|__";
502
503     function getEndRegexp ($match) {
504         return $match;
505     }
506     
507     function markup ($match, $body) {
508         $tag = $match == "''" ? 'em' : 'strong';
509         return new HtmlElement($tag, $body);
510     }
511 }
512
513 class Markup_nestled_emphasis extends BalancedMarkup
514 {
515     function getStartRegexp() {
516         static $start_regexp = false;
517
518         if (!$start_regexp) {
519             // The three possible delimiters
520             // (none of which can be followed by itself.)
521             $i = "_ (?! _)";
522             $b = "\\* (?! \\*)";
523             $tt = "= (?! =)";
524
525             $any = "(?: ${i}|${b}|${tt})"; // any of the three.
526
527             // Any of [_*=] is okay if preceded by space or one of [-"'/:]
528             $start[] = "(?<= \\s|^|[-\"'\\/:]) ${any}";
529
530             // _ or * is okay after = as long as not immediately followed by =
531             $start[] = "(?<= =) (?: ${i}|${b}) (?! =)";
532             // etc...
533             $start[] = "(?<= _) (?: ${b}|${tt}) (?! _)";
534             $start[] = "(?<= \\*) (?: ${i}|${tt}) (?! \\*)";
535
536
537             // any delimiter okay after an opening brace ( [{<(] )
538             // as long as it's not immediately followed by the matching closing
539             // brace.
540             $start[] = "(?<= { ) ${any} (?! } )";
541             $start[] = "(?<= < ) ${any} (?! > )";
542             $start[] = "(?<= \\( ) ${any} (?! \\) )";
543             
544             $start = "(?:" . join('|', $start) . ")";
545             
546             // Any of the above must be immediately followed by non-whitespace.
547             $start_regexp = $start . "(?= \S)";
548         }
549
550         return $start_regexp;
551     }
552
553     function getEndRegexp ($match) {
554         $chr = preg_quote($match);
555         return "(?<= \S | ^ ) (?<! $chr) $chr (?! $chr) (?= \s | [-)}>\"'\\/:.,;!? _*=] | $)";
556     }
557     
558     function markup ($match, $body) {
559         switch ($match) {
560         case '*': return new HtmlElement('b', $body);
561         case '=': return new HtmlElement('tt', $body);
562         case '_': return new HtmlElement('i', $body);
563         }
564     }
565 }
566
567 class Markup_html_emphasis extends BalancedMarkup
568 {
569     var $_start_regexp = 
570         "<(?: b|big|i|small|tt|em|strong|cite|code|dfn|kbd|samp|var|sup|sub )>";
571
572     function getEndRegexp ($match) {
573         return "<\\/" . substr($match, 1);
574     }
575     
576     function markup ($match, $body) {
577         $tag = substr($match, 1, -1);
578         return new HtmlElement($tag, $body);
579     }
580 }
581
582 class Markup_html_abbr extends BalancedMarkup
583 {
584     //rurban: abbr|acronym need an optional title tag.
585     //sf.net bug #728595
586     var $_start_regexp = "<(?: abbr|acronym )(?: \stitle=[^>]*)?>";
587
588     function getEndRegexp ($match) {
589         if (substr($match,1,4) == 'abbr')
590             $tag = 'abbr';
591         else
592             $tag = 'acronym';
593         return "<\\/" . $tag . '>';
594     }
595     
596     function markup ($match, $body) {
597         if (substr($match,1,4) == 'abbr')
598             $tag = 'abbr';
599         else
600             $tag = 'acronym';
601         $rest = substr($match,1+strlen($tag),-1);
602         if (!empty($rest)) {
603             list($key,$val) = explode("=",$rest);
604             $args = array($key => $val);
605         } else $args = array();
606         return new HtmlElement($tag, $args, $body);
607     }
608 }
609
610 // Special version for single-line plugins formatting, 
611 //  like: '<small>< ?plugin PopularNearby ? ></small>'
612 class Markup_plugin extends SimpleMarkup
613 {
614     var $_match_regexp = '<\?plugin(?:-form)?\s[^\n]+?\?>';
615
616     function markup ($match) {
617         //$xml = new Cached_PluginInvocation($match);
618         //$xml->setTightness(true,true);
619         return new Cached_PluginInvocation($match);
620     }
621 }
622
623
624 // TODO: "..." => "&#133;"  browser specific display (not cached?)
625 // TODO: "--" => "&emdash;" browser specific display (not cached?)
626
627 // FIXME: escape '&' somehow.
628 class Markup_isonumchars  extends SimpleMarkup {
629     // var $_match_regexp = '<\?plugin(?:-form)?\s[^\n]+?\? >';
630     // no hexnums yet, like &#x00A4; <=> &curren;
631     var $_match_regexp = '\&\#\d{2,5};';
632     
633     function markup ($match) {
634         return $match;
635     }
636 }
637
638 // FIXME: escape '&' somehow.
639 class Markup_isohexchars extends SimpleMarkup {
640     var $_match_regexp = '\&\#x[0-9a-fA-F]{2,4};';
641     
642     function markup ($match) {
643         return $match;
644     }
645 }
646
647 // FIXME: Do away with magic phpwiki forms.  (Maybe phpwiki: links too?)
648 // FIXME: Do away with plugin-links.  They seem not to be used.
649 //Plugin link
650
651
652 class InlineTransformer
653 {
654     var $_regexps = array();
655     var $_markup = array();
656     
657     function InlineTransformer ($markup_types = false) {
658         if (!$markup_types)
659             $markup_types = array('escape', /*'isonumchars', 'isohexchars',*/
660                                   'bracketlink', 'url',
661                                   'interwiki', 'wikiword', 'linebreak',
662                                   'old_emphasis', 'nestled_emphasis',
663                                   'html_emphasis', 'html_abbr', 'plugin');
664         foreach ($markup_types as $mtype) {
665             $class = "Markup_$mtype";
666             $this->_addMarkup(new $class);
667         }
668     }
669
670     function _addMarkup ($markup) {
671         if (isa($markup, 'SimpleMarkup'))
672             $regexp = $markup->getMatchRegexp();
673         else
674             $regexp = $markup->getStartRegexp();
675
676         assert(!isset($this->_markup[$regexp]));
677         $this->_regexps[] = $regexp;
678         $this->_markup[] = $markup;
679     }
680         
681     function parse (&$text, $end_regexps = array('$')) {
682         $regexps = $this->_regexps;
683
684         // $end_re takes precedence: "favor reduce over shift"
685         array_unshift($regexps, $end_regexps[0]);
686         //array_push($regexps, $end_regexps[0]);
687         $regexps = new RegexpSet($regexps);
688         
689         $input = $text;
690         $output = new XmlContent;
691
692         $match = $regexps->match($input);
693         
694         while ($match) {
695             if ($match->regexp_ind == 0) {
696                 // No start pattern found before end pattern.
697                 // We're all done!
698                 if (isset($markup) and is_object($markup) and isa($markup,'Markup_plugin')) {
699                     $current =& $output->_content[count($output->_content)-1];
700                     $current->setTightness(true,true);
701                 }
702                 $output->pushContent($match->prematch);
703                 $text = $match->postmatch;
704                 return $output;
705             }
706
707             $markup = $this->_markup[$match->regexp_ind - 1];
708             $body = $this->_parse_markup_body($markup, $match->match, $match->postmatch, $end_regexps);
709             if (!$body) {
710                 // Couldn't match balanced expression.
711                 // Ignore and look for next matching start regexp.
712                 $match = $regexps->nextMatch($input, $match);
713                 continue;
714             }
715
716             // Matched markup.  Eat input, push output.
717             // FIXME: combine adjacent strings.
718             $current = $markup->markup($match->match, $body);
719             $input = $match->postmatch;
720             if (isset($markup) and is_object($markup) and isa($markup,'Markup_plugin')) {
721                 $current->setTightness(true,true);
722             }
723             $output->pushContent($match->prematch, $current);
724
725             $match = $regexps->match($input);
726         }
727
728         // No pattern matched, not even the end pattern.
729         // Parse fails.
730         return false;
731     }
732
733     function _parse_markup_body ($markup, $match, &$text, $end_regexps) {
734         if (isa($markup, 'SimpleMarkup'))
735             return true;        // Done. SimpleMarkup is simple.
736
737         if (!is_object($markup)) return false; // Some error: Should assert
738         array_unshift($end_regexps, $markup->getEndRegexp($match));
739
740         // Optimization: if no end pattern in text, we know the
741         // parse will fail.  This is an important optimization,
742         // e.g. when text is "*lots *of *start *delims *with
743         // *no *matching *end *delims".
744         $ends_pat = "/(?:" . join(").*(?:", $end_regexps) . ")/xs";
745         if (!preg_match($ends_pat, $text))
746             return false;
747         return $this->parse($text, $end_regexps);
748     }
749 }
750
751 class LinkTransformer extends InlineTransformer
752 {
753     function LinkTransformer () {
754         $this->InlineTransformer(array('escape', 'bracketlink', 'url',
755                                        'interwiki', 'wikiword'));
756     }
757 }
758
759 function TransformInline($text, $markup = 2.0, $basepage=false) {
760     static $trfm;
761     
762     if (empty($trfm)) {
763         $trfm = new InlineTransformer;
764     }
765     
766     if ($markup < 2.0) {
767         $text = ConvertOldMarkup($text, 'inline');
768     }
769
770     if ($basepage) {
771         return new CacheableMarkup($trfm->parse($text), $basepage);
772     }
773     return $trfm->parse($text);
774 }
775
776 function TransformLinks($text, $markup = 2.0, $basepage = false) {
777     static $trfm;
778     
779     if (empty($trfm)) {
780         $trfm = new LinkTransformer;
781     }
782
783     if ($markup < 2.0) {
784         $text = ConvertOldMarkup($text, 'links');
785     }
786     
787     if ($basepage) {
788         return new CacheableMarkup($trfm->parse($text), $basepage);
789     }
790     return $trfm->parse($text);
791 }
792
793 // (c-file-style: "gnu")
794 // Local Variables:
795 // mode: php
796 // tab-width: 8
797 // c-basic-offset: 4
798 // c-hanging-comment-ender-p: nil
799 // indent-tabs-mode: nil
800 // End:   
801 ?>