1 <?php rcs_id('$Id: InlineParser.php,v 1.40 2004-05-02 15:10:05 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) {
92 $this->_regexps = array_unique($regexps);
96 * Search text for the next matching regexp from the Regexp Set.
98 * @param string $text The text to search.
100 * @return RegexpSet_match A RegexpSet_match object, or false if no match.
102 function match ($text) {
103 return $this->_match($text, $this->_regexps, '*?');
107 * Search for next matching regexp.
109 * Here, 'next' has two meanings:
111 * Match the next regexp(s) in the set, at the same position as the last match.
113 * If that fails, match the whole RegexpSet, starting after the position of the
116 * @param string $text Text to search.
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.
122 * @return RegexpSet_match A RegexpSet_match object, or false if no match.
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);
129 $repeat = sprintf('{%d}', $pos);
130 if ( ($match = $this->_match($text, $regexps, $repeat)) ) {
131 $match->regexp_ind += $prevMatch->regexp_ind + 1;
137 // Failed. Look for match after current position.
138 $repeat = sprintf('{%d,}?', $pos + 1);
139 return $this->_match($text, $this->_regexps, $repeat);
143 function _match ($text, $regexps, $repeat) {
144 $pat= "/ ( . $repeat ) ( (" . join(')|(', $regexps) . ") ) /Axs";
146 if (! preg_match($pat, $text, $m)) {
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;
157 PrintXML(HTML::dl(HTML::dt("input"),
158 HTML::dd(HTML::pre($text)),
160 HTML::dd(HTML::pre($match->match)),
162 HTML::dd(HTML::pre($regexps[$match->regexp_ind])),
163 HTML::dt("prematch"),
164 HTML::dd(HTML::pre($match->prematch))));
173 * A simple markup rule (i.e. terminal token).
175 * These are defined by a regexp.
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.
186 * @return string Regexp which matches this token.
188 function getMatchRegexp () {
189 return $this->_match_regexp;
192 /** Markup matching text.
194 * @param string $match The text which matched the regexp
195 * (obtained from getMatchRegexp).
197 * @return mixed The expansion of the matched text.
199 function markup ($match /*, $body */) {
200 trigger_error("pure virtual", E_USER_ERROR);
205 * A balanced markup rule.
207 * These are defined by a start regexp, and an end regexp.
213 /** Get the starting regexp for this rule.
215 * @return string The starting regexp.
217 function getStartRegexp () {
218 return $this->_start_regexp;
221 /** Get the ending regexp for this rule.
223 * @param string $match The text which matched the starting regexp.
225 * @return string The ending regexp.
227 function getEndRegexp ($match) {
228 return $this->_end_regexp;
231 /** Get expansion for matching input.
233 * @param string $match The text which matched the starting regexp.
235 * @param mixed $body Transformed text found between the starting
236 * and ending regexps.
238 * @return mixed The expansion of the matched text.
240 function markup ($match, $body) {
241 trigger_error("pure virtual", E_USER_ERROR);
245 class Markup_escape extends SimpleMarkup
247 function getMatchRegexp () {
248 return ESCAPE_CHAR . '(?: [[:alnum:]]+ | .)';
251 function markup ($match) {
252 assert(strlen($match) >= 2);
253 return substr($match, 1);
257 function LinkBracketLink($bracketlink) {
258 //include_once("lib/interwiki.php");
259 $intermap = getInterwikiMap();
261 // $bracketlink will start and end with brackets; in between will
262 // be either a page name, a URL or both separated by a pipe.
264 // strip brackets and leading space
265 preg_match('/(\#?) \[\s* (?: (.*?) \s* (?<!' . ESCAPE_CHAR . ')(\|) )? \s* (.+?) \s*\]/x',
266 $bracketlink, $matches);
267 list (, $hash, $label, $bar, $rawlink) = $matches;
269 $label = UnWikiEscape($label);
271 * Check if the user has typed a explicit URL. This solves the
272 * problem where the URLs have a ~ character, which would be stripped away.
273 * "[http:/server/~name/]" will work as expected
274 * "http:/server/~name/" will NOT work as expected, will remove the ~
276 if (strstr($rawlink, "http://") or strstr($rawlink, "https://"))
279 $link = UnWikiEscape($rawlink);
282 // if label looks like a url to an image, we want an image link.
283 if (preg_match("/\\.(" . INLINE_IMAGES . ")$/i", $label)) {
285 if (preg_match("/^" . $intermap->getRegexp() . ":/", $label)) {
286 $imgurl = $intermap->link($label);
287 $imgurl = $imgurl->getAttr('href');
288 } elseif (! preg_match("#^(" . ALLOWED_PROTOCOLS . "):#", $imgurl)) {
289 // local theme linkname like 'images/next.gif'.
291 $imgurl = $Theme->getImageURL($imgurl);
293 $label = LinkImage($imgurl, $link);
297 // It's an anchor, not a link...
298 $id = MangleXmlIdentifier($link);
299 return HTML::a(array('name' => $id, 'id' => $id),
300 $bar ? $label : $link);
303 if (preg_match("#^(" . ALLOWED_PROTOCOLS . "):#", $link)) {
304 // if it's an image, embed it; otherwise, it's a regular link
305 if (preg_match("/\\.(" . INLINE_IMAGES . ")$/i", $link))
306 return LinkImage($link, $label);
308 return new Cached_ExternalLink($link, $label);
310 elseif (preg_match("/^phpwiki:/", $link))
311 return new Cached_PhpwikiURL($link, $label);
313 * Inline images in Interwiki urls's:
314 * [File:my_image.gif] inlines the image,
315 * File:my_image.gif shows a plain inter-wiki link,
316 * [what a pic|File:my_image.gif] shows a named inter-wiki link to the gif
317 * [File:my_image.gif|what a pic] shows a inlimed image linked to the page "what a pic"
319 elseif (preg_match("/^" . $intermap->getRegexp() . ":/", $link)) {
320 if (empty($label) && preg_match("/\\.(" . INLINE_IMAGES . ")$/i", $link)) {
321 // if without label => inlined image [File:xx.gif]
322 $imgurl = $intermap->link($link);
323 return LinkImage($imgurl->getAttr('href'), $label);
325 return new Cached_InterwikiLink($link, $label);
327 // Split anchor off end of pagename.
328 if (preg_match('/\A(.*)(?<!'.ESCAPE_CHAR.')#(.*?)\Z/', $rawlink, $m)) {
329 list(,$rawlink,$anchor) = $m;
330 $pagename = UnWikiEscape($rawlink);
331 $anchor = UnWikiEscape($anchor);
339 return new Cached_WikiLink($pagename, $label, $anchor);
343 class Markup_bracketlink extends SimpleMarkup
345 var $_match_regexp = "\\#? \\[ .*? [^]\\s] .*? \\]";
347 function markup ($match) {
348 $link = LinkBracketLink($match);
349 assert($link->isInlineElement());
354 class Markup_url extends SimpleMarkup
356 function getMatchRegexp () {
357 return "(?<![[:alnum:]]) (?:" . ALLOWED_PROTOCOLS . ") : [^\s<>\"']+ (?<![ ,.?; \] \) ])";
360 function markup ($match) {
361 return new Cached_ExternalLink(UnWikiEscape($match));
366 class Markup_interwiki extends SimpleMarkup
368 function getMatchRegexp () {
370 $map = getInterwikiMap();
371 return "(?<! [[:alnum:]])" . $map->getRegexp(). ": \S+ (?<![ ,.?;! \] \) \" \' ])";
374 function markup ($match) {
375 //$map = getInterwikiMap();
376 return new Cached_InterwikiLink(UnWikiEscape($match));
380 class Markup_wikiword extends SimpleMarkup
382 function getMatchRegexp () {
383 global $WikiNameRegexp;
384 return " $WikiNameRegexp";
387 function markup ($match) {
388 if ($this->_isWikiUserPage($match))
389 return new Cached_UserLink($match); //$this->_UserLink($match);
391 return new Cached_WikiLink($match);
394 // FIXME: there's probably a more useful place to put these two functions
395 function _isWikiUserPage ($page) {
397 $dbi = $request->getDbh();
398 $page_handle = $dbi->getPage($page);
399 if ($page_handle->get('pref'))
405 function _UserLink($PageName) {
406 $link = HTML::a(array('href' => $PageName));
407 $link->pushContent(PossiblyGlueIconToText('wikiuser', $PageName));
408 $link->setAttr('class', 'wikiuser');
413 class Markup_linebreak extends SimpleMarkup
415 //var $_match_regexp = "(?: (?<! %) %%% (?! %) | <(?:br|BR)> | <(?:br|BR) \/> )";
416 var $_match_regexp = "(?: (?<! %) %%% (?! %) | <(?:br|BR)> )";
418 function markup ($match) {
423 class Markup_old_emphasis extends BalancedMarkup
425 var $_start_regexp = "''|__";
427 function getEndRegexp ($match) {
431 function markup ($match, $body) {
432 $tag = $match == "''" ? 'em' : 'strong';
433 return new HtmlElement($tag, $body);
437 class Markup_nestled_emphasis extends BalancedMarkup
439 function getStartRegexp() {
440 static $start_regexp = false;
442 if (!$start_regexp) {
443 // The three possible delimiters
444 // (none of which can be followed by itself.)
449 $any = "(?: ${i}|${b}|${tt})"; // any of the three.
451 // Any of [_*=] is okay if preceded by space or one of [-"'/:]
452 $start[] = "(?<= \\s|^|[-\"'\\/:]) ${any}";
454 // _ or * is okay after = as long as not immediately followed by =
455 $start[] = "(?<= =) (?: ${i}|${b}) (?! =)";
457 $start[] = "(?<= _) (?: ${b}|${tt}) (?! _)";
458 $start[] = "(?<= \\*) (?: ${i}|${tt}) (?! \\*)";
461 // any delimiter okay after an opening brace ( [{<(] )
462 // as long as it's not immediately followed by the matching closing
464 $start[] = "(?<= { ) ${any} (?! } )";
465 $start[] = "(?<= < ) ${any} (?! > )";
466 $start[] = "(?<= \\( ) ${any} (?! \\) )";
468 $start = "(?:" . join('|', $start) . ")";
470 // Any of the above must be immediately followed by non-whitespace.
471 $start_regexp = $start . "(?= \S)";
474 return $start_regexp;
477 function getEndRegexp ($match) {
478 $chr = preg_quote($match);
479 return "(?<= \S | ^ ) (?<! $chr) $chr (?! $chr) (?= \s | [-)}>\"'\\/:.,;!? _*=] | $)";
482 function markup ($match, $body) {
484 case '*': return new HtmlElement('b', $body);
485 case '=': return new HtmlElement('tt', $body);
486 case '_': return new HtmlElement('i', $body);
491 class Markup_html_emphasis extends BalancedMarkup
493 var $_start_regexp = "<(?: b|big|i|small|tt|
495 cite|code|dfn|kbd|samp|var|
498 function getEndRegexp ($match) {
499 return "<\\/" . substr($match, 1);
502 function markup ($match, $body) {
503 $tag = substr($match, 1, -1);
504 return new HtmlElement($tag, $body);
508 class Markup_html_abbr extends BalancedMarkup
510 //rurban: abbr|acronym need an optional title tag.
512 var $_start_regexp = "<(?: abbr|acronym )(?: \stitle=[^>]*)?>";
514 function getEndRegexp ($match) {
515 if (substr($match,1,4) == 'abbr')
519 return "<\\/" . $tag . '>';
522 function markup ($match, $body) {
523 if (substr($match,1,4) == 'abbr')
527 $rest = substr($match,1+strlen($tag),-1);
529 list($key,$val) = explode("=",$rest);
530 $args = array($key => $val);
531 } else $args = array();
532 return new HtmlElement($tag, $args, $body);
536 // Special version for single-line plugins formatting,
537 // like: '<small>< ? plugin PopularNearby ? ></small>'
538 class Markup_plugin extends SimpleMarkup
540 var $_match_regexp = '<\?plugin(?:-form)?\s.+?\?>';
542 function markup ($match) {
543 return new Cached_PluginInvocation($match);
548 // TODO: "..." => "…" browser specific display (not cached?)
549 // TODO: "--" => "&emdash;" browser specific display (not cached?)
551 // FIXME: Do away with magic phpwiki forms. (Maybe phpwiki: links too?)
552 // FIXME: Do away with plugin-links. They seem not to be used.
556 class InlineTransformer
558 var $_regexps = array();
559 var $_markup = array();
561 function InlineTransformer ($markup_types = false) {
563 $markup_types = array('escape', 'bracketlink', 'url',
564 'interwiki', 'wikiword', 'linebreak',
565 'old_emphasis', 'nestled_emphasis',
566 'html_emphasis', 'html_abbr', 'plugin');
568 foreach ($markup_types as $mtype) {
569 $class = "Markup_$mtype";
570 $this->_addMarkup(new $class);
574 function _addMarkup ($markup) {
575 if (isa($markup, 'SimpleMarkup'))
576 $regexp = $markup->getMatchRegexp();
578 $regexp = $markup->getStartRegexp();
580 assert(!isset($this->_markup[$regexp]));
581 $this->_regexps[] = $regexp;
582 $this->_markup[] = $markup;
585 function parse (&$text, $end_regexps = array('$')) {
586 $regexps = $this->_regexps;
588 // $end_re takes precedence: "favor reduce over shift"
589 array_unshift($regexps, $end_regexps[0]);
590 $regexps = new RegexpSet($regexps);
593 $output = new XmlContent;
595 $match = $regexps->match($input);
598 if ($match->regexp_ind == 0) {
599 // No start pattern found before end pattern.
601 $output->pushContent($match->prematch);
602 $text = $match->postmatch;
606 $markup = $this->_markup[$match->regexp_ind - 1];
607 //if (!$markup) return false;
608 $body = $this->_parse_markup_body($markup, $match->match, $match->postmatch, $end_regexps);
610 // Couldn't match balanced expression.
611 // Ignore and look for next matching start regexp.
612 $match = $regexps->nextMatch($input, $match);
616 // Matched markup. Eat input, push output.
617 // FIXME: combine adjacent strings.
618 $input = $match->postmatch;
619 $output->pushContent($match->prematch,
620 $markup->markup($match->match, $body));
622 $match = $regexps->match($input);
625 // No pattern matched, not even the end pattern.
630 function _parse_markup_body ($markup, $match, &$text, $end_regexps) {
631 if (isa($markup, 'SimpleMarkup'))
632 return true; // Done. SimpleMarkup is simple.
634 array_unshift($end_regexps, $markup->getEndRegexp($match));
635 // Optimization: if no end pattern in text, we know the
636 // parse will fail. This is an important optimization,
637 // e.g. when text is "*lots *of *start *delims *with
638 // *no *matching *end *delims".
639 $ends_pat = "/(?:" . join(").*(?:", $end_regexps) . ")/xs";
640 if (!preg_match($ends_pat, $text))
642 return $this->parse($text, $end_regexps);
646 class LinkTransformer extends InlineTransformer
648 function LinkTransformer () {
649 $this->InlineTransformer(array('escape', 'bracketlink', 'url',
650 'interwiki', 'wikiword'));
654 function TransformInline($text, $markup = 2.0, $basepage=false) {
658 $trfm = new InlineTransformer;
662 $text = ConvertOldMarkup($text, 'inline');
666 return new CacheableMarkup($trfm->parse($text), $basepage);
668 return $trfm->parse($text);
671 function TransformLinks($text, $markup = 2.0, $basepage = false) {
675 $trfm = new LinkTransformer;
679 $text = ConvertOldMarkup($text, 'links');
683 return new CacheableMarkup($trfm->parse($text), $basepage);
685 return $trfm->parse($text);
688 // (c-file-style: "gnu")
693 // c-hanging-comment-ender-p: nil
694 // indent-tabs-mode: nil