3 /* Copyright (C) 2002 Geoffrey T. Dairiki <dairiki@dairiki.org>
4 * Copyright (C) 2004-2010 Reini Urban
5 * Copyright (C) 2008-2010 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 along
20 * with PhpWiki; if not, write to the Free Software Foundation, Inc.,
21 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 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 'lib/CachedMarkup.php';
38 require_once(dirname(__FILE__) . '/stdlib.php');
40 function WikiEscape($text)
42 return str_replace('#', ESCAPE_CHAR . '#', $text);
45 function UnWikiEscape($text)
47 return preg_replace('/' . ESCAPE_CHAR . '(.)/', '\1', $text);
51 * Return type from RegexpSet::match and RegexpSet::nextMatch.
58 * The text leading up the the next match.
66 * The text following the matched text.
70 * Index of the regular expression which matched.
76 * A set of regular expressions.
78 * This class is probably only useful for InlineTransformer.
84 * @param array $regexps A list of regular expressions. The
85 * regular expressions should not include any sub-pattern groups
86 * "(...)". (Anonymous groups, like "(?:...)", as well as
87 * look-ahead and look-behind assertions are okay.)
89 function RegexpSet($regexps)
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)
105 return $this->_match($text, $this->_regexps, '*?');
109 * Search for next matching regexp.
111 * Here, 'next' has two meanings:
113 * Match the next regexp(s) in the set, at the same position as the last match.
115 * If that fails, match the whole RegexpSet, starting after the position of the
118 * @param string $text Text to search.
120 * @param RegexpSet_match $prevMatch A RegexpSet_match object.
121 * $prevMatch should be a match object obtained by a previous
122 * match upon the same value of $text.
124 * @return RegexpSet_match A RegexpSet_match object, or false if no match.
126 function nextMatch($text, $prevMatch)
128 // Try to find match at same position.
129 $pos = strlen($prevMatch->prematch);
130 $regexps = array_slice($this->_regexps, $prevMatch->regexp_ind + 1);
132 $repeat = sprintf('{%d}', $pos);
133 if (($match = $this->_match($text, $regexps, $repeat))) {
134 $match->regexp_ind += $prevMatch->regexp_ind + 1;
140 // Failed. Look for match after current position.
141 $repeat = sprintf('{%d,}?', $pos + 1);
142 return $this->_match($text, $this->_regexps, $repeat);
145 // Syntax: http://www.pcre.org/pcre.txt
146 // x - EXTENDED, ignore whitespace
150 function _match($text, $regexps, $repeat)
152 // If one of the regexps is an empty string, php will crash here:
153 // sf.net: Fatal error: Allowed memory size of 8388608 bytes exhausted
154 // (tried to allocate 634 bytes)
155 if (_INLINE_OPTIMIZATION) { // disabled, wrong
156 // So we try to minize memory usage, by looping explicitly,
157 // and storing only those regexp which actually match.
158 // There may be more than one, so we have to find the longest,
159 // and match inside until the shortest is empty.
161 $matched_ind = array();
162 for ($i = 0; $i < count($regexps); $i++) {
163 if (!trim($regexps[$i])) {
164 trigger_error("empty regexp $i", E_USER_WARNING);
167 $pat = "/ ( . $repeat ) ( " . $regexps[$i] . " ) /x";
168 if (preg_match($pat, $text, $_m)) {
169 $m = $_m; // FIXME: prematch, postmatch is wrong
170 $matched[] = $regexps[$i];
175 // To overcome ANCHORED:
176 // We could sort by longest match and iterate over these.
177 if (empty($matched)) return false;
179 $match = new RegexpSet_match;
181 // Optimization: if the matches are only "$" and another, then omit "$"
182 if (!_INLINE_OPTIMIZATION or count($matched) > 2) {
183 assert(!empty($repeat));
184 assert(!empty($regexps));
185 // We could do much better, if we would know the matching markup for the
186 // longest regexp match:
187 $hugepat = "/ ( . $repeat ) ( (" . join(')|(', $regexps) . ") ) /Asx";
188 // Proposed premature optimization 1:
189 //$hugepat= "/ ( . $repeat ) ( (" . join(')|(', array_values($matched)) . ") ) /Asx";
190 if (!preg_match($hugepat, $text, $m)) {
193 // Proposed premature optimization 1:
194 //$match->regexp_ind = $matched_ind[count($m) - 4];
195 $match->regexp_ind = count($m) - 4;
197 $match->regexp_ind = $regexp_ind;
200 $match->postmatch = substr($text, strlen($m[0]));
201 $match->prematch = $m[1];
202 $match->match = $m[2];
205 if (DEBUG & _DEBUG_PARSER) {
206 static $_already_dumped = 0;
207 if (!$_already_dumped) {
209 if (_INLINE_OPTIMIZATION)
211 var_dump($matched_ind);
213 $_already_dumped = 1;
214 PrintXML(HTML::dl(HTML::dt("input"),
215 HTML::dd(HTML::pre($text)),
217 HTML::dd(HTML::pre($match->regexp_ind, ":", $regexps[$match->regexp_ind])),
218 HTML::dt("prematch"),
219 HTML::dd(HTML::pre($match->prematch)),
221 HTML::dd(HTML::pre($match->match)),
222 HTML::dt("postmatch"),
223 HTML::dd(HTML::pre($match->postmatch))
231 * A simple markup rule (i.e. terminal token).
233 * These are defined by a regexp.
235 * When a match is found for the regexp, the matching text is replaced.
236 * The replacement content is obtained by calling the SimpleMarkup::markup method.
244 * @return string Regexp which matches this token.
246 function getMatchRegexp()
248 return $this->_match_regexp;
251 /** Markup matching text.
253 * @param string $match The text which matched the regexp
254 * (obtained from getMatchRegexp).
256 * @return mixed The expansion of the matched text.
258 function markup($match /*, $body */)
260 trigger_error("pure virtual", E_USER_ERROR);
265 * A balanced markup rule.
267 * These are defined by a start regexp, and an end regexp.
273 /** Get the starting regexp for this rule.
275 * @return string The starting regexp.
277 function getStartRegexp()
279 return $this->_start_regexp;
282 /** Get the ending regexp for this rule.
284 * @param string $match The text which matched the starting regexp.
286 * @return string The ending regexp.
288 function getEndRegexp($match)
290 return $this->_end_regexp;
293 /** Get expansion for matching input.
295 * @param string $match The text which matched the starting regexp.
297 * @param mixed $body Transformed text found between the starting
298 * and ending regexps.
300 * @return mixed The expansion of the matched text.
302 function markup($match, $body)
304 trigger_error("pure virtual", E_USER_ERROR);
308 class Markup_escape extends SimpleMarkup
310 function getMatchRegexp()
312 return ESCAPE_CHAR . '(?: [[:alnum:]]+ | .)';
315 function markup($match)
317 assert(strlen($match) >= 2);
318 return substr($match, 1);
323 * [image.jpg size=50% border=5], [image.jpg size=50x30]
324 * Support for the following attributes: see stdlib.php:LinkImage()
325 * size=<percent>%, size=<width>x<height>
326 * border=n, align=\w+, hspace=n, vspace=n
328 * title, lang, id, alt
330 function isImageLink($link)
332 if (!$link) return false;
333 assert(defined('INLINE_IMAGES'));
334 return preg_match("/\\.(" . INLINE_IMAGES . ")$/i", $link)
335 or preg_match("/\\.(" . INLINE_IMAGES . ")\s+(size|border|align|hspace|vspace|type|data|width|height|title|lang|id|alt)=/i", $link);
338 function LinkBracketLink($bracketlink)
341 // $bracketlink will start and end with brackets; in between will
342 // be either a page name, a URL or both separated by a pipe.
344 $wikicreolesyntax = false;
346 if (string_starts_with($bracketlink, "[[") or string_starts_with($bracketlink, "#[[")) {
347 $wikicreolesyntax = true;
348 $bracketlink = str_replace("[[", "[", $bracketlink);
349 $bracketlink = str_replace("]]", "]", $bracketlink);
352 // Strip brackets and leading space
353 // bug#1904088 Some brackets links on 2 lines cause the parser to crash
354 preg_match('/(\#?) \[\s* (?: (.*?) \s* (?<!' . ESCAPE_CHAR . ')(\|) )? \s* (.+?) \s*\]/x',
355 str_replace("\n", " ", $bracketlink), $matches);
356 if (count($matches) < 4) {
357 // "[ personal\ninformation manager | PhpWiki:PersonalWiki ]"
358 trigger_error(_("Invalid [] syntax ignored") . _(": ") . $bracketlink, E_USER_WARNING);
359 return new Cached_Link;
361 list (, $hash, $label, $bar, $rawlink) = $matches;
363 if ($wikicreolesyntax and $label) {
369 // Mediawiki compatibility: allow "Image:" and "File:"
370 // as synonyms of "Upload:"
371 // Allow "upload:", "image:" and "file:" also
372 // Remove spaces before and after ":", if any
373 if (string_starts_with($rawlink, "Upload")) {
374 $rawlink = preg_replace("/^Upload\\s*:\\s*/", "Upload:", $rawlink);
375 } elseif (string_starts_with($rawlink, "upload")) {
376 $rawlink = preg_replace("/^upload\\s*:\\s*/", "Upload:", $rawlink);
377 } elseif (string_starts_with($rawlink, "Image")) {
378 $rawlink = preg_replace("/^Image\\s*:\\s*/", "Upload:", $rawlink);
379 } elseif (string_starts_with($rawlink, "image")) {
380 $rawlink = preg_replace("/^image\\s*:\\s*/", "Upload:", $rawlink);
381 } elseif (string_starts_with($rawlink, "File")) {
382 $rawlink = preg_replace("/^File\\s*:\\s*/", "Upload:", $rawlink);
383 } elseif (string_starts_with($rawlink, "file")) {
384 $rawlink = preg_replace("/^file\\s*:\\s*/", "Upload:", $rawlink);
387 $label = UnWikiEscape($label);
389 * Check if the user has typed a explicit URL. This solves the
390 * problem where the URLs have a ~ character, which would be stripped away.
391 * "[http:/server/~name/]" will work as expected
392 * "http:/server/~name/" will NOT work as expected, will remove the ~
394 if (string_starts_with($rawlink, "http://")
395 or string_starts_with($rawlink, "https://")
398 // Mozilla Browser URI Obfuscation Weakness 2004-06-14
399 // http://www.securityfocus.com/bid/10532/
400 // goodurl+"%2F%20%20%20."+badurl
401 if (preg_match("/%2F(%20)+\./i", $rawlink)) {
402 $rawlink = preg_replace("/%2F(%20)+\./i", "%2F.", $rawlink);
405 // Check page name lenght
406 if (!string_starts_with($rawlink, "Upload:")) {
407 if (strlen($rawlink) > MAX_PAGENAME_LENGTH) {
408 return HTML::span(array('class' => 'error'),
409 _('Page name too long'));
412 // Check illegal characters in page names: <>[]{}|"
413 if (preg_match("/[<\[\{\|\"\}\]>]/", $rawlink, $matches) > 0) {
414 return HTML::span(array('class' => 'error'),
415 sprintf(_("Illegal character '%s' in page name."),
418 $link = UnWikiEscape($rawlink);
421 /* Relatives links by Joel Schaubert.
422 * Recognize [../bla] or [/bla] as relative links, without needing http://
423 * but [ /link ] only if SUBPAGE_SEPERATOR is not "/".
424 * Normally /Page links to the subpage /Page.
426 if (SUBPAGE_SEPARATOR == '/') {
427 if (preg_match('/^\.\.\//', $link)) {
428 return new Cached_ExternalLink($link, $label);
430 } elseif (preg_match('/^(\.\.\/|\/)/', $link)) {
431 return new Cached_ExternalLink($link, $label);
434 // Handle "[[SandBox|{{image.jpg}}]]" and "[[SandBox|{{image.jpg|alt text}}]]"
435 if (string_starts_with($label, "{{")) {
436 $imgurl = substr($label, 2, -2); // Remove "{{" and "}}"
437 $pipe = strpos($imgurl, '|');
438 if ($pipe === false) {
439 $label = LinkImage(getUploadDataPath() . $imgurl, $link);
441 list($img, $alt) = explode("|", $imgurl);
442 $label = LinkImage(getUploadDataPath() . $img, $alt);
447 // If label looks like a url to an image or object, we want an image link.
448 if (isImageLink($label)) {
450 $intermap = getInterwikiMap();
451 if (preg_match("/^" . $intermap->getRegexp() . ":/", $label)) {
452 $imgurl = $intermap->link($label);
453 $imgurl = $imgurl->getAttr('href');
454 } elseif (!preg_match("#^(" . ALLOWED_PROTOCOLS . "):#", $imgurl)) {
455 // local theme linkname like 'images/next.gif'.
457 $imgurl = $WikiTheme->getImageURL($imgurl);
459 // for objects (non-images) the link is taken as alt tag,
460 // which is in return taken as alternative img
461 $label = LinkImage($imgurl, $link);
465 // It's an anchor, not a link...
466 $id = MangleXmlIdentifier($link);
467 return HTML::a(array('name' => $id, 'id' => $id),
468 $bar ? $label : $link);
471 if (preg_match("#^(" . ALLOWED_PROTOCOLS . "):#", $link)) {
472 // if it's an image, embed it; otherwise, it's a regular link
473 if (isImageLink($link) and empty($label)) // patch #1348996 by Robert Litwiniec
474 return LinkImage($link, $label);
476 return new Cached_ExternalLink($link, $label);
477 } elseif (substr($link, 0, 8) == 'phpwiki:')
478 return new Cached_PhpwikiURL($link, $label); /* Semantic relations and attributes.
479 * Relation and attribute names must be word chars only, no space.
480 * Links and Attributes may contain everything. word, nums, units, space, groupsep, numsep, ...
482 elseif (preg_match("/^ (\w+) (:[:=]) (.*) $/x", $link) and !isImageLink($link))
483 return new Cached_SemanticLink($link, $label); /* Do not store the link */
484 elseif (substr($link, 0, 1) == ':')
485 return new Cached_WikiLink($link, $label); /*
486 * Inline images in Interwiki urls's:
487 * [File:my_image.gif] inlines the image,
488 * File:my_image.gif shows a plain inter-wiki link,
489 * [what a pic|File:my_image.gif] shows a named inter-wiki link to the gif
490 * [File:my_image.gif|what a pic] shows an inlined image linked to the page "what a pic"
492 * Note that for simplicity we will accept embedded object tags (non-images)
493 * here also, and seperate them later in LinkImage()
495 elseif (strstr($link, ':')
496 and ($intermap = getInterwikiMap())
497 and preg_match("/^" . $intermap->getRegexp() . ":/", $link)
499 // trigger_error("label: $label link: $link", E_USER_WARNING);
500 if (empty($label) and isImageLink($link)) {
501 // if without label => inlined image [File:xx.gif]
502 $imgurl = $intermap->link($link);
503 return LinkImage($imgurl->getAttr('href'));
505 return new Cached_InterwikiLink($link, $label);
507 // Split anchor off end of pagename.
508 if (preg_match('/\A(.*)(?<!' . ESCAPE_CHAR . ')#(.*?)\Z/', $rawlink, $m)) {
509 list(, $rawlink, $anchor) = $m;
510 $pagename = UnWikiEscape($rawlink);
511 $anchor = UnWikiEscape($anchor);
518 return new Cached_WikiLink($pagename, $label, $anchor);
522 class Markup_wikicreolebracketlink extends SimpleMarkup
524 var $_match_regexp = "\\#? \\[\\[ .*? [^]\\s] .*? \\]\\]";
526 function markup($match)
528 $link = LinkBracketLink($match);
529 assert($link->isInlineElement());
534 class Markup_bracketlink extends SimpleMarkup
536 var $_match_regexp = "\\#? \\[ .*? [^]\\s] .*? \\]";
538 function markup($match)
540 $link = LinkBracketLink($match);
541 assert($link->isInlineElement());
546 class Markup_spellcheck extends SimpleMarkup
548 function Markup_spellcheck()
550 $this->suggestions = $GLOBALS['request']->getArg('suggestions');
553 function getMatchRegexp()
555 if (empty($this->suggestions))
556 return "(?# false )";
557 $words = array_keys($this->suggestions);
558 return "(?<= \W ) (?:" . join('|', $words) . ") (?= \W )";
561 function markup($match)
563 if (empty($this->suggestions) or empty($this->suggestions[$match]))
565 return new Cached_SpellCheck(UnWikiEscape($match), $this->suggestions[$match]);
569 class Markup_searchhighlight extends SimpleMarkup
571 function Markup_searchhighlight()
573 $result = $GLOBALS['request']->_searchhighlight;
574 require_once 'lib/TextSearchQuery.php';
575 $query = new TextSearchQuery($result['query']);
576 $this->hilight_re = $query->getHighlightRegexp();
577 $this->engine = $result['engine'];
580 function getMatchRegexp()
582 return $this->hilight_re;
585 function markup($match)
587 return new Cached_SearchHighlight(UnWikiEscape($match), $this->engine);
591 class Markup_url extends SimpleMarkup
593 function getMatchRegexp()
595 return "(?<![[:alnum:]]) (?:" . ALLOWED_PROTOCOLS . ") : [^\s<>\"']+ (?<![ ,.?; \] \) ])";
598 function markup($match)
600 return new Cached_ExternalLink(UnWikiEscape($match));
604 class Markup_interwiki extends SimpleMarkup
606 function getMatchRegexp()
608 $map = getInterwikiMap();
609 return "(?<! [[:alnum:]])" . $map->getRegexp() . ": [^:=]\S+ (?<![ ,.?;! \] \) \" \' ])";
612 function markup($match)
614 return new Cached_InterwikiLink(UnWikiEscape($match));
618 class Markup_semanticlink extends SimpleMarkup
620 // No units seperated by space allowed here
621 // For :: (relations) only words, no comma,
622 // but for := (attributes) comma and dots are allowed. Units with groupsep.
623 // Ending dots or comma are not part of the link.
624 var $_match_regexp = "(?: \w+:=\S+(?<![\.,]))|(?: \w+::[\w\.]+(?<!\.))";
626 function markup($match)
628 return new Cached_SemanticLink(UnWikiEscape($match));
632 class Markup_wikiword extends SimpleMarkup
634 function getMatchRegexp()
636 global $WikiNameRegexp;
637 if (!trim($WikiNameRegexp)) return " " . WIKI_NAME_REGEXP;
638 return " $WikiNameRegexp";
641 function markup($match)
643 if (!$match) return false;
644 if ($this->_isWikiUserPage($match))
645 return new Cached_UserLink($match); //$this->_UserLink($match);
647 return new Cached_WikiLink($match);
650 // FIXME: there's probably a more useful place to put these two functions
651 function _isWikiUserPage($page)
654 $dbi = $request->getDbh();
655 $page_handle = $dbi->getPage($page);
656 if ($page_handle and $page_handle->get('pref'))
662 function _UserLink($PageName)
664 $link = HTML::a(array('href' => $PageName));
665 $link->pushContent(PossiblyGlueIconToText('wikiuser', $PageName));
666 $link->setAttr('class', 'wikiuser');
671 class Markup_linebreak extends SimpleMarkup
673 var $_match_regexp = "(?: (?<! %) %%% (?! %) | \\\\\\\\ | <\s*(?:br|BR)\s*> | <\s*(?:br|BR)\s*\/\s*> )";
675 function markup($match)
681 class Markup_wikicreole_italics extends BalancedMarkup
683 var $_start_regexp = "\\/\\/";
685 function getEndRegexp($match)
690 function markup($match, $body)
693 return new HtmlElement($tag, $body);
697 class Markup_wikicreole_bold extends BalancedMarkup
699 var $_start_regexp = "\\*\\*";
701 function getEndRegexp($match)
706 function markup($match, $body)
709 return new HtmlElement($tag, $body);
713 class Markup_wikicreole_monospace extends BalancedMarkup
715 var $_start_regexp = "\\#\\#";
717 function getEndRegexp($match)
722 function markup($match, $body)
724 return new HtmlElement('span', array('class' => 'tt'), $body);
728 class Markup_wikicreole_underline extends BalancedMarkup
730 var $_start_regexp = "\\_\\_";
732 function getEndRegexp($match)
737 function markup($match, $body)
740 return new HtmlElement($tag, $body);
744 class Markup_wikicreole_superscript extends BalancedMarkup
746 var $_start_regexp = "\\^\\^";
748 function getEndRegexp($match)
753 function markup($match, $body)
756 return new HtmlElement($tag, $body);
760 class Markup_wikicreole_subscript extends BalancedMarkup
762 var $_start_regexp = ",,";
764 function getEndRegexp($match)
769 function markup($match, $body)
772 return new HtmlElement($tag, $body);
776 class Markup_old_emphasis extends BalancedMarkup
778 var $_start_regexp = "''";
780 function getEndRegexp($match)
785 function markup($match, $body)
788 return new HtmlElement($tag, $body);
792 class Markup_nestled_emphasis extends BalancedMarkup
794 function getStartRegexp()
796 static $start_regexp = false;
798 if (!$start_regexp) {
799 // The three possible delimiters
800 // (none of which can be followed by itself.)
805 $any = "(?: ${i}|${b}|${tt})"; // any of the three.
807 // Any of [_*=] is okay if preceded by space or one of [-"'/:]
808 $start[] = "(?<= \\s|^|[-\"'\\/:]) ${any}";
810 // _ or * is okay after = as long as not immediately followed by =
811 $start[] = "(?<= =) (?: ${i}|${b}) (?! =)";
813 $start[] = "(?<= _) (?: ${b}|${tt}) (?! _)";
814 $start[] = "(?<= \\*) (?: ${i}|${tt}) (?! \\*)";
816 // any delimiter okay after an opening brace ( [{<(] )
817 // as long as it's not immediately followed by the matching closing
819 $start[] = "(?<= { ) ${any} (?! } )";
820 $start[] = "(?<= < ) ${any} (?! > )";
821 $start[] = "(?<= \\( ) ${any} (?! \\) )";
823 $start = "(?:" . join('|', $start) . ")";
825 // Any of the above must be immediately followed by non-whitespace.
826 $start_regexp = $start . "(?= \S)";
829 return $start_regexp;
832 function getEndRegexp($match)
834 $chr = preg_quote($match);
835 return "(?<= \S | ^ ) (?<! $chr) $chr (?! $chr) (?= \s | [-)}>\"'\\/:.,;!? _*=] | $)";
838 function markup($match, $body)
842 return new HtmlElement('b', $body);
844 return new HtmlElement('span', array('class' => 'tt'), $body);
846 return new HtmlElement('i', $body);
851 class Markup_html_emphasis extends BalancedMarkup
854 "<(?: b|big|i|small|tt|em|strong|cite|code|dfn|kbd|samp|s|strike|del|var|sup|sub )>";
856 function getEndRegexp($match)
858 return "<\\/" . substr($match, 1);
861 function markup($match, $body)
863 $tag = substr($match, 1, -1);
864 return new HtmlElement($tag, $body);
868 class Markup_html_divspan extends BalancedMarkup
871 "<(?: div|span )(?: \s[^>]*)?>";
873 function getEndRegexp($match)
875 if (substr($match, 1, 4) == 'span')
879 return "<\\/" . $tag . '>';
882 function markup($match, $body)
884 if (substr($match, 1, 4) == 'span')
888 $rest = substr($match, 1 + strlen($tag), -1);
890 $args = parse_attributes($rest);
894 return new HtmlElement($tag, $args, $body);
899 class Markup_html_abbr extends BalancedMarkup
901 //rurban: abbr|acronym need an optional title tag.
903 var $_start_regexp = "<(?: abbr|acronym )(?: [^>]*)?>";
905 function getEndRegexp($match)
907 if (substr($match, 1, 4) == 'abbr')
911 return "<\\/" . $tag . '>';
914 function markup($match, $body)
916 if (substr($match, 1, 4) == 'abbr')
920 $rest = substr($match, 1 + strlen($tag), -1);
921 $attrs = parse_attributes($rest);
922 // Remove attributes other than title and lang
923 $allowedargs = array();
924 foreach ($attrs as $key => $value) {
925 if (in_array($key, array("title", "lang"))) {
926 $allowedargs[$key] = $value;
929 return new HtmlElement($tag, $allowedargs, $body);
933 /** ENABLE_MARKUP_COLOR
934 * See http://www.pmwiki.org/wiki/PmWiki/WikiStyles and
935 * http://www.flexwiki.com/default.aspx/FlexWiki/FormattingRules.html
937 class Markup_color extends BalancedMarkup
939 // %color=blue% blue text %% and back to normal
940 var $_start_regexp = "%color=(?: [^%]*)%";
941 var $_end_regexp = "%%";
943 function markup($match, $body)
945 $color = strtolower(substr($match, 7, -1));
947 $morecolors = array('beige' => '#f5f5dc',
948 'brown' => '#a52a2a',
949 'chocolate' => '#d2691e',
952 'ivory' => '#fffff0',
953 'indigo' => '#4b0082',
954 'magenta' => '#ff00ff',
955 'orange' => '#ffa500',
957 'salmon' => '#fa8072',
959 'turquoise' => '#40e0d0',
960 'violet' => '#ee82ee',
963 if (isset($morecolors[$color])) {
964 $color = $morecolors[$color];
967 // HTML 4 defines the following 16 colors
968 if (in_array($color, array('aqua', 'black', 'blue', 'fuchsia',
969 'gray', 'green', 'lime', 'maroon',
970 'navy', 'olive', 'purple', 'red',
971 'silver', 'teal', 'white', 'yellow'))
972 or ((substr($color, 0, 1) == '#')
973 and ((strlen($color) == 4) or (strlen($color) == 7))
974 and (strspn(substr($color, 1), '0123456789abcdef') == strlen($color) - 1))
976 return new HtmlElement('span', array('style' => "color: $color"), $body);
978 return new HtmlElement('span', array('class' => 'error'),
979 sprintf(_("unknown color %s ignored"), substr($match, 7, -1)));
984 // Wikicreole placeholder
986 class Markup_placeholder extends SimpleMarkup
988 var $_match_regexp = '<<<.*?>>>';
990 function markup($match)
992 return HTML::span($match);
996 // Single-line HTML comment
997 // <!-- This is a comment -->
998 class Markup_html_comment extends SimpleMarkup
1000 var $_match_regexp = '<!--.*?-->';
1002 function markup($match)
1004 return HTML::raw('');
1008 // Special version for single-line plugins formatting,
1009 // like: '<small>< ?plugin PopularNearby ? ></small>'
1010 class Markup_plugin extends SimpleMarkup
1012 var $_match_regexp = '<\?plugin(?:-form)?\s[^\n]+?\?>';
1014 function markup($match)
1016 return new Cached_PluginInvocation($match);
1020 // Special version for single-line Wikicreole plugins formatting.
1021 class Markup_plugin_wikicreole extends SimpleMarkup
1023 var $_match_regexp = '<<[^\n]+?>>';
1025 function markup($match)
1027 $pi = str_replace("<<", "<?plugin ", $match);
1028 $pi = str_replace(">>", " ?>", $pi);
1029 return new Cached_PluginInvocation($pi);
1033 // Special version for plugins in xml syntax, mediawiki-style
1034 // <name arg=value>body</name> or <name /> => < ? plugin pluginname arg=value body ? >
1035 // PLUGIN_MARKUP_MAP = "html:RawHtml dot:GraphViz toc:CreateToc amath:AsciiMath richtable:RichTable include:IncludePage tex:TexToPng"
1036 class Markup_xml_plugin extends BalancedMarkup
1038 //var $_start_regexp = "<(?: ".join('|',PLUGIN_MARKUP_MAP)." )(?: \s[^>]*)>";
1040 function getStartRegexp()
1042 global $PLUGIN_MARKUP_MAP;
1043 static $_start_regexp;
1044 if ($_start_regexp) return $_start_regexp;
1045 if (empty($PLUGIN_MARKUP_MAP)) return '';
1046 //"<(?: html|search|extsearch|dot|toc|math|richtable|include|tex )(?: \s[^>]*)>"
1047 $_start_regexp = "<(?: " . join('|', array_keys($PLUGIN_MARKUP_MAP)) . " )(?: \s[^>]*|\\/ )>";
1048 return $_start_regexp;
1051 function getEndRegexp($match)
1053 return "<\\/" . $match . '>';
1056 function markup($match, $body)
1058 global $PLUGIN_MARKUP_MAP;
1059 $name = substr($match, 2, -2);
1061 if (preg_match('/^(\S+)\|(.*)$/', $name, $_m)) {
1063 $vars = $_m[2]; //str_replace(' ', '&', $_m[2]);
1065 if (!isset($PLUGIN_MARKUP_MAP[$name])) {
1066 trigger_error("No plugin for $name $vars defined.", E_USER_WARNING);
1069 $plugin = $PLUGIN_MARKUP_MAP[$name];
1070 return new Cached_PluginInvocation("<" . "?plugin $plugin $vars $body ?" . ">");
1075 * Mediawiki <nowiki>
1076 * <nowiki>...</nowiki>
1078 class Markup_nowiki extends SimpleMarkup
1080 var $_match_regexp = '<nowiki>.*?<\/nowiki>';
1082 function markup($match)
1084 // Remove <nowiki> and </nowiki>
1085 return HTML::raw(substr($match, 8, -9));
1090 * Wikicreole preformatted
1094 class Markup_wikicreole_preformatted extends SimpleMarkup
1096 var $_match_regexp = '\{\{\{.*?\}\}\}';
1098 function markup($match)
1100 // Remove {{{ and }}}
1101 return new HtmlElement('span', array('class' => 'tt'), substr($match, 3, -3));
1105 /** ENABLE_MARKUP_TEMPLATE
1106 * Template syntax similar to Mediawiki
1108 * => < ? plugin Template page=template ? >
1109 * {{template|var1=value1|var2=value|...}}
1110 * => < ? plugin Template page=template var=value ... ? >
1112 * The {{...}} syntax is also used for:
1113 * - Wikicreole images
1115 * - predefined icons
1117 class Markup_template_plugin extends SimpleMarkup
1119 // patch #1732793: allow \n, mult. {{ }} in one line, and single letters
1120 var $_match_regexp = '\{\{.*?\}\}';
1122 function markup($match)
1125 $page = substr($match, 2, -2);
1126 $page = trim($page);
1128 // Check for predefined icons.
1129 $predefinedicons = array(":)" => "ic_smile.png",
1130 ":(" => "ic_sad.png",
1131 ":P" => "ic_tongue.png",
1132 ":D" => "ic_biggrin.png",
1133 ";)" => "ic_wink.png",
1134 "(y)" => "ic_handyes.png",
1135 "(n)" => "ic_handno.png",
1136 "(i)" => "ic_info.png",
1137 "(/)" => "ic_check.png",
1138 "(x)" => "ic_cross.png",
1139 "(!)" => "ic_danger.png",
1140 "(+)" => "ic_plus.png",
1141 "(-)" => "ic_minus.png",
1142 "(?)" => "ic_help.png",
1143 "(on)" => "ic_lighton.png",
1144 "(off)" => "ic_lightoff.png",
1145 "(*)" => "ic_yellowstar.png",
1146 "(*r)" => "ic_redstar.png",
1147 "(*g)" => "ic_greenstar.png",
1148 "(*b)" => "ic_bluestar.png",
1149 "(*y)" => "ic_yellowstar.png",
1151 foreach ($predefinedicons as $ascii => $icon) {
1152 if ($page == $ascii) {
1153 return LinkImage(DATA_PATH . "/themes/default/images/$icon", $page);
1157 if (strpos($page, "|") === false) {
1161 $imagename = substr($page, 0, strpos($page, "|"));
1162 $alt = ltrim(strstr($page, "|"), "|");
1165 // It's not a Mediawiki template, it's a Wikicreole image
1166 if (is_image($imagename)) {
1167 if ((strpos($imagename, "http://") === 0) || (strpos($imagename, "https://") === 0)) {
1168 return LinkImage($imagename, $alt);
1169 } elseif ($imagename[0] == '/') {
1170 return LinkImage(DATA_PATH . '/' . $imagename, $alt);
1172 return LinkImage(getUploadDataPath() . $imagename, $alt);
1177 if (is_video($imagename)) {
1178 $s = '<' . '?plugin Video file="' . $imagename . '" ?' . '>';
1179 return new Cached_PluginInvocation($s);
1182 $page = str_replace("\n", "", $page);
1184 // The argument value might contain a double quote (")
1185 // We have to encode that.
1186 $page = htmlspecialchars($page);
1190 if (preg_match('/^(\S+?)\|(.*)$/', $page, $_m)) {
1192 $vars = '"' . preg_replace('/\|/', '" "', $_m[2]) . '"';
1193 $vars = preg_replace('/"(\S+)=([^"]*)"/', '\\1="\\2"', $vars);
1196 // page may contain a version number
1197 // {{foo?version=5}}
1198 // in that case, output is "page=foo rev=5"
1199 if (strstr($page, "?")) {
1200 $page = str_replace("?version=", "\" rev=\"", $page);
1204 $s = '<' . '?plugin Template page="' . $page . '" ' . $vars . ' ?' . '>';
1206 $s = '<' . '?plugin Template page="' . $page . '" ?' . '>';
1207 return new Cached_PluginInvocation($s);
1211 // "..." => "…" browser specific display (not cached?)
1212 // Support some HTML::Entities: (C) for copy, --- for mdash, -- for ndash
1213 // TODO: "--" => "&emdash;" browser specific display (not cached?)
1215 class Markup_html_entities extends SimpleMarkup
1217 //var $_match_regexp = '(: \.\.\.|\-\-|\-\-\-|\(C\) )';
1219 function Markup_html_entities()
1221 $this->_entities = array('...' => '…',
1225 '©' => '©',
1226 '™' => '™',
1228 $this->_match_regexp =
1230 join('|', array_map('preg_quote', array_keys($this->_entities))) .
1234 function markup($match)
1236 return HTML::Raw($this->_entities[$match]);
1240 class Markup_isonumchars extends SimpleMarkup
1242 var $_match_regexp = '\&\#\d{2,5};';
1244 function markup($match)
1246 return HTML::Raw($match);
1250 class Markup_isohexchars extends SimpleMarkup
1252 // hexnums, like ¤ <=> ¤
1253 var $_match_regexp = '\&\#x[0-9a-fA-F]{2,4};';
1255 function markup($match)
1257 return HTML::Raw($match);
1261 // FIXME: Do away with magic phpwiki forms. (Maybe phpwiki: links too?)
1263 class InlineTransformer
1265 var $_regexps = array();
1266 var $_markup = array();
1268 function InlineTransformer($markup_types = false)
1271 // We need to extend the inline parsers by certain actions, like SearchHighlight,
1272 // SpellCheck and maybe CreateToc.
1273 if (!$markup_types) {
1274 $non_default = false;
1275 $markup_types = array
1276 ('escape', 'wikicreolebracketlink', 'bracketlink', 'url',
1277 'html_comment', 'placeholder',
1278 'interwiki', 'semanticlink', 'wikiword', 'linebreak',
1279 'wikicreole_superscript',
1280 'wikicreole_subscript',
1281 'wikicreole_italics', 'wikicreole_bold',
1282 'wikicreole_monospace',
1283 'wikicreole_underline',
1284 'old_emphasis', 'nestled_emphasis',
1285 'html_emphasis', 'html_abbr', 'plugin', 'plugin_wikicreole',
1286 'isonumchars', 'isohexchars', /*'html_entities'*/
1288 if (DISABLE_MARKUP_WIKIWORD)
1289 $markup_types = array_remove($markup_types, 'wikiword');
1291 $action = $request->getArg('action');
1292 if ($action == 'SpellCheck' and $request->getArg('suggestions')) { // insert it after url
1293 array_splice($markup_types, 2, 1, array('url', 'spellcheck'));
1295 if (isset($request->_searchhighlight)) { // insert it after url
1296 array_splice($markup_types, 2, 1, array('url', 'searchhighlight'));
1297 //$request->setArg('searchhighlight', false);
1300 $non_default = true;
1302 foreach ($markup_types as $mtype) {
1303 $class = "Markup_$mtype";
1304 $this->_addMarkup(new $class);
1306 $this->_addMarkup(new Markup_nowiki);
1307 if (ENABLE_MARKUP_DIVSPAN and !$non_default)
1308 $this->_addMarkup(new Markup_html_divspan);
1309 if (ENABLE_MARKUP_COLOR and !$non_default)
1310 $this->_addMarkup(new Markup_color);
1311 // Markup_wikicreole_preformatted must be before Markup_template_plugin
1312 $this->_addMarkup(new Markup_wikicreole_preformatted);
1313 if (ENABLE_MARKUP_TEMPLATE and !$non_default)
1314 $this->_addMarkup(new Markup_template_plugin);
1315 // This does not work yet
1316 if (PLUGIN_MARKUP_MAP and !$non_default)
1317 $this->_addMarkup(new Markup_xml_plugin);
1320 function _addMarkup($markup)
1322 if (isa($markup, 'SimpleMarkup'))
1323 $regexp = $markup->getMatchRegexp();
1325 $regexp = $markup->getStartRegexp();
1327 assert(!isset($this->_markup[$regexp]));
1328 assert(strlen(trim($regexp)) > 0);
1329 $this->_regexps[] = $regexp;
1330 $this->_markup[] = $markup;
1333 function parse(&$text, $end_regexps = array('$'))
1335 $regexps = $this->_regexps;
1337 // $end_re takes precedence: "favor reduce over shift"
1338 array_unshift($regexps, $end_regexps[0]);
1339 //array_push($regexps, $end_regexps[0]);
1340 $regexps = new RegexpSet($regexps);
1343 $output = new XmlContent;
1345 $match = $regexps->match($input);
1348 if ($match->regexp_ind == 0) {
1349 // No start pattern found before end pattern.
1351 if (isset($markup) and is_object($markup)
1352 and isa($markup, 'Markup_plugin')
1354 $current =& $output->_content[count($output->_content) - 1];
1355 $current->setTightness(true, true);
1357 $output->pushContent($match->prematch);
1358 $text = $match->postmatch;
1362 $markup = $this->_markup[$match->regexp_ind - 1];
1363 $body = $this->_parse_markup_body($markup, $match->match,
1364 $match->postmatch, $end_regexps);
1366 // Couldn't match balanced expression.
1367 // Ignore and look for next matching start regexp.
1368 $match = $regexps->nextMatch($input, $match);
1372 // Matched markup. Eat input, push output.
1373 // FIXME: combine adjacent strings.
1374 if (isa($markup, 'SimpleMarkup'))
1375 $current = $markup->markup($match->match);
1377 $current = $markup->markup($match->match, $body);
1378 $input = $match->postmatch;
1379 if (isset($markup) and is_object($markup)
1380 and isa($markup, 'Markup_plugin')
1382 $current->setTightness(true, true);
1384 $output->pushContent($match->prematch, $current);
1386 $match = $regexps->match($input);
1389 // No pattern matched, not even the end pattern.
1394 function _parse_markup_body($markup, $match, &$text, $end_regexps)
1396 if (isa($markup, 'SimpleMarkup'))
1397 return true; // Done. SimpleMarkup is simple.
1399 if (!is_object($markup)) return false; // Some error: Should assert
1400 array_unshift($end_regexps, $markup->getEndRegexp($match));
1402 // Optimization: if no end pattern in text, we know the
1403 // parse will fail. This is an important optimization,
1404 // e.g. when text is "*lots *of *start *delims *with
1405 // *no *matching *end *delims".
1406 $ends_pat = "/(?:" . join(").*(?:", $end_regexps) . ")/xs";
1407 if (!preg_match($ends_pat, $text))
1409 return $this->parse($text, $end_regexps);
1413 class LinkTransformer extends InlineTransformer
1415 function LinkTransformer()
1417 $this->InlineTransformer(array('escape', 'wikicreolebracketlink', 'bracketlink', 'url',
1418 'semanticlink', 'interwiki', 'wikiword',
1423 class NowikiTransformer extends InlineTransformer
1425 function NowikiTransformer()
1427 $this->InlineTransformer
1429 'html_emphasis', 'html_abbr', 'plugin', 'plugin_wikicreole',
1430 'isonumchars', 'isohexchars', /*'html_entities',*/
1435 function TransformInline($text, $markup = 2.0, $basepage = false)
1438 $action = $GLOBALS['request']->getArg('action');
1439 if (empty($trfm) or $action == 'SpellCheck') {
1440 $trfm = new InlineTransformer;
1443 if ($markup < 2.0) {
1444 $text = ConvertOldMarkup($text, 'inline');
1448 return new CacheableMarkup($trfm->parse($text), $basepage);
1450 return $trfm->parse($text);
1453 function TransformLinks($text, $markup = 2.0, $basepage = false)
1458 $trfm = new LinkTransformer;
1461 if ($markup < 2.0) {
1462 $text = ConvertOldMarkup($text, 'links');
1466 return new CacheableMarkup($trfm->parse($text), $basepage);
1468 return $trfm->parse($text);
1472 * Transform only html markup and entities.
1474 function TransformInlineNowiki($text, $markup = 2.0, $basepage = false)
1479 $trfm = new NowikiTransformer;
1482 return new CacheableMarkup($trfm->parse($text), $basepage);
1484 return $trfm->parse($text);
1490 // c-basic-offset: 4
1491 // c-hanging-comment-ender-p: nil
1492 // indent-tabs-mode: nil