2 rcs_id('$Id: InlineParser.php,v 1.100 2008-08-03 15:52:31 vargenau Exp $');
3 /* Copyright (C) 2002 Geoffrey T. Dairiki <dairiki@dairiki.org>
4 * Copyright (C) 2004-2008 Reini Urban
5 * Copyright (C) 2008 Marc-Etienne Vargenau
7 * This file is part of PhpWiki.
9 * PhpWiki is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
14 * PhpWiki is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
19 * You should have received a copy of the GNU General Public License
20 * along with PhpWiki; if not, write to the Free Software
21 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
24 * This is the code which deals with the inline part of the (new-style)
28 * @author Geoffrey T. Dairiki, Reini Urban
34 * This is the character used in wiki markup to escape characters with
37 define('ESCAPE_CHAR', '~');
39 require_once(dirname(__FILE__).'/HtmlElement.php');
40 require_once('lib/CachedMarkup.php');
41 require_once(dirname(__FILE__).'/stdlib.php');
44 function WikiEscape($text) {
45 return str_replace('#', ESCAPE_CHAR . '#', $text);
48 function UnWikiEscape($text) {
49 return preg_replace('/' . ESCAPE_CHAR . '(.)/', '\1', $text);
53 * Return type from RegexpSet::match and RegexpSet::nextMatch.
57 class RegexpSet_match {
59 * The text leading up the the next match.
67 * The text following the matched text.
71 * Index of the regular expression which matched.
77 * A set of regular expressions.
79 * This class is probably only useful for InlineTransformer.
85 * @param array $regexps A list of regular expressions. The
86 * regular expressions should not include any sub-pattern groups
87 * "(...)". (Anonymous groups, like "(?:...)", as well as
88 * look-ahead and look-behind assertions are okay.)
90 function RegexpSet ($regexps) {
92 $this->_regexps = array_unique($regexps);
93 if (!defined('_INLINE_OPTIMIZATION')) define('_INLINE_OPTIMIZATION',0);
97 * Search text for the next matching regexp from the Regexp Set.
99 * @param string $text The text to search.
101 * @return RegexpSet_match A RegexpSet_match object, or false if no match.
103 function match ($text) {
104 return $this->_match($text, $this->_regexps, '*?');
108 * Search for next matching regexp.
110 * Here, 'next' has two meanings:
112 * Match the next regexp(s) in the set, at the same position as the last match.
114 * If that fails, match the whole RegexpSet, starting after the position of the
117 * @param string $text Text to search.
119 * @param RegexpSet_match $prevMatch A RegexpSet_match object.
120 * $prevMatch should be a match object obtained by a previous
121 * match upon the same value of $text.
123 * @return RegexpSet_match A RegexpSet_match object, or false if no match.
125 function nextMatch ($text, $prevMatch) {
126 // Try to find match at same position.
127 $pos = strlen($prevMatch->prematch);
128 $regexps = array_slice($this->_regexps, $prevMatch->regexp_ind + 1);
130 $repeat = sprintf('{%d}', $pos);
131 if ( ($match = $this->_match($text, $regexps, $repeat)) ) {
132 $match->regexp_ind += $prevMatch->regexp_ind + 1;
138 // Failed. Look for match after current position.
139 $repeat = sprintf('{%d,}?', $pos + 1);
140 return $this->_match($text, $this->_regexps, $repeat);
143 // Syntax: http://www.pcre.org/pcre.txt
144 // x - EXTENDED, ignore whitespace
148 function _match ($text, $regexps, $repeat) {
149 // If one of the regexps is an empty string, php will crash here:
150 // sf.net: Fatal error: Allowed memory size of 8388608 bytes exhausted
151 // (tried to allocate 634 bytes)
152 if (_INLINE_OPTIMIZATION) { // disabled, wrong
153 // So we try to minize memory usage, by looping explicitly,
154 // and storing only those regexp which actually match.
155 // There may be more than one, so we have to find the longest,
156 // and match inside until the shortest is empty.
157 $matched = array(); $matched_ind = array();
158 for ($i=0; $i<count($regexps); $i++) {
159 if (!trim($regexps[$i])) {
160 trigger_error("empty regexp $i", E_USER_WARNING);
163 $pat= "/ ( . $repeat ) ( " . $regexps[$i] . " ) /x";
164 if (preg_match($pat, $text, $_m)) {
165 $m = $_m; // FIXME: prematch, postmatch is wrong
166 $matched[] = $regexps[$i];
171 // To overcome ANCHORED:
172 // We could sort by longest match and iterate over these.
173 if (empty($matched)) return false;
175 $match = new RegexpSet_match;
177 // Optimization: if the matches are only "$" and another, then omit "$"
178 if (! _INLINE_OPTIMIZATION or count($matched) > 2) {
179 assert(!empty($repeat));
180 assert(!empty($regexps));
181 // We could do much better, if we would know the matching markup for the
182 // longest regexp match:
183 $hugepat= "/ ( . $repeat ) ( (" . join(')|(', $regexps) . ") ) /Asx";
184 // Proposed premature optimization 1:
185 //$hugepat= "/ ( . $repeat ) ( (" . join(')|(', array_values($matched)) . ") ) /Asx";
186 if (! preg_match($hugepat, $text, $m)) {
189 // Proposed premature optimization 1:
190 //$match->regexp_ind = $matched_ind[count($m) - 4];
191 $match->regexp_ind = count($m) - 4;
193 $match->regexp_ind = $regexp_ind;
196 $match->postmatch = substr($text, strlen($m[0]));
197 $match->prematch = $m[1];
198 $match->match = $m[2];
201 if (DEBUG & _DEBUG_PARSER) {
202 static $_already_dumped = 0;
203 if (!$_already_dumped) {
205 if (_INLINE_OPTIMIZATION)
207 var_dump($matched_inc);
209 $_already_dumped = 1;
210 PrintXML(HTML::dl(HTML::dt("input"),
211 HTML::dd(HTML::pre($text)),
213 HTML::dd(HTML::pre($match->regexp_ind, ":", $regexps[$match->regexp_ind])),
214 HTML::dt("prematch"),
215 HTML::dd(HTML::pre($match->prematch)),
217 HTML::dd(HTML::pre($match->match)),
218 HTML::dt("postmatch"),
219 HTML::dd(HTML::pre($match->postmatch))
229 * A simple markup rule (i.e. terminal token).
231 * These are defined by a regexp.
233 * When a match is found for the regexp, the matching text is replaced.
234 * The replacement content is obtained by calling the SimpleMarkup::markup method.
242 * @return string Regexp which matches this token.
244 function getMatchRegexp () {
245 return $this->_match_regexp;
248 /** Markup matching text.
250 * @param string $match The text which matched the regexp
251 * (obtained from getMatchRegexp).
253 * @return mixed The expansion of the matched text.
255 function markup ($match /*, $body */) {
256 trigger_error("pure virtual", E_USER_ERROR);
261 * A balanced markup rule.
263 * These are defined by a start regexp, and an end regexp.
269 /** Get the starting regexp for this rule.
271 * @return string The starting regexp.
273 function getStartRegexp () {
274 return $this->_start_regexp;
277 /** Get the ending regexp for this rule.
279 * @param string $match The text which matched the starting regexp.
281 * @return string The ending regexp.
283 function getEndRegexp ($match) {
284 return $this->_end_regexp;
287 /** Get expansion for matching input.
289 * @param string $match The text which matched the starting regexp.
291 * @param mixed $body Transformed text found between the starting
292 * and ending regexps.
294 * @return mixed The expansion of the matched text.
296 function markup ($match, $body) {
297 trigger_error("pure virtual", E_USER_ERROR);
301 class Markup_escape extends SimpleMarkup
303 function getMatchRegexp () {
304 return ESCAPE_CHAR . '(?: [[:alnum:]]+ | .)';
307 function markup ($match) {
308 assert(strlen($match) >= 2);
309 return substr($match, 1);
314 * [image.jpg size=50% border=5], [image.jpg size=50x30]
315 * Support for the following attributes: see stdlib.php:LinkImage()
316 * size=<precent>%, size=<width>x<height>
317 * border=n, align=\w+, hspace=n, vspace=n
319 function isImageLink($link) {
320 if (!$link) return false;
321 assert(defined('INLINE_IMAGES'));
322 return preg_match("/\\.(" . INLINE_IMAGES . ")$/i", $link)
323 or preg_match("/\\.(" . INLINE_IMAGES . ")\s+(size|border|align|hspace|vspace|type|data|width|height)=/i", $link);
326 function LinkBracketLink($bracketlink) {
328 // $bracketlink will start and end with brackets; in between will
329 // be either a page name, a URL or both separated by a pipe.
331 // Strip brackets and leading space
332 // bug#1904088 Some brackets links on 2 lines cause the parser to crash
333 preg_match('/(\#?) \[\s* (?: (.*?) \s* (?<!' . ESCAPE_CHAR . ')(\|) )? \s* (.+?) \s*\]/x',
334 str_replace("\n", " ", $bracketlink), $matches);
335 if (count($matches) < 4) {
336 // "[ personal\ninformation manager | PhpWiki:PersonalWiki ]"
337 trigger_error(_("Invalid [] syntax ignored").": ".$bracketlink, E_USER_WARNING);
338 return new Cached_Link;
340 list (, $hash, $label, $bar, $rawlink) = $matches;
342 $label = UnWikiEscape($label);
344 * Check if the user has typed a explicit URL. This solves the
345 * problem where the URLs have a ~ character, which would be stripped away.
346 * "[http:/server/~name/]" will work as expected
347 * "http:/server/~name/" will NOT work as expected, will remove the ~
349 if ( string_starts_with ($rawlink, "http://")
350 or string_starts_with ($rawlink, "https://") )
353 // Mozilla Browser URI Obfuscation Weakness 2004-06-14
354 // http://www.securityfocus.com/bid/10532/
355 // goodurl+"%2F%20%20%20."+badurl
356 if (preg_match("/%2F(%20)+\./i", $rawlink)) {
357 $rawlink = preg_replace("/%2F(%20)+\./i","%2F.",$rawlink);
360 $link = UnWikiEscape($rawlink);
362 /* Relatives links by Joel Schaubert.
363 * Recognize [../bla] or [/bla] as relative links, without needing http://
364 * but [ /link ] only if SUBPAGE_SEPERATOR is not "/".
365 * Normally /Page links to the subpage /Page.
367 if (SUBPAGE_SEPARATOR == '/') {
368 if (preg_match('/^\.\.\//', $link)) {
369 return new Cached_ExternalLink($link, $label);
371 } else if (preg_match('/^(\.\.\/|\/)/', $link)) {
372 return new Cached_ExternalLink($link, $label);
375 // If label looks like a url to an image or object, we want an image link.
376 if (isImageLink($label)) {
378 $intermap = getInterwikiMap();
379 if (preg_match("/^" . $intermap->getRegexp() . ":/", $label)) {
380 $imgurl = $intermap->link($label);
381 $imgurl = $imgurl->getAttr('href');
382 } elseif (! preg_match("#^(" . ALLOWED_PROTOCOLS . "):#", $imgurl)) {
383 // local theme linkname like 'images/next.gif'.
385 $imgurl = $WikiTheme->getImageURL($imgurl);
387 // for objects (non-images) the link is taken as alt tag,
388 // which is in return taken as alternative img
389 $label = LinkImage($imgurl, $link);
393 // It's an anchor, not a link...
394 $id = MangleXmlIdentifier($link);
395 return HTML::a(array('name' => $id, 'id' => $id),
396 $bar ? $label : $link);
399 if (preg_match("#^(" . ALLOWED_PROTOCOLS . "):#", $link)) {
400 // if it's an image, embed it; otherwise, it's a regular link
401 if (isImageLink($link) and empty($label)) // patch #1348996 by Robert Litwiniec
402 return LinkImage($link, $label);
404 return new Cached_ExternalLink($link, $label);
406 elseif (substr($link,0,8) == 'phpwiki:')
407 return new Cached_PhpwikiURL($link, $label);
409 /* Semantic relations and attributes.
410 * Relation and attribute names must be word chars only, no space.
411 * Links and Attributes may contain everything. word, nums, units, space, groupsep, numsep, ...
413 elseif (preg_match("/^ (\w+) (:[:=]) (.*) $/x", $link) and !isImageLink($link))
414 return new Cached_SemanticLink($link, $label);
416 /* Do not store the link */
417 elseif (substr($link,0,1) == ':')
418 return new Cached_WikiLink($link, $label);
421 * Inline images in Interwiki urls's:
422 * [File:my_image.gif] inlines the image,
423 * File:my_image.gif shows a plain inter-wiki link,
424 * [what a pic|File:my_image.gif] shows a named inter-wiki link to the gif
425 * [File:my_image.gif|what a pic] shows a inlimed image linked to the page "what a pic"
427 * Note that for simplicity we will accept embedded object tags (non-images)
428 * here also, and seperate them later in LinkImage()
430 elseif (strstr($link,':')
431 and ($intermap = getInterwikiMap())
432 and preg_match("/^" . $intermap->getRegexp() . ":/", $link))
434 // trigger_error("label: $label link: $link", E_USER_WARNING);
435 if (empty($label) and isImageLink($link)) {
436 // if without label => inlined image [File:xx.gif]
437 $imgurl = $intermap->link($link);
438 return LinkImage($imgurl->getAttr('href'), $link);
440 return new Cached_InterwikiLink($link, $label);
442 // Split anchor off end of pagename.
443 if (preg_match('/\A(.*)(?<!'.ESCAPE_CHAR.')#(.*?)\Z/', $rawlink, $m)) {
444 list(,$rawlink,$anchor) = $m;
445 $pagename = UnWikiEscape($rawlink);
446 $anchor = UnWikiEscape($anchor);
454 return new Cached_WikiLink($pagename, $label, $anchor);
458 class Markup_bracketlink extends SimpleMarkup
460 var $_match_regexp = "\\#? \\[ .*? [^]\\s] .*? \\]";
462 function markup ($match) {
463 $link = LinkBracketLink($match);
464 assert($link->isInlineElement());
469 class Markup_spellcheck extends SimpleMarkup
471 function Markup_spellcheck () {
472 $this->suggestions = $GLOBALS['request']->getArg('suggestions');
474 function getMatchRegexp () {
475 if (empty($this->suggestions))
476 return "(?# false )";
477 $words = array_keys($this->suggestions);
478 return "(?<= \W ) (?:" . join('|', $words) . ") (?= \W )";
481 function markup ($match) {
482 if (empty($this->suggestions) or empty($this->suggestions[$match]))
484 return new Cached_SpellCheck(UnWikiEscape($match), $this->suggestions[$match]);
488 class Markup_searchhighlight extends SimpleMarkup
490 function Markup_searchhighlight () {
491 $result = $GLOBALS['request']->_searchhighlight;
492 require_once("lib/TextSearchQuery.php");
493 $query = new TextSearchQuery($result['query']);
494 $this->hilight_re = $query->getHighlightRegexp();
495 $this->engine = $result['engine'];
497 function getMatchRegexp () {
498 return $this->hilight_re;
500 function markup ($match) {
501 return new Cached_SearchHighlight(UnWikiEscape($match), $this->engine);
505 class Markup_url extends SimpleMarkup
507 function getMatchRegexp () {
508 return "(?<![[:alnum:]]) (?:" . ALLOWED_PROTOCOLS . ") : [^\s<>\"']+ (?<![ ,.?; \] \) ])";
511 function markup ($match) {
512 return new Cached_ExternalLink(UnWikiEscape($match));
516 class Markup_interwiki extends SimpleMarkup
518 function getMatchRegexp () {
519 $map = getInterwikiMap();
520 return "(?<! [[:alnum:]])" . $map->getRegexp(). ": [^:=]\S+ (?<![ ,.?;! \] \) \" \' ])";
523 function markup ($match) {
524 return new Cached_InterwikiLink(UnWikiEscape($match));
528 class Markup_semanticlink extends SimpleMarkup
530 // No units seperated by space allowed here
531 // For :: (relations) only words, no comma,
532 // but for := (attributes) comma and dots are allowed. Units with groupsep.
533 // Ending dots or comma are not part of the link.
534 var $_match_regexp = "(?: \w+:=\S+(?<![\.,]))|(?: \w+::[\w\.]+(?<!\.))";
536 function markup ($match) {
537 return new Cached_SemanticLink(UnWikiEscape($match));
541 class Markup_wikiword extends SimpleMarkup
543 function getMatchRegexp () {
544 global $WikiNameRegexp;
545 if (!trim($WikiNameRegexp)) return " " . WIKI_NAME_REGEXP;
546 return " $WikiNameRegexp";
549 function markup ($match) {
550 if (!$match) return false;
551 if ($this->_isWikiUserPage($match))
552 return new Cached_UserLink($match); //$this->_UserLink($match);
554 return new Cached_WikiLink($match);
557 // FIXME: there's probably a more useful place to put these two functions
558 function _isWikiUserPage ($page) {
560 $dbi = $request->getDbh();
561 $page_handle = $dbi->getPage($page);
562 if ($page_handle and $page_handle->get('pref'))
568 function _UserLink($PageName) {
569 $link = HTML::a(array('href' => $PageName));
570 $link->pushContent(PossiblyGlueIconToText('wikiuser', $PageName));
571 $link->setAttr('class', 'wikiuser');
576 class Markup_linebreak extends SimpleMarkup
578 //var $_match_regexp = "(?: (?<! %) %%% (?! %) | <(?:br|BR)> | <(?:br|BR) \/> )";
579 var $_match_regexp = "(?: (?<! %) %%% (?! %) | <(?:br|BR)> )";
581 function markup ($match) {
586 class Markup_wikicreole_subscript extends BalancedMarkup
588 var $_start_regexp = ",,";
590 function getEndRegexp ($match) {
594 function markup ($match, $body) {
596 return new HtmlElement($tag, $body);
600 class Markup_old_emphasis extends BalancedMarkup
602 var $_start_regexp = "''|__";
604 function getEndRegexp ($match) {
608 function markup ($match, $body) {
609 $tag = $match == "''" ? 'em' : 'strong';
610 return new HtmlElement($tag, $body);
614 class Markup_nestled_emphasis extends BalancedMarkup
616 function getStartRegexp() {
617 static $start_regexp = false;
619 if (!$start_regexp) {
620 // The three possible delimiters
621 // (none of which can be followed by itself.)
626 $any = "(?: ${i}|${b}|${tt})"; // any of the three.
628 // Any of [_*=] is okay if preceded by space or one of [-"'/:]
629 $start[] = "(?<= \\s|^|[-\"'\\/:]) ${any}";
631 // _ or * is okay after = as long as not immediately followed by =
632 $start[] = "(?<= =) (?: ${i}|${b}) (?! =)";
634 $start[] = "(?<= _) (?: ${b}|${tt}) (?! _)";
635 $start[] = "(?<= \\*) (?: ${i}|${tt}) (?! \\*)";
638 // any delimiter okay after an opening brace ( [{<(] )
639 // as long as it's not immediately followed by the matching closing
641 $start[] = "(?<= { ) ${any} (?! } )";
642 $start[] = "(?<= < ) ${any} (?! > )";
643 $start[] = "(?<= \\( ) ${any} (?! \\) )";
645 $start = "(?:" . join('|', $start) . ")";
647 // Any of the above must be immediately followed by non-whitespace.
648 $start_regexp = $start . "(?= \S)";
651 return $start_regexp;
654 function getEndRegexp ($match) {
655 $chr = preg_quote($match);
656 return "(?<= \S | ^ ) (?<! $chr) $chr (?! $chr) (?= \s | [-)}>\"'\\/:.,;!? _*=] | $)";
659 function markup ($match, $body) {
661 case '*': return new HtmlElement('b', $body);
662 case '=': return new HtmlElement('tt', $body);
663 case '_': return new HtmlElement('i', $body);
668 class Markup_html_emphasis extends BalancedMarkup
671 "<(?: b|big|i|small|tt|em|strong|cite|code|dfn|kbd|samp|s|strike|del|var|sup|sub )>";
673 function getEndRegexp ($match) {
674 return "<\\/" . substr($match, 1);
677 function markup ($match, $body) {
678 $tag = substr($match, 1, -1);
679 return new HtmlElement($tag, $body);
683 class Markup_html_divspan extends BalancedMarkup
686 "<(?: div|span )(?: \s[^>]*)?>";
688 function getEndRegexp ($match) {
689 if (substr($match,1,4) == 'span')
693 return "<\\/" . $tag . '>';
696 function markup ($match, $body) {
697 if (substr($match,1,4) == 'span')
701 $rest = substr($match,1+strlen($tag),-1);
703 list($key,$val) = explode("=",$rest);
704 $args = array($key => $val);
705 } else $args = array();
706 return new HtmlElement($tag, $args, $body);
711 class Markup_html_abbr extends BalancedMarkup
713 //rurban: abbr|acronym need an optional title tag.
715 var $_start_regexp = "<(?: abbr|acronym )(?: \stitle=[^>]*)?>";
717 function getEndRegexp ($match) {
718 if (substr($match,1,4) == 'abbr')
722 return "<\\/" . $tag . '>';
725 function markup ($match, $body) {
726 if (substr($match,1,4) == 'abbr')
730 $rest = substr($match,1+strlen($tag),-1);
732 list($key,$val) = explode("=",$rest);
733 $args = array($key => $val);
734 } else $args = array();
735 return new HtmlElement($tag, $args, $body);
739 /** ENABLE_MARKUP_COLOR
740 * See http://www.pmwiki.org/wiki/PmWiki/WikiStyles and
741 * http://www.flexwiki.com/default.aspx/FlexWiki/FormattingRules.html
743 class Markup_color extends BalancedMarkup {
744 // %color=blue% blue text %% and back to normal
745 var $_start_regexp = "%color=(?: [^%]*)%";
746 var $_end_regexp = "%%";
748 function markup ($match, $body) {
749 $color = strtoupper(substr($match, 7, -1));
750 if (strlen($color) != 7
751 and in_array($color, array('RED', 'BLUE', 'GRAY', 'YELLOW', 'GREEN', 'CYAN', 'BLACK')))
752 { // must be a valid color name
753 return new HtmlElement('font', array('color' => $color), $body);
754 } elseif ((substr($color,0,1) == '#')
755 and (strspn(substr($color,1),'0123456789ABCDEF') == strlen($color)-1)) {
756 return new HtmlElement('font', array('color' => $color), $body);
758 trigger_error(sprintf(_("unknown color %s ignored"), substr($match, 7, -1)), E_USER_WARNING);
764 // Special version for single-line plugins formatting,
765 // like: '<small>< ?plugin PopularNearby ? ></small>'
766 class Markup_plugin extends SimpleMarkup
768 var $_match_regexp = '<\?plugin(?:-form)?\s[^\n]+?\?>';
770 function markup ($match) {
771 //$xml = new Cached_PluginInvocation($match);
772 //$xml->setTightness(true,true);
773 return new Cached_PluginInvocation($match);
777 // Special version for plugins in xml syntax
778 // <name arg=value>body</name> or <name /> => < ? plugin pluginname arg=value body ? >
779 // PLUGIN_MARKUP_MAP = "html:RawHtml dot:GraphViz toc:CreateToc amath:AsciiMath richtable:RichTable include:IncludePage tex:TexToPng"
780 class Markup_xml_plugin extends BalancedMarkup
782 //var $_start_regexp = "<(?: ".join('|',PLUGIN_MARKUP_MAP)." )(?: \s[^>]*)>";
784 function getStartRegexp () {
785 global $PLUGIN_MARKUP_MAP;
786 static $_start_regexp;
787 if ($_start_regexp) return $_start_regexp;
788 if (empty($PLUGIN_MARKUP_MAP))
790 //"<(?: html|dot|toc|amath|richtable|include|tex )(?: \s[^>]*)>"
791 $_start_regexp = "<(?: ".join('|',array_keys($PLUGIN_MARKUP_MAP))." )(?: \s[^>]* | / )>";
792 return $_start_regexp;
794 function getEndRegexp ($match) {
795 return "<\\/" . $match . '>';
797 function markup ($match, $body) {
798 global $PLUGIN_MARKUP_MAP;
799 $name = substr($match,2,-2);
801 if (preg_match('/^(\S+)\|(.*)$/', $name, $_m)) {
803 $vars = $_m[2]; //str_replace(' ', '&', $_m[2]);
805 if (!isset($PLUGIN_MARKUP_MAP[$name])) {
806 trigger_error("No plugin for $name $vars defined.", E_USER_WARNING);
809 $plugin = $PLUGIN_MARKUP_MAP[$name];
810 return new Cached_PluginInvocation("<"."?plugin $plugin $vars $body ?".">");
814 /** ENABLE_MARKUP_TEMPLATE
815 * Template syntax similar to mediawiki
817 * => < ? plugin Template page=template ? >
818 * {{template|var1=value1|var2=value|...}}
819 * => < ? plugin Template page=template var=value ... ? >
821 class Markup_template_plugin extends SimpleMarkup
823 // patch #1732793: allow \n, mult. {{ }} in one line, and single letters
824 var $_match_regexp = '\{\{.*?\}\}';
826 function markup ($match) {
827 $page = substr(str_replace("\n", "", $match),2,-2); $vars = '';
828 if (preg_match('/^(\S+?)\|(.*)$/', $page, $_m)) {
830 $vars = '"' . preg_replace('/\|/', '" "', $_m[2]) . '"';
831 $vars = preg_replace('/"(\S+)=([^"]*)"/', '\\1="\\2"', $vars);
834 $s = '<'.'?plugin Template page="'.$page.'" '.$vars.' ?'.'>';
836 $s = '<'.'?plugin Template page="' . $page . '" ?'.'>';
837 return new Cached_PluginInvocation($s);
841 /** ENABLE_MARKUP_MEDIAWIKI_TABLE
842 * Table syntax similar to mediawiki
844 * => <?plugin MediawikiTable
848 class Markup_mediawikitable_plugin extends SimpleMarkup
850 var $_match_regexp = '\{\|.*?\|\}';
852 function markup ($match) {
853 $s = str_replace("{|", "", $match);
854 $s = str_replace("|}", "", $s);
855 $s = '<'.'?plugin MediawikiTable ' . $s . '?'.'>';
856 return new Cached_PluginInvocation($s);
860 // "..." => "…" browser specific display (not cached?)
861 // Support some HTML::Entities: (C) for copy, --- for mdash, -- for ndash
862 // TODO: "--" => "&emdash;" browser specific display (not cached?)
864 class Markup_html_entities extends SimpleMarkup {
865 //var $_match_regexp = '(: \.\.\.|\-\-|\-\-\-|\(C\) )';
867 function Markup_html_entities() {
868 $this->_entities = array('...' => '…',
872 '©' => '©',
873 '™' => '™',
875 $this->_match_regexp =
877 join('|', array_map('preg_quote', array_keys($this->_entities))) .
881 function markup ($match) {
882 return HTML::Raw($this->_entities[$match]);
886 class Markup_isonumchars extends SimpleMarkup {
887 var $_match_regexp = '\&\#\d{2,5};';
889 function markup ($match) {
890 return HTML::Raw($match);
894 class Markup_isohexchars extends SimpleMarkup {
895 // hexnums, like ¤ <=> ¤
896 var $_match_regexp = '\&\#x[0-9a-fA-F]{2,4};';
898 function markup ($match) {
899 return HTML::Raw($match);
903 // FIXME: Do away with magic phpwiki forms. (Maybe phpwiki: links too?)
904 // FIXME: Do away with plugin-links. They seem not to be used.
907 class InlineTransformer
909 var $_regexps = array();
910 var $_markup = array();
912 function InlineTransformer ($markup_types = false) {
914 // We need to extend the inline parsers by certain actions, like SearchHighlight,
915 // SpellCheck and maybe CreateToc.
916 if (!$markup_types) {
917 $non_default = false;
918 $markup_types = array
919 ('escape', 'bracketlink', 'url',
920 'interwiki', 'semanticlink', 'wikiword', 'linebreak',
921 'wikicreole_subscript', 'old_emphasis', 'nestled_emphasis',
922 'html_emphasis', 'html_abbr', 'plugin',
923 'isonumchars', 'isohexchars', /*'html_entities'*/
925 if (DISABLE_MARKUP_WIKIWORD)
926 $markup_types = array_remove($markup_types, 'wikiword');
928 $action = $request->getArg('action');
929 if ($action == 'SpellCheck' and $request->getArg('suggestions'))
930 { // insert it after url
931 array_splice($markup_types, 2, 1, array('url','spellcheck'));
933 if (isset($request->_searchhighlight))
934 { // insert it after url
935 array_splice($markup_types, 2, 1, array('url','searchhighlight'));
936 //$request->setArg('searchhighlight', false);
941 foreach ($markup_types as $mtype) {
942 $class = "Markup_$mtype";
943 $this->_addMarkup(new $class);
945 if (ENABLE_MARKUP_DIVSPAN and !$non_default)
946 $this->_addMarkup(new Markup_html_divspan);
947 if (ENABLE_MARKUP_COLOR and !$non_default)
948 $this->_addMarkup(new Markup_color);
949 if (ENABLE_MARKUP_TEMPLATE and !$non_default)
950 $this->_addMarkup(new Markup_template_plugin);
951 if (ENABLE_MARKUP_MEDIAWIKI_TABLE)
952 $this->_addMarkup(new Markup_mediawikitable_plugin);
953 // This does not work yet
954 if (0 and PLUGIN_MARKUP_MAP and !$non_default)
955 $this->_addMarkup(new Markup_xml_plugin);
958 function _addMarkup ($markup) {
959 if (isa($markup, 'SimpleMarkup'))
960 $regexp = $markup->getMatchRegexp();
962 $regexp = $markup->getStartRegexp();
964 assert( !isset($this->_markup[$regexp]) );
965 assert( strlen(trim($regexp)) > 0 );
966 $this->_regexps[] = $regexp;
967 $this->_markup[] = $markup;
970 function parse (&$text, $end_regexps = array('$')) {
971 $regexps = $this->_regexps;
973 // $end_re takes precedence: "favor reduce over shift"
974 array_unshift($regexps, $end_regexps[0]);
975 //array_push($regexps, $end_regexps[0]);
976 $regexps = new RegexpSet($regexps);
979 $output = new XmlContent;
981 $match = $regexps->match($input);
984 if ($match->regexp_ind == 0) {
985 // No start pattern found before end pattern.
987 if (isset($markup) and is_object($markup)
988 and isa($markup,'Markup_plugin'))
990 $current =& $output->_content[count($output->_content)-1];
991 $current->setTightness(true,true);
993 $output->pushContent($match->prematch);
994 $text = $match->postmatch;
998 $markup = $this->_markup[$match->regexp_ind - 1];
999 $body = $this->_parse_markup_body($markup, $match->match,
1000 $match->postmatch, $end_regexps);
1002 // Couldn't match balanced expression.
1003 // Ignore and look for next matching start regexp.
1004 $match = $regexps->nextMatch($input, $match);
1008 // Matched markup. Eat input, push output.
1009 // FIXME: combine adjacent strings.
1010 if (isa($markup, 'SimpleMarkup'))
1011 $current = $markup->markup($match->match);
1013 $current = $markup->markup($match->match, $body);
1014 $input = $match->postmatch;
1015 if (isset($markup) and is_object($markup)
1016 and isa($markup,'Markup_plugin'))
1018 $current->setTightness(true,true);
1020 $output->pushContent($match->prematch, $current);
1022 $match = $regexps->match($input);
1025 // No pattern matched, not even the end pattern.
1030 function _parse_markup_body ($markup, $match, &$text, $end_regexps) {
1031 if (isa($markup, 'SimpleMarkup'))
1032 return true; // Done. SimpleMarkup is simple.
1034 if (!is_object($markup)) return false; // Some error: Should assert
1035 array_unshift($end_regexps, $markup->getEndRegexp($match));
1037 // Optimization: if no end pattern in text, we know the
1038 // parse will fail. This is an important optimization,
1039 // e.g. when text is "*lots *of *start *delims *with
1040 // *no *matching *end *delims".
1041 $ends_pat = "/(?:" . join(").*(?:", $end_regexps) . ")/xs";
1042 if (!preg_match($ends_pat, $text))
1044 return $this->parse($text, $end_regexps);
1048 class LinkTransformer extends InlineTransformer
1050 function LinkTransformer () {
1051 $this->InlineTransformer(array('escape', 'bracketlink', 'url',
1052 'semanticlink', 'interwiki', 'wikiword',
1057 class NowikiTransformer extends InlineTransformer
1059 function NowikiTransformer () {
1060 $this->InlineTransformer
1062 'html_emphasis', 'html_abbr', 'plugin',
1063 'isonumchars', 'isohexchars', /*'html_entities',*/
1068 function TransformInline($text, $markup = 2.0, $basepage=false) {
1070 $action = $GLOBALS['request']->getArg('action');
1071 if (empty($trfm) or $action == 'SpellCheck') {
1072 $trfm = new InlineTransformer;
1075 if ($markup < 2.0) {
1076 $text = ConvertOldMarkup($text, 'inline');
1080 return new CacheableMarkup($trfm->parse($text), $basepage);
1082 return $trfm->parse($text);
1085 function TransformLinks($text, $markup = 2.0, $basepage = false) {
1089 $trfm = new LinkTransformer;
1092 if ($markup < 2.0) {
1093 $text = ConvertOldMarkup($text, 'links');
1097 return new CacheableMarkup($trfm->parse($text), $basepage);
1099 return $trfm->parse($text);
1103 * Transform only html markup and entities.
1105 function TransformInlineNowiki($text, $markup = 2.0, $basepage=false) {
1109 $trfm = new NowikiTransformer;
1112 return new CacheableMarkup($trfm->parse($text), $basepage);
1114 return $trfm->parse($text);
1118 // $Log: not supported by cvs2svn $
1119 // Revision 1.99 2008/05/06 19:23:17 rurban
1122 // Revision 1.98 2008/03/21 20:35:52 rurban
1123 // Improve upon embedded ImgObject, such as [ *.mp3 ], objects.
1124 // Object tags now render as label correctly and param tags are also added.
1126 // Revision 1.97 2008/03/18 20:25:49 rurban
1127 // Fixed "\n" => " " in [ link parsing ] by suggestion of Marc-Etienne
1129 // Revision 1.96 2008/03/17 19:06:39 rurban
1130 // fix bug#1904088 Some brackets links with \n cause the parser to crash
1132 // Revision 1.95 2008/02/15 20:02:49 vargenau
1133 // Allow <s> to strike; update Help for <s> and <strike>
1135 // Revision 1.94 2008/01/31 20:40:10 vargenau
1136 // Implemented Mediawiki-like syntax for tables
1138 // Revision 1.93 2007/09/26 16:54:34 rurban
1139 // Fix Bug#1802827 Template does not get expanded with {{ }} syntax.
1142 // Revision 1.92 2007/08/10 21:58:01 rurban
1143 // Improve SemanticLink parsings:
1144 // No units seperated by space allowed without []
1145 // For :: (relations) only words, no comma,
1146 // but for := (attributes) comma and dots are allowed. Units with groupsep.
1147 // Ending dots or comma are not part of the link.
1149 // Revision 1.91 2007/06/07 18:56:57 rurban
1150 // patch #1732793: allow \n, mult. {{ }} in one line, and single
1151 // letters (slightly improved) by AlJeux and ReiniUrban
1153 // Revision 1.90 2007/03/18 17:35:14 rurban
1154 // Fix :DontStoreLink
1156 // Revision 1.89 2007/02/17 14:16:28 rurban
1157 // fix color GREY to GRAY
1159 // Revision 1.88 2007/01/21 13:15:50 rurban
1160 // Support spaces in attributes and relation links
1162 // Revision 1.87 2007/01/20 15:53:51 rurban
1163 // Rewrite of SearchHighlight: through ActionPage and InlineParser
1165 // Revision 1.86 2007/01/20 11:25:07 rurban
1166 // add SpellCheck support
1168 // Revision 1.85 2007/01/07 18:42:49 rurban
1169 // 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
1171 // Revision 1.84 2007/01/02 13:18:07 rurban
1172 // fix semantic attributes syntax :=, not :-, disable DIVSPAN and PLUGIN_MARKUP_MAP
1174 // Revision 1.83 2006/12/22 00:23:24 rurban
1175 // Fix Bug #1540007 "hardened-php issue, crawlers related"
1176 // Broken str_replace with strings > 200 chars
1178 // Revision 1.82 2006/12/02 19:53:05 rurban
1179 // Simplify DISABLE_MARKUP_WIKIWORD handling by adding the new function
1180 // stdlib: array_remove(). Hopefully PHP will not add this natively sooner
1183 // Revision 1.81 2006/11/19 13:52:52 rurban
1184 // improve debug output: regex only once
1186 // Revision 1.80 2006/10/12 06:32:30 rurban
1187 // Optionally support new tags <div>, <span> with ENABLE_MARKUP_DIVSPAN (in work)
1189 // Revision 1.79 2006/10/08 12:38:11 rurban
1190 // New special interwiki link markup [:LinkTo] without storing the backlink
1192 // Revision 1.78 2006/09/03 09:53:52 rurban
1193 // more colors, case-insensitive color names
1195 // Revision 1.77 2006/08/25 19:02:02 rurban
1196 // patch #1348996 by Robert Litwiniec: fix show image semantics if label is given
1198 // Revision 1.76 2006/08/19 11:02:35 rurban
1199 // add strike and del to html emphasis: Patch #1542894 by Kai Krakow
1201 // Revision 1.75 2006/08/15 13:43:10 rurban
1202 // add Markup_xml_plugin (untested) and fix Markup_template_plugin
1204 // Revision 1.74 2006/07/23 14:03:18 rurban
1205 // add new feature: DISABLE_MARKUP_WIKIWORD
1207 // Revision 1.73 2006/04/15 12:20:36 rurban
1208 // fix relatives links patch by Joel Schaubert for [/
1210 // Revision 1.72 2006/03/07 20:43:29 rurban
1211 // relative external link, if no internal subpage. by joel Schaubert
1213 // Revision 1.71 2005/11/14 22:31:12 rurban
1214 // add SemanticWeb support
1216 // Revision 1.70 2005/10/31 16:45:23 rurban
1217 // added cfg-able markups only for default TextTransformation, not for links and others
1219 // Revision 1.69 2005/09/14 05:57:19 rurban
1220 // make ENABLE_MARKUP_TEMPLATE optional
1222 // Revision 1.68 2005/09/10 21:24:32 rurban
1223 // optionally support {{Template|vars}} syntax
1225 // Revision 1.67 2005/06/06 17:41:20 rurban
1226 // support new ENABLE_MARKUP_COLOR
1228 // Revision 1.66 2005/04/23 11:15:49 rurban
1229 // handle allowed inlined objects within INLINE_IMAGES
1231 // Revision 1.65 2005/03/27 18:24:17 rurban
1235 // (c-file-style: "gnu")
1239 // c-basic-offset: 4
1240 // c-hanging-comment-ender-p: nil
1241 // indent-tabs-mode: nil