2 rcs_id('$Id: InlineParser.php,v 1.54 2004-06-14 11:31:21 rurban Exp $');
3 /* Copyright (C) 2002 Geoffrey T. Dairiki <dairiki@dairiki.org>
4 * Copyright (C) 2004 Reini Urban
6 * This file is part of PhpWiki.
8 * PhpWiki is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
13 * PhpWiki is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License
19 * along with PhpWiki; if not, write to the Free Software
20 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23 * This is the code which deals with the inline part of the (new-style)
27 * @author Geoffrey T. Dairiki
33 * This is the character used in wiki markup to escape characters with
36 define('ESCAPE_CHAR', '~');
38 require_once(dirname(__FILE__).'/HtmlElement.php');
39 require_once('lib/CachedMarkup.php');
40 require_once(dirname(__FILE__).'/stdlib.php');
43 function WikiEscape($text) {
44 return str_replace('#', ESCAPE_CHAR . '#', $text);
47 function UnWikiEscape($text) {
48 return preg_replace('/' . ESCAPE_CHAR . '(.)/', '\1', $text);
52 * Return type from RegexpSet::match and RegexpSet::nextMatch.
56 class RegexpSet_match {
58 * The text leading up the the next match.
66 * The text following the matched text.
70 * Index of the regular expression which matched.
76 * A set of regular expressions.
78 * This class is probably only useful for InlineTransformer.
84 * @param array $regexps A list of regular expressions. The
85 * regular expressions should not include any sub-pattern groups
86 * "(...)". (Anonymous groups, like "(?:...)", as well as
87 * look-ahead and look-behind assertions are okay.)
89 function RegexpSet ($regexps) {
91 $this->_regexps = array_unique($regexps);
92 if (!defined('_INLINE_OPTIMIZATION')) define('_INLINE_OPTIMIZATION',0);
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);
142 // Syntax: http://www.pcre.org/pcre.txt
143 // x - EXTENDED, ignore whitespace
147 function _match ($text, $regexps, $repeat) {
148 // If one of the regexps is an empty string, php will crash here:
149 // sf.net: Fatal error: Allowed memory size of 8388608 bytes exhausted
150 // (tried to allocate 634 bytes)
151 if (_INLINE_OPTIMIZATION) { // disabled, wrong
152 // So we try to minize memory usage, by looping explicitly,
153 // and storing only those regexp which actually match.
154 // There may be more than one, so we have to find the longest,
155 // and match inside until the shortest is empty.
156 $matched = array(); $matched_ind = array();
157 for ($i=0; $i<count($regexps); $i++) {
158 if (!trim($regexps[$i])) {
159 trigger_error("empty regexp $i",E_USER_WARNING);
162 $pat= "/ ( . $repeat ) ( " . $regexps[$i] . " ) /x";
163 if (preg_match($pat, $text, $_m)) {
164 $m = $_m; // FIXME: prematch, postmatch is wrong
165 $matched[] = $regexps[$i];
170 // To overcome ANCHORED:
171 // We could sort by longest match and iterate over these.
172 if (empty($matched)) return false;
174 $match = new RegexpSet_match;
176 // Optimization: if the matches are only "$" and another, then omit "$"
177 if (! _INLINE_OPTIMIZATION or count($matched) > 2) {
178 // We could do much better, if we would know the matching markup for the
179 // longest regexp match:
180 $hugepat= "/ ( . $repeat ) ( (" . join(')|(', $regexps) . ") ) /Asx";
181 // Proposed premature optimization 1:
182 //$hugepat= "/ ( . $repeat ) ( (" . join(')|(', array_values($matched)) . ") ) /Asx";
183 if (! preg_match($hugepat, $text, $m)) {
186 // Proposed premature optimization 1:
187 //$match->regexp_ind = $matched_ind[count($m) - 4];
188 $match->regexp_ind = count($m) - 4;
190 $match->regexp_ind = $regexp_ind;
193 $match->postmatch = substr($text, strlen($m[0]));
194 $match->prematch = $m[1];
195 $match->match = $m[2];
200 var_dump($regexps); var_dump($matched); var_dump($matched_inc);
201 PrintXML(HTML::dl(HTML::dt("input"),
202 HTML::dd(HTML::pre($text)),
204 HTML::dd(HTML::pre($match->regexp_ind, ":", $regexps[$match->regexp_ind])),
205 HTML::dt("prematch"),
206 HTML::dd(HTML::pre($match->prematch)),
208 HTML::dd(HTML::pre($match->match)),
209 HTML::dt("postmatch"),
210 HTML::dd(HTML::pre($match->postmatch))
221 * A simple markup rule (i.e. terminal token).
223 * These are defined by a regexp.
225 * When a match is found for the regexp, the matching text is replaced.
226 * The replacement content is obtained by calling the SimpleMarkup::markup method.
234 * @return string Regexp which matches this token.
236 function getMatchRegexp () {
237 return $this->_match_regexp;
240 /** Markup matching text.
242 * @param string $match The text which matched the regexp
243 * (obtained from getMatchRegexp).
245 * @return mixed The expansion of the matched text.
247 function markup ($match /*, $body */) {
248 trigger_error("pure virtual", E_USER_ERROR);
253 * A balanced markup rule.
255 * These are defined by a start regexp, and an end regexp.
261 /** Get the starting regexp for this rule.
263 * @return string The starting regexp.
265 function getStartRegexp () {
266 return $this->_start_regexp;
269 /** Get the ending regexp for this rule.
271 * @param string $match The text which matched the starting regexp.
273 * @return string The ending regexp.
275 function getEndRegexp ($match) {
276 return $this->_end_regexp;
279 /** Get expansion for matching input.
281 * @param string $match The text which matched the starting regexp.
283 * @param mixed $body Transformed text found between the starting
284 * and ending regexps.
286 * @return mixed The expansion of the matched text.
288 function markup ($match, $body) {
289 trigger_error("pure virtual", E_USER_ERROR);
293 class Markup_escape extends SimpleMarkup
295 function getMatchRegexp () {
296 return ESCAPE_CHAR . '(?: [[:alnum:]]+ | .)';
299 function markup ($match) {
300 assert(strlen($match) >= 2);
301 return substr($match, 1);
306 * [image.jpg size=50% border=5], [image.jpg size=50x30]
307 * Support for the following attributes: see stdlib.php:LinkImage()
308 * size=<precent>%, size=<width>x<height>
309 * border=n, align=\w+, hspace=n, vspace=n
311 function isImageLink($link) {
312 if (!$link) return false;
313 return preg_match("/\\.(" . INLINE_IMAGES . ")$/i", $link)
314 or preg_match("/\\.(" . INLINE_IMAGES . ")\s+(size|border|align|hspace|vspace)=/i", $link);
317 function LinkBracketLink($bracketlink) {
319 // $bracketlink will start and end with brackets; in between will
320 // be either a page name, a URL or both separated by a pipe.
322 // strip brackets and leading space
323 preg_match('/(\#?) \[\s* (?: (.*?) \s* (?<!' . ESCAPE_CHAR . ')(\|) )? \s* (.+?) \s*\]/x',
324 $bracketlink, $matches);
325 list (, $hash, $label, $bar, $rawlink) = $matches;
327 $label = UnWikiEscape($label);
329 * Check if the user has typed a explicit URL. This solves the
330 * problem where the URLs have a ~ character, which would be stripped away.
331 * "[http:/server/~name/]" will work as expected
332 * "http:/server/~name/" will NOT work as expected, will remove the ~
334 if (strstr($rawlink, "http://") or strstr($rawlink, "https://"))
337 $link = UnWikiEscape($rawlink);
340 // if label looks like a url to an image, we want an image link.
341 if (isImageLink($label)) {
343 $intermap = getInterwikiMap();
344 if (preg_match("/^" . $intermap->getRegexp() . ":/", $label)) {
345 $imgurl = $intermap->link($label);
346 $imgurl = $imgurl->getAttr('href');
347 } elseif (! preg_match("#^(" . ALLOWED_PROTOCOLS . "):#", $imgurl)) {
348 // local theme linkname like 'images/next.gif'.
350 $imgurl = $WikiTheme->getImageURL($imgurl);
352 $label = LinkImage($imgurl, $link);
356 // It's an anchor, not a link...
357 $id = MangleXmlIdentifier($link);
358 return HTML::a(array('name' => $id, 'id' => $id),
359 $bar ? $label : $link);
362 if (preg_match("#^(" . ALLOWED_PROTOCOLS . "):#", $link)) {
363 // if it's an image, embed it; otherwise, it's a regular link
364 if (isImageLink($link))
365 return LinkImage($link, $label);
367 return new Cached_ExternalLink($link, $label);
369 elseif (preg_match("/^phpwiki:/", $link))
370 return new Cached_PhpwikiURL($link, $label);
372 * Inline images in Interwiki urls's:
373 * [File:my_image.gif] inlines the image,
374 * File:my_image.gif shows a plain inter-wiki link,
375 * [what a pic|File:my_image.gif] shows a named inter-wiki link to the gif
376 * [File:my_image.gif|what a pic] shows a inlimed image linked to the page "what a pic"
378 elseif (strstr($link,':') and
379 ($intermap = getInterwikiMap()) and
380 preg_match("/^" . $intermap->getRegexp() . ":/", $link)) {
381 if (empty($label) && isImageLink($link)) {
382 // if without label => inlined image [File:xx.gif]
383 $imgurl = $intermap->link($link);
384 return LinkImage($imgurl->getAttr('href'), $label);
386 return new Cached_InterwikiLink($link, $label);
388 // Split anchor off end of pagename.
389 if (preg_match('/\A(.*)(?<!'.ESCAPE_CHAR.')#(.*?)\Z/', $rawlink, $m)) {
390 list(,$rawlink,$anchor) = $m;
391 $pagename = UnWikiEscape($rawlink);
392 $anchor = UnWikiEscape($anchor);
400 return new Cached_WikiLink($pagename, $label, $anchor);
404 class Markup_bracketlink extends SimpleMarkup
406 var $_match_regexp = "\\#? \\[ .*? [^]\\s] .*? \\]";
408 function markup ($match) {
409 $link = LinkBracketLink($match);
410 assert($link->isInlineElement());
415 class Markup_url extends SimpleMarkup
417 function getMatchRegexp () {
418 return "(?<![[:alnum:]]) (?:" . ALLOWED_PROTOCOLS . ") : [^\s<>\"']+ (?<![ ,.?; \] \) ])";
421 function markup ($match) {
422 return new Cached_ExternalLink(UnWikiEscape($match));
427 class Markup_interwiki extends SimpleMarkup
429 function getMatchRegexp () {
431 $map = getInterwikiMap();
432 return "(?<! [[:alnum:]])" . $map->getRegexp(). ": \S+ (?<![ ,.?;! \] \) \" \' ])";
435 function markup ($match) {
436 //$map = getInterwikiMap();
437 return new Cached_InterwikiLink(UnWikiEscape($match));
441 class Markup_wikiword extends SimpleMarkup
443 function getMatchRegexp () {
444 global $WikiNameRegexp;
445 if (!trim($WikiNameRegexp)) return " " . WIKI_NAME_REGEXP;
446 return " $WikiNameRegexp";
449 function markup ($match) {
450 if (!$match) return false;
451 if ($this->_isWikiUserPage($match))
452 return new Cached_UserLink($match); //$this->_UserLink($match);
454 return new Cached_WikiLink($match);
457 // FIXME: there's probably a more useful place to put these two functions
458 function _isWikiUserPage ($page) {
460 $dbi = $request->getDbh();
461 $page_handle = $dbi->getPage($page);
462 if ($page_handle and $page_handle->get('pref'))
468 function _UserLink($PageName) {
469 $link = HTML::a(array('href' => $PageName));
470 $link->pushContent(PossiblyGlueIconToText('wikiuser', $PageName));
471 $link->setAttr('class', 'wikiuser');
476 class Markup_linebreak extends SimpleMarkup
478 //var $_match_regexp = "(?: (?<! %) %%% (?! %) | <(?:br|BR)> | <(?:br|BR) \/> )";
479 var $_match_regexp = "(?: (?<! %) %%% (?! %) | <(?:br|BR)> )";
481 function markup ($match) {
486 class Markup_old_emphasis extends BalancedMarkup
488 var $_start_regexp = "''|__";
490 function getEndRegexp ($match) {
494 function markup ($match, $body) {
495 $tag = $match == "''" ? 'em' : 'strong';
496 return new HtmlElement($tag, $body);
500 class Markup_nestled_emphasis extends BalancedMarkup
502 function getStartRegexp() {
503 static $start_regexp = false;
505 if (!$start_regexp) {
506 // The three possible delimiters
507 // (none of which can be followed by itself.)
512 $any = "(?: ${i}|${b}|${tt})"; // any of the three.
514 // Any of [_*=] is okay if preceded by space or one of [-"'/:]
515 $start[] = "(?<= \\s|^|[-\"'\\/:]) ${any}";
517 // _ or * is okay after = as long as not immediately followed by =
518 $start[] = "(?<= =) (?: ${i}|${b}) (?! =)";
520 $start[] = "(?<= _) (?: ${b}|${tt}) (?! _)";
521 $start[] = "(?<= \\*) (?: ${i}|${tt}) (?! \\*)";
524 // any delimiter okay after an opening brace ( [{<(] )
525 // as long as it's not immediately followed by the matching closing
527 $start[] = "(?<= { ) ${any} (?! } )";
528 $start[] = "(?<= < ) ${any} (?! > )";
529 $start[] = "(?<= \\( ) ${any} (?! \\) )";
531 $start = "(?:" . join('|', $start) . ")";
533 // Any of the above must be immediately followed by non-whitespace.
534 $start_regexp = $start . "(?= \S)";
537 return $start_regexp;
540 function getEndRegexp ($match) {
541 $chr = preg_quote($match);
542 return "(?<= \S | ^ ) (?<! $chr) $chr (?! $chr) (?= \s | [-)}>\"'\\/:.,;!? _*=] | $)";
545 function markup ($match, $body) {
547 case '*': return new HtmlElement('b', $body);
548 case '=': return new HtmlElement('tt', $body);
549 case '_': return new HtmlElement('i', $body);
554 class Markup_html_emphasis extends BalancedMarkup
557 "<(?: b|big|i|small|tt|em|strong|cite|code|dfn|kbd|samp|var|sup|sub )>";
559 function getEndRegexp ($match) {
560 return "<\\/" . substr($match, 1);
563 function markup ($match, $body) {
564 $tag = substr($match, 1, -1);
565 return new HtmlElement($tag, $body);
569 class Markup_html_abbr extends BalancedMarkup
571 //rurban: abbr|acronym need an optional title tag.
573 var $_start_regexp = "<(?: abbr|acronym )(?: \stitle=[^>]*)?>";
575 function getEndRegexp ($match) {
576 if (substr($match,1,4) == 'abbr')
580 return "<\\/" . $tag . '>';
583 function markup ($match, $body) {
584 if (substr($match,1,4) == 'abbr')
588 $rest = substr($match,1+strlen($tag),-1);
590 list($key,$val) = explode("=",$rest);
591 $args = array($key => $val);
592 } else $args = array();
593 return new HtmlElement($tag, $args, $body);
597 // Special version for single-line plugins formatting,
598 // like: '<small>< ?plugin PopularNearby ? ></small>'
599 class Markup_plugin extends SimpleMarkup
601 var $_match_regexp = '<\?plugin(?:-form)?\s[^\n]+?\?>';
603 function markup ($match) {
604 //$xml = new Cached_PluginInvocation($match);
605 //$xml->setTightness(true,true);
606 return new Cached_PluginInvocation($match);
611 // TODO: "..." => "…" browser specific display (not cached?)
612 // TODO: "--" => "&emdash;" browser specific display (not cached?)
614 // FIXME: Do away with magic phpwiki forms. (Maybe phpwiki: links too?)
615 // FIXME: Do away with plugin-links. They seem not to be used.
619 class InlineTransformer
621 var $_regexps = array();
622 var $_markup = array();
624 function InlineTransformer ($markup_types = false) {
626 $markup_types = array('escape', 'bracketlink', 'url',
627 'interwiki', 'wikiword', 'linebreak',
628 'old_emphasis', 'nestled_emphasis',
629 'html_emphasis', 'html_abbr', 'plugin');
630 foreach ($markup_types as $mtype) {
631 $class = "Markup_$mtype";
632 $this->_addMarkup(new $class);
636 function _addMarkup ($markup) {
637 if (isa($markup, 'SimpleMarkup'))
638 $regexp = $markup->getMatchRegexp();
640 $regexp = $markup->getStartRegexp();
642 assert(!isset($this->_markup[$regexp]));
643 $this->_regexps[] = $regexp;
644 $this->_markup[] = $markup;
647 function parse (&$text, $end_regexps = array('$')) {
648 $regexps = $this->_regexps;
650 // $end_re takes precedence: "favor reduce over shift"
651 array_unshift($regexps, $end_regexps[0]);
652 //array_push($regexps, $end_regexps[0]);
653 $regexps = new RegexpSet($regexps);
656 $output = new XmlContent;
658 $match = $regexps->match($input);
661 if ($match->regexp_ind == 0) {
662 // No start pattern found before end pattern.
664 if (isset($markup) and is_object($markup) and isa($markup,'Markup_plugin')) {
665 $current =& $output->_content[count($output->_content)-1];
666 $current->setTightness(true,true);
668 $output->pushContent($match->prematch);
669 $text = $match->postmatch;
673 $markup = $this->_markup[$match->regexp_ind - 1];
674 $body = $this->_parse_markup_body($markup, $match->match, $match->postmatch, $end_regexps);
676 // Couldn't match balanced expression.
677 // Ignore and look for next matching start regexp.
678 $match = $regexps->nextMatch($input, $match);
682 // Matched markup. Eat input, push output.
683 // FIXME: combine adjacent strings.
684 $current = $markup->markup($match->match, $body);
685 $input = $match->postmatch;
686 if (isset($markup) and is_object($markup) and isa($markup,'Markup_plugin')) {
687 $current->setTightness(true,true);
689 $output->pushContent($match->prematch, $current);
691 $match = $regexps->match($input);
694 // No pattern matched, not even the end pattern.
699 function _parse_markup_body ($markup, $match, &$text, $end_regexps) {
700 if (isa($markup, 'SimpleMarkup'))
701 return true; // Done. SimpleMarkup is simple.
703 if (!is_object($markup)) return false; // Some error: Should assert
704 array_unshift($end_regexps, $markup->getEndRegexp($match));
706 // Optimization: if no end pattern in text, we know the
707 // parse will fail. This is an important optimization,
708 // e.g. when text is "*lots *of *start *delims *with
709 // *no *matching *end *delims".
710 $ends_pat = "/(?:" . join(").*(?:", $end_regexps) . ")/xs";
711 if (!preg_match($ends_pat, $text))
713 return $this->parse($text, $end_regexps);
717 class LinkTransformer extends InlineTransformer
719 function LinkTransformer () {
720 $this->InlineTransformer(array('escape', 'bracketlink', 'url',
721 'interwiki', 'wikiword'));
725 function TransformInline($text, $markup = 2.0, $basepage=false) {
729 $trfm = new InlineTransformer;
733 $text = ConvertOldMarkup($text, 'inline');
737 return new CacheableMarkup($trfm->parse($text), $basepage);
739 return $trfm->parse($text);
742 function TransformLinks($text, $markup = 2.0, $basepage = false) {
746 $trfm = new LinkTransformer;
750 $text = ConvertOldMarkup($text, 'links');
754 return new CacheableMarkup($trfm->parse($text), $basepage);
756 return $trfm->parse($text);
759 // (c-file-style: "gnu")
764 // c-hanging-comment-ender-p: nil
765 // indent-tabs-mode: nil