2 rcs_id('$Id: InlineParser.php,v 1.50 2004-05-12 10:49:54 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);
95 * Search text for the next matching regexp from the Regexp Set.
97 * @param string $text The text to search.
99 * @return RegexpSet_match A RegexpSet_match object, or false if no match.
101 function match ($text) {
102 return $this->_match($text, $this->_regexps, '*?');
106 * Search for next matching regexp.
108 * Here, 'next' has two meanings:
110 * Match the next regexp(s) in the set, at the same position as the last match.
112 * If that fails, match the whole RegexpSet, starting after the position of the
115 * @param string $text Text to search.
117 * @param RegexpSet_match $prevMatch A RegexpSet_match object.
118 * $prevMatch should be a match object obtained by a previous
119 * match upon the same value of $text.
121 * @return RegexpSet_match A RegexpSet_match object, or false if no match.
123 function nextMatch ($text, $prevMatch) {
124 // Try to find match at same position.
125 $pos = strlen($prevMatch->prematch);
126 $regexps = array_slice($this->_regexps, $prevMatch->regexp_ind + 1);
128 $repeat = sprintf('{%d}', $pos);
129 if ( ($match = $this->_match($text, $regexps, $repeat)) ) {
130 $match->regexp_ind += $prevMatch->regexp_ind + 1;
136 // Failed. Look for match after current position.
137 $repeat = sprintf('{%d,}?', $pos + 1);
138 return $this->_match($text, $this->_regexps, $repeat);
142 function _match ($text, $regexps, $repeat) {
143 // If one of the regexps is an empty string, php will crash here:
144 // sf.net: Fatal error: Allowed memory size of 8388608 bytes exhausted
145 // (tried to allocate 634 bytes)
147 // So we try to minize memory usage, by looping explicitly,
148 // and storing only those regexp which actually match.
149 // There may be more than one, so we have to find the longest,
150 // and match inside until the shortest is empty.
151 $matched = array(); $matched_ind = array();
152 for ($i=0; $i<count($regexps); $i++) {
153 if (!trim($regexps[$i])) {
154 trigger_error("empty regexp $i",E_USER_WARNING);
157 $pat= "/ ( . $repeat ) ( " . $regexps[$i] . " ) /x";
158 if (preg_match($pat, $text, $_m)) {
160 $matched[] = $regexps[$i];
165 // To overcome ANCHORED:
166 // We could sort by longest match and iterate over these.
167 if (empty($matched)) return false;
168 $match = new RegexpSet_match;
170 // Optimization: if the matches are only "$" and another, then omit "$"
171 // Syntax: http://www.pcre.org/pcre.txt
172 // x - EXTENDED, ignore whitespace
176 if (count($matched) > 2) {
177 // We could do much better, if we would know the matching markup for the
178 // longest regexp match:
179 $hugepat= "/ ( . $repeat ) ( (" . join(')|(', $regexps) . ") ) /Asx";
180 // Proposed premature optimization 1:
181 //$hugepat= "/ ( . $repeat ) ( (" . join(')|(', array_values($matched)) . ") ) /Asx";
182 if (! preg_match($hugepat, $text, $m)) {
185 // Proposed premature optimization 1:
186 //$match->regexp_ind = $matched_ind[count($m) - 4];
187 $match->regexp_ind = count($m) - 4;
189 $match->regexp_ind = $regexp_ind;
192 $match->postmatch = substr($text, strlen($m[0]));
193 $match->prematch = $m[1];
194 $match->match = $m[2];
199 var_dump($regexps); var_dump($matched); var_dump($matched_inc);
200 PrintXML(HTML::dl(HTML::dt("input"),
201 HTML::dd(HTML::pre($text)),
203 HTML::dd(HTML::pre($match->regexp_ind, ":", $regexps[$match->regexp_ind])),
204 HTML::dt("prematch"),
205 HTML::dd(HTML::pre($match->prematch)),
207 HTML::dd(HTML::pre($match->match)),
208 HTML::dt("postmatch"),
209 HTML::dd(HTML::pre($match->postmatch))
220 * A simple markup rule (i.e. terminal token).
222 * These are defined by a regexp.
224 * When a match is found for the regexp, the matching text is replaced.
225 * The replacement content is obtained by calling the SimpleMarkup::markup method.
233 * @return string Regexp which matches this token.
235 function getMatchRegexp () {
236 return $this->_match_regexp;
239 /** Markup matching text.
241 * @param string $match The text which matched the regexp
242 * (obtained from getMatchRegexp).
244 * @return mixed The expansion of the matched text.
246 function markup ($match /*, $body */) {
247 trigger_error("pure virtual", E_USER_ERROR);
252 * A balanced markup rule.
254 * These are defined by a start regexp, and an end regexp.
260 /** Get the starting regexp for this rule.
262 * @return string The starting regexp.
264 function getStartRegexp () {
265 return $this->_start_regexp;
268 /** Get the ending regexp for this rule.
270 * @param string $match The text which matched the starting regexp.
272 * @return string The ending regexp.
274 function getEndRegexp ($match) {
275 return $this->_end_regexp;
278 /** Get expansion for matching input.
280 * @param string $match The text which matched the starting regexp.
282 * @param mixed $body Transformed text found between the starting
283 * and ending regexps.
285 * @return mixed The expansion of the matched text.
287 function markup ($match, $body) {
288 trigger_error("pure virtual", E_USER_ERROR);
292 class Markup_escape extends SimpleMarkup
294 function getMatchRegexp () {
295 return ESCAPE_CHAR . '(?: [[:alnum:]]+ | .)';
298 function markup ($match) {
299 assert(strlen($match) >= 2);
300 return substr($match, 1);
305 * [image.jpg size=50% border=5], [image.jpg size=50x30]
306 * Support for the following attributes: see stdlib.php:LinkImage()
307 * size=<precent>%, size=<width>x<height>
308 * border=n, align=\w+, hspace=n, vspace=n
310 function isImageLink($link) {
311 if (!$link) return false;
312 return preg_match("/\\.(" . INLINE_IMAGES . ")$/i", $link)
313 or preg_match("/\\.(" . INLINE_IMAGES . ")\s+(size|border|align|hspace|vspace)=/i", $link);
316 function LinkBracketLink($bracketlink) {
318 // $bracketlink will start and end with brackets; in between will
319 // be either a page name, a URL or both separated by a pipe.
321 // strip brackets and leading space
322 preg_match('/(\#?) \[\s* (?: (.*?) \s* (?<!' . ESCAPE_CHAR . ')(\|) )? \s* (.+?) \s*\]/x',
323 $bracketlink, $matches);
324 list (, $hash, $label, $bar, $rawlink) = $matches;
326 $label = UnWikiEscape($label);
328 * Check if the user has typed a explicit URL. This solves the
329 * problem where the URLs have a ~ character, which would be stripped away.
330 * "[http:/server/~name/]" will work as expected
331 * "http:/server/~name/" will NOT work as expected, will remove the ~
333 if (strstr($rawlink, "http://") or strstr($rawlink, "https://"))
336 $link = UnWikiEscape($rawlink);
339 // if label looks like a url to an image, we want an image link.
340 if (isImageLink($label)) {
342 if (preg_match("/^" . $intermap->getRegexp() . ":/", $label)) {
343 $imgurl = $intermap->link($label);
344 $imgurl = $imgurl->getAttr('href');
345 } elseif (! preg_match("#^(" . ALLOWED_PROTOCOLS . "):#", $imgurl)) {
346 // local theme linkname like 'images/next.gif'.
348 $imgurl = $Theme->getImageURL($imgurl);
350 $label = LinkImage($imgurl, $link);
354 // It's an anchor, not a link...
355 $id = MangleXmlIdentifier($link);
356 return HTML::a(array('name' => $id, 'id' => $id),
357 $bar ? $label : $link);
360 if (preg_match("#^(" . ALLOWED_PROTOCOLS . "):#", $link)) {
361 // if it's an image, embed it; otherwise, it's a regular link
362 if (isImageLink($link))
363 return LinkImage($link, $label);
365 return new Cached_ExternalLink($link, $label);
367 elseif (preg_match("/^phpwiki:/", $link))
368 return new Cached_PhpwikiURL($link, $label);
370 * Inline images in Interwiki urls's:
371 * [File:my_image.gif] inlines the image,
372 * File:my_image.gif shows a plain inter-wiki link,
373 * [what a pic|File:my_image.gif] shows a named inter-wiki link to the gif
374 * [File:my_image.gif|what a pic] shows a inlimed image linked to the page "what a pic"
376 elseif (strstr($link,':') and
377 ($intermap = getInterwikiMap()) and
378 preg_match("/^" . $intermap->getRegexp() . ":/", $link)) {
379 if (empty($label) && isImageLink($link)) {
380 // if without label => inlined image [File:xx.gif]
381 $imgurl = $intermap->link($link);
382 return LinkImage($imgurl->getAttr('href'), $label);
384 return new Cached_InterwikiLink($link, $label);
386 // Split anchor off end of pagename.
387 if (preg_match('/\A(.*)(?<!'.ESCAPE_CHAR.')#(.*?)\Z/', $rawlink, $m)) {
388 list(,$rawlink,$anchor) = $m;
389 $pagename = UnWikiEscape($rawlink);
390 $anchor = UnWikiEscape($anchor);
398 return new Cached_WikiLink($pagename, $label, $anchor);
402 class Markup_bracketlink extends SimpleMarkup
404 var $_match_regexp = "\\#? \\[ .*? [^]\\s] .*? \\]";
406 function markup ($match) {
407 $link = LinkBracketLink($match);
408 assert($link->isInlineElement());
413 class Markup_url extends SimpleMarkup
415 function getMatchRegexp () {
416 return "(?<![[:alnum:]]) (?:" . ALLOWED_PROTOCOLS . ") : [^\s<>\"']+ (?<![ ,.?; \] \) ])";
419 function markup ($match) {
420 return new Cached_ExternalLink(UnWikiEscape($match));
425 class Markup_interwiki extends SimpleMarkup
427 function getMatchRegexp () {
429 $map = getInterwikiMap();
430 return "(?<! [[:alnum:]])" . $map->getRegexp(). ": \S+ (?<![ ,.?;! \] \) \" \' ])";
433 function markup ($match) {
434 //$map = getInterwikiMap();
435 return new Cached_InterwikiLink(UnWikiEscape($match));
439 class Markup_wikiword extends SimpleMarkup
441 function getMatchRegexp () {
442 global $WikiNameRegexp;
443 if (!trim($WikiNameRegexp)) return " " . WIKI_NAME_REGEXP;
444 return " $WikiNameRegexp";
447 function markup ($match) {
448 if (!$match) return false;
449 if ($this->_isWikiUserPage($match))
450 return new Cached_UserLink($match); //$this->_UserLink($match);
452 return new Cached_WikiLink($match);
455 // FIXME: there's probably a more useful place to put these two functions
456 function _isWikiUserPage ($page) {
458 $dbi = $request->getDbh();
459 $page_handle = $dbi->getPage($page);
460 if ($page_handle and $page_handle->get('pref'))
466 function _UserLink($PageName) {
467 $link = HTML::a(array('href' => $PageName));
468 $link->pushContent(PossiblyGlueIconToText('wikiuser', $PageName));
469 $link->setAttr('class', 'wikiuser');
474 class Markup_linebreak extends SimpleMarkup
476 //var $_match_regexp = "(?: (?<! %) %%% (?! %) | <(?:br|BR)> | <(?:br|BR) \/> )";
477 var $_match_regexp = "(?: (?<! %) %%% (?! %) | <(?:br|BR)> )";
479 function markup ($match) {
484 class Markup_old_emphasis extends BalancedMarkup
486 var $_start_regexp = "''|__";
488 function getEndRegexp ($match) {
492 function markup ($match, $body) {
493 $tag = $match == "''" ? 'em' : 'strong';
494 return new HtmlElement($tag, $body);
498 class Markup_nestled_emphasis extends BalancedMarkup
500 function getStartRegexp() {
501 static $start_regexp = false;
503 if (!$start_regexp) {
504 // The three possible delimiters
505 // (none of which can be followed by itself.)
510 $any = "(?: ${i}|${b}|${tt})"; // any of the three.
512 // Any of [_*=] is okay if preceded by space or one of [-"'/:]
513 $start[] = "(?<= \\s|^|[-\"'\\/:]) ${any}";
515 // _ or * is okay after = as long as not immediately followed by =
516 $start[] = "(?<= =) (?: ${i}|${b}) (?! =)";
518 $start[] = "(?<= _) (?: ${b}|${tt}) (?! _)";
519 $start[] = "(?<= \\*) (?: ${i}|${tt}) (?! \\*)";
522 // any delimiter okay after an opening brace ( [{<(] )
523 // as long as it's not immediately followed by the matching closing
525 $start[] = "(?<= { ) ${any} (?! } )";
526 $start[] = "(?<= < ) ${any} (?! > )";
527 $start[] = "(?<= \\( ) ${any} (?! \\) )";
529 $start = "(?:" . join('|', $start) . ")";
531 // Any of the above must be immediately followed by non-whitespace.
532 $start_regexp = $start . "(?= \S)";
535 return $start_regexp;
538 function getEndRegexp ($match) {
539 $chr = preg_quote($match);
540 return "(?<= \S | ^ ) (?<! $chr) $chr (?! $chr) (?= \s | [-)}>\"'\\/:.,;!? _*=] | $)";
543 function markup ($match, $body) {
545 case '*': return new HtmlElement('b', $body);
546 case '=': return new HtmlElement('tt', $body);
547 case '_': return new HtmlElement('i', $body);
552 class Markup_html_emphasis extends BalancedMarkup
555 "<(?: b|big|i|small|tt|em|strong|cite|code|dfn|kbd|samp|var|sup|sub )>";
557 function getEndRegexp ($match) {
558 return "<\\/" . substr($match, 1);
561 function markup ($match, $body) {
562 $tag = substr($match, 1, -1);
563 return new HtmlElement($tag, $body);
567 class Markup_html_abbr extends BalancedMarkup
569 //rurban: abbr|acronym need an optional title tag.
571 var $_start_regexp = "<(?: abbr|acronym )(?: \stitle=[^>]*)?>";
573 function getEndRegexp ($match) {
574 if (substr($match,1,4) == 'abbr')
578 return "<\\/" . $tag . '>';
581 function markup ($match, $body) {
582 if (substr($match,1,4) == 'abbr')
586 $rest = substr($match,1+strlen($tag),-1);
588 list($key,$val) = explode("=",$rest);
589 $args = array($key => $val);
590 } else $args = array();
591 return new HtmlElement($tag, $args, $body);
595 // Special version for single-line plugins formatting,
596 // like: '<small>< ?plugin PopularNearby ? ></small>'
597 class Markup_plugin extends SimpleMarkup
599 var $_match_regexp = '<\?plugin(?:-form)?\s[^\n]+?\?>';
601 function markup ($match) {
602 //$xml = new Cached_PluginInvocation($match);
603 //$xml->setTightness(true,true);
604 return new Cached_PluginInvocation($match);
609 // TODO: "..." => "…" browser specific display (not cached?)
610 // TODO: "--" => "&emdash;" browser specific display (not cached?)
612 // FIXME: Do away with magic phpwiki forms. (Maybe phpwiki: links too?)
613 // FIXME: Do away with plugin-links. They seem not to be used.
617 class InlineTransformer
619 var $_regexps = array();
620 var $_markup = array();
622 function InlineTransformer ($markup_types = false) {
624 $markup_types = array('escape', 'bracketlink', 'url',
625 'interwiki', 'wikiword', 'linebreak',
626 'old_emphasis', 'nestled_emphasis',
627 'html_emphasis', 'html_abbr', 'plugin');
628 foreach ($markup_types as $mtype) {
629 $class = "Markup_$mtype";
630 $this->_addMarkup(new $class);
634 function _addMarkup ($markup) {
635 if (isa($markup, 'SimpleMarkup'))
636 $regexp = $markup->getMatchRegexp();
638 $regexp = $markup->getStartRegexp();
640 assert(!isset($this->_markup[$regexp]));
641 $this->_regexps[] = $regexp;
642 $this->_markup[] = $markup;
645 function parse (&$text, $end_regexps = array('$')) {
646 $regexps = $this->_regexps;
648 // $end_re takes precedence: "favor reduce over shift"
649 array_unshift($regexps, $end_regexps[0]);
650 //array_push($regexps, $end_regexps[0]);
651 $regexps = new RegexpSet($regexps);
654 $output = new XmlContent;
656 $match = $regexps->match($input);
659 if ($match->regexp_ind == 0) {
660 // No start pattern found before end pattern.
662 if (isset($markup) and is_object($markup) and isa($markup,'Markup_plugin')) {
663 $current =& $output->_content[count($output->_content)-1];
664 $current->setTightness(true,true);
666 $output->pushContent($match->prematch);
667 $text = $match->postmatch;
671 $markup = $this->_markup[$match->regexp_ind - 1];
672 $body = $this->_parse_markup_body($markup, $match->match, $match->postmatch, $end_regexps);
674 // Couldn't match balanced expression.
675 // Ignore and look for next matching start regexp.
676 $match = $regexps->nextMatch($input, $match);
680 // Matched markup. Eat input, push output.
681 // FIXME: combine adjacent strings.
682 $current = $markup->markup($match->match, $body);
683 $input = $match->postmatch;
684 if (isset($markup) and is_object($markup) and isa($markup,'Markup_plugin')) {
685 $current->setTightness(true,true);
687 $output->pushContent($match->prematch, $current);
689 $match = $regexps->match($input);
692 // No pattern matched, not even the end pattern.
697 function _parse_markup_body ($markup, $match, &$text, $end_regexps) {
698 if (isa($markup, 'SimpleMarkup'))
699 return true; // Done. SimpleMarkup is simple.
701 if (!is_object($markup)) return false; // Some error: Should assert
702 array_unshift($end_regexps, $markup->getEndRegexp($match));
704 // Optimization: if no end pattern in text, we know the
705 // parse will fail. This is an important optimization,
706 // e.g. when text is "*lots *of *start *delims *with
707 // *no *matching *end *delims".
708 $ends_pat = "/(?:" . join(").*(?:", $end_regexps) . ")/xs";
709 if (!preg_match($ends_pat, $text))
711 return $this->parse($text, $end_regexps);
715 class LinkTransformer extends InlineTransformer
717 function LinkTransformer () {
718 $this->InlineTransformer(array('escape', 'bracketlink', 'url',
719 'interwiki', 'wikiword'));
723 function TransformInline($text, $markup = 2.0, $basepage=false) {
727 $trfm = new InlineTransformer;
731 $text = ConvertOldMarkup($text, 'inline');
735 return new CacheableMarkup($trfm->parse($text), $basepage);
737 return $trfm->parse($text);
740 function TransformLinks($text, $markup = 2.0, $basepage = false) {
744 $trfm = new LinkTransformer;
748 $text = ConvertOldMarkup($text, 'links');
752 return new CacheableMarkup($trfm->parse($text), $basepage);
754 return $trfm->parse($text);
757 // (c-file-style: "gnu")
762 // c-hanging-comment-ender-p: nil
763 // indent-tabs-mode: nil