3 /* Copyright (C) 2002 Geoffrey T. Dairiki <dairiki@dairiki.org>
4 * Copyright (C) 2004-2009 Reini Urban
5 * Copyright (C) 2008-2009 Marc-Etienne Vargenau, Alcatel-Lucent
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
32 * This is the character used in wiki markup to escape characters with
35 define('ESCAPE_CHAR', '~');
37 require_once(dirname(__FILE__).'/HtmlElement.php');
38 require_once('lib/CachedMarkup.php');
39 require_once(dirname(__FILE__).'/stdlib.php');
42 function WikiEscape($text) {
43 return str_replace('#', ESCAPE_CHAR . '#', $text);
46 function UnWikiEscape($text) {
47 return preg_replace('/' . ESCAPE_CHAR . '(.)/', '\1', $text);
51 * Return type from RegexpSet::match and RegexpSet::nextMatch.
55 class RegexpSet_match {
57 * The text leading up the the next match.
65 * The text following the matched text.
69 * Index of the regular expression which matched.
75 * A set of regular expressions.
77 * This class is probably only useful for InlineTransformer.
83 * @param array $regexps A list of regular expressions. The
84 * regular expressions should not include any sub-pattern groups
85 * "(...)". (Anonymous groups, like "(?:...)", as well as
86 * look-ahead and look-behind assertions are okay.)
88 function RegexpSet ($regexps) {
90 $this->_regexps = array_unique($regexps);
91 if (!defined('_INLINE_OPTIMIZATION')) define('_INLINE_OPTIMIZATION',0);
95 * Search text for the next matching regexp from the Regexp Set.
97 * @param string $text The text to search.
99 * @return RegexpSet_match A RegexpSet_match object, or false if no match.
101 function match ($text) {
102 return $this->_match($text, $this->_regexps, '*?');
106 * Search for next matching regexp.
108 * Here, 'next' has two meanings:
110 * Match the next regexp(s) in the set, at the same position as the last match.
112 * If that fails, match the whole RegexpSet, starting after the position of the
115 * @param string $text Text to search.
117 * @param RegexpSet_match $prevMatch A RegexpSet_match object.
118 * $prevMatch should be a match object obtained by a previous
119 * match upon the same value of $text.
121 * @return RegexpSet_match A RegexpSet_match object, or false if no match.
123 function nextMatch ($text, $prevMatch) {
124 // Try to find match at same position.
125 $pos = strlen($prevMatch->prematch);
126 $regexps = array_slice($this->_regexps, $prevMatch->regexp_ind + 1);
128 $repeat = sprintf('{%d}', $pos);
129 if ( ($match = $this->_match($text, $regexps, $repeat)) ) {
130 $match->regexp_ind += $prevMatch->regexp_ind + 1;
136 // Failed. Look for match after current position.
137 $repeat = sprintf('{%d,}?', $pos + 1);
138 return $this->_match($text, $this->_regexps, $repeat);
141 // Syntax: http://www.pcre.org/pcre.txt
142 // x - EXTENDED, ignore whitespace
146 function _match ($text, $regexps, $repeat) {
147 // If one of the regexps is an empty string, php will crash here:
148 // sf.net: Fatal error: Allowed memory size of 8388608 bytes exhausted
149 // (tried to allocate 634 bytes)
150 if (_INLINE_OPTIMIZATION) { // disabled, wrong
151 // So we try to minize memory usage, by looping explicitly,
152 // and storing only those regexp which actually match.
153 // There may be more than one, so we have to find the longest,
154 // and match inside until the shortest is empty.
155 $matched = array(); $matched_ind = array();
156 for ($i=0; $i<count($regexps); $i++) {
157 if (!trim($regexps[$i])) {
158 trigger_error("empty regexp $i", E_USER_WARNING);
161 $pat= "/ ( . $repeat ) ( " . $regexps[$i] . " ) /x";
162 if (preg_match($pat, $text, $_m)) {
163 $m = $_m; // FIXME: prematch, postmatch is wrong
164 $matched[] = $regexps[$i];
169 // To overcome ANCHORED:
170 // We could sort by longest match and iterate over these.
171 if (empty($matched)) return false;
173 $match = new RegexpSet_match;
175 // Optimization: if the matches are only "$" and another, then omit "$"
176 if (! _INLINE_OPTIMIZATION or count($matched) > 2) {
177 assert(!empty($repeat));
178 assert(!empty($regexps));
179 // We could do much better, if we would know the matching markup for the
180 // longest regexp match:
181 $hugepat= "/ ( . $repeat ) ( (" . join(')|(', $regexps) . ") ) /Asx";
182 // Proposed premature optimization 1:
183 //$hugepat= "/ ( . $repeat ) ( (" . join(')|(', array_values($matched)) . ") ) /Asx";
184 if (! preg_match($hugepat, $text, $m)) {
187 // Proposed premature optimization 1:
188 //$match->regexp_ind = $matched_ind[count($m) - 4];
189 $match->regexp_ind = count($m) - 4;
191 $match->regexp_ind = $regexp_ind;
194 $match->postmatch = substr($text, strlen($m[0]));
195 $match->prematch = $m[1];
196 $match->match = $m[2];
199 if (DEBUG & _DEBUG_PARSER) {
200 static $_already_dumped = 0;
201 if (!$_already_dumped) {
203 if (_INLINE_OPTIMIZATION)
205 var_dump($matched_ind);
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=<percent>%, size=<width>x<height>
315 * border=n, align=\w+, hspace=n, vspace=n
317 * title, lang, id, alt
319 function isImageLink($link) {
320 if (!$link) return false;
321 assert(defined('INLINE_IMAGES'));
322 return preg_match("/\\.(" . INLINE_IMAGES . ")/i", $link);
325 function LinkBracketLink($bracketlink) {
327 // $bracketlink will start and end with brackets; in between will
328 // be either a page name, a URL or both separated by a pipe.
330 $wikicreolesyntax = false;
332 if (string_starts_with($bracketlink, "[[") or string_starts_with($bracketlink, "#[[")) {
333 $wikicreolesyntax = true;
334 $bracketlink = str_replace("[[", "[", $bracketlink);
335 $bracketlink = str_replace("]]", "]", $bracketlink);
338 // Strip brackets and leading space
339 // bug#1904088 Some brackets links on 2 lines cause the parser to crash
340 preg_match('/(\#?) \[\s* (?: (.*?) \s* (?<!' . ESCAPE_CHAR . ')(\|) )? \s* (.+?) \s*\]/x',
341 str_replace("\n", " ", $bracketlink), $matches);
342 if (count($matches) < 4) {
343 // "[ personal\ninformation manager | PhpWiki:PersonalWiki ]"
344 trigger_error(_("Invalid [] syntax ignored").": ".$bracketlink, E_USER_WARNING);
345 return new Cached_Link;
347 list (, $hash, $label, $bar, $rawlink) = $matches;
349 if ($wikicreolesyntax and $label) {
355 // Mediawiki compatibility: allow "Image:" and "File:"
356 // as synonyms of "Upload:"
357 if (string_starts_with($rawlink, "Image:")) {
358 $rawlink = str_replace("Image:", "Upload:", $rawlink);
360 if (string_starts_with($rawlink, "File:")) {
361 $rawlink = str_replace("File:", "Upload:", $rawlink);
364 $label = UnWikiEscape($label);
366 * Check if the user has typed a explicit URL. This solves the
367 * problem where the URLs have a ~ character, which would be stripped away.
368 * "[http:/server/~name/]" will work as expected
369 * "http:/server/~name/" will NOT work as expected, will remove the ~
371 if ( string_starts_with ($rawlink, "http://")
372 or string_starts_with ($rawlink, "https://") )
375 // Mozilla Browser URI Obfuscation Weakness 2004-06-14
376 // http://www.securityfocus.com/bid/10532/
377 // goodurl+"%2F%20%20%20."+badurl
378 if (preg_match("/%2F(%20)+\./i", $rawlink)) {
379 $rawlink = preg_replace("/%2F(%20)+\./i","%2F.",$rawlink);
382 $link = UnWikiEscape($rawlink);
384 /* Relatives links by Joel Schaubert.
385 * Recognize [../bla] or [/bla] as relative links, without needing http://
386 * but [ /link ] only if SUBPAGE_SEPERATOR is not "/".
387 * Normally /Page links to the subpage /Page.
389 if (SUBPAGE_SEPARATOR == '/') {
390 if (preg_match('/^\.\.\//', $link)) {
391 return new Cached_ExternalLink($link, $label);
393 } else if (preg_match('/^(\.\.\/|\/)/', $link)) {
394 return new Cached_ExternalLink($link, $label);
397 // Handle "[[SandBox|{{image.jpg}}]]" and "[[SandBox|{{image.jpg|alt text}}]]"
398 if (string_starts_with($label, "{{")) {
399 $imgurl = substr($label, 2, -2); // Remove "{{" and "}}"
400 $pipe = strpos($imgurl, '|');
401 if ($pipe === false) {
402 $label = LinkImage(getUploadDataPath() . $imgurl, $link);
404 list($img, $alt) = explode("|", $imgurl);
405 $label = LinkImage(getUploadDataPath() . $img, $alt);
410 // If label looks like a url to an image or object, we want an image link.
411 if (isImageLink($label)) {
413 $intermap = getInterwikiMap();
414 if (preg_match("/^" . $intermap->getRegexp() . ":/", $label)) {
415 $imgurl = $intermap->link($label);
416 $imgurl = $imgurl->getAttr('href');
417 } elseif (! preg_match("#^(" . ALLOWED_PROTOCOLS . "):#", $imgurl)) {
418 // local theme linkname like 'images/next.gif'.
420 $imgurl = $WikiTheme->getImageURL($imgurl);
422 // for objects (non-images) the link is taken as alt tag,
423 // which is in return taken as alternative img
424 $label = LinkImage($imgurl, $link);
428 // It's an anchor, not a link...
429 $id = MangleXmlIdentifier($link);
430 return HTML::a(array('name' => $id, 'id' => $id),
431 $bar ? $label : $link);
434 if (preg_match("#^(" . ALLOWED_PROTOCOLS . "):#", $link)) {
435 // if it's an image, embed it; otherwise, it's a regular link
436 if (isImageLink($link) and empty($label)) // patch #1348996 by Robert Litwiniec
437 return LinkImage($link, $label);
439 return new Cached_ExternalLink($link, $label);
441 elseif (substr($link,0,8) == 'phpwiki:')
442 return new Cached_PhpwikiURL($link, $label);
444 /* Semantic relations and attributes.
445 * Relation and attribute names must be word chars only, no space.
446 * Links and Attributes may contain everything. word, nums, units, space, groupsep, numsep, ...
448 elseif (preg_match("/^ (\w+) (:[:=]) (.*) $/x", $link) and !isImageLink($link))
449 return new Cached_SemanticLink($link, $label);
451 /* Do not store the link */
452 elseif (substr($link,0,1) == ':')
453 return new Cached_WikiLink($link, $label);
456 * Inline images in Interwiki urls's:
457 * [File:my_image.gif] inlines the image,
458 * File:my_image.gif shows a plain inter-wiki link,
459 * [what a pic|File:my_image.gif] shows a named inter-wiki link to the gif
460 * [File:my_image.gif|what a pic] shows an inlined image linked to the page "what a pic"
462 * Note that for simplicity we will accept embedded object tags (non-images)
463 * here also, and seperate them later in LinkImage()
465 elseif (strstr($link,':')
466 and ($intermap = getInterwikiMap())
467 and preg_match("/^" . $intermap->getRegexp() . ":/", $link))
469 // trigger_error("label: $label link: $link", E_USER_WARNING);
470 if (empty($label) and isImageLink($link)) {
471 // if without label => inlined image [File:xx.gif]
472 $imgurl = $intermap->link($link);
473 return LinkImage($imgurl->getAttr('href'));
475 return new Cached_InterwikiLink($link, $label);
477 // Split anchor off end of pagename.
478 if (preg_match('/\A(.*)(?<!'.ESCAPE_CHAR.')#(.*?)\Z/', $rawlink, $m)) {
479 list(,$rawlink,$anchor) = $m;
480 $pagename = UnWikiEscape($rawlink);
481 $anchor = UnWikiEscape($anchor);
489 return new Cached_WikiLink($pagename, $label, $anchor);
493 class Markup_wikicreolebracketlink extends SimpleMarkup
495 var $_match_regexp = "\\#? \\[\\[ .*? [^]\\s] .*? \\]\\]";
497 function markup ($match) {
498 $link = LinkBracketLink($match);
499 assert($link->isInlineElement());
504 class Markup_bracketlink extends SimpleMarkup
506 var $_match_regexp = "\\#? \\[ .*? [^]\\s] .*? \\]";
508 function markup ($match) {
509 $link = LinkBracketLink($match);
510 assert($link->isInlineElement());
515 class Markup_spellcheck extends SimpleMarkup
517 function Markup_spellcheck () {
518 $this->suggestions = $GLOBALS['request']->getArg('suggestions');
520 function getMatchRegexp () {
521 if (empty($this->suggestions))
522 return "(?# false )";
523 $words = array_keys($this->suggestions);
524 return "(?<= \W ) (?:" . join('|', $words) . ") (?= \W )";
527 function markup ($match) {
528 if (empty($this->suggestions) or empty($this->suggestions[$match]))
530 return new Cached_SpellCheck(UnWikiEscape($match), $this->suggestions[$match]);
534 class Markup_searchhighlight extends SimpleMarkup
536 function Markup_searchhighlight () {
537 $result = $GLOBALS['request']->_searchhighlight;
538 require_once("lib/TextSearchQuery.php");
539 $query = new TextSearchQuery($result['query']);
540 $this->hilight_re = $query->getHighlightRegexp();
541 $this->engine = $result['engine'];
543 function getMatchRegexp () {
544 return $this->hilight_re;
546 function markup ($match) {
547 return new Cached_SearchHighlight(UnWikiEscape($match), $this->engine);
551 class Markup_url extends SimpleMarkup
553 function getMatchRegexp () {
554 return "(?<![[:alnum:]]) (?:" . ALLOWED_PROTOCOLS . ") : [^\s<>\"']+ (?<![ ,.?; \] \) ])";
557 function markup ($match) {
558 return new Cached_ExternalLink(UnWikiEscape($match));
562 class Markup_interwiki extends SimpleMarkup
564 function getMatchRegexp () {
565 $map = getInterwikiMap();
566 return "(?<! [[:alnum:]])" . $map->getRegexp(). ": [^:=]\S+ (?<![ ,.?;! \] \) \" \' ])";
569 function markup ($match) {
570 return new Cached_InterwikiLink(UnWikiEscape($match));
574 class Markup_semanticlink extends SimpleMarkup
576 // No units seperated by space allowed here
577 // For :: (relations) only words, no comma,
578 // but for := (attributes) comma and dots are allowed. Units with groupsep.
579 // Ending dots or comma are not part of the link.
580 var $_match_regexp = "(?: \w+:=\S+(?<![\.,]))|(?: \w+::[\w\.]+(?<!\.))";
582 function markup ($match) {
583 return new Cached_SemanticLink(UnWikiEscape($match));
587 class Markup_wikiword extends SimpleMarkup
589 function getMatchRegexp () {
590 global $WikiNameRegexp;
591 if (!trim($WikiNameRegexp)) return " " . WIKI_NAME_REGEXP;
592 return " $WikiNameRegexp";
595 function markup ($match) {
596 if (!$match) return false;
597 if ($this->_isWikiUserPage($match))
598 return new Cached_UserLink($match); //$this->_UserLink($match);
600 return new Cached_WikiLink($match);
603 // FIXME: there's probably a more useful place to put these two functions
604 function _isWikiUserPage ($page) {
606 $dbi = $request->getDbh();
607 $page_handle = $dbi->getPage($page);
608 if ($page_handle and $page_handle->get('pref'))
614 function _UserLink($PageName) {
615 $link = HTML::a(array('href' => $PageName));
616 $link->pushContent(PossiblyGlueIconToText('wikiuser', $PageName));
617 $link->setAttr('class', 'wikiuser');
622 class Markup_linebreak extends SimpleMarkup
624 //var $_match_regexp = "(?: (?<! %) %%% (?! %) | <(?:br|BR)> | <(?:br|BR) \/> )";
625 var $_match_regexp = "(?: (?<! %) %%% (?! %) | \\\\\\\\ | <(?:br|BR)> )";
627 function markup ($match) {
632 class Markup_wikicreole_italics extends BalancedMarkup
634 var $_start_regexp = "\\/\\/";
636 function getEndRegexp ($match) {
640 function markup ($match, $body) {
642 return new HtmlElement($tag, $body);
646 class Markup_wikicreole_bold extends BalancedMarkup
648 var $_start_regexp = "\\*\\*";
650 function getEndRegexp ($match) {
654 function markup ($match, $body) {
656 return new HtmlElement($tag, $body);
660 class Markup_wikicreole_monospace extends BalancedMarkup
662 var $_start_regexp = "\\#\\#";
664 function getEndRegexp ($match) {
668 function markup ($match, $body) {
670 return new HtmlElement($tag, $body);
674 class Markup_wikicreole_superscript extends BalancedMarkup
676 var $_start_regexp = "\\^\\^";
678 function getEndRegexp ($match) {
682 function markup ($match, $body) {
684 return new HtmlElement($tag, $body);
688 class Markup_wikicreole_subscript extends BalancedMarkup
690 var $_start_regexp = ",,";
692 function getEndRegexp ($match) {
696 function markup ($match, $body) {
698 return new HtmlElement($tag, $body);
702 class Markup_old_emphasis extends BalancedMarkup
704 var $_start_regexp = "''|__";
706 function getEndRegexp ($match) {
710 function markup ($match, $body) {
711 $tag = $match == "''" ? 'em' : 'strong';
712 return new HtmlElement($tag, $body);
716 class Markup_nestled_emphasis extends BalancedMarkup
718 function getStartRegexp() {
719 static $start_regexp = false;
721 if (!$start_regexp) {
722 // The three possible delimiters
723 // (none of which can be followed by itself.)
728 $any = "(?: ${i}|${b}|${tt})"; // any of the three.
730 // Any of [_*=] is okay if preceded by space or one of [-"'/:]
731 $start[] = "(?<= \\s|^|[-\"'\\/:]) ${any}";
733 // _ or * is okay after = as long as not immediately followed by =
734 $start[] = "(?<= =) (?: ${i}|${b}) (?! =)";
736 $start[] = "(?<= _) (?: ${b}|${tt}) (?! _)";
737 $start[] = "(?<= \\*) (?: ${i}|${tt}) (?! \\*)";
740 // any delimiter okay after an opening brace ( [{<(] )
741 // as long as it's not immediately followed by the matching closing
743 $start[] = "(?<= { ) ${any} (?! } )";
744 $start[] = "(?<= < ) ${any} (?! > )";
745 $start[] = "(?<= \\( ) ${any} (?! \\) )";
747 $start = "(?:" . join('|', $start) . ")";
749 // Any of the above must be immediately followed by non-whitespace.
750 $start_regexp = $start . "(?= \S)";
753 return $start_regexp;
756 function getEndRegexp ($match) {
757 $chr = preg_quote($match);
758 return "(?<= \S | ^ ) (?<! $chr) $chr (?! $chr) (?= \s | [-)}>\"'\\/:.,;!? _*=] | $)";
761 function markup ($match, $body) {
763 case '*': return new HtmlElement('b', $body);
764 case '=': return new HtmlElement('tt', $body);
765 case '_': return new HtmlElement('i', $body);
770 class Markup_html_emphasis extends BalancedMarkup
773 "<(?: b|big|i|small|tt|em|strong|cite|code|dfn|kbd|samp|s|strike|del|var|sup|sub )>";
775 function getEndRegexp ($match) {
776 return "<\\/" . substr($match, 1);
779 function markup ($match, $body) {
780 $tag = substr($match, 1, -1);
781 return new HtmlElement($tag, $body);
785 class Markup_html_divspan extends BalancedMarkup
788 "<(?: div|span )(?: \s[^>]*)?>";
790 function getEndRegexp ($match) {
791 if (substr($match,1,4) == 'span')
795 return "<\\/" . $tag . '>';
798 function markup ($match, $body) {
799 if (substr($match,1,4) == 'span')
803 $rest = substr($match,1+strlen($tag),-1);
805 $args = parse_attributes($rest);
809 return new HtmlElement($tag, $args, $body);
814 class Markup_html_abbr extends BalancedMarkup
816 //rurban: abbr|acronym need an optional title tag.
818 var $_start_regexp = "<(?: abbr|acronym )(?: [^>]*)?>";
820 function getEndRegexp ($match) {
821 if (substr($match,1,4) == 'abbr')
825 return "<\\/" . $tag . '>';
828 function markup ($match, $body) {
829 if (substr($match,1,4) == 'abbr')
833 $rest = substr($match,1+strlen($tag),-1);
834 $attrs = parse_attributes($rest);
835 // Remove attributes other than title and lang
836 $allowedargs = array();
837 foreach ($attrs as $key => $value) {
838 if (in_array ($key, array("title", "lang"))) {
839 $allowedargs[$key] = $value;
842 return new HtmlElement($tag, $allowedargs, $body);
846 /** ENABLE_MARKUP_COLOR
847 * See http://www.pmwiki.org/wiki/PmWiki/WikiStyles and
848 * http://www.flexwiki.com/default.aspx/FlexWiki/FormattingRules.html
850 class Markup_color extends BalancedMarkup {
851 // %color=blue% blue text %% and back to normal
852 var $_start_regexp = "%color=(?: [^%]*)%";
853 var $_end_regexp = "%%";
855 function markup ($match, $body) {
856 $color = strtolower(substr($match, 7, -1));
858 $morecolors = array('beige' => '#f5f5dc',
859 'brown' => '#a52a2a',
860 'chocolate' => '#d2691e',
863 'ivory' => '#fffff0',
864 'indigo' => '#4b0082',
865 'magenta' => '#ff00ff',
866 'orange' => '#ffa500',
868 'salmon' => '#fa8072',
870 'turquoise' => '#40e0d0',
871 'violet' => '#ee82ee',
874 if (isset($morecolors[$color])) {
875 $color = $morecolors[$color];
878 // HTML 4 defines the following 16 colors
879 if (in_array($color, array('aqua', 'black', 'blue', 'fuchsia',
880 'gray', 'green', 'lime', 'maroon',
881 'navy', 'olive', 'purple', 'red',
882 'silver', 'teal', 'white', 'yellow'))
883 or ((substr($color,0,1) == '#')
884 and ((strlen($color) == 4) or (strlen($color) == 7))
885 and (strspn(substr($color,1),'0123456789abcdef') == strlen($color)-1))) {
886 return new HtmlElement('span', array('style' => "color: $color"), $body);
888 return new HtmlElement('span', array('class' => 'error'),
889 sprintf(_("unknown color %s ignored"), substr($match, 7, -1)));
894 // Wikicreole placeholder
896 class Markup_placeholder extends SimpleMarkup
898 var $_match_regexp = '<<<.*?>>>';
900 function markup ($match) {
901 return HTML::span($match);
905 // Single-line HTML comment
906 // <!-- This is a comment -->
907 class Markup_html_comment extends SimpleMarkup
909 var $_match_regexp = '<!--.*?-->';
911 function markup ($match) {
912 return HTML::raw('');
916 // Special version for single-line plugins formatting,
917 // like: '<small>< ?plugin PopularNearby ? ></small>'
918 class Markup_plugin extends SimpleMarkup
920 var $_match_regexp = '<\?plugin(?:-form)?\s[^\n]+?\?>';
922 function markup ($match) {
923 return new Cached_PluginInvocation($match);
927 // Special version for single-line Wikicreole plugins formatting.
928 class Markup_plugin_wikicreole extends SimpleMarkup
930 var $_match_regexp = '<<[^\n]+?>>';
932 function markup ($match) {
933 $pi = str_replace("<<", "<?plugin ", $match);
934 $pi = str_replace(">>", " ?>", $pi);
935 return new Cached_PluginInvocation($pi);
941 * <nowiki>...</nowiki>
943 class Markup_nowiki extends SimpleMarkup
945 var $_match_regexp = '<nowiki>.*?<\/nowiki>';
947 function markup ($match) {
948 // Remove <nowiki> and </nowiki>
949 return HTML::raw(substr($match, 8, -9));
954 * Wikicreole preformatted
958 class Markup_wikicreole_preformatted extends SimpleMarkup
960 var $_match_regexp = '\{\{\{.*?\}\}\}';
962 function markup ($match) {
963 // Remove {{{ and }}}
964 return new HtmlElement('tt', substr($match, 3, -3));
969 * Template syntax similar to Mediawiki
971 * => < ? plugin Template page=template ? >
972 * {{template|var1=value1|var2=value|...}}
973 * => < ? plugin Template page=template var=value ... ? >
975 * The {{...}} syntax is also used for:
976 * - Wikicreole images
980 class Markup_template_plugin extends SimpleMarkup
982 // patch #1732793: allow \n, mult. {{ }} in one line, and single letters
983 var $_match_regexp = '\{\{.*?\}\}';
985 function markup ($match) {
987 $page = substr($match,2,-2);
989 // Check for predefined icons.
990 $predefinedicons = array(":)" => "ic_smile.png",
991 ":(" => "ic_sad.png",
992 ":P" => "ic_tongue.png",
993 ":D" => "ic_biggrin.png",
994 ";)" => "ic_wink.png",
995 "(y)" => "ic_handyes.png",
996 "(n)" => "ic_handno.png",
997 "(i)" => "ic_info.png",
998 "(/)" => "ic_check.png",
999 "(x)" => "ic_cross.png",
1000 "(!)" => "ic_danger.png",
1001 "(+)" => "ic_plus.png",
1002 "(-)" => "ic_minus.png",
1003 "(?)" => "ic_help.png",
1004 "(on)" => "ic_lighton.png",
1005 "(off)" => "ic_lightoff.png",
1006 "(*)" => "ic_yellowstar.png",
1007 "(*r)" => "ic_redstar.png",
1008 "(*g)" => "ic_greenstar.png",
1009 "(*b)" => "ic_bluestar.png",
1010 "(*y)" => "ic_yellowstar.png",
1012 foreach ($predefinedicons as $ascii => $icon) {
1013 if (trim($page) == $ascii) {
1014 return LinkImage(DATA_PATH . "/themes/default/images/$icon", $page);
1018 if (strpos($page, "|") === false) {
1022 $imagename = substr($page, 0, strpos($page, "|"));
1023 $alt = ltrim(strstr($page, "|"), "|");
1026 // It's not a Mediawiki template, it's a Wikicreole image
1027 if (is_image($imagename)) {
1028 if ($imagename[0] == '/') {
1029 return LinkImage(DATA_PATH . '/' . $imagename, $alt);
1031 return LinkImage(getUploadDataPath() . $imagename, $alt);
1036 if (is_video($imagename)) {
1037 $s = '<'.'?plugin Video file="' . $imagename . '" ?'.'>';
1038 return new Cached_PluginInvocation($s);
1041 $page = str_replace("\n", "", $page);
1044 if (preg_match('/^(\S+?)\|(.*)$/', $page, $_m)) {
1046 $vars = '"' . preg_replace('/\|/', '" "', $_m[2]) . '"';
1047 $vars = preg_replace('/"(\S+)=([^"]*)"/', '\\1="\\2"', $vars);
1050 // page may contain a version number
1051 // {{foo?version=5}}
1052 // in that case, output is "page=foo rev=5"
1053 if (strstr($page, "?")) {
1054 $page = str_replace("?version=", "\" rev=\"", $page);
1058 $s = '<'.'?plugin Template page="'.$page.'" '.$vars.' ?'.'>';
1060 $s = '<'.'?plugin Template page="' . $page . '" ?'.'>';
1061 return new Cached_PluginInvocation($s);
1065 // "..." => "…" browser specific display (not cached?)
1066 // Support some HTML::Entities: (C) for copy, --- for mdash, -- for ndash
1067 // TODO: "--" => "&emdash;" browser specific display (not cached?)
1069 class Markup_html_entities extends SimpleMarkup {
1070 //var $_match_regexp = '(: \.\.\.|\-\-|\-\-\-|\(C\) )';
1072 function Markup_html_entities() {
1073 $this->_entities = array('...' => '…',
1077 '©' => '©',
1078 '™' => '™',
1080 $this->_match_regexp =
1082 join('|', array_map('preg_quote', array_keys($this->_entities))) .
1086 function markup ($match) {
1087 return HTML::Raw($this->_entities[$match]);
1091 class Markup_isonumchars extends SimpleMarkup {
1092 var $_match_regexp = '\&\#\d{2,5};';
1094 function markup ($match) {
1095 return HTML::Raw($match);
1099 class Markup_isohexchars extends SimpleMarkup {
1100 // hexnums, like ¤ <=> ¤
1101 var $_match_regexp = '\&\#x[0-9a-fA-F]{2,4};';
1103 function markup ($match) {
1104 return HTML::Raw($match);
1108 // FIXME: Do away with magic phpwiki forms. (Maybe phpwiki: links too?)
1110 class InlineTransformer
1112 var $_regexps = array();
1113 var $_markup = array();
1115 function InlineTransformer ($markup_types = false) {
1117 // We need to extend the inline parsers by certain actions, like SearchHighlight,
1118 // SpellCheck and maybe CreateToc.
1119 if (!$markup_types) {
1120 $non_default = false;
1121 $markup_types = array
1122 ('escape', 'wikicreolebracketlink', 'bracketlink', 'url',
1123 'html_comment', 'placeholder',
1124 'interwiki', 'semanticlink', 'wikiword', 'linebreak',
1125 'wikicreole_superscript',
1126 'wikicreole_subscript',
1127 'wikicreole_italics', 'wikicreole_bold',
1128 'wikicreole_monospace',
1129 'old_emphasis', 'nestled_emphasis',
1130 'html_emphasis', 'html_abbr', 'plugin', 'plugin_wikicreole',
1131 'isonumchars', 'isohexchars', /*'html_entities'*/
1133 if (DISABLE_MARKUP_WIKIWORD)
1134 $markup_types = array_remove($markup_types, 'wikiword');
1136 $action = $request->getArg('action');
1137 if ($action == 'SpellCheck' and $request->getArg('suggestions'))
1138 { // insert it after url
1139 array_splice($markup_types, 2, 1, array('url','spellcheck'));
1141 if (isset($request->_searchhighlight))
1142 { // insert it after url
1143 array_splice($markup_types, 2, 1, array('url','searchhighlight'));
1144 //$request->setArg('searchhighlight', false);
1147 $non_default = true;
1149 foreach ($markup_types as $mtype) {
1150 $class = "Markup_$mtype";
1151 $this->_addMarkup(new $class);
1153 $this->_addMarkup(new Markup_nowiki);
1154 if (ENABLE_MARKUP_DIVSPAN and !$non_default)
1155 $this->_addMarkup(new Markup_html_divspan);
1156 if (ENABLE_MARKUP_COLOR and !$non_default)
1157 $this->_addMarkup(new Markup_color);
1158 // Markup_wikicreole_preformatted must be before Markup_template_plugin
1159 $this->_addMarkup(new Markup_wikicreole_preformatted);
1160 $this->_addMarkup(new Markup_template_plugin);
1163 function _addMarkup ($markup) {
1164 if (isa($markup, 'SimpleMarkup'))
1165 $regexp = $markup->getMatchRegexp();
1167 $regexp = $markup->getStartRegexp();
1169 assert( !isset($this->_markup[$regexp]) );
1170 assert( strlen(trim($regexp)) > 0 );
1171 $this->_regexps[] = $regexp;
1172 $this->_markup[] = $markup;
1175 function parse (&$text, $end_regexps = array('$')) {
1176 $regexps = $this->_regexps;
1178 // $end_re takes precedence: "favor reduce over shift"
1179 array_unshift($regexps, $end_regexps[0]);
1180 //array_push($regexps, $end_regexps[0]);
1181 $regexps = new RegexpSet($regexps);
1184 $output = new XmlContent;
1186 $match = $regexps->match($input);
1189 if ($match->regexp_ind == 0) {
1190 // No start pattern found before end pattern.
1192 if (isset($markup) and is_object($markup)
1193 and isa($markup,'Markup_plugin'))
1195 $current =& $output->_content[count($output->_content)-1];
1196 $current->setTightness(true,true);
1198 $output->pushContent($match->prematch);
1199 $text = $match->postmatch;
1203 $markup = $this->_markup[$match->regexp_ind - 1];
1204 $body = $this->_parse_markup_body($markup, $match->match,
1205 $match->postmatch, $end_regexps);
1207 // Couldn't match balanced expression.
1208 // Ignore and look for next matching start regexp.
1209 $match = $regexps->nextMatch($input, $match);
1213 // Matched markup. Eat input, push output.
1214 // FIXME: combine adjacent strings.
1215 if (isa($markup, 'SimpleMarkup'))
1216 $current = $markup->markup($match->match);
1218 $current = $markup->markup($match->match, $body);
1219 $input = $match->postmatch;
1220 if (isset($markup) and is_object($markup)
1221 and isa($markup,'Markup_plugin'))
1223 $current->setTightness(true,true);
1225 $output->pushContent($match->prematch, $current);
1227 $match = $regexps->match($input);
1230 // No pattern matched, not even the end pattern.
1235 function _parse_markup_body ($markup, $match, &$text, $end_regexps) {
1236 if (isa($markup, 'SimpleMarkup'))
1237 return true; // Done. SimpleMarkup is simple.
1239 if (!is_object($markup)) return false; // Some error: Should assert
1240 array_unshift($end_regexps, $markup->getEndRegexp($match));
1242 // Optimization: if no end pattern in text, we know the
1243 // parse will fail. This is an important optimization,
1244 // e.g. when text is "*lots *of *start *delims *with
1245 // *no *matching *end *delims".
1246 $ends_pat = "/(?:" . join(").*(?:", $end_regexps) . ")/xs";
1247 if (!preg_match($ends_pat, $text))
1249 return $this->parse($text, $end_regexps);
1253 class LinkTransformer extends InlineTransformer
1255 function LinkTransformer () {
1256 $this->InlineTransformer(array('escape', 'wikicreolebracketlink', 'bracketlink', 'url',
1257 'semanticlink', 'interwiki', 'wikiword',
1262 class NowikiTransformer extends InlineTransformer
1264 function NowikiTransformer () {
1265 $this->InlineTransformer
1267 'html_emphasis', 'html_abbr', 'plugin', 'plugin_wikicreole',
1268 'isonumchars', 'isohexchars', /*'html_entities',*/
1273 function TransformInline($text, $markup = 2.0, $basepage=false) {
1275 $action = $GLOBALS['request']->getArg('action');
1276 if (empty($trfm) or $action == 'SpellCheck') {
1277 $trfm = new InlineTransformer;
1280 if ($markup < 2.0) {
1281 $text = ConvertOldMarkup($text, 'inline');
1285 return new CacheableMarkup($trfm->parse($text), $basepage);
1287 return $trfm->parse($text);
1290 function TransformLinks($text, $markup = 2.0, $basepage = false) {
1294 $trfm = new LinkTransformer;
1297 if ($markup < 2.0) {
1298 $text = ConvertOldMarkup($text, 'links');
1302 return new CacheableMarkup($trfm->parse($text), $basepage);
1304 return $trfm->parse($text);
1308 * Transform only html markup and entities.
1310 function TransformInlineNowiki($text, $markup = 2.0, $basepage=false) {
1314 $trfm = new NowikiTransformer;
1317 return new CacheableMarkup($trfm->parse($text), $basepage);
1319 return $trfm->parse($text);
1322 // (c-file-style: "gnu")
1326 // c-basic-offset: 4
1327 // c-hanging-comment-ender-p: nil
1328 // indent-tabs-mode: nil