2 rcs_id('$Id: InlineParser.php,v 1.86 2007-01-20 11:25:07 rurban Exp $');
3 /* Copyright (C) 2002 Geoffrey T. Dairiki <dairiki@dairiki.org>
4 * Copyright (C) 2004,2005,2006 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, Reini Urban
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 assert(!empty($repeat));
179 assert(!empty($regexps));
180 // We could do much better, if we would know the matching markup for the
181 // longest regexp match:
182 $hugepat= "/ ( . $repeat ) ( (" . join(')|(', $regexps) . ") ) /Asx";
183 // Proposed premature optimization 1:
184 //$hugepat= "/ ( . $repeat ) ( (" . join(')|(', array_values($matched)) . ") ) /Asx";
185 if (! preg_match($hugepat, $text, $m)) {
188 // Proposed premature optimization 1:
189 //$match->regexp_ind = $matched_ind[count($m) - 4];
190 $match->regexp_ind = count($m) - 4;
192 $match->regexp_ind = $regexp_ind;
195 $match->postmatch = substr($text, strlen($m[0]));
196 $match->prematch = $m[1];
197 $match->match = $m[2];
200 if (DEBUG & _DEBUG_PARSER) {
201 static $_already_dumped = 0;
202 if (!$_already_dumped) {
205 var_dump($matched_inc);
207 $_already_dumped = 1;
208 PrintXML(HTML::dl(HTML::dt("input"),
209 HTML::dd(HTML::pre($text)),
211 HTML::dd(HTML::pre($match->regexp_ind, ":", $regexps[$match->regexp_ind])),
212 HTML::dt("prematch"),
213 HTML::dd(HTML::pre($match->prematch)),
215 HTML::dd(HTML::pre($match->match)),
216 HTML::dt("postmatch"),
217 HTML::dd(HTML::pre($match->postmatch))
227 * A simple markup rule (i.e. terminal token).
229 * These are defined by a regexp.
231 * When a match is found for the regexp, the matching text is replaced.
232 * The replacement content is obtained by calling the SimpleMarkup::markup method.
240 * @return string Regexp which matches this token.
242 function getMatchRegexp () {
243 return $this->_match_regexp;
246 /** Markup matching text.
248 * @param string $match The text which matched the regexp
249 * (obtained from getMatchRegexp).
251 * @return mixed The expansion of the matched text.
253 function markup ($match /*, $body */) {
254 trigger_error("pure virtual", E_USER_ERROR);
259 * A balanced markup rule.
261 * These are defined by a start regexp, and an end regexp.
267 /** Get the starting regexp for this rule.
269 * @return string The starting regexp.
271 function getStartRegexp () {
272 return $this->_start_regexp;
275 /** Get the ending regexp for this rule.
277 * @param string $match The text which matched the starting regexp.
279 * @return string The ending regexp.
281 function getEndRegexp ($match) {
282 return $this->_end_regexp;
285 /** Get expansion for matching input.
287 * @param string $match The text which matched the starting regexp.
289 * @param mixed $body Transformed text found between the starting
290 * and ending regexps.
292 * @return mixed The expansion of the matched text.
294 function markup ($match, $body) {
295 trigger_error("pure virtual", E_USER_ERROR);
299 class Markup_escape extends SimpleMarkup
301 function getMatchRegexp () {
302 return ESCAPE_CHAR . '(?: [[:alnum:]]+ | .)';
305 function markup ($match) {
306 assert(strlen($match) >= 2);
307 return substr($match, 1);
312 * [image.jpg size=50% border=5], [image.jpg size=50x30]
313 * Support for the following attributes: see stdlib.php:LinkImage()
314 * size=<precent>%, size=<width>x<height>
315 * border=n, align=\w+, hspace=n, vspace=n
317 function isImageLink($link) {
318 if (!$link) return false;
319 assert(defined('INLINE_IMAGES'));
320 return preg_match("/\\.(" . INLINE_IMAGES . ")$/i", $link)
321 or preg_match("/\\.(" . INLINE_IMAGES . ")\s+(size|border|align|hspace|vspace)=/i", $link);
324 function LinkBracketLink($bracketlink) {
326 // $bracketlink will start and end with brackets; in between will
327 // be either a page name, a URL or both separated by a pipe.
329 // Strip brackets and leading space
330 // FIXME: \n inside [] will lead to errors
331 preg_match('/(\#?) \[\s* (?: (.*?) \s* (?<!' . ESCAPE_CHAR . ')(\|) )? \s* (.+?) \s*\]/x',
332 $bracketlink, $matches);
333 if (count($matches) < 4) {
334 trigger_error(_("Invalid [] syntax ignored").": ".$bracketlink, E_USER_WARNING);
335 return new Cached_Link;
337 list (, $hash, $label, $bar, $rawlink) = $matches;
339 $label = UnWikiEscape($label);
341 * Check if the user has typed a explicit URL. This solves the
342 * problem where the URLs have a ~ character, which would be stripped away.
343 * "[http:/server/~name/]" will work as expected
344 * "http:/server/~name/" will NOT work as expected, will remove the ~
346 if (strstr($rawlink, "http://") or strstr($rawlink, "https://")) {
348 // Mozilla Browser URI Obfuscation Weakness 2004-06-14
349 // http://www.securityfocus.com/bid/10532/
350 // goodurl+"%2F%20%20%20."+badurl
351 if (preg_match("/%2F(%20)+\./i", $rawlink)) {
352 $rawlink = preg_replace("/%2F(%20)+\./i","%2F.",$rawlink);
355 $link = UnWikiEscape($rawlink);
357 /* Relatives links by Joel Schaubert.
358 * Recognize [../bla] or [/bla] as relative links, without needing http://
359 * but [ /link ] only if SUBPAGE_SEPERATOR is not "/".
360 * Normally /Page links to the subpage /Page.
362 if (SUBPAGE_SEPARATOR == '/') {
363 if (preg_match('/^\.\.\//', $link)) {
364 return new Cached_ExternalLink($link, $label);
366 } else if (preg_match('/^(\.\.\/|\/)/', $link)) {
367 return new Cached_ExternalLink($link, $label);
370 // if label looks like a url to an image, we want an image link.
371 if (isImageLink($label)) {
373 $intermap = getInterwikiMap();
374 if (preg_match("/^" . $intermap->getRegexp() . ":/", $label)) {
375 $imgurl = $intermap->link($label);
376 $imgurl = $imgurl->getAttr('href');
377 } elseif (! preg_match("#^(" . ALLOWED_PROTOCOLS . "):#", $imgurl)) {
378 // local theme linkname like 'images/next.gif'.
380 $imgurl = $WikiTheme->getImageURL($imgurl);
382 $label = LinkImage($imgurl, $link);
386 // It's an anchor, not a link...
387 $id = MangleXmlIdentifier($link);
388 return HTML::a(array('name' => $id, 'id' => $id),
389 $bar ? $label : $link);
392 if (preg_match("#^(" . ALLOWED_PROTOCOLS . "):#", $link)) {
393 // if it's an image, embed it; otherwise, it's a regular link
394 if (isImageLink($link) and empty($label)) // patch #1348996 by Robert Litwiniec
395 return LinkImage($link, $label);
397 return new Cached_ExternalLink($link, $label);
399 elseif (substr($link,0,8) == 'phpwiki:')
400 return new Cached_PhpwikiURL($link, $label);
401 /* Semantic relations and attributes. Relations must be word chars only! no space */
402 elseif (preg_match("/^ (\w+) (:[:=]) (\w.*) $/x", $link) and !isImageLink($link))
403 return new Cached_SemanticLink($link, $label);
404 /* Do not store the link */
405 elseif (substr($link,0,1) == ':')
406 return new Cached_InterwikiLink($link, $label);
408 * Inline images in Interwiki urls's:
409 * [File:my_image.gif] inlines the image,
410 * File:my_image.gif shows a plain inter-wiki link,
411 * [what a pic|File:my_image.gif] shows a named inter-wiki link to the gif
412 * [File:my_image.gif|what a pic] shows a inlimed image linked to the page "what a pic"
414 * Note that for simplicity we will accept embedded object tags (non-images)
415 * here also, and seperate them later in LinkImage()
417 elseif (strstr($link,':')
418 and ($intermap = getInterwikiMap())
419 and preg_match("/^" . $intermap->getRegexp() . ":/", $link))
421 // trigger_error("label: $label link: $link", E_USER_WARNING);
422 if (empty($label) and isImageLink($link)) {
423 // if without label => inlined image [File:xx.gif]
424 $imgurl = $intermap->link($link);
425 return LinkImage($imgurl->getAttr('href'), $label);
427 return new Cached_InterwikiLink($link, $label);
429 // Split anchor off end of pagename.
430 if (preg_match('/\A(.*)(?<!'.ESCAPE_CHAR.')#(.*?)\Z/', $rawlink, $m)) {
431 list(,$rawlink,$anchor) = $m;
432 $pagename = UnWikiEscape($rawlink);
433 $anchor = UnWikiEscape($anchor);
441 return new Cached_WikiLink($pagename, $label, $anchor);
445 class Markup_bracketlink extends SimpleMarkup
447 var $_match_regexp = "\\#? \\[ .*? [^]\\s] .*? \\]";
449 function markup ($match) {
450 $link = LinkBracketLink($match);
451 assert($link->isInlineElement());
456 class Markup_spellcheck extends SimpleMarkup
458 function Markup_spellcheck () {
459 $this->suggestions = $GLOBALS['request']->getArg('suggestions');
461 function getMatchRegexp () {
462 if (empty($this->suggestions))
463 return "(?# false )";
464 $words = array_keys($this->suggestions);
465 return "(?<= \W ) (?:" . join('|', $words) . ") (?= \W )";
468 function markup ($match) {
469 if (empty($this->suggestions) or empty($this->suggestions[$match]))
471 return new Cached_SpellCheck(UnWikiEscape($match), $this->suggestions[$match]);
475 class Markup_url extends SimpleMarkup
477 function getMatchRegexp () {
478 return "(?<![[:alnum:]]) (?:" . ALLOWED_PROTOCOLS . ") : [^\s<>\"']+ (?<![ ,.?; \] \) ])";
481 function markup ($match) {
482 return new Cached_ExternalLink(UnWikiEscape($match));
486 class Markup_interwiki extends SimpleMarkup
488 function getMatchRegexp () {
489 $map = getInterwikiMap();
490 return "(?<! [[:alnum:]])" . $map->getRegexp(). ": [^:=]\S+ (?<![ ,.?;! \] \) \" \' ])";
493 function markup ($match) {
494 return new Cached_InterwikiLink(UnWikiEscape($match));
498 class Markup_semanticlink extends SimpleMarkup
500 var $_match_regexp = "(?:\w+:[:=]\S+)"; // no units seperated by space allowed here
502 function markup ($match) {
503 return new Cached_SemanticLink(UnWikiEscape($match));
507 class Markup_wikiword extends SimpleMarkup
509 function getMatchRegexp () {
510 global $WikiNameRegexp;
511 if (!trim($WikiNameRegexp)) return " " . WIKI_NAME_REGEXP;
512 return " $WikiNameRegexp";
515 function markup ($match) {
516 if (!$match) return false;
517 if ($this->_isWikiUserPage($match))
518 return new Cached_UserLink($match); //$this->_UserLink($match);
520 return new Cached_WikiLink($match);
523 // FIXME: there's probably a more useful place to put these two functions
524 function _isWikiUserPage ($page) {
526 $dbi = $request->getDbh();
527 $page_handle = $dbi->getPage($page);
528 if ($page_handle and $page_handle->get('pref'))
534 function _UserLink($PageName) {
535 $link = HTML::a(array('href' => $PageName));
536 $link->pushContent(PossiblyGlueIconToText('wikiuser', $PageName));
537 $link->setAttr('class', 'wikiuser');
542 class Markup_linebreak extends SimpleMarkup
544 //var $_match_regexp = "(?: (?<! %) %%% (?! %) | <(?:br|BR)> | <(?:br|BR) \/> )";
545 var $_match_regexp = "(?: (?<! %) %%% (?! %) | <(?:br|BR)> )";
547 function markup ($match) {
552 class Markup_old_emphasis extends BalancedMarkup
554 var $_start_regexp = "''|__";
556 function getEndRegexp ($match) {
560 function markup ($match, $body) {
561 $tag = $match == "''" ? 'em' : 'strong';
562 return new HtmlElement($tag, $body);
566 class Markup_nestled_emphasis extends BalancedMarkup
568 function getStartRegexp() {
569 static $start_regexp = false;
571 if (!$start_regexp) {
572 // The three possible delimiters
573 // (none of which can be followed by itself.)
578 $any = "(?: ${i}|${b}|${tt})"; // any of the three.
580 // Any of [_*=] is okay if preceded by space or one of [-"'/:]
581 $start[] = "(?<= \\s|^|[-\"'\\/:]) ${any}";
583 // _ or * is okay after = as long as not immediately followed by =
584 $start[] = "(?<= =) (?: ${i}|${b}) (?! =)";
586 $start[] = "(?<= _) (?: ${b}|${tt}) (?! _)";
587 $start[] = "(?<= \\*) (?: ${i}|${tt}) (?! \\*)";
590 // any delimiter okay after an opening brace ( [{<(] )
591 // as long as it's not immediately followed by the matching closing
593 $start[] = "(?<= { ) ${any} (?! } )";
594 $start[] = "(?<= < ) ${any} (?! > )";
595 $start[] = "(?<= \\( ) ${any} (?! \\) )";
597 $start = "(?:" . join('|', $start) . ")";
599 // Any of the above must be immediately followed by non-whitespace.
600 $start_regexp = $start . "(?= \S)";
603 return $start_regexp;
606 function getEndRegexp ($match) {
607 $chr = preg_quote($match);
608 return "(?<= \S | ^ ) (?<! $chr) $chr (?! $chr) (?= \s | [-)}>\"'\\/:.,;!? _*=] | $)";
611 function markup ($match, $body) {
613 case '*': return new HtmlElement('b', $body);
614 case '=': return new HtmlElement('tt', $body);
615 case '_': return new HtmlElement('i', $body);
620 class Markup_html_emphasis extends BalancedMarkup
623 "<(?: b|big|i|small|tt|em|strong|cite|code|dfn|kbd|samp|strike|del|var|sup|sub )>";
625 function getEndRegexp ($match) {
626 return "<\\/" . substr($match, 1);
629 function markup ($match, $body) {
630 $tag = substr($match, 1, -1);
631 return new HtmlElement($tag, $body);
635 class Markup_html_divspan extends BalancedMarkup
638 "<(?: div|span )(?: \s[^>]*)?>";
640 function getEndRegexp ($match) {
641 if (substr($match,1,4) == 'span')
645 return "<\\/" . $tag . '>';
648 function markup ($match, $body) {
649 if (substr($match,1,4) == 'span')
653 $rest = substr($match,1+strlen($tag),-1);
655 list($key,$val) = explode("=",$rest);
656 $args = array($key => $val);
657 } else $args = array();
658 return new HtmlElement($tag, $args, $body);
663 class Markup_html_abbr extends BalancedMarkup
665 //rurban: abbr|acronym need an optional title tag.
667 var $_start_regexp = "<(?: abbr|acronym )(?: \stitle=[^>]*)?>";
669 function getEndRegexp ($match) {
670 if (substr($match,1,4) == 'abbr')
674 return "<\\/" . $tag . '>';
677 function markup ($match, $body) {
678 if (substr($match,1,4) == 'abbr')
682 $rest = substr($match,1+strlen($tag),-1);
684 list($key,$val) = explode("=",$rest);
685 $args = array($key => $val);
686 } else $args = array();
687 return new HtmlElement($tag, $args, $body);
691 /** ENABLE_MARKUP_COLOR
692 * See http://www.pmwiki.org/wiki/PmWiki/WikiStyles and
693 * http://www.flexwiki.com/default.aspx/FlexWiki/FormattingRules.html
695 class Markup_color extends BalancedMarkup {
696 // %color=blue% blue text %% and back to normal
697 var $_start_regexp = "%color=(?: [^%]*)%";
698 var $_end_regexp = "%%";
700 function markup ($match, $body) {
701 $color = strtoupper(substr($match, 7, -1));
702 if (strlen($color) != 7
703 and in_array($color, array('RED', 'BLUE', 'GREY', 'YELLOW', 'GREEN', 'CYAN', 'BLACK')))
704 { // must be a valid color name
705 return new HtmlElement('font', array('color' => $color), $body);
706 } elseif ((substr($color,0,1) == '#')
707 and (strspn(substr($color,1),'0123456789ABCDEF') == strlen($color)-1)) {
708 return new HtmlElement('font', array('color' => $color), $body);
710 trigger_error(sprintf(_("unknown color %s ignored"), substr($match, 7, -1)), E_USER_WARNING);
716 // Special version for single-line plugins formatting,
717 // like: '<small>< ?plugin PopularNearby ? ></small>'
718 class Markup_plugin extends SimpleMarkup
720 var $_match_regexp = '<\?plugin(?:-form)?\s[^\n]+?\?>';
722 function markup ($match) {
723 //$xml = new Cached_PluginInvocation($match);
724 //$xml->setTightness(true,true);
725 return new Cached_PluginInvocation($match);
729 // Special version for plugins in xml syntax
730 // <name arg=value>body</name> or <name /> => < ? plugin pluginname arg=value body ? >
731 // PLUGIN_MARKUP_MAP = "html:RawHtml dot:GraphViz toc:CreateToc amath:AsciiMath richtable:RichTable include:IncludePage tex:TexToPng"
732 class Markup_xml_plugin extends BalancedMarkup
734 //var $_start_regexp = "<(?: ".join('|',PLUGIN_MARKUP_MAP)." )(?: \s[^>]*)>";
736 function getStartRegexp () {
737 global $PLUGIN_MARKUP_MAP;
738 static $_start_regexp;
739 if ($_start_regexp) return $_start_regexp;
740 if (empty($PLUGIN_MARKUP_MAP))
742 //"<(?: html|dot|toc|amath|richtable|include|tex )(?: \s[^>]*)>"
743 $_start_regexp = "<(?: ".join('|',array_keys($PLUGIN_MARKUP_MAP))." )(?: \s[^>]* | / )>";
744 return $_start_regexp;
746 function getEndRegexp ($match) {
747 return "<\\/" . $match . '>';
749 function markup ($match, $body) {
750 global $PLUGIN_MARKUP_MAP;
751 $name = substr($match,2,-2);
753 if (preg_match('/^(\S+)\|(.*)$/', $name, $_m)) {
755 $vars = $_m[2]; //str_replace(' ', '&', $_m[2]);
757 if (!isset($PLUGIN_MARKUP_MAP[$name])) {
758 trigger_error("No plugin for $name $vars defined.", E_USER_WARNING);
761 $plugin = $PLUGIN_MARKUP_MAP[$name];
762 return new Cached_PluginInvocation("<"."?plugin $plugin $vars $body ?".">");
766 /** ENABLE_MARKUP_TEMPLATE
767 * Template syntax similar to mediawiki
769 * => < ? plugin Template page=template ? >
770 * {{template|var=value|...}}
771 * => < ? plugin Template page=template var=value ... ? >
773 class Markup_template_plugin extends SimpleMarkup
775 var $_match_regexp = '\{\{\w[^\n]+\}\}';
777 function markup ($match) {
778 $page = substr($match, 2, -2); $vars = '';
779 if (preg_match('/^(\S+)\|(.*)$/', $page, $_m)) {
781 $vars = preg_replace('/\|/', ' ', $_m[2]);
784 $s = '<'.'?plugin Template page="' . $page . '" ' . $vars . ' ?'.'>';
786 $s = '<'.'?plugin Template page="' . $page . '" ?'.'>';
787 return new Cached_PluginInvocation($s);
791 // "..." => "…" browser specific display (not cached?)
792 // Support some HTML::Entities: (C) for copy, --- for mdash, -- for ndash
793 // TODO: "--" => "&emdash;" browser specific display (not cached?)
795 class Markup_html_entities extends SimpleMarkup {
796 //var $_match_regexp = '(: \.\.\.|\-\-|\-\-\-|\(C\) )';
798 function Markup_html_entities() {
799 $this->_entities = array('...' => '…',
803 '©' => '©',
804 '™' => '™',
806 $this->_match_regexp =
808 join('|', array_map('preg_quote', array_keys($this->_entities))) .
812 function markup ($match) {
813 return HTML::Raw($this->_entities[$match]);
817 class Markup_isonumchars extends SimpleMarkup {
818 var $_match_regexp = '\&\#\d{2,5};';
820 function markup ($match) {
821 return HTML::Raw($match);
825 class Markup_isohexchars extends SimpleMarkup {
826 // hexnums, like ¤ <=> ¤
827 var $_match_regexp = '\&\#x[0-9a-fA-F]{2,4};';
829 function markup ($match) {
830 return HTML::Raw($match);
834 // FIXME: Do away with magic phpwiki forms. (Maybe phpwiki: links too?)
835 // FIXME: Do away with plugin-links. They seem not to be used.
838 class InlineTransformer
840 var $_regexps = array();
841 var $_markup = array();
843 function InlineTransformer ($markup_types = false) {
844 // We need to extend the inline parsers by certain actions, like SearchHighlight,
845 // SpellCheck and maybe CreateToc.
846 if (!$markup_types) {
847 $non_default = false;
848 $markup_types = array
849 ('escape', 'bracketlink', 'url',
850 'interwiki', 'semanticlink', 'wikiword', 'linebreak',
851 'old_emphasis', 'nestled_emphasis',
852 'html_emphasis', 'html_abbr', 'plugin',
853 'isonumchars', 'isohexchars', /*'html_entities'*/
855 if (DISABLE_MARKUP_WIKIWORD)
856 $markup_types = array_remove($markup_types, 'wikiword');
858 $action = $GLOBALS['request']->getArg('action');
859 if ($action == 'SpellCheck' and $GLOBALS['request']->getArg('suggestions'))
860 { // insert it after url
861 array_splice($markup_types, 2, 1, array('url','spellcheck'));
866 foreach ($markup_types as $mtype) {
867 $class = "Markup_$mtype";
868 $this->_addMarkup(new $class);
870 if (ENABLE_MARKUP_DIVSPAN and !$non_default)
871 $this->_addMarkup(new Markup_html_divspan);
872 if (ENABLE_MARKUP_COLOR and !$non_default)
873 $this->_addMarkup(new Markup_color);
874 if (ENABLE_MARKUP_TEMPLATE and !$non_default)
875 $this->_addMarkup(new Markup_template_plugin);
876 // This does not work yet
877 if (0 and PLUGIN_MARKUP_MAP and !$non_default)
878 $this->_addMarkup(new Markup_xml_plugin);
881 function _addMarkup ($markup) {
882 if (isa($markup, 'SimpleMarkup'))
883 $regexp = $markup->getMatchRegexp();
885 $regexp = $markup->getStartRegexp();
887 assert( !isset($this->_markup[$regexp]) );
888 assert( strlen(trim($regexp)) > 0 );
889 $this->_regexps[] = $regexp;
890 $this->_markup[] = $markup;
893 function parse (&$text, $end_regexps = array('$')) {
894 $regexps = $this->_regexps;
896 // $end_re takes precedence: "favor reduce over shift"
897 array_unshift($regexps, $end_regexps[0]);
898 //array_push($regexps, $end_regexps[0]);
899 $regexps = new RegexpSet($regexps);
902 $output = new XmlContent;
904 $match = $regexps->match($input);
907 if ($match->regexp_ind == 0) {
908 // No start pattern found before end pattern.
910 if (isset($markup) and is_object($markup)
911 and isa($markup,'Markup_plugin'))
913 $current =& $output->_content[count($output->_content)-1];
914 $current->setTightness(true,true);
916 $output->pushContent($match->prematch);
917 $text = $match->postmatch;
921 $markup = $this->_markup[$match->regexp_ind - 1];
922 $body = $this->_parse_markup_body($markup, $match->match,
923 $match->postmatch, $end_regexps);
925 // Couldn't match balanced expression.
926 // Ignore and look for next matching start regexp.
927 $match = $regexps->nextMatch($input, $match);
931 // Matched markup. Eat input, push output.
932 // FIXME: combine adjacent strings.
933 if (isa($markup, 'SimpleMarkup'))
934 $current = $markup->markup($match->match);
936 $current = $markup->markup($match->match, $body);
937 $input = $match->postmatch;
938 if (isset($markup) and is_object($markup)
939 and isa($markup,'Markup_plugin'))
941 $current->setTightness(true,true);
943 $output->pushContent($match->prematch, $current);
945 $match = $regexps->match($input);
948 // No pattern matched, not even the end pattern.
953 function _parse_markup_body ($markup, $match, &$text, $end_regexps) {
954 if (isa($markup, 'SimpleMarkup'))
955 return true; // Done. SimpleMarkup is simple.
957 if (!is_object($markup)) return false; // Some error: Should assert
958 array_unshift($end_regexps, $markup->getEndRegexp($match));
960 // Optimization: if no end pattern in text, we know the
961 // parse will fail. This is an important optimization,
962 // e.g. when text is "*lots *of *start *delims *with
963 // *no *matching *end *delims".
964 $ends_pat = "/(?:" . join(").*(?:", $end_regexps) . ")/xs";
965 if (!preg_match($ends_pat, $text))
967 return $this->parse($text, $end_regexps);
971 class LinkTransformer extends InlineTransformer
973 function LinkTransformer () {
974 $this->InlineTransformer(array('escape', 'bracketlink', 'url',
975 'semanticlink', 'interwiki', 'wikiword',
980 class NowikiTransformer extends InlineTransformer
982 function NowikiTransformer () {
983 $this->InlineTransformer
985 'html_emphasis', 'html_abbr', 'plugin',
986 'isonumchars', 'isohexchars', /*'html_entities',*/
991 function TransformInline($text, $markup = 2.0, $basepage=false) {
993 $action = $GLOBALS['request']->getArg('action');
994 if (empty($trfm) or $action == 'SpellCheck') {
995 $trfm = new InlineTransformer;
999 $text = ConvertOldMarkup($text, 'inline');
1003 return new CacheableMarkup($trfm->parse($text), $basepage);
1005 return $trfm->parse($text);
1008 function TransformLinks($text, $markup = 2.0, $basepage = false) {
1012 $trfm = new LinkTransformer;
1015 if ($markup < 2.0) {
1016 $text = ConvertOldMarkup($text, 'links');
1020 return new CacheableMarkup($trfm->parse($text), $basepage);
1022 return $trfm->parse($text);
1026 * Transform only html markup and entities.
1028 function TransformInlineNowiki($text, $markup = 2.0, $basepage=false) {
1032 $trfm = new NowikiTransformer;
1035 return new CacheableMarkup($trfm->parse($text), $basepage);
1037 return $trfm->parse($text);
1041 // $Log: not supported by cvs2svn $
1042 // Revision 1.85 2007/01/07 18:42:49 rurban
1043 // Add support for non-bracket semantic relation parsing. Assert empty regex (interwikimap?) earlier. Change {{Template||}} vars handling to new style. Stricter interwikimap matching not to find semantic links
1045 // Revision 1.84 2007/01/02 13:18:07 rurban
1046 // fix semantic attributes syntax :=, not :-, disable DIVSPAN and PLUGIN_MARKUP_MAP
1048 // Revision 1.83 2006/12/22 00:23:24 rurban
1049 // Fix Bug #1540007 "hardened-php issue, crawlers related"
1050 // Broken str_replace with strings > 200 chars
1052 // Revision 1.82 2006/12/02 19:53:05 rurban
1053 // Simplify DISABLE_MARKUP_WIKIWORD handling by adding the new function
1054 // stdlib: array_remove(). Hopefully PHP will not add this natively sooner
1057 // Revision 1.81 2006/11/19 13:52:52 rurban
1058 // improve debug output: regex only once
1060 // Revision 1.80 2006/10/12 06:32:30 rurban
1061 // Optionally support new tags <div>, <span> with ENABLE_MARKUP_DIVSPAN (in work)
1063 // Revision 1.79 2006/10/08 12:38:11 rurban
1064 // New special interwiki link markup [:LinkTo] without storing the backlink
1066 // Revision 1.78 2006/09/03 09:53:52 rurban
1067 // more colors, case-insensitive color names
1069 // Revision 1.77 2006/08/25 19:02:02 rurban
1070 // patch #1348996 by Robert Litwiniec: fix show image semantics if label is given
1072 // Revision 1.76 2006/08/19 11:02:35 rurban
1073 // add strike and del to html emphasis: Patch #1542894 by Kai Krakow
1075 // Revision 1.75 2006/08/15 13:43:10 rurban
1076 // add Markup_xml_plugin (untested) and fix Markup_template_plugin
1078 // Revision 1.74 2006/07/23 14:03:18 rurban
1079 // add new feature: DISABLE_MARKUP_WIKIWORD
1081 // Revision 1.73 2006/04/15 12:20:36 rurban
1082 // fix relatives links patch by Joel Schaubert for [/
1084 // Revision 1.72 2006/03/07 20:43:29 rurban
1085 // relative external link, if no internal subpage. by joel Schaubert
1087 // Revision 1.71 2005/11/14 22:31:12 rurban
1088 // add SemanticWeb support
1090 // Revision 1.70 2005/10/31 16:45:23 rurban
1091 // added cfg-able markups only for default TextTransformation, not for links and others
1093 // Revision 1.69 2005/09/14 05:57:19 rurban
1094 // make ENABLE_MARKUP_TEMPLATE optional
1096 // Revision 1.68 2005/09/10 21:24:32 rurban
1097 // optionally support {{Template|vars}} syntax
1099 // Revision 1.67 2005/06/06 17:41:20 rurban
1100 // support new ENABLE_MARKUP_COLOR
1102 // Revision 1.66 2005/04/23 11:15:49 rurban
1103 // handle allowed inlined objects within INLINE_IMAGES
1105 // Revision 1.65 2005/03/27 18:24:17 rurban
1109 // (c-file-style: "gnu")
1113 // c-basic-offset: 4
1114 // c-hanging-comment-ender-p: nil
1115 // indent-tabs-mode: nil