1 <?php rcs_id('$Id: InlineParser.php,v 1.37 2004-04-19 23:13:03 zorloc Exp $');
\r
2 /* Copyright (C) 2002, Geoffrey T. Dairiki <dairiki@dairiki.org>
\r
4 * This file is part of PhpWiki.
\r
6 * PhpWiki is free software; you can redistribute it and/or modify
\r
7 * it under the terms of the GNU General Public License as published by
\r
8 * the Free Software Foundation; either version 2 of the License, or
\r
9 * (at your option) any later version.
\r
11 * PhpWiki is distributed in the hope that it will be useful,
\r
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
\r
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
\r
14 * GNU General Public License for more details.
\r
16 * You should have received a copy of the GNU General Public License
\r
17 * along with PhpWiki; if not, write to the Free Software
\r
18 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
\r
21 * This is the code which deals with the inline part of the (new-style)
\r
25 * @author Geoffrey T. Dairiki
\r
31 * This is the character used in wiki markup to escape characters with
\r
34 define('ESCAPE_CHAR', '~');
\r
36 require_once('lib/HtmlElement.php');
\r
37 require_once('lib/CachedMarkup.php');
\r
38 //require_once('lib/interwiki.php');
\r
39 require_once('lib/stdlib.php');
\r
42 function WikiEscape($text) {
\r
43 return str_replace('#', ESCAPE_CHAR . '#', $text);
\r
46 function UnWikiEscape($text) {
\r
47 return preg_replace('/' . ESCAPE_CHAR . '(.)/', '\1', $text);
\r
51 * Return type from RegexpSet::match and RegexpSet::nextMatch.
\r
55 class RegexpSet_match {
\r
57 * The text leading up the the next match.
\r
67 * The text following the matched text.
\r
72 * Index of the regular expression which matched.
\r
78 * A set of regular expressions.
\r
80 * This class is probably only useful for InlineTransformer.
\r
86 * @param array $regexps A list of regular expressions. The
\r
87 * regular expressions should not include any sub-pattern groups
\r
88 * "(...)". (Anonymous groups, like "(?:...)", as well as
\r
89 * look-ahead and look-behind assertions are okay.)
\r
91 function RegexpSet ($regexps) {
\r
92 $this->_regexps = $regexps;
\r
96 * Search text for the next matching regexp from the Regexp Set.
\r
98 * @param string $text The text to search.
\r
100 * @return RegexpSet_match A RegexpSet_match object, or false if no match.
\r
102 function match ($text) {
\r
103 return $this->_match($text, $this->_regexps, '*?');
\r
107 * Search for next matching regexp.
\r
109 * Here, 'next' has two meanings:
\r
111 * Match the next regexp(s) in the set, at the same position as the last match.
\r
113 * If that fails, match the whole RegexpSet, starting after the position of the
\r
116 * @param string $text Text to search.
\r
118 * @param RegexpSet_match $prevMatch A RegexpSet_match object.
\r
119 * $prevMatch should be a match object obtained by a previous
\r
120 * match upon the same value of $text.
\r
122 * @return RegexpSet_match A RegexpSet_match object, or false if no match.
\r
124 function nextMatch ($text, $prevMatch) {
\r
125 // Try to find match at same position.
\r
126 $pos = strlen($prevMatch->prematch);
\r
127 $regexps = array_slice($this->_regexps, $prevMatch->regexp_ind + 1);
\r
129 $repeat = sprintf('{%d}', $pos);
\r
130 if ( ($match = $this->_match($text, $regexps, $repeat)) ) {
\r
131 $match->regexp_ind += $prevMatch->regexp_ind + 1;
\r
137 // Failed. Look for match after current position.
\r
138 $repeat = sprintf('{%d,}?', $pos + 1);
\r
139 return $this->_match($text, $this->_regexps, $repeat);
\r
143 function _match ($text, $regexps, $repeat) {
\r
144 $pat= "/ ( . $repeat ) ( (" . join(')|(', $regexps) . ") ) /Axs";
\r
146 if (! preg_match($pat, $text, $m)) {
\r
150 $match = new RegexpSet_match;
\r
151 $match->postmatch = substr($text, strlen($m[0]));
\r
152 $match->prematch = $m[1];
\r
153 $match->match = $m[2];
\r
154 $match->regexp_ind = count($m) - 4;
\r
157 PrintXML(HTML::dl(HTML::dt("input"),
\r
158 HTML::dd(HTML::pre($text)),
\r
160 HTML::dd(HTML::pre($match->match)),
\r
161 HTML::dt("regexp"),
\r
162 HTML::dd(HTML::pre($regexps[$match->regexp_ind])),
\r
163 HTML::dt("prematch"),
\r
164 HTML::dd(HTML::pre($match->prematch))));
\r
173 * A simple markup rule (i.e. terminal token).
\r
175 * These are defined by a regexp.
\r
177 * When a match is found for the regexp, the matching text is replaced.
\r
178 * The replacement content is obtained by calling the SimpleMarkup::markup method.
\r
182 var $_match_regexp;
\r
186 * @return string Regexp which matches this token.
\r
188 function getMatchRegexp () {
\r
189 return $this->_match_regexp;
\r
192 /** Markup matching text.
\r
194 * @param string $match The text which matched the regexp
\r
195 * (obtained from getMatchRegexp).
\r
197 * @return mixed The expansion of the matched text.
\r
199 function markup ($match /*, $body */) {
\r
200 trigger_error("pure virtual", E_USER_ERROR);
\r
205 * A balanced markup rule.
\r
207 * These are defined by a start regexp, and and end regexp.
\r
209 class BalancedMarkup
\r
211 var $_start_regexp;
\r
213 /** Get the starting regexp for this rule.
\r
215 * @return string The starting regexp.
\r
217 function getStartRegexp () {
\r
218 return $this->_start_regexp;
\r
221 /** Get the ending regexp for this rule.
\r
223 * @param string $match The text which matched the starting regexp.
\r
225 * @return string The ending regexp.
\r
227 function getEndRegexp ($match) {
\r
228 return $this->_end_regexp;
\r
231 /** Get expansion for matching input.
\r
233 * @param string $match The text which matched the starting regexp.
\r
235 * @param mixed $body Transformed text found between the starting
\r
236 * and ending regexps.
\r
238 * @return mixed The expansion of the matched text.
\r
240 function markup ($match, $body) {
\r
241 trigger_error("pure virtual", E_USER_ERROR);
\r
245 class Markup_escape extends SimpleMarkup
\r
247 function getMatchRegexp () {
\r
248 return ESCAPE_CHAR . '(?: [[:alnum:]]+ | .)';
\r
251 function markup ($match) {
\r
252 assert(strlen($match) >= 2);
\r
253 return substr($match, 1);
\r
257 function LinkBracketLink($bracketlink) {
\r
258 //include_once("lib/interwiki.php");
\r
259 $intermap = getInterwikiMap();
\r
261 // $bracketlink will start and end with brackets; in between will
\r
262 // be either a page name, a URL or both separated by a pipe.
\r
264 // strip brackets and leading space
\r
265 preg_match('/(\#?) \[\s* (?: (.*?) \s* (?<!' . ESCAPE_CHAR . ')(\|) )? \s* (.+?) \s*\]/x',
\r
266 $bracketlink, $matches);
\r
267 list (, $hash, $label, $bar, $rawlink) = $matches;
\r
269 $label = UnWikiEscape($label);
\r
271 * Check if the user has typed a explicit URL. This solves the
\r
272 * problem where the URLs have a ~ character, which would be stripped away.
\r
273 * "[http:/server/~name/]" will work as expected
\r
274 * "http:/server/~name/" will NOT work as expected, will remove the ~
\r
276 if (strstr($rawlink, "http://") or strstr($rawlink, "https://"))
\r
279 $link = UnWikiEscape($rawlink);
\r
282 // if label looks like a url to an image, we want an image link.
\r
283 if (preg_match("/\\.(" . INLINE_IMAGES . ")$/i", $label)) {
\r
285 if (preg_match("/^" . $intermap->getRegexp() . ":/", $label)) {
\r
286 $imgurl = $intermap->link($label);
\r
287 $imgurl = $imgurl->getAttr('href');
\r
288 } elseif (! preg_match("#^(" . ALLOWED_PROTOCOLS . "):#", $imgurl)) {
\r
289 // local theme linkname like 'images/next.gif'.
\r
291 $imgurl = $Theme->getImageURL($imgurl);
\r
293 $label = LinkImage($imgurl, $link);
\r
297 // It's an anchor, not a link...
\r
298 $id = MangleXmlIdentifier($link);
\r
299 return HTML::a(array('name' => $id, 'id' => $id),
\r
300 $bar ? $label : $link);
\r
303 if (preg_match("#^(" . ALLOWED_PROTOCOLS . "):#", $link)) {
\r
304 // if it's an image, embed it; otherwise, it's a regular link
\r
305 if (preg_match("/\\.(" . INLINE_IMAGES . ")$/i", $link))
\r
306 return LinkImage($link, $label);
\r
308 return new Cached_ExternalLink($link, $label);
\r
310 elseif (preg_match("/^phpwiki:/", $link))
\r
311 return new Cached_PhpwikiURL($link, $label);
\r
313 * Inline images in Interwiki urls's:
\r
314 * [File:my_image.gif] inlines the image,
\r
315 * File:my_image.gif shows a plain inter-wiki link,
\r
316 * [what a pic|File:my_image.gif] shows a named inter-wiki link to the gif
\r
317 * [File:my_image.gif|what a pic] shows a inlimed image linked to the page "what a pic"
\r
319 elseif (preg_match("/^" . $intermap->getRegexp() . ":/", $link)) {
\r
320 if (empty($label) && preg_match("/\\.(" . INLINE_IMAGES . ")$/i", $link)) {
\r
321 // if without label => inlined image [File:xx.gif]
\r
322 $imgurl = $intermap->link($link);
\r
323 return LinkImage($imgurl->getAttr('href'), $label);
\r
325 return new Cached_InterwikiLink($link, $label);
\r
327 // Split anchor off end of pagename.
\r
328 if (preg_match('/\A(.*)(?<!'.ESCAPE_CHAR.')#(.*?)\Z/', $rawlink, $m)) {
\r
329 list(,$rawlink,$anchor) = $m;
\r
330 $pagename = UnWikiEscape($rawlink);
\r
331 $anchor = UnWikiEscape($anchor);
\r
339 return new Cached_WikiLink($pagename, $label, $anchor);
\r
343 class Markup_bracketlink extends SimpleMarkup
\r
345 var $_match_regexp = "\\#? \\[ .*? [^]\\s] .*? \\]";
\r
347 function markup ($match) {
\r
348 $link = LinkBracketLink($match);
\r
349 assert($link->isInlineElement());
\r
354 class Markup_url extends SimpleMarkup
\r
356 function getMatchRegexp () {
\r
357 return "(?<![[:alnum:]]) (?:" . ALLOWED_PROTOCOLS . ") : [^\s<>\"']+ (?<![ ,.?; \] \) ])";
\r
360 function markup ($match) {
\r
361 return new Cached_ExternalLink(UnWikiEscape($match));
\r
366 class Markup_interwiki extends SimpleMarkup
\r
368 function getMatchRegexp () {
\r
370 $map = getInterwikiMap();
\r
371 return "(?<! [[:alnum:]])" . $map->getRegexp(). ": \S+ (?<![ ,.?;! \] \) \" \' ])";
\r
374 function markup ($match) {
\r
375 //$map = getInterwikiMap();
\r
376 return new Cached_InterwikiLink(UnWikiEscape($match));
\r
380 class Markup_wikiword extends SimpleMarkup
\r
382 function getMatchRegexp () {
\r
383 global $WikiNameRegexp;
\r
384 return " $WikiNameRegexp";
\r
387 function markup ($match) {
\r
388 if ($this->_isWikiUserPage($match))
\r
389 return new Cached_UserLink($match); //$this->_UserLink($match);
\r
391 return new Cached_WikiLink($match);
\r
394 // FIXME: there's probably a more useful place to put these two functions
\r
395 function _isWikiUserPage ($page) {
\r
397 $dbi = $request->getDbh();
\r
398 $page_handle = $dbi->getPage($page);
\r
399 if ($page_handle->get('pref'))
\r
405 function _UserLink($PageName) {
\r
406 $link = HTML::a(array('href' => $PageName));
\r
407 $link->pushContent(PossiblyGlueIconToText('wikiuser', $PageName));
\r
408 $link->setAttr('class', 'wikiuser');
\r
413 class Markup_linebreak extends SimpleMarkup
\r
415 //var $_match_regexp = "(?: (?<! %) %%% (?! %) | <(?:br|BR)> | <(?:br|BR) \/> )";
\r
416 var $_match_regexp = "(?: (?<! %) %%% (?! %) | <(?:br|BR)> )";
\r
418 function markup ($match) {
\r
423 class Markup_old_emphasis extends BalancedMarkup
\r
425 var $_start_regexp = "''|__";
\r
427 function getEndRegexp ($match) {
\r
431 function markup ($match, $body) {
\r
432 $tag = $match == "''" ? 'em' : 'strong';
\r
433 return new HtmlElement($tag, $body);
\r
437 class Markup_nestled_emphasis extends BalancedMarkup
\r
439 function getStartRegexp() {
\r
440 static $start_regexp = false;
\r
442 if (!$start_regexp) {
\r
443 // The three possible delimiters
\r
444 // (none of which can be followed by itself.)
\r
446 $b = "\\* (?! \\*)";
\r
449 $any = "(?: ${i}|${b}|${tt})"; // any of the three.
\r
451 // Any of [_*=] is okay if preceded by space or one of [-"'/:]
\r
452 $start[] = "(?<= \\s|^|[-\"'\\/:]) ${any}";
\r
454 // _ or * is okay after = as long as not immediately followed by =
\r
455 $start[] = "(?<= =) (?: ${i}|${b}) (?! =)";
\r
457 $start[] = "(?<= _) (?: ${b}|${tt}) (?! _)";
\r
458 $start[] = "(?<= \\*) (?: ${i}|${tt}) (?! \\*)";
\r
461 // any delimiter okay after an opening brace ( [{<(] )
\r
462 // as long as it's not immediately followed by the matching closing
\r
464 $start[] = "(?<= { ) ${any} (?! } )";
\r
465 $start[] = "(?<= < ) ${any} (?! > )";
\r
466 $start[] = "(?<= \\( ) ${any} (?! \\) )";
\r
468 $start = "(?:" . join('|', $start) . ")";
\r
470 // Any of the above must be immediately followed by non-whitespace.
\r
471 $start_regexp = $start . "(?= \S)";
\r
474 return $start_regexp;
\r
477 function getEndRegexp ($match) {
\r
478 $chr = preg_quote($match);
\r
479 return "(?<= \S | ^ ) (?<! $chr) $chr (?! $chr) (?= \s | [-)}>\"'\\/:.,;!? _*=] | $)";
\r
482 function markup ($match, $body) {
\r
484 case '*': return new HtmlElement('b', $body);
\r
485 case '=': return new HtmlElement('tt', $body);
\r
486 case '_': return new HtmlElement('i', $body);
\r
491 class Markup_html_emphasis extends BalancedMarkup
\r
493 var $_start_regexp = "<(?: b|big|i|small|tt|
\r
495 cite|code|dfn|kbd|samp|var|
\r
497 //rurban: abbr|acronym need an optional title tag.
\r
498 //sf.net bug #728595
\r
500 function getEndRegexp ($match) {
\r
501 return "<\\/" . substr($match, 1);
\r
504 function markup ($match, $body) {
\r
505 $tag = substr($match, 1, -1);
\r
506 return new HtmlElement($tag, $body);
\r
510 class Markup_html_abbr extends BalancedMarkup
\r
512 //rurban: abbr|acronym need an optional title tag.
\r
513 //sf.net bug #728595
\r
514 var $_start_regexp = "<(?: abbr|acronym )(?: \stitle=[^>]*)?>";
\r
516 function getEndRegexp ($match) {
\r
517 if (substr($match,1,4) == 'abbr')
\r
521 return "<\\/" . $tag . '>';
\r
524 function markup ($match, $body) {
\r
525 if (substr($match,1,4) == 'abbr')
\r
529 $rest = substr($match,1+strlen($tag),-1);
\r
530 if (!empty($rest)) {
\r
531 list($key,$val) = explode("=",$rest);
\r
532 $args = array($key => $val);
\r
533 } else $args = array();
\r
534 return new HtmlElement($tag, $args, $body);
\r
538 // FIXME: Do away with magic phpwiki forms. (Maybe phpwiki: links too?)
\r
539 // FIXME: Do away with plugin-links. They seem not to be used.
\r
543 class InlineTransformer
\r
545 var $_regexps = array();
\r
546 var $_markup = array();
\r
548 function InlineTransformer ($markup_types = false) {
\r
549 if (!$markup_types)
\r
550 $markup_types = array('escape', 'bracketlink', 'url',
\r
551 'interwiki', 'wikiword', 'linebreak',
\r
552 'old_emphasis', 'nestled_emphasis',
\r
553 'html_emphasis', 'html_abbr');
\r
555 foreach ($markup_types as $mtype) {
\r
556 $class = "Markup_$mtype";
\r
557 $this->_addMarkup(new $class);
\r
561 function _addMarkup ($markup) {
\r
562 if (isa($markup, 'SimpleMarkup'))
\r
563 $regexp = $markup->getMatchRegexp();
\r
565 $regexp = $markup->getStartRegexp();
\r
567 assert(!isset($this->_markup[$regexp]));
\r
568 $this->_regexps[] = $regexp;
\r
569 $this->_markup[] = $markup;
\r
572 function parse (&$text, $end_regexps = array('$')) {
\r
573 $regexps = $this->_regexps;
\r
575 // $end_re takes precedence: "favor reduce over shift"
\r
576 array_unshift($regexps, $end_regexps[0]);
\r
577 $regexps = new RegexpSet($regexps);
\r
580 $output = new XmlContent;
\r
582 $match = $regexps->match($input);
\r
585 if ($match->regexp_ind == 0) {
\r
586 // No start pattern found before end pattern.
\r
588 $output->pushContent($match->prematch);
\r
589 $text = $match->postmatch;
\r
593 $markup = $this->_markup[$match->regexp_ind - 1];
\r
594 //if (!$markup) return false;
\r
595 $body = $this->_parse_markup_body($markup, $match->match, $match->postmatch, $end_regexps);
\r
597 // Couldn't match balanced expression.
\r
598 // Ignore and look for next matching start regexp.
\r
599 $match = $regexps->nextMatch($input, $match);
\r
603 // Matched markup. Eat input, push output.
\r
604 // FIXME: combine adjacent strings.
\r
605 $input = $match->postmatch;
\r
606 $output->pushContent($match->prematch,
\r
607 $markup->markup($match->match, $body));
\r
609 $match = $regexps->match($input);
\r
612 // No pattern matched, not even the end pattern.
\r
617 function _parse_markup_body ($markup, $match, &$text, $end_regexps) {
\r
618 if (isa($markup, 'SimpleMarkup'))
\r
619 return true; // Done. SimpleMarkup is simple.
\r
621 array_unshift($end_regexps, $markup->getEndRegexp($match));
\r
622 // Optimization: if no end pattern in text, we know the
\r
623 // parse will fail. This is an important optimization,
\r
624 // e.g. when text is "*lots *of *start *delims *with
\r
625 // *no *matching *end *delims".
\r
626 $ends_pat = "/(?:" . join(").*(?:", $end_regexps) . ")/xs";
\r
627 if (!preg_match($ends_pat, $text))
\r
629 return $this->parse($text, $end_regexps);
\r
633 class LinkTransformer extends InlineTransformer
\r
635 function LinkTransformer () {
\r
636 $this->InlineTransformer(array('escape', 'bracketlink', 'url',
\r
637 'interwiki', 'wikiword'));
\r
641 function TransformInline($text, $markup = 2.0, $basepage=false) {
\r
644 if (empty($trfm)) {
\r
645 $trfm = new InlineTransformer;
\r
648 if ($markup < 2.0) {
\r
649 $text = ConvertOldMarkup($text, 'inline');
\r
653 return new CacheableMarkup($trfm->parse($text), $basepage);
\r
655 return $trfm->parse($text);
\r
658 function TransformLinks($text, $markup = 2.0, $basepage = false) {
\r
661 if (empty($trfm)) {
\r
662 $trfm = new LinkTransformer;
\r
665 if ($markup < 2.0) {
\r
666 $text = ConvertOldMarkup($text, 'links');
\r
670 return new CacheableMarkup($trfm->parse($text), $basepage);
\r
672 return $trfm->parse($text);
\r
675 // (c-file-style: "gnu")
\r
676 // Local Variables:
\r
679 // c-basic-offset: 4
\r
680 // c-hanging-comment-ender-p: nil
\r
681 // indent-tabs-mode: nil
\r