2 rcs_id('$Id: InlineParser.php,v 1.99 2008-05-06 19:23:17 rurban 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_old_emphasis extends BalancedMarkup
588 var $_start_regexp = "''|__";
590 function getEndRegexp ($match) {
594 function markup ($match, $body) {
595 $tag = $match == "''" ? 'em' : 'strong';
596 return new HtmlElement($tag, $body);
600 class Markup_nestled_emphasis extends BalancedMarkup
602 function getStartRegexp() {
603 static $start_regexp = false;
605 if (!$start_regexp) {
606 // The three possible delimiters
607 // (none of which can be followed by itself.)
612 $any = "(?: ${i}|${b}|${tt})"; // any of the three.
614 // Any of [_*=] is okay if preceded by space or one of [-"'/:]
615 $start[] = "(?<= \\s|^|[-\"'\\/:]) ${any}";
617 // _ or * is okay after = as long as not immediately followed by =
618 $start[] = "(?<= =) (?: ${i}|${b}) (?! =)";
620 $start[] = "(?<= _) (?: ${b}|${tt}) (?! _)";
621 $start[] = "(?<= \\*) (?: ${i}|${tt}) (?! \\*)";
624 // any delimiter okay after an opening brace ( [{<(] )
625 // as long as it's not immediately followed by the matching closing
627 $start[] = "(?<= { ) ${any} (?! } )";
628 $start[] = "(?<= < ) ${any} (?! > )";
629 $start[] = "(?<= \\( ) ${any} (?! \\) )";
631 $start = "(?:" . join('|', $start) . ")";
633 // Any of the above must be immediately followed by non-whitespace.
634 $start_regexp = $start . "(?= \S)";
637 return $start_regexp;
640 function getEndRegexp ($match) {
641 $chr = preg_quote($match);
642 return "(?<= \S | ^ ) (?<! $chr) $chr (?! $chr) (?= \s | [-)}>\"'\\/:.,;!? _*=] | $)";
645 function markup ($match, $body) {
647 case '*': return new HtmlElement('b', $body);
648 case '=': return new HtmlElement('tt', $body);
649 case '_': return new HtmlElement('i', $body);
654 class Markup_html_emphasis extends BalancedMarkup
657 "<(?: b|big|i|small|tt|em|strong|cite|code|dfn|kbd|samp|s|strike|del|var|sup|sub )>";
659 function getEndRegexp ($match) {
660 return "<\\/" . substr($match, 1);
663 function markup ($match, $body) {
664 $tag = substr($match, 1, -1);
665 return new HtmlElement($tag, $body);
669 class Markup_html_divspan extends BalancedMarkup
672 "<(?: div|span )(?: \s[^>]*)?>";
674 function getEndRegexp ($match) {
675 if (substr($match,1,4) == 'span')
679 return "<\\/" . $tag . '>';
682 function markup ($match, $body) {
683 if (substr($match,1,4) == 'span')
687 $rest = substr($match,1+strlen($tag),-1);
689 list($key,$val) = explode("=",$rest);
690 $args = array($key => $val);
691 } else $args = array();
692 return new HtmlElement($tag, $args, $body);
697 class Markup_html_abbr extends BalancedMarkup
699 //rurban: abbr|acronym need an optional title tag.
701 var $_start_regexp = "<(?: abbr|acronym )(?: \stitle=[^>]*)?>";
703 function getEndRegexp ($match) {
704 if (substr($match,1,4) == 'abbr')
708 return "<\\/" . $tag . '>';
711 function markup ($match, $body) {
712 if (substr($match,1,4) == 'abbr')
716 $rest = substr($match,1+strlen($tag),-1);
718 list($key,$val) = explode("=",$rest);
719 $args = array($key => $val);
720 } else $args = array();
721 return new HtmlElement($tag, $args, $body);
725 /** ENABLE_MARKUP_COLOR
726 * See http://www.pmwiki.org/wiki/PmWiki/WikiStyles and
727 * http://www.flexwiki.com/default.aspx/FlexWiki/FormattingRules.html
729 class Markup_color extends BalancedMarkup {
730 // %color=blue% blue text %% and back to normal
731 var $_start_regexp = "%color=(?: [^%]*)%";
732 var $_end_regexp = "%%";
734 function markup ($match, $body) {
735 $color = strtoupper(substr($match, 7, -1));
736 if (strlen($color) != 7
737 and in_array($color, array('RED', 'BLUE', 'GRAY', 'YELLOW', 'GREEN', 'CYAN', 'BLACK')))
738 { // must be a valid color name
739 return new HtmlElement('font', array('color' => $color), $body);
740 } elseif ((substr($color,0,1) == '#')
741 and (strspn(substr($color,1),'0123456789ABCDEF') == strlen($color)-1)) {
742 return new HtmlElement('font', array('color' => $color), $body);
744 trigger_error(sprintf(_("unknown color %s ignored"), substr($match, 7, -1)), E_USER_WARNING);
750 // Special version for single-line plugins formatting,
751 // like: '<small>< ?plugin PopularNearby ? ></small>'
752 class Markup_plugin extends SimpleMarkup
754 var $_match_regexp = '<\?plugin(?:-form)?\s[^\n]+?\?>';
756 function markup ($match) {
757 //$xml = new Cached_PluginInvocation($match);
758 //$xml->setTightness(true,true);
759 return new Cached_PluginInvocation($match);
763 // Special version for plugins in xml syntax
764 // <name arg=value>body</name> or <name /> => < ? plugin pluginname arg=value body ? >
765 // PLUGIN_MARKUP_MAP = "html:RawHtml dot:GraphViz toc:CreateToc amath:AsciiMath richtable:RichTable include:IncludePage tex:TexToPng"
766 class Markup_xml_plugin extends BalancedMarkup
768 //var $_start_regexp = "<(?: ".join('|',PLUGIN_MARKUP_MAP)." )(?: \s[^>]*)>";
770 function getStartRegexp () {
771 global $PLUGIN_MARKUP_MAP;
772 static $_start_regexp;
773 if ($_start_regexp) return $_start_regexp;
774 if (empty($PLUGIN_MARKUP_MAP))
776 //"<(?: html|dot|toc|amath|richtable|include|tex )(?: \s[^>]*)>"
777 $_start_regexp = "<(?: ".join('|',array_keys($PLUGIN_MARKUP_MAP))." )(?: \s[^>]* | / )>";
778 return $_start_regexp;
780 function getEndRegexp ($match) {
781 return "<\\/" . $match . '>';
783 function markup ($match, $body) {
784 global $PLUGIN_MARKUP_MAP;
785 $name = substr($match,2,-2);
787 if (preg_match('/^(\S+)\|(.*)$/', $name, $_m)) {
789 $vars = $_m[2]; //str_replace(' ', '&', $_m[2]);
791 if (!isset($PLUGIN_MARKUP_MAP[$name])) {
792 trigger_error("No plugin for $name $vars defined.", E_USER_WARNING);
795 $plugin = $PLUGIN_MARKUP_MAP[$name];
796 return new Cached_PluginInvocation("<"."?plugin $plugin $vars $body ?".">");
800 /** ENABLE_MARKUP_TEMPLATE
801 * Template syntax similar to mediawiki
803 * => < ? plugin Template page=template ? >
804 * {{template|var1=value1|var2=value|...}}
805 * => < ? plugin Template page=template var=value ... ? >
807 class Markup_template_plugin extends SimpleMarkup
809 // patch #1732793: allow \n, mult. {{ }} in one line, and single letters
810 var $_match_regexp = '\{\{.*?\}\}';
812 function markup ($match) {
813 $page = substr(str_replace("\n", "", $match),2,-2); $vars = '';
814 if (preg_match('/^(\S+?)\|(.*)$/', $page, $_m)) {
816 $vars = '"' . preg_replace('/\|/', '" "', $_m[2]) . '"';
817 $vars = preg_replace('/"(\S+)=([^"]*)"/', '\\1="\\2"', $vars);
820 $s = '<'.'?plugin Template page="'.$page.'" '.$vars.' ?'.'>';
822 $s = '<'.'?plugin Template page="' . $page . '" ?'.'>';
823 return new Cached_PluginInvocation($s);
827 /** ENABLE_MARKUP_MEDIAWIKI_TABLE
828 * Table syntax similar to mediawiki
830 * => <?plugin MediawikiTable
834 class Markup_mediawikitable_plugin extends SimpleMarkup
836 var $_match_regexp = '\{\|.*?\|\}';
838 function markup ($match) {
839 $s = str_replace("{|", "", $match);
840 $s = str_replace("|}", "", $s);
841 $s = '<'.'?plugin MediawikiTable ' . $s . '?'.'>';
842 return new Cached_PluginInvocation($s);
846 // "..." => "…" browser specific display (not cached?)
847 // Support some HTML::Entities: (C) for copy, --- for mdash, -- for ndash
848 // TODO: "--" => "&emdash;" browser specific display (not cached?)
850 class Markup_html_entities extends SimpleMarkup {
851 //var $_match_regexp = '(: \.\.\.|\-\-|\-\-\-|\(C\) )';
853 function Markup_html_entities() {
854 $this->_entities = array('...' => '…',
858 '©' => '©',
859 '™' => '™',
861 $this->_match_regexp =
863 join('|', array_map('preg_quote', array_keys($this->_entities))) .
867 function markup ($match) {
868 return HTML::Raw($this->_entities[$match]);
872 class Markup_isonumchars extends SimpleMarkup {
873 var $_match_regexp = '\&\#\d{2,5};';
875 function markup ($match) {
876 return HTML::Raw($match);
880 class Markup_isohexchars extends SimpleMarkup {
881 // hexnums, like ¤ <=> ¤
882 var $_match_regexp = '\&\#x[0-9a-fA-F]{2,4};';
884 function markup ($match) {
885 return HTML::Raw($match);
889 // FIXME: Do away with magic phpwiki forms. (Maybe phpwiki: links too?)
890 // FIXME: Do away with plugin-links. They seem not to be used.
893 class InlineTransformer
895 var $_regexps = array();
896 var $_markup = array();
898 function InlineTransformer ($markup_types = false) {
900 // We need to extend the inline parsers by certain actions, like SearchHighlight,
901 // SpellCheck and maybe CreateToc.
902 if (!$markup_types) {
903 $non_default = false;
904 $markup_types = array
905 ('escape', 'bracketlink', 'url',
906 'interwiki', 'semanticlink', 'wikiword', 'linebreak',
907 'old_emphasis', 'nestled_emphasis',
908 'html_emphasis', 'html_abbr', 'plugin',
909 'isonumchars', 'isohexchars', /*'html_entities'*/
911 if (DISABLE_MARKUP_WIKIWORD)
912 $markup_types = array_remove($markup_types, 'wikiword');
914 $action = $request->getArg('action');
915 if ($action == 'SpellCheck' and $request->getArg('suggestions'))
916 { // insert it after url
917 array_splice($markup_types, 2, 1, array('url','spellcheck'));
919 if (isset($request->_searchhighlight))
920 { // insert it after url
921 array_splice($markup_types, 2, 1, array('url','searchhighlight'));
922 //$request->setArg('searchhighlight', false);
927 foreach ($markup_types as $mtype) {
928 $class = "Markup_$mtype";
929 $this->_addMarkup(new $class);
931 if (ENABLE_MARKUP_DIVSPAN and !$non_default)
932 $this->_addMarkup(new Markup_html_divspan);
933 if (ENABLE_MARKUP_COLOR and !$non_default)
934 $this->_addMarkup(new Markup_color);
935 if (ENABLE_MARKUP_TEMPLATE and !$non_default)
936 $this->_addMarkup(new Markup_template_plugin);
937 if (ENABLE_MARKUP_MEDIAWIKI_TABLE)
938 $this->_addMarkup(new Markup_mediawikitable_plugin);
939 // This does not work yet
940 if (0 and PLUGIN_MARKUP_MAP and !$non_default)
941 $this->_addMarkup(new Markup_xml_plugin);
944 function _addMarkup ($markup) {
945 if (isa($markup, 'SimpleMarkup'))
946 $regexp = $markup->getMatchRegexp();
948 $regexp = $markup->getStartRegexp();
950 assert( !isset($this->_markup[$regexp]) );
951 assert( strlen(trim($regexp)) > 0 );
952 $this->_regexps[] = $regexp;
953 $this->_markup[] = $markup;
956 function parse (&$text, $end_regexps = array('$')) {
957 $regexps = $this->_regexps;
959 // $end_re takes precedence: "favor reduce over shift"
960 array_unshift($regexps, $end_regexps[0]);
961 //array_push($regexps, $end_regexps[0]);
962 $regexps = new RegexpSet($regexps);
965 $output = new XmlContent;
967 $match = $regexps->match($input);
970 if ($match->regexp_ind == 0) {
971 // No start pattern found before end pattern.
973 if (isset($markup) and is_object($markup)
974 and isa($markup,'Markup_plugin'))
976 $current =& $output->_content[count($output->_content)-1];
977 $current->setTightness(true,true);
979 $output->pushContent($match->prematch);
980 $text = $match->postmatch;
984 $markup = $this->_markup[$match->regexp_ind - 1];
985 $body = $this->_parse_markup_body($markup, $match->match,
986 $match->postmatch, $end_regexps);
988 // Couldn't match balanced expression.
989 // Ignore and look for next matching start regexp.
990 $match = $regexps->nextMatch($input, $match);
994 // Matched markup. Eat input, push output.
995 // FIXME: combine adjacent strings.
996 if (isa($markup, 'SimpleMarkup'))
997 $current = $markup->markup($match->match);
999 $current = $markup->markup($match->match, $body);
1000 $input = $match->postmatch;
1001 if (isset($markup) and is_object($markup)
1002 and isa($markup,'Markup_plugin'))
1004 $current->setTightness(true,true);
1006 $output->pushContent($match->prematch, $current);
1008 $match = $regexps->match($input);
1011 // No pattern matched, not even the end pattern.
1016 function _parse_markup_body ($markup, $match, &$text, $end_regexps) {
1017 if (isa($markup, 'SimpleMarkup'))
1018 return true; // Done. SimpleMarkup is simple.
1020 if (!is_object($markup)) return false; // Some error: Should assert
1021 array_unshift($end_regexps, $markup->getEndRegexp($match));
1023 // Optimization: if no end pattern in text, we know the
1024 // parse will fail. This is an important optimization,
1025 // e.g. when text is "*lots *of *start *delims *with
1026 // *no *matching *end *delims".
1027 $ends_pat = "/(?:" . join(").*(?:", $end_regexps) . ")/xs";
1028 if (!preg_match($ends_pat, $text))
1030 return $this->parse($text, $end_regexps);
1034 class LinkTransformer extends InlineTransformer
1036 function LinkTransformer () {
1037 $this->InlineTransformer(array('escape', 'bracketlink', 'url',
1038 'semanticlink', 'interwiki', 'wikiword',
1043 class NowikiTransformer extends InlineTransformer
1045 function NowikiTransformer () {
1046 $this->InlineTransformer
1048 'html_emphasis', 'html_abbr', 'plugin',
1049 'isonumchars', 'isohexchars', /*'html_entities',*/
1054 function TransformInline($text, $markup = 2.0, $basepage=false) {
1056 $action = $GLOBALS['request']->getArg('action');
1057 if (empty($trfm) or $action == 'SpellCheck') {
1058 $trfm = new InlineTransformer;
1061 if ($markup < 2.0) {
1062 $text = ConvertOldMarkup($text, 'inline');
1066 return new CacheableMarkup($trfm->parse($text), $basepage);
1068 return $trfm->parse($text);
1071 function TransformLinks($text, $markup = 2.0, $basepage = false) {
1075 $trfm = new LinkTransformer;
1078 if ($markup < 2.0) {
1079 $text = ConvertOldMarkup($text, 'links');
1083 return new CacheableMarkup($trfm->parse($text), $basepage);
1085 return $trfm->parse($text);
1089 * Transform only html markup and entities.
1091 function TransformInlineNowiki($text, $markup = 2.0, $basepage=false) {
1095 $trfm = new NowikiTransformer;
1098 return new CacheableMarkup($trfm->parse($text), $basepage);
1100 return $trfm->parse($text);
1104 // $Log: not supported by cvs2svn $
1105 // Revision 1.98 2008/03/21 20:35:52 rurban
1106 // Improve upon embedded ImgObject, such as [ *.mp3 ], objects.
1107 // Object tags now render as label correctly and param tags are also added.
1109 // Revision 1.97 2008/03/18 20:25:49 rurban
1110 // Fixed "\n" => " " in [ link parsing ] by suggestion of Marc-Etienne
1112 // Revision 1.96 2008/03/17 19:06:39 rurban
1113 // fix bug#1904088 Some brackets links with \n cause the parser to crash
1115 // Revision 1.95 2008/02/15 20:02:49 vargenau
1116 // Allow <s> to strike; update Help for <s> and <strike>
1118 // Revision 1.94 2008/01/31 20:40:10 vargenau
1119 // Implemented Mediawiki-like syntax for tables
1121 // Revision 1.93 2007/09/26 16:54:34 rurban
1122 // Fix Bug#1802827 Template does not get expanded with {{ }} syntax.
1125 // Revision 1.92 2007/08/10 21:58:01 rurban
1126 // Improve SemanticLink parsings:
1127 // No units seperated by space allowed without []
1128 // For :: (relations) only words, no comma,
1129 // but for := (attributes) comma and dots are allowed. Units with groupsep.
1130 // Ending dots or comma are not part of the link.
1132 // Revision 1.91 2007/06/07 18:56:57 rurban
1133 // patch #1732793: allow \n, mult. {{ }} in one line, and single
1134 // letters (slightly improved) by AlJeux and ReiniUrban
1136 // Revision 1.90 2007/03/18 17:35:14 rurban
1137 // Fix :DontStoreLink
1139 // Revision 1.89 2007/02/17 14:16:28 rurban
1140 // fix color GREY to GRAY
1142 // Revision 1.88 2007/01/21 13:15:50 rurban
1143 // Support spaces in attributes and relation links
1145 // Revision 1.87 2007/01/20 15:53:51 rurban
1146 // Rewrite of SearchHighlight: through ActionPage and InlineParser
1148 // Revision 1.86 2007/01/20 11:25:07 rurban
1149 // add SpellCheck support
1151 // Revision 1.85 2007/01/07 18:42:49 rurban
1152 // 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
1154 // Revision 1.84 2007/01/02 13:18:07 rurban
1155 // fix semantic attributes syntax :=, not :-, disable DIVSPAN and PLUGIN_MARKUP_MAP
1157 // Revision 1.83 2006/12/22 00:23:24 rurban
1158 // Fix Bug #1540007 "hardened-php issue, crawlers related"
1159 // Broken str_replace with strings > 200 chars
1161 // Revision 1.82 2006/12/02 19:53:05 rurban
1162 // Simplify DISABLE_MARKUP_WIKIWORD handling by adding the new function
1163 // stdlib: array_remove(). Hopefully PHP will not add this natively sooner
1166 // Revision 1.81 2006/11/19 13:52:52 rurban
1167 // improve debug output: regex only once
1169 // Revision 1.80 2006/10/12 06:32:30 rurban
1170 // Optionally support new tags <div>, <span> with ENABLE_MARKUP_DIVSPAN (in work)
1172 // Revision 1.79 2006/10/08 12:38:11 rurban
1173 // New special interwiki link markup [:LinkTo] without storing the backlink
1175 // Revision 1.78 2006/09/03 09:53:52 rurban
1176 // more colors, case-insensitive color names
1178 // Revision 1.77 2006/08/25 19:02:02 rurban
1179 // patch #1348996 by Robert Litwiniec: fix show image semantics if label is given
1181 // Revision 1.76 2006/08/19 11:02:35 rurban
1182 // add strike and del to html emphasis: Patch #1542894 by Kai Krakow
1184 // Revision 1.75 2006/08/15 13:43:10 rurban
1185 // add Markup_xml_plugin (untested) and fix Markup_template_plugin
1187 // Revision 1.74 2006/07/23 14:03:18 rurban
1188 // add new feature: DISABLE_MARKUP_WIKIWORD
1190 // Revision 1.73 2006/04/15 12:20:36 rurban
1191 // fix relatives links patch by Joel Schaubert for [/
1193 // Revision 1.72 2006/03/07 20:43:29 rurban
1194 // relative external link, if no internal subpage. by joel Schaubert
1196 // Revision 1.71 2005/11/14 22:31:12 rurban
1197 // add SemanticWeb support
1199 // Revision 1.70 2005/10/31 16:45:23 rurban
1200 // added cfg-able markups only for default TextTransformation, not for links and others
1202 // Revision 1.69 2005/09/14 05:57:19 rurban
1203 // make ENABLE_MARKUP_TEMPLATE optional
1205 // Revision 1.68 2005/09/10 21:24:32 rurban
1206 // optionally support {{Template|vars}} syntax
1208 // Revision 1.67 2005/06/06 17:41:20 rurban
1209 // support new ENABLE_MARKUP_COLOR
1211 // Revision 1.66 2005/04/23 11:15:49 rurban
1212 // handle allowed inlined objects within INLINE_IMAGES
1214 // Revision 1.65 2005/03/27 18:24:17 rurban
1218 // (c-file-style: "gnu")
1222 // c-basic-offset: 4
1223 // c-hanging-comment-ender-p: nil
1224 // indent-tabs-mode: nil