]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/InlineParser.php
Bug fix: for magic PhpWiki URLs, "lock page to enable link" message was
[SourceForge/phpwiki.git] / lib / InlineParser.php
1 <?php rcs_id('$Id: InlineParser.php,v 1.27 2003-02-26 00:39:30 dairiki 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         $this->_regexps = $regexps;
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
143     function _match ($text, $regexps, $repeat) {
144         $pat= "/ ( . $repeat ) ( (" . join(')|(', $regexps) . ") ) /Axs";
145
146         if (! preg_match($pat, $text, $m)) {
147             return false;
148         }
149         
150         $match = new RegexpSet_match;
151         $match->postmatch = substr($text, strlen($m[0]));
152         $match->prematch = $m[1];
153         $match->match = $m[2];
154         $match->regexp_ind = count($m) - 4;
155
156         /* DEBUGGING
157         PrintXML(HTML::dl(HTML::dt("input"),
158                           HTML::dd(HTML::pre($text)),
159                           HTML::dt("match"),
160                           HTML::dd(HTML::pre($match->match)),
161                           HTML::dt("regexp"),
162                           HTML::dd(HTML::pre($regexps[$match->regexp_ind])),
163                           HTML::dt("prematch"),
164                           HTML::dd(HTML::pre($match->prematch))));
165         */
166         return $match;
167     }
168 }
169
170
171
172 /**
173  * A simple markup rule (i.e. terminal token).
174  *
175  * These are defined by a regexp.
176  *
177  * When a match is found for the regexp, the matching text is replaced.
178  * The replacement content is obtained by calling the SimpleMarkup::markup method.
179  */ 
180 class SimpleMarkup
181 {
182     var $_match_regexp;
183
184     /** Get regexp.
185      *
186      * @return string Regexp which matches this token.
187      */
188     function getMatchRegexp () {
189         return $this->_match_regexp;
190     }
191
192     /** Markup matching text.
193      *
194      * @param string $match The text which matched the regexp
195      * (obtained from getMatchRegexp).
196      *
197      * @return mixed The expansion of the matched text.
198      */
199     function markup ($match /*, $body */) {
200         trigger_error("pure virtual", E_USER_ERROR);
201     }
202 }
203
204 /**
205  * A balanced markup rule.
206  *
207  * These are defined by a start regexp, and and end regexp.
208  */ 
209 class BalancedMarkup
210 {
211     var $_start_regexp;
212
213     /** Get the starting regexp for this rule.
214      *
215      * @return string The starting regexp.
216      */
217     function getStartRegexp () {
218         return $this->_start_regexp;
219     }
220     
221     /** Get the ending regexp for this rule.
222      *
223      * @param string $match The text which matched the starting regexp.
224      *
225      * @return string The ending regexp.
226      */
227     function getEndRegexp ($match) {
228         return $this->_end_regexp;
229     }
230
231     /** Get expansion for matching input.
232      *
233      * @param string $match The text which matched the starting regexp.
234      *
235      * @param mixed $body Transformed text found between the starting
236      * and ending regexps.
237      *
238      * @return mixed The expansion of the matched text.
239      */
240     function markup ($match, $body) {
241         trigger_error("pure virtual", E_USER_ERROR);
242     }
243 }
244
245 class Markup_escape  extends SimpleMarkup
246 {
247     function getMatchRegexp () {
248         return ESCAPE_CHAR . ".";
249     }
250     
251     function markup ($match) {
252         assert(strlen($match) == 2);
253         return $match[1];
254     }
255 }
256
257 function LinkBracketLink($bracketlink) {
258     global $request, $AllowedProtocols, $InlineImages;
259
260     include_once("lib/interwiki.php");
261     $intermap = InterWikiMap::GetMap($request);
262     
263     // $bracketlink will start and end with brackets; in between will
264     // be either a page name, a URL or both separated by a pipe.
265     
266     // strip brackets and leading space
267     preg_match('/(\#?) \[\s* (?: (.*?) \s* (?<!' . ESCAPE_CHAR . ')(\|) )? \s* (.+?) \s*\]/x',
268                $bracketlink, $matches);
269     list (, $hash, $label, $bar, $rawlink) = $matches;
270
271     $label = UnWikiEscape($label);
272     $link = UnWikiEscape($rawlink);
273
274     // if label looks like a url to an image, we want an image link.
275     if (preg_match("/\\.($InlineImages)$/i", $label)) {
276         $imgurl = $label;
277         if (! preg_match("#^($AllowedProtocols):#", $imgurl)) {
278             // linkname like 'images/next.gif'.
279             global $Theme;
280             $imgurl = $Theme->getImageURL($linkname);
281         }
282         $label = LinkImage($imgurl, $link);
283     }
284
285     if ($hash) {
286         // It's an anchor, not a link...
287         $id = MangleXmlIdentifier($link);
288         return HTML::a(array('name' => $id, 'id' => $id),
289                        $bar ? $label : $link);
290     }
291
292     if (preg_match("#^($AllowedProtocols):#", $link)) {
293         // if it's an image, embed it; otherwise, it's a regular link
294         if (preg_match("/\\.($InlineImages)$/i", $link))
295             // no image link, just the src. see [img|link] above
296             return LinkImage($link, $label);
297         else
298             return new Cached_ExternalLink($link, $label);
299     }
300     elseif (preg_match("/^phpwiki:/", $link))
301         return new Cached_PhpwikiURL($link, $label);
302     elseif (preg_match("/^" . $intermap->getRegexp() . ":/", $link))
303         return new Cached_InterwikiLink($link, $label);
304     else {
305         // Split anchor off end of pagename.
306         if (preg_match('/\A(.*)(?<!'.ESCAPE_CHAR.')#(.*?)\Z/', $rawlink, $m)) {
307             list(,$rawlink,$anchor) = $m;
308             $pagename = UnWikiEscape($rawlink);
309             $anchor = UnWikiEscape($anchor);
310             if (!$label)
311                 $label = $link;
312         }
313         else {
314             $pagename = $link;
315             $anchor = false;
316         }
317         return new Cached_WikiLink($pagename, $label, $anchor);
318     }
319 }
320
321 class Markup_bracketlink  extends SimpleMarkup
322 {
323     var $_match_regexp = "\\#? \\[ .*? [^]\\s] .*? \\]";
324     
325     function markup ($match) {
326         $link = LinkBracketLink($match);
327         assert($link->isInlineElement());
328         return $link;
329     }
330 }
331
332 class Markup_url extends SimpleMarkup
333 {
334     function getMatchRegexp () {
335         global $AllowedProtocols;
336         return "(?<![[:alnum:]]) (?:$AllowedProtocols) : [^\s<>\"']+ (?<![ ,.?; \] \) ])";
337     }
338     
339     function markup ($match) {
340         return new Cached_ExternalLink(UnWikiEscape($match));
341     }
342 }
343
344
345 class Markup_interwiki extends SimpleMarkup
346 {
347     function getMatchRegexp () {
348         global $request;
349         $map = InterWikiMap::GetMap($request);
350         return "(?<! [[:alnum:]])" . $map->getRegexp(). ": \S+ (?<![ ,.?;! \] \) \" \' ])";
351     }
352
353     function markup ($match) {
354         global $request;
355         $map = InterWikiMap::GetMap($request);
356         return new Cached_InterwikiLink(UnWikiEscape($match));
357     }
358 }
359
360 class Markup_wikiword extends SimpleMarkup
361 {
362     function getMatchRegexp () {
363         global $WikiNameRegexp;
364         return " $WikiNameRegexp";
365     }
366         
367     function markup ($match) {
368         return new Cached_WikiLink($match);
369     }
370 }
371
372 class Markup_linebreak extends SimpleMarkup
373 {
374     var $_match_regexp = "(?: (?<! %) %%% (?! %) | <(?:br|BR)> )";
375
376     function markup () {
377         return HTML::br();
378     }
379 }
380
381 class Markup_old_emphasis  extends BalancedMarkup
382 {
383     var $_start_regexp = "''|__";
384
385     function getEndRegexp ($match) {
386         return $match;
387     }
388     
389     function markup ($match, $body) {
390         $tag = $match == "''" ? 'em' : 'strong';
391         return new HtmlElement($tag, $body);
392     }
393 }
394
395 class Markup_nestled_emphasis extends BalancedMarkup
396 {
397     function getStartRegexp() {
398         static $start_regexp = false;
399
400         if (!$start_regexp) {
401             // The three possible delimiters
402             // (none of which can be followed by itself.)
403             $i = "_ (?! _)";
404             $b = "\\* (?! \\*)";
405             $tt = "= (?! =)";
406
407             $any = "(?: ${i}|${b}|${tt})"; // any of the three.
408
409             // Any of [_*=] is okay if preceded by space or one of [-"'/:]
410             $start[] = "(?<= \\s|^|[-\"'\\/:]) ${any}";
411
412             // _ or * is okay after = as long as not immediately followed by =
413             $start[] = "(?<= =) (?: ${i}|${b}) (?! =)";
414             // etc...
415             $start[] = "(?<= _) (?: ${b}|${tt}) (?! _)";
416             $start[] = "(?<= \\*) (?: ${i}|${tt}) (?! \\*)";
417
418
419             // any delimiter okay after an opening brace ( [{<(] )
420             // as long as it's not immediately followed by the matching closing
421             // brace.
422             $start[] = "(?<= { ) ${any} (?! } )";
423             $start[] = "(?<= < ) ${any} (?! > )";
424             $start[] = "(?<= \\( ) ${any} (?! \\) )";
425             
426             $start = "(?:" . join('|', $start) . ")";
427             
428             // Any of the above must be immediately followed by non-whitespace.
429             $start_regexp = $start . "(?= \S)";
430         }
431
432         return $start_regexp;
433     }
434
435     function getEndRegexp ($match) {
436         $chr = preg_quote($match);
437         return "(?<= \S | ^ ) (?<! $chr) $chr (?! $chr) (?= \s | [-)}>\"'\\/:.,;!? _*=] | $)";
438     }
439     
440     function markup ($match, $body) {
441         switch ($match) {
442         case '*': return new HtmlElement('b', $body);
443         case '=': return new HtmlElement('tt', $body);
444         case '_':  return new HtmlElement('i', $body);
445         }
446     }
447 }
448
449 class Markup_html_emphasis extends BalancedMarkup
450 {
451     var $_start_regexp = "<(?: b|big|i|small|tt|
452                                em|strong|
453                                abbr|acronym|cite|code|dfn|kbd|samp|var|
454                                sup|sub )>";
455
456     function getEndRegexp ($match) {
457         return "<\\/" . substr($match, 1);
458     }
459     
460     function markup ($match, $body) {
461         $tag = substr($match, 1, -1);
462         return new HtmlElement($tag, $body);
463     }
464 }
465
466 // FIXME: Do away with magic phpwiki forms.  (Maybe phpwiki: links too?)
467 // FIXME: Do away with plugin-links.  They seem not to be used.
468 //Plugin link
469
470
471 class InlineTransformer
472 {
473     var $_regexps = array();
474     var $_markup = array();
475     
476     function InlineTransformer ($markup_types = false) {
477         if (!$markup_types)
478             $markup_types = array('escape', 'bracketlink', 'url',
479                                   'interwiki', 'wikiword', 'linebreak',
480                                   'old_emphasis', 'nestled_emphasis',
481                                   'html_emphasis');
482
483         foreach ($markup_types as $mtype) {
484             $class = "Markup_$mtype";
485             $this->_addMarkup(new $class);
486         }
487     }
488
489     function _addMarkup ($markup) {
490         if (isa($markup, 'SimpleMarkup'))
491             $regexp = $markup->getMatchRegexp();
492         else
493             $regexp = $markup->getStartRegexp();
494
495         assert(!isset($this->_markup[$regexp]));
496         $this->_regexps[] = $regexp;
497         $this->_markup[] = $markup;
498     }
499         
500     function parse (&$text, $end_regexps = array('$')) {
501         $regexps = $this->_regexps;
502
503         // $end_re takes precedence: "favor reduce over shift"
504         array_unshift($regexps, $end_regexps[0]);
505         $regexps = new RegexpSet($regexps);
506         
507         $input = $text;
508         $output = new XmlContent;
509
510         $match = $regexps->match($input);
511         
512         while ($match) {
513             if ($match->regexp_ind == 0) {
514                 // No start pattern found before end pattern.
515                 // We're all done!
516                 $output->pushContent($match->prematch);
517                 $text = $match->postmatch;
518                 return $output;
519             }
520
521             $markup = $this->_markup[$match->regexp_ind - 1];
522             $body = $this->_parse_markup_body($markup, $match->match, $match->postmatch, $end_regexps);
523             if (!$body) {
524                 // Couldn't match balanced expression.
525                 // Ignore and look for next matching start regexp.
526                 $match = $regexps->nextMatch($input, $match);
527                 continue;
528             }
529
530             // Matched markup.  Eat input, push output.
531             // FIXME: combine adjacent strings.
532             $input = $match->postmatch;
533             $output->pushContent($match->prematch,
534                                  $markup->markup($match->match, $body));
535
536             $match = $regexps->match($input);
537         }
538
539         // No pattern matched, not even the end pattern.
540         // Parse fails.
541         return false;
542     }
543
544     function _parse_markup_body ($markup, $match, &$text, $end_regexps) {
545         if (isa($markup, 'SimpleMarkup'))
546             return true;        // Done. SimpleMarkup is simple.
547
548         array_unshift($end_regexps, $markup->getEndRegexp($match));
549         // Optimization: if no end pattern in text, we know the
550         // parse will fail.  This is an important optimization,
551         // e.g. when text is "*lots *of *start *delims *with
552         // *no *matching *end *delims".
553         $ends_pat = "/(?:" . join(").*(?:", $end_regexps) . ")/xs";
554         if (!preg_match($ends_pat, $text))
555             return false;
556         return $this->parse($text, $end_regexps);
557     }
558 }
559
560 class LinkTransformer extends InlineTransformer
561 {
562     function LinkTransformer () {
563         $this->InlineTransformer(array('escape', 'bracketlink', 'url',
564                                        'interwiki', 'wikiword'));
565     }
566 }
567
568 function TransformInline($text, $markup = 2.0, $basepage=false) {
569     static $trfm;
570     
571     if (empty($trfm)) {
572         $trfm = new InlineTransformer;
573     }
574     
575     if ($markup < 2.0) {
576         $text = ConvertOldMarkup($text, 'inline');
577     }
578
579     if ($basepage) {
580         return new CacheableMarkup($trfm->parse($text), $basepage);
581     }
582     return $trfm->parse($text);
583 }
584
585 function TransformLinks($text, $markup = 2.0, $basepage = false) {
586     static $trfm;
587     
588     if (empty($trfm)) {
589         $trfm = new LinkTransformer;
590     }
591
592     if ($markup < 2.0) {
593         $text = ConvertOldMarkup($text, 'links');
594     }
595     
596     if ($basepage) {
597         return new CacheableMarkup($trfm->parse($text), $basepage);
598     }
599     return $trfm->parse($text);
600 }
601
602 // (c-file-style: "gnu")
603 // Local Variables:
604 // mode: php
605 // tab-width: 8
606 // c-basic-offset: 4
607 // c-hanging-comment-ender-p: nil
608 // indent-tabs-mode: nil
609 // End:   
610 ?>