]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/InlineParser.php
revert and removed some comments
[SourceForge/phpwiki.git] / lib / InlineParser.php
1 <?php rcs_id('$Id: InlineParser.php,v 1.43 2004-05-06 20:30:46 rurban Exp $');
2 /* Copyright (C) 2002, Geoffrey T. Dairiki <dairiki@dairiki.org>
3  *
4  * This file is part of PhpWiki.
5  * 
6  * PhpWiki is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 2 of the License, or
9  * (at your option) any later version.
10  * 
11  * PhpWiki is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  * 
16  * You should have received a copy of the GNU General Public License
17  * along with PhpWiki; if not, write to the Free Software
18  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19  */
20 /**
21  * This is the code which deals with the inline part of the (new-style)
22  * wiki-markup.
23  *
24  * @package Markup
25  * @author Geoffrey T. Dairiki
26  */
27 /**
28  */
29
30 /**
31  * This is the character used in wiki markup to escape characters with
32  * special meaning.
33  */
34 define('ESCAPE_CHAR', '~');
35
36 require_once('lib/HtmlElement.php');
37 require_once('lib/CachedMarkup.php');
38 //require_once('lib/interwiki.php');
39 require_once('lib/stdlib.php');
40
41
42 function WikiEscape($text) {
43     return str_replace('#', ESCAPE_CHAR . '#', $text);
44 }
45
46 function UnWikiEscape($text) {
47     return preg_replace('/' . ESCAPE_CHAR . '(.)/', '\1', $text);
48 }
49
50 /**
51  * Return type from RegexpSet::match and RegexpSet::nextMatch.
52  *
53  * @see RegexpSet
54  */
55 class RegexpSet_match {
56     /**
57      * The text leading up the the next match.
58      */
59     var $prematch;
60
61     /**
62      * The matched text.
63      */
64     var $match;
65
66     /**
67      * The text following the matched text.
68      */
69     var $postmatch;
70
71     /**
72      * Index of the regular expression which matched.
73      */
74     var $regexp_ind;
75 }
76
77 /**
78  * A set of regular expressions.
79  *
80  * This class is probably only useful for InlineTransformer.
81  */
82 class RegexpSet
83 {
84     /** Constructor
85      *
86      * @param array $regexps A list of regular expressions.  The
87      * regular expressions should not include any sub-pattern groups
88      * "(...)".  (Anonymous groups, like "(?:...)", as well as
89      * look-ahead and look-behind assertions are okay.)
90      */
91     function RegexpSet ($regexps) {
92         assert($regexps);
93         $this->_regexps = array_unique($regexps);
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
144     function _match ($text, $regexps, $repeat) {
145         $pat= "/ ( . $repeat ) ( (" . join(')|(', $regexps) . ") ) /Axs";
146
147         if (! preg_match($pat, $text, $m)) {
148             return false;
149         }
150         
151         $match = new RegexpSet_match;
152         $match->postmatch = substr($text, strlen($m[0]));
153         $match->prematch = $m[1];
154         $match->match = $m[2];
155         $match->regexp_ind = count($m) - 4;
156
157         /* DEBUGGING
158         PrintXML(HTML::dl(HTML::dt("input"),
159                           HTML::dd(HTML::pre($text)),
160                           HTML::dt("match"),
161                           HTML::dd(HTML::pre($match->match)),
162                           HTML::dt("regexp"),
163                           HTML::dd(HTML::pre($regexps[$match->regexp_ind])),
164                           HTML::dt("prematch"),
165                           HTML::dd(HTML::pre($match->prematch))));
166         */
167         return $match;
168     }
169 }
170
171
172
173 /**
174  * A simple markup rule (i.e. terminal token).
175  *
176  * These are defined by a regexp.
177  *
178  * When a match is found for the regexp, the matching text is replaced.
179  * The replacement content is obtained by calling the SimpleMarkup::markup method.
180  */ 
181 class SimpleMarkup
182 {
183     var $_match_regexp;
184
185     /** Get regexp.
186      *
187      * @return string Regexp which matches this token.
188      */
189     function getMatchRegexp () {
190         return $this->_match_regexp;
191     }
192
193     /** Markup matching text.
194      *
195      * @param string $match The text which matched the regexp
196      * (obtained from getMatchRegexp).
197      *
198      * @return mixed The expansion of the matched text.
199      */
200     function markup ($match /*, $body */) {
201         trigger_error("pure virtual", E_USER_ERROR);
202     }
203 }
204
205 /**
206  * A balanced markup rule.
207  *
208  * These are defined by a start regexp, and an end regexp.
209  */ 
210 class BalancedMarkup
211 {
212     var $_start_regexp;
213
214     /** Get the starting regexp for this rule.
215      *
216      * @return string The starting regexp.
217      */
218     function getStartRegexp () {
219         return $this->_start_regexp;
220     }
221     
222     /** Get the ending regexp for this rule.
223      *
224      * @param string $match The text which matched the starting regexp.
225      *
226      * @return string The ending regexp.
227      */
228     function getEndRegexp ($match) {
229         return $this->_end_regexp;
230     }
231
232     /** Get expansion for matching input.
233      *
234      * @param string $match The text which matched the starting regexp.
235      *
236      * @param mixed $body Transformed text found between the starting
237      * and ending regexps.
238      *
239      * @return mixed The expansion of the matched text.
240      */
241     function markup ($match, $body) {
242         trigger_error("pure virtual", E_USER_ERROR);
243     }
244 }
245
246 class Markup_escape  extends SimpleMarkup
247 {
248     function getMatchRegexp () {
249         return ESCAPE_CHAR . '(?: [[:alnum:]]+ | .)';
250     }
251     
252     function markup ($match) {
253         assert(strlen($match) >= 2);
254         return substr($match, 1);
255     }
256 }
257
258 function LinkBracketLink($bracketlink) {
259     //include_once("lib/interwiki.php");
260     $intermap = getInterwikiMap();
261     
262     // $bracketlink will start and end with brackets; in between will
263     // be either a page name, a URL or both separated by a pipe.
264     
265     // strip brackets and leading space
266     preg_match('/(\#?) \[\s* (?: (.*?) \s* (?<!' . ESCAPE_CHAR . ')(\|) )? \s* (.+?) \s*\]/x',
267                $bracketlink, $matches);
268     list (, $hash, $label, $bar, $rawlink) = $matches;
269
270     $label = UnWikiEscape($label);
271     /*
272      * Check if the user has typed a explicit URL. This solves the
273      * problem where the URLs have a ~ character, which would be stripped away.
274      *   "[http:/server/~name/]" will work as expected
275      *   "http:/server/~name/"   will NOT work as expected, will remove the ~
276      */
277     if (strstr($rawlink, "http://") or strstr($rawlink, "https://"))
278         $link = $rawlink;
279     else
280         $link  = UnWikiEscape($rawlink);
281
282     // [label|link]
283     // if label looks like a url to an image, we want an image link.
284     if (preg_match("/\\.(" . INLINE_IMAGES . ")$/i", $label)) {
285         $imgurl = $label;
286         if (preg_match("/^" . $intermap->getRegexp() . ":/", $label)) {
287             $imgurl = $intermap->link($label);
288             $imgurl = $imgurl->getAttr('href');
289         } elseif (! preg_match("#^(" . ALLOWED_PROTOCOLS . "):#", $imgurl)) {
290             // local theme linkname like 'images/next.gif'.
291             global $Theme;
292             $imgurl = $Theme->getImageURL($imgurl);
293         }
294         $label = LinkImage($imgurl, $link);
295     }
296
297     if ($hash) {
298         // It's an anchor, not a link...
299         $id = MangleXmlIdentifier($link);
300         return HTML::a(array('name' => $id, 'id' => $id),
301                        $bar ? $label : $link);
302     }
303
304     if (preg_match("#^(" . ALLOWED_PROTOCOLS . "):#", $link)) {
305         // if it's an image, embed it; otherwise, it's a regular link
306         if (preg_match("/\\.(" . INLINE_IMAGES . ")$/i", $link))
307             return LinkImage($link, $label);
308         else
309             return new Cached_ExternalLink($link, $label);
310     }
311     elseif (preg_match("/^phpwiki:/", $link))
312         return new Cached_PhpwikiURL($link, $label);
313     /*
314      * Inline images in Interwiki urls's:
315      * [File:my_image.gif] inlines the image,
316      * File:my_image.gif shows a plain inter-wiki link,
317      * [what a pic|File:my_image.gif] shows a named inter-wiki link to the gif
318      * [File:my_image.gif|what a pic] shows a inlimed image linked to the page "what a pic"
319      */
320     elseif (preg_match("/^" . $intermap->getRegexp() . ":/", $link)) {
321         if (empty($label) && preg_match("/\\.(" . INLINE_IMAGES . ")$/i", $link)) {
322             // if without label => inlined image [File:xx.gif]
323             $imgurl = $intermap->link($link);
324             return LinkImage($imgurl->getAttr('href'), $label);
325         }
326         return new Cached_InterwikiLink($link, $label);
327     } else {
328         // Split anchor off end of pagename.
329         if (preg_match('/\A(.*)(?<!'.ESCAPE_CHAR.')#(.*?)\Z/', $rawlink, $m)) {
330             list(,$rawlink,$anchor) = $m;
331             $pagename = UnWikiEscape($rawlink);
332             $anchor = UnWikiEscape($anchor);
333             if (!$label)
334                 $label = $link;
335         }
336         else {
337             $pagename = $link;
338             $anchor = false;
339         }
340         return new Cached_WikiLink($pagename, $label, $anchor);
341     }
342 }
343
344 class Markup_bracketlink  extends SimpleMarkup
345 {
346     var $_match_regexp = "\\#? \\[ .*? [^]\\s] .*? \\]";
347     
348     function markup ($match) {
349         $link = LinkBracketLink($match);
350         assert($link->isInlineElement());
351         return $link;
352     }
353 }
354
355 class Markup_url extends SimpleMarkup
356 {
357     function getMatchRegexp () {
358         return "(?<![[:alnum:]]) (?:" . ALLOWED_PROTOCOLS . ") : [^\s<>\"']+ (?<![ ,.?; \] \) ])";
359     }
360     
361     function markup ($match) {
362         return new Cached_ExternalLink(UnWikiEscape($match));
363     }
364 }
365
366
367 class Markup_interwiki extends SimpleMarkup
368 {
369     function getMatchRegexp () {
370         global $request;
371         $map = getInterwikiMap();
372         return "(?<! [[:alnum:]])" . $map->getRegexp(). ": \S+ (?<![ ,.?;! \] \) \" \' ])";
373     }
374
375     function markup ($match) {
376         //$map = getInterwikiMap();
377         return new Cached_InterwikiLink(UnWikiEscape($match));
378     }
379 }
380
381 class Markup_wikiword extends SimpleMarkup
382 {
383     function getMatchRegexp () {
384         global $WikiNameRegexp;
385         return " $WikiNameRegexp";
386     }
387
388     function markup ($match) {
389         if (!$match) return false;
390         if ($this->_isWikiUserPage($match))
391             return new Cached_UserLink($match); //$this->_UserLink($match);
392         else
393             return new Cached_WikiLink($match);
394     }
395
396     // FIXME: there's probably a more useful place to put these two functions    
397     function _isWikiUserPage ($page) {
398         global $request;
399         $dbi = $request->getDbh();
400         $page_handle = $dbi->getPage($page);
401         if ($page_handle and $page_handle->get('pref'))
402             return true;
403         else
404             return false;
405     }
406
407     function _UserLink($PageName) {
408         $link = HTML::a(array('href' => $PageName));
409         $link->pushContent(PossiblyGlueIconToText('wikiuser', $PageName));
410         $link->setAttr('class', 'wikiuser');
411         return $link;
412     }
413 }
414
415 class Markup_linebreak extends SimpleMarkup
416 {
417     //var $_match_regexp = "(?: (?<! %) %%% (?! %) | <(?:br|BR)> | <(?:br|BR) \/> )";
418     var $_match_regexp = "(?: (?<! %) %%% (?! %) | <(?:br|BR)> )";
419
420     function markup ($match) {
421         return HTML::br();
422     }
423 }
424
425 class Markup_old_emphasis  extends BalancedMarkup
426 {
427     var $_start_regexp = "''|__";
428
429     function getEndRegexp ($match) {
430         return $match;
431     }
432     
433     function markup ($match, $body) {
434         $tag = $match == "''" ? 'em' : 'strong';
435         return new HtmlElement($tag, $body);
436     }
437 }
438
439 class Markup_nestled_emphasis extends BalancedMarkup
440 {
441     function getStartRegexp() {
442         static $start_regexp = false;
443
444         if (!$start_regexp) {
445             // The three possible delimiters
446             // (none of which can be followed by itself.)
447             $i = "_ (?! _)";
448             $b = "\\* (?! \\*)";
449             $tt = "= (?! =)";
450
451             $any = "(?: ${i}|${b}|${tt})"; // any of the three.
452
453             // Any of [_*=] is okay if preceded by space or one of [-"'/:]
454             $start[] = "(?<= \\s|^|[-\"'\\/:]) ${any}";
455
456             // _ or * is okay after = as long as not immediately followed by =
457             $start[] = "(?<= =) (?: ${i}|${b}) (?! =)";
458             // etc...
459             $start[] = "(?<= _) (?: ${b}|${tt}) (?! _)";
460             $start[] = "(?<= \\*) (?: ${i}|${tt}) (?! \\*)";
461
462
463             // any delimiter okay after an opening brace ( [{<(] )
464             // as long as it's not immediately followed by the matching closing
465             // brace.
466             $start[] = "(?<= { ) ${any} (?! } )";
467             $start[] = "(?<= < ) ${any} (?! > )";
468             $start[] = "(?<= \\( ) ${any} (?! \\) )";
469             
470             $start = "(?:" . join('|', $start) . ")";
471             
472             // Any of the above must be immediately followed by non-whitespace.
473             $start_regexp = $start . "(?= \S)";
474         }
475
476         return $start_regexp;
477     }
478
479     function getEndRegexp ($match) {
480         $chr = preg_quote($match);
481         return "(?<= \S | ^ ) (?<! $chr) $chr (?! $chr) (?= \s | [-)}>\"'\\/:.,;!? _*=] | $)";
482     }
483     
484     function markup ($match, $body) {
485         switch ($match) {
486         case '*': return new HtmlElement('b', $body);
487         case '=': return new HtmlElement('tt', $body);
488         case '_':  return new HtmlElement('i', $body);
489         }
490     }
491 }
492
493 class Markup_html_emphasis extends BalancedMarkup
494 {
495     var $_start_regexp = "<(?: b|big|i|small|tt|
496                                em|strong|
497                                cite|code|dfn|kbd|samp|var|
498                                sup|sub )>";
499
500     function getEndRegexp ($match) {
501         return "<\\/" . substr($match, 1);
502     }
503     
504     function markup ($match, $body) {
505         $tag = substr($match, 1, -1);
506         return new HtmlElement($tag, $body);
507     }
508 }
509
510 class Markup_html_abbr extends BalancedMarkup
511 {
512     //rurban: abbr|acronym need an optional title tag.
513     //sf.net bug #728595
514     var $_start_regexp = "<(?: abbr|acronym )(?: \stitle=[^>]*)?>";
515
516     function getEndRegexp ($match) {
517         if (substr($match,1,4) == 'abbr')
518             $tag = 'abbr';
519         else
520             $tag = 'acronym';
521         return "<\\/" . $tag . '>';
522     }
523     
524     function markup ($match, $body) {
525         if (substr($match,1,4) == 'abbr')
526             $tag = 'abbr';
527         else
528             $tag = 'acronym';
529         $rest = substr($match,1+strlen($tag),-1);
530         if (!empty($rest)) {
531             list($key,$val) = explode("=",$rest);
532             $args = array($key => $val);
533         } else $args = array();
534         return new HtmlElement($tag, $args, $body);
535     }
536 }
537
538 // Special version for single-line plugins formatting, 
539 //  like: '<small>< ?plugin PopularNearby ? ></small>'
540 class Markup_plugin extends SimpleMarkup
541 {
542     var $_match_regexp = '<\?plugin(?:-form)?\s[^\n]+?\?>';
543
544     function markup ($match) {
545         return new Cached_PluginInvocation($match);
546     }
547 }
548
549
550 // TODO: "..." => "&#133;"  browser specific display (not cached?)
551 // TODO: "--" => "&emdash;" browser specific display (not cached?)
552
553 // FIXME: Do away with magic phpwiki forms.  (Maybe phpwiki: links too?)
554 // FIXME: Do away with plugin-links.  They seem not to be used.
555 //Plugin link
556
557
558 class InlineTransformer
559 {
560     var $_regexps = array();
561     var $_markup = array();
562     
563     function InlineTransformer ($markup_types = false) {
564         if (!$markup_types)
565             $markup_types = array('escape', 'bracketlink', 'url',
566                                   'interwiki', 'wikiword', 'linebreak',
567                                   'old_emphasis', 'nestled_emphasis',
568                                   'html_emphasis', 'html_abbr', 'plugin');
569
570         foreach ($markup_types as $mtype) {
571             $class = "Markup_$mtype";
572             $this->_addMarkup(new $class);
573         }
574     }
575
576     function _addMarkup ($markup) {
577         if (isa($markup, 'SimpleMarkup'))
578             $regexp = $markup->getMatchRegexp();
579         else
580             $regexp = $markup->getStartRegexp();
581
582         assert(!isset($this->_markup[$regexp]));
583         $this->_regexps[] = $regexp;
584         $this->_markup[] = $markup;
585     }
586         
587     function parse (&$text, $end_regexps = array('$')) {
588         $regexps = $this->_regexps;
589
590         // $end_re takes precedence: "favor reduce over shift"
591         array_unshift($regexps, $end_regexps[0]);
592         $regexps = new RegexpSet($regexps);
593         
594         $input = $text;
595         $output = new XmlContent;
596
597         $match = $regexps->match($input);
598         
599         while ($match) {
600             if ($match->regexp_ind == 0) {
601                 // No start pattern found before end pattern.
602                 // We're all done!
603                 $output->pushContent($match->prematch);
604                 $text = $match->postmatch;
605                 return $output;
606             }
607
608             $markup = $this->_markup[$match->regexp_ind - 1];
609             $body = $this->_parse_markup_body($markup, $match->match, $match->postmatch, $end_regexps);
610             if (!$body) {
611                 // Couldn't match balanced expression.
612                 // Ignore and look for next matching start regexp.
613                 $match = $regexps->nextMatch($input, $match);
614                 continue;
615             }
616
617             // Matched markup.  Eat input, push output.
618             // FIXME: combine adjacent strings.
619             $input = $match->postmatch;
620             $output->pushContent($match->prematch,
621                                  $markup->markup($match->match, $body));
622
623             $match = $regexps->match($input);
624         }
625
626         // No pattern matched, not even the end pattern.
627         // Parse fails.
628         return false;
629     }
630
631     function _parse_markup_body ($markup, $match, &$text, $end_regexps) {
632         if (isa($markup, 'SimpleMarkup'))
633             return true;        // Done. SimpleMarkup is simple.
634         array_unshift($end_regexps, $markup->getEndRegexp($match));
635
636         if (!is_object($markup)) return false;
637         // Optimization: if no end pattern in text, we know the
638         // parse will fail.  This is an important optimization,
639         // e.g. when text is "*lots *of *start *delims *with
640         // *no *matching *end *delims".
641         $ends_pat = "/(?:" . join(").*(?:", $end_regexps) . ")/xs";
642         if (!preg_match($ends_pat, $text))
643             return false;
644         return $this->parse($text, $end_regexps);
645     }
646 }
647
648 class LinkTransformer extends InlineTransformer
649 {
650     function LinkTransformer () {
651         $this->InlineTransformer(array('escape', 'bracketlink', 'url',
652                                        'interwiki', 'wikiword'));
653     }
654 }
655
656 function TransformInline($text, $markup = 2.0, $basepage=false) {
657     static $trfm;
658     
659     if (empty($trfm)) {
660         $trfm = new InlineTransformer;
661     }
662     
663     if ($markup < 2.0) {
664         $text = ConvertOldMarkup($text, 'inline');
665     }
666
667     if ($basepage) {
668         return new CacheableMarkup($trfm->parse($text), $basepage);
669     }
670     return $trfm->parse($text);
671 }
672
673 function TransformLinks($text, $markup = 2.0, $basepage = false) {
674     static $trfm;
675     
676     if (empty($trfm)) {
677         $trfm = new LinkTransformer;
678     }
679
680     if ($markup < 2.0) {
681         $text = ConvertOldMarkup($text, 'links');
682     }
683     
684     if ($basepage) {
685         return new CacheableMarkup($trfm->parse($text), $basepage);
686     }
687     return $trfm->parse($text);
688 }
689
690 // (c-file-style: "gnu")
691 // Local Variables:
692 // mode: php
693 // tab-width: 8
694 // c-basic-offset: 4
695 // c-hanging-comment-ender-p: nil
696 // indent-tabs-mode: nil
697 // End:   
698 ?>