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>
4 * This file is part of PhpWiki.
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.
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.
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
21 * This is the code which deals with the inline part of the (new-style)
25 * @author Geoffrey T. Dairiki
31 * This is the character used in wiki markup to escape characters with
34 define('ESCAPE_CHAR', '~');
36 require_once('lib/HtmlElement.php');
37 require_once('lib/CachedMarkup.php');
38 //require_once('lib/interwiki.php');
39 require_once('lib/stdlib.php');
42 function WikiEscape($text) {
43 return str_replace('#', ESCAPE_CHAR . '#', $text);
46 function UnWikiEscape($text) {
47 return preg_replace('/' . ESCAPE_CHAR . '(.)/', '\1', $text);
51 * Return type from RegexpSet::match and RegexpSet::nextMatch.
55 class RegexpSet_match {
57 * The text leading up the the next match.
67 * The text following the matched text.
72 * Index of the regular expression which matched.
78 * A set of regular expressions.
80 * This class is probably only useful for InlineTransformer.
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.)
91 function RegexpSet ($regexps) {
93 $this->_regexps = array_unique($regexps);
97 * Search text for the next matching regexp from the Regexp Set.
99 * @param string $text The text to search.
101 * @return RegexpSet_match A RegexpSet_match object, or false if no match.
103 function match ($text) {
104 return $this->_match($text, $this->_regexps, '*?');
108 * Search for next matching regexp.
110 * Here, 'next' has two meanings:
112 * Match the next regexp(s) in the set, at the same position as the last match.
114 * If that fails, match the whole RegexpSet, starting after the position of the
117 * @param string $text Text to search.
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.
123 * @return RegexpSet_match A RegexpSet_match object, or false if no match.
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);
130 $repeat = sprintf('{%d}', $pos);
131 if ( ($match = $this->_match($text, $regexps, $repeat)) ) {
132 $match->regexp_ind += $prevMatch->regexp_ind + 1;
138 // Failed. Look for match after current position.
139 $repeat = sprintf('{%d,}?', $pos + 1);
140 return $this->_match($text, $this->_regexps, $repeat);
144 function _match ($text, $regexps, $repeat) {
145 $pat= "/ ( . $repeat ) ( (" . join(')|(', $regexps) . ") ) /Axs";
147 if (! preg_match($pat, $text, $m)) {
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;
158 PrintXML(HTML::dl(HTML::dt("input"),
159 HTML::dd(HTML::pre($text)),
161 HTML::dd(HTML::pre($match->match)),
163 HTML::dd(HTML::pre($regexps[$match->regexp_ind])),
164 HTML::dt("prematch"),
165 HTML::dd(HTML::pre($match->prematch))));
174 * A simple markup rule (i.e. terminal token).
176 * These are defined by a regexp.
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.
187 * @return string Regexp which matches this token.
189 function getMatchRegexp () {
190 return $this->_match_regexp;
193 /** Markup matching text.
195 * @param string $match The text which matched the regexp
196 * (obtained from getMatchRegexp).
198 * @return mixed The expansion of the matched text.
200 function markup ($match /*, $body */) {
201 trigger_error("pure virtual", E_USER_ERROR);
206 * A balanced markup rule.
208 * These are defined by a start regexp, and an end regexp.
214 /** Get the starting regexp for this rule.
216 * @return string The starting regexp.
218 function getStartRegexp () {
219 return $this->_start_regexp;
222 /** Get the ending regexp for this rule.
224 * @param string $match The text which matched the starting regexp.
226 * @return string The ending regexp.
228 function getEndRegexp ($match) {
229 return $this->_end_regexp;
232 /** Get expansion for matching input.
234 * @param string $match The text which matched the starting regexp.
236 * @param mixed $body Transformed text found between the starting
237 * and ending regexps.
239 * @return mixed The expansion of the matched text.
241 function markup ($match, $body) {
242 trigger_error("pure virtual", E_USER_ERROR);
246 class Markup_escape extends SimpleMarkup
248 function getMatchRegexp () {
249 return ESCAPE_CHAR . '(?: [[:alnum:]]+ | .)';
252 function markup ($match) {
253 assert(strlen($match) >= 2);
254 return substr($match, 1);
258 function LinkBracketLink($bracketlink) {
259 //include_once("lib/interwiki.php");
260 $intermap = getInterwikiMap();
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.
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;
270 $label = UnWikiEscape($label);
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 ~
277 if (strstr($rawlink, "http://") or strstr($rawlink, "https://"))
280 $link = UnWikiEscape($rawlink);
283 // if label looks like a url to an image, we want an image link.
284 if (preg_match("/\\.(" . INLINE_IMAGES . ")$/i", $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'.
292 $imgurl = $Theme->getImageURL($imgurl);
294 $label = LinkImage($imgurl, $link);
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);
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);
309 return new Cached_ExternalLink($link, $label);
311 elseif (preg_match("/^phpwiki:/", $link))
312 return new Cached_PhpwikiURL($link, $label);
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"
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);
326 return new Cached_InterwikiLink($link, $label);
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);
340 return new Cached_WikiLink($pagename, $label, $anchor);
344 class Markup_bracketlink extends SimpleMarkup
346 var $_match_regexp = "\\#? \\[ .*? [^]\\s] .*? \\]";
348 function markup ($match) {
349 $link = LinkBracketLink($match);
350 assert($link->isInlineElement());
355 class Markup_url extends SimpleMarkup
357 function getMatchRegexp () {
358 return "(?<![[:alnum:]]) (?:" . ALLOWED_PROTOCOLS . ") : [^\s<>\"']+ (?<![ ,.?; \] \) ])";
361 function markup ($match) {
362 return new Cached_ExternalLink(UnWikiEscape($match));
367 class Markup_interwiki extends SimpleMarkup
369 function getMatchRegexp () {
371 $map = getInterwikiMap();
372 return "(?<! [[:alnum:]])" . $map->getRegexp(). ": \S+ (?<![ ,.?;! \] \) \" \' ])";
375 function markup ($match) {
376 //$map = getInterwikiMap();
377 return new Cached_InterwikiLink(UnWikiEscape($match));
381 class Markup_wikiword extends SimpleMarkup
383 function getMatchRegexp () {
384 global $WikiNameRegexp;
385 return " $WikiNameRegexp";
388 function markup ($match) {
389 if (!$match) return false;
390 if ($this->_isWikiUserPage($match))
391 return new Cached_UserLink($match); //$this->_UserLink($match);
393 return new Cached_WikiLink($match);
396 // FIXME: there's probably a more useful place to put these two functions
397 function _isWikiUserPage ($page) {
399 $dbi = $request->getDbh();
400 $page_handle = $dbi->getPage($page);
401 if ($page_handle and $page_handle->get('pref'))
407 function _UserLink($PageName) {
408 $link = HTML::a(array('href' => $PageName));
409 $link->pushContent(PossiblyGlueIconToText('wikiuser', $PageName));
410 $link->setAttr('class', 'wikiuser');
415 class Markup_linebreak extends SimpleMarkup
417 //var $_match_regexp = "(?: (?<! %) %%% (?! %) | <(?:br|BR)> | <(?:br|BR) \/> )";
418 var $_match_regexp = "(?: (?<! %) %%% (?! %) | <(?:br|BR)> )";
420 function markup ($match) {
425 class Markup_old_emphasis extends BalancedMarkup
427 var $_start_regexp = "''|__";
429 function getEndRegexp ($match) {
433 function markup ($match, $body) {
434 $tag = $match == "''" ? 'em' : 'strong';
435 return new HtmlElement($tag, $body);
439 class Markup_nestled_emphasis extends BalancedMarkup
441 function getStartRegexp() {
442 static $start_regexp = false;
444 if (!$start_regexp) {
445 // The three possible delimiters
446 // (none of which can be followed by itself.)
451 $any = "(?: ${i}|${b}|${tt})"; // any of the three.
453 // Any of [_*=] is okay if preceded by space or one of [-"'/:]
454 $start[] = "(?<= \\s|^|[-\"'\\/:]) ${any}";
456 // _ or * is okay after = as long as not immediately followed by =
457 $start[] = "(?<= =) (?: ${i}|${b}) (?! =)";
459 $start[] = "(?<= _) (?: ${b}|${tt}) (?! _)";
460 $start[] = "(?<= \\*) (?: ${i}|${tt}) (?! \\*)";
463 // any delimiter okay after an opening brace ( [{<(] )
464 // as long as it's not immediately followed by the matching closing
466 $start[] = "(?<= { ) ${any} (?! } )";
467 $start[] = "(?<= < ) ${any} (?! > )";
468 $start[] = "(?<= \\( ) ${any} (?! \\) )";
470 $start = "(?:" . join('|', $start) . ")";
472 // Any of the above must be immediately followed by non-whitespace.
473 $start_regexp = $start . "(?= \S)";
476 return $start_regexp;
479 function getEndRegexp ($match) {
480 $chr = preg_quote($match);
481 return "(?<= \S | ^ ) (?<! $chr) $chr (?! $chr) (?= \s | [-)}>\"'\\/:.,;!? _*=] | $)";
484 function markup ($match, $body) {
486 case '*': return new HtmlElement('b', $body);
487 case '=': return new HtmlElement('tt', $body);
488 case '_': return new HtmlElement('i', $body);
493 class Markup_html_emphasis extends BalancedMarkup
495 var $_start_regexp = "<(?: b|big|i|small|tt|
497 cite|code|dfn|kbd|samp|var|
500 function getEndRegexp ($match) {
501 return "<\\/" . substr($match, 1);
504 function markup ($match, $body) {
505 $tag = substr($match, 1, -1);
506 return new HtmlElement($tag, $body);
510 class Markup_html_abbr extends BalancedMarkup
512 //rurban: abbr|acronym need an optional title tag.
514 var $_start_regexp = "<(?: abbr|acronym )(?: \stitle=[^>]*)?>";
516 function getEndRegexp ($match) {
517 if (substr($match,1,4) == 'abbr')
521 return "<\\/" . $tag . '>';
524 function markup ($match, $body) {
525 if (substr($match,1,4) == 'abbr')
529 $rest = substr($match,1+strlen($tag),-1);
531 list($key,$val) = explode("=",$rest);
532 $args = array($key => $val);
533 } else $args = array();
534 return new HtmlElement($tag, $args, $body);
538 // Special version for single-line plugins formatting,
539 // like: '<small>< ?plugin PopularNearby ? ></small>'
540 class Markup_plugin extends SimpleMarkup
542 var $_match_regexp = '<\?plugin(?:-form)?\s[^\n]+?\?>';
544 function markup ($match) {
545 return new Cached_PluginInvocation($match);
550 // TODO: "..." => "…" browser specific display (not cached?)
551 // TODO: "--" => "&emdash;" browser specific display (not cached?)
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.
558 class InlineTransformer
560 var $_regexps = array();
561 var $_markup = array();
563 function InlineTransformer ($markup_types = false) {
565 $markup_types = array('escape', 'bracketlink', 'url',
566 'interwiki', 'wikiword', 'linebreak',
567 'old_emphasis', 'nestled_emphasis',
568 'html_emphasis', 'html_abbr', 'plugin');
570 foreach ($markup_types as $mtype) {
571 $class = "Markup_$mtype";
572 $this->_addMarkup(new $class);
576 function _addMarkup ($markup) {
577 if (isa($markup, 'SimpleMarkup'))
578 $regexp = $markup->getMatchRegexp();
580 $regexp = $markup->getStartRegexp();
582 assert(!isset($this->_markup[$regexp]));
583 $this->_regexps[] = $regexp;
584 $this->_markup[] = $markup;
587 function parse (&$text, $end_regexps = array('$')) {
588 $regexps = $this->_regexps;
590 // $end_re takes precedence: "favor reduce over shift"
591 array_unshift($regexps, $end_regexps[0]);
592 $regexps = new RegexpSet($regexps);
595 $output = new XmlContent;
597 $match = $regexps->match($input);
600 if ($match->regexp_ind == 0) {
601 // No start pattern found before end pattern.
603 $output->pushContent($match->prematch);
604 $text = $match->postmatch;
608 $markup = $this->_markup[$match->regexp_ind - 1];
609 $body = $this->_parse_markup_body($markup, $match->match, $match->postmatch, $end_regexps);
611 // Couldn't match balanced expression.
612 // Ignore and look for next matching start regexp.
613 $match = $regexps->nextMatch($input, $match);
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));
623 $match = $regexps->match($input);
626 // No pattern matched, not even the end pattern.
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));
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))
644 return $this->parse($text, $end_regexps);
648 class LinkTransformer extends InlineTransformer
650 function LinkTransformer () {
651 $this->InlineTransformer(array('escape', 'bracketlink', 'url',
652 'interwiki', 'wikiword'));
656 function TransformInline($text, $markup = 2.0, $basepage=false) {
660 $trfm = new InlineTransformer;
664 $text = ConvertOldMarkup($text, 'inline');
668 return new CacheableMarkup($trfm->parse($text), $basepage);
670 return $trfm->parse($text);
673 function TransformLinks($text, $markup = 2.0, $basepage = false) {
677 $trfm = new LinkTransformer;
681 $text = ConvertOldMarkup($text, 'links');
685 return new CacheableMarkup($trfm->parse($text), $basepage);
687 return $trfm->parse($text);
690 // (c-file-style: "gnu")
695 // c-hanging-comment-ender-p: nil
696 // indent-tabs-mode: nil