]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/InlineParser.php
Prevent from some PHP5 warnings (ref args, no :: object init)
[SourceForge/phpwiki.git] / lib / InlineParser.php
1 <?php rcs_id('$Id: InlineParser.php,v 1.36 2004-04-19 18:27:45 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         $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 . '(?: [[:alnum:]]+ | .)';
249     }
250     
251     function markup ($match) {
252         assert(strlen($match) >= 2);
253         return substr($match, 1);
254     }
255 }
256
257 function LinkBracketLink($bracketlink) {
258     global $AllowedProtocols, $InlineImages;
259
260     //include_once("lib/interwiki.php");
261     $intermap = getInterwikiMap();
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     /*
273      * Check if the user has typed a explicit URL. This solves the
274      * problem where the URLs have a ~ character, which would be stripped away.
275      *   "[http:/server/~name/]" will work as expected
276      *   "http:/server/~name/"   will NOT work as expected, will remove the ~
277      */
278     if (strstr($rawlink, "http://") or strstr($rawlink, "https://"))
279         $link = $rawlink;
280     else
281         $link  = UnWikiEscape($rawlink);
282
283     // [label|link]
284     // if label looks like a url to an image, we want an image link.
285     if (preg_match("/\\.($InlineImages)$/i", $label)) {
286         $imgurl = $label;
287         if (preg_match("/^" . $intermap->getRegexp() . ":/", $label)) {
288             $imgurl = $intermap->link($label);
289             $imgurl = $imgurl->getAttr('href');
290         } elseif (! preg_match("#^($AllowedProtocols):#", $imgurl)) {
291             // local theme linkname like 'images/next.gif'.
292             global $Theme;
293             $imgurl = $Theme->getImageURL($imgurl);
294         }
295         $label = LinkImage($imgurl, $link);
296     }
297
298     if ($hash) {
299         // It's an anchor, not a link...
300         $id = MangleXmlIdentifier($link);
301         return HTML::a(array('name' => $id, 'id' => $id),
302                        $bar ? $label : $link);
303     }
304
305     if (preg_match("#^($AllowedProtocols):#", $link)) {
306         // if it's an image, embed it; otherwise, it's a regular link
307         if (preg_match("/\\.($InlineImages)$/i", $link))
308             return LinkImage($link, $label);
309         else
310             return new Cached_ExternalLink($link, $label);
311     }
312     elseif (preg_match("/^phpwiki:/", $link))
313         return new Cached_PhpwikiURL($link, $label);
314     /*
315      * Inline images in Interwiki urls's:
316      * [File:my_image.gif] inlines the image,
317      * File:my_image.gif shows a plain inter-wiki link,
318      * [what a pic|File:my_image.gif] shows a named inter-wiki link to the gif
319      * [File:my_image.gif|what a pic] shows a inlimed image linked to the page "what a pic"
320      */
321     elseif (preg_match("/^" . $intermap->getRegexp() . ":/", $link)) {
322         if (empty($label) && preg_match("/\\.($InlineImages)$/i", $link)) {
323             // if without label => inlined image [File:xx.gif]
324             $imgurl = $intermap->link($link);
325             return LinkImage($imgurl->getAttr('href'), $label);
326         }
327         return new Cached_InterwikiLink($link, $label);
328     } else {
329         // Split anchor off end of pagename.
330         if (preg_match('/\A(.*)(?<!'.ESCAPE_CHAR.')#(.*?)\Z/', $rawlink, $m)) {
331             list(,$rawlink,$anchor) = $m;
332             $pagename = UnWikiEscape($rawlink);
333             $anchor = UnWikiEscape($anchor);
334             if (!$label)
335                 $label = $link;
336         }
337         else {
338             $pagename = $link;
339             $anchor = false;
340         }
341         return new Cached_WikiLink($pagename, $label, $anchor);
342     }
343 }
344
345 class Markup_bracketlink  extends SimpleMarkup
346 {
347     var $_match_regexp = "\\#? \\[ .*? [^]\\s] .*? \\]";
348     
349     function markup ($match) {
350         $link = LinkBracketLink($match);
351         assert($link->isInlineElement());
352         return $link;
353     }
354 }
355
356 class Markup_url extends SimpleMarkup
357 {
358     function getMatchRegexp () {
359         global $AllowedProtocols;
360         return "(?<![[:alnum:]]) (?:$AllowedProtocols) : [^\s<>\"']+ (?<![ ,.?; \] \) ])";
361     }
362     
363     function markup ($match) {
364         return new Cached_ExternalLink(UnWikiEscape($match));
365     }
366 }
367
368
369 class Markup_interwiki extends SimpleMarkup
370 {
371     function getMatchRegexp () {
372         global $request;
373         $map = getInterwikiMap();
374         return "(?<! [[:alnum:]])" . $map->getRegexp(). ": \S+ (?<![ ,.?;! \] \) \" \' ])";
375     }
376
377     function markup ($match) {
378         //$map = getInterwikiMap();
379         return new Cached_InterwikiLink(UnWikiEscape($match));
380     }
381 }
382
383 class Markup_wikiword extends SimpleMarkup
384 {
385     function getMatchRegexp () {
386         global $WikiNameRegexp;
387         return " $WikiNameRegexp";
388     }
389
390     function markup ($match) {
391         if ($this->_isWikiUserPage($match))
392             return new Cached_UserLink($match); //$this->_UserLink($match);
393         else
394             return new Cached_WikiLink($match);
395     }
396
397     // FIXME: there's probably a more useful place to put these two functions    
398     function _isWikiUserPage ($page) {
399         global $request;
400         $dbi = $request->getDbh();
401         $page_handle = $dbi->getPage($page);
402         if ($page_handle->get('pref'))
403             return true;
404         else
405             return false;
406     }
407
408     function _UserLink($PageName) {
409         $link = HTML::a(array('href' => $PageName));
410         $link->pushContent(PossiblyGlueIconToText('wikiuser', $PageName));
411         $link->setAttr('class', 'wikiuser');
412         return $link;
413     }
414 }
415
416 class Markup_linebreak extends SimpleMarkup
417 {
418     //var $_match_regexp = "(?: (?<! %) %%% (?! %) | <(?:br|BR)> | <(?:br|BR) \/> )";
419     var $_match_regexp = "(?: (?<! %) %%% (?! %) | <(?:br|BR)> )";
420
421     function markup ($match) {
422         return HTML::br();
423     }
424 }
425
426 class Markup_old_emphasis  extends BalancedMarkup
427 {
428     var $_start_regexp = "''|__";
429
430     function getEndRegexp ($match) {
431         return $match;
432     }
433     
434     function markup ($match, $body) {
435         $tag = $match == "''" ? 'em' : 'strong';
436         return new HtmlElement($tag, $body);
437     }
438 }
439
440 class Markup_nestled_emphasis extends BalancedMarkup
441 {
442     function getStartRegexp() {
443         static $start_regexp = false;
444
445         if (!$start_regexp) {
446             // The three possible delimiters
447             // (none of which can be followed by itself.)
448             $i = "_ (?! _)";
449             $b = "\\* (?! \\*)";
450             $tt = "= (?! =)";
451
452             $any = "(?: ${i}|${b}|${tt})"; // any of the three.
453
454             // Any of [_*=] is okay if preceded by space or one of [-"'/:]
455             $start[] = "(?<= \\s|^|[-\"'\\/:]) ${any}";
456
457             // _ or * is okay after = as long as not immediately followed by =
458             $start[] = "(?<= =) (?: ${i}|${b}) (?! =)";
459             // etc...
460             $start[] = "(?<= _) (?: ${b}|${tt}) (?! _)";
461             $start[] = "(?<= \\*) (?: ${i}|${tt}) (?! \\*)";
462
463
464             // any delimiter okay after an opening brace ( [{<(] )
465             // as long as it's not immediately followed by the matching closing
466             // brace.
467             $start[] = "(?<= { ) ${any} (?! } )";
468             $start[] = "(?<= < ) ${any} (?! > )";
469             $start[] = "(?<= \\( ) ${any} (?! \\) )";
470             
471             $start = "(?:" . join('|', $start) . ")";
472             
473             // Any of the above must be immediately followed by non-whitespace.
474             $start_regexp = $start . "(?= \S)";
475         }
476
477         return $start_regexp;
478     }
479
480     function getEndRegexp ($match) {
481         $chr = preg_quote($match);
482         return "(?<= \S | ^ ) (?<! $chr) $chr (?! $chr) (?= \s | [-)}>\"'\\/:.,;!? _*=] | $)";
483     }
484     
485     function markup ($match, $body) {
486         switch ($match) {
487         case '*': return new HtmlElement('b', $body);
488         case '=': return new HtmlElement('tt', $body);
489         case '_':  return new HtmlElement('i', $body);
490         }
491     }
492 }
493
494 class Markup_html_emphasis extends BalancedMarkup
495 {
496     var $_start_regexp = "<(?: b|big|i|small|tt|
497                                em|strong|
498                                cite|code|dfn|kbd|samp|var|
499                                sup|sub )>";
500     //rurban: abbr|acronym need an optional title tag.
501     //sf.net bug #728595
502
503     function getEndRegexp ($match) {
504         return "<\\/" . substr($match, 1);
505     }
506     
507     function markup ($match, $body) {
508         $tag = substr($match, 1, -1);
509         return new HtmlElement($tag, $body);
510     }
511 }
512
513 class Markup_html_abbr extends BalancedMarkup
514 {
515     //rurban: abbr|acronym need an optional title tag.
516     //sf.net bug #728595
517     var $_start_regexp = "<(?: abbr|acronym )(?: \stitle=[^>]*)?>";
518
519     function getEndRegexp ($match) {
520         if (substr($match,1,4) == 'abbr')
521             $tag = 'abbr';
522         else
523             $tag = 'acronym';
524         return "<\\/" . $tag . '>';
525     }
526     
527     function markup ($match, $body) {
528         if (substr($match,1,4) == 'abbr')
529             $tag = 'abbr';
530         else
531             $tag = 'acronym';
532         $rest = substr($match,1+strlen($tag),-1);
533         if (!empty($rest)) {
534             list($key,$val) = explode("=",$rest);
535             $args = array($key => $val);
536         } else $args = array();
537         return new HtmlElement($tag, $args, $body);
538     }
539 }
540
541 // FIXME: Do away with magic phpwiki forms.  (Maybe phpwiki: links too?)
542 // FIXME: Do away with plugin-links.  They seem not to be used.
543 //Plugin link
544
545
546 class InlineTransformer
547 {
548     var $_regexps = array();
549     var $_markup = array();
550     
551     function InlineTransformer ($markup_types = false) {
552         if (!$markup_types)
553             $markup_types = array('escape', 'bracketlink', 'url',
554                                   'interwiki', 'wikiword', 'linebreak',
555                                   'old_emphasis', 'nestled_emphasis',
556                                   'html_emphasis', 'html_abbr');
557
558         foreach ($markup_types as $mtype) {
559             $class = "Markup_$mtype";
560             $this->_addMarkup(new $class);
561         }
562     }
563
564     function _addMarkup ($markup) {
565         if (isa($markup, 'SimpleMarkup'))
566             $regexp = $markup->getMatchRegexp();
567         else
568             $regexp = $markup->getStartRegexp();
569
570         assert(!isset($this->_markup[$regexp]));
571         $this->_regexps[] = $regexp;
572         $this->_markup[] = $markup;
573     }
574         
575     function parse (&$text, $end_regexps = array('$')) {
576         $regexps = $this->_regexps;
577
578         // $end_re takes precedence: "favor reduce over shift"
579         array_unshift($regexps, $end_regexps[0]);
580         $regexps = new RegexpSet($regexps);
581         
582         $input = $text;
583         $output = new XmlContent;
584
585         $match = $regexps->match($input);
586         
587         while ($match) {
588             if ($match->regexp_ind == 0) {
589                 // No start pattern found before end pattern.
590                 // We're all done!
591                 $output->pushContent($match->prematch);
592                 $text = $match->postmatch;
593                 return $output;
594             }
595
596             $markup = $this->_markup[$match->regexp_ind - 1];
597             //if (!$markup) return false;
598             $body = $this->_parse_markup_body($markup, $match->match, $match->postmatch, $end_regexps);
599             if (!$body) {
600                 // Couldn't match balanced expression.
601                 // Ignore and look for next matching start regexp.
602                 $match = $regexps->nextMatch($input, $match);
603                 continue;
604             }
605
606             // Matched markup.  Eat input, push output.
607             // FIXME: combine adjacent strings.
608             $input = $match->postmatch;
609             $output->pushContent($match->prematch,
610                                  $markup->markup($match->match, $body));
611
612             $match = $regexps->match($input);
613         }
614
615         // No pattern matched, not even the end pattern.
616         // Parse fails.
617         return false;
618     }
619
620     function _parse_markup_body ($markup, $match, &$text, $end_regexps) {
621         if (isa($markup, 'SimpleMarkup'))
622             return true;        // Done. SimpleMarkup is simple.
623
624         array_unshift($end_regexps, $markup->getEndRegexp($match));
625         // Optimization: if no end pattern in text, we know the
626         // parse will fail.  This is an important optimization,
627         // e.g. when text is "*lots *of *start *delims *with
628         // *no *matching *end *delims".
629         $ends_pat = "/(?:" . join(").*(?:", $end_regexps) . ")/xs";
630         if (!preg_match($ends_pat, $text))
631             return false;
632         return $this->parse($text, $end_regexps);
633     }
634 }
635
636 class LinkTransformer extends InlineTransformer
637 {
638     function LinkTransformer () {
639         $this->InlineTransformer(array('escape', 'bracketlink', 'url',
640                                        'interwiki', 'wikiword'));
641     }
642 }
643
644 function TransformInline($text, $markup = 2.0, $basepage=false) {
645     static $trfm;
646     
647     if (empty($trfm)) {
648         $trfm = new InlineTransformer;
649     }
650     
651     if ($markup < 2.0) {
652         $text = ConvertOldMarkup($text, 'inline');
653     }
654
655     if ($basepage) {
656         return new CacheableMarkup($trfm->parse($text), $basepage);
657     }
658     return $trfm->parse($text);
659 }
660
661 function TransformLinks($text, $markup = 2.0, $basepage = false) {
662     static $trfm;
663     
664     if (empty($trfm)) {
665         $trfm = new LinkTransformer;
666     }
667
668     if ($markup < 2.0) {
669         $text = ConvertOldMarkup($text, 'links');
670     }
671     
672     if ($basepage) {
673         return new CacheableMarkup($trfm->parse($text), $basepage);
674     }
675     return $trfm->parse($text);
676 }
677
678 // (c-file-style: "gnu")
679 // Local Variables:
680 // mode: php
681 // tab-width: 8
682 // c-basic-offset: 4
683 // c-hanging-comment-ender-p: nil
684 // indent-tabs-mode: nil
685 // End:   
686 ?>