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
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.
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 __construct($regexps)
91 $this->_regexps = array_unique($regexps);
92 if (!defined('_INLINE_OPTIMIZATION')) define('_INLINE_OPTIMIZATION', 0);
96 * Search text for the next matching regexp from the Regexp Set.
98 * @param string $text The text to search.
100 * @return RegexpSet_match A RegexpSet_match object, or false if no match.
102 function match($text)
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)
127 // Try to find match at same position.
128 $pos = strlen($prevMatch->prematch);
129 $regexps = array_slice($this->_regexps, $prevMatch->regexp_ind + 1);
131 $repeat = sprintf('{%d}', $pos);
132 if (($match = $this->_match($text, $regexps, $repeat))) {
133 $match->regexp_ind += $prevMatch->regexp_ind + 1;
139 // Failed. Look for match after current position.
140 $repeat = sprintf('{%d,}?', $pos + 1);
141 return $this->_match($text, $this->_regexps, $repeat);
144 // Syntax: http://www.pcre.org/pcre.txt
145 // x - EXTENDED, ignore whitespace
149 function _match($text, $regexps, $repeat)
151 // If one of the regexps is an empty string, php will crash here:
152 // sf.net: Fatal error: Allowed memory size of 8388608 bytes exhausted
153 // (tried to allocate 634 bytes)
154 if (_INLINE_OPTIMIZATION) { // disabled, wrong
155 // So we try to minize memory usage, by looping explicitly,
156 // and storing only those regexp which actually match.
157 // There may be more than one, so we have to find the longest,
158 // and match inside until the shortest is empty.
160 $matched_ind = array();
161 for ($i = 0; $i < count($regexps); $i++) {
162 if (!trim($regexps[$i])) {
163 trigger_error("empty regexp $i", E_USER_WARNING);
166 $pat = "/ ( . $repeat ) ( " . $regexps[$i] . " ) /x";
167 if (preg_match($pat, $text, $_m)) {
168 $m = $_m; // FIXME: prematch, postmatch is wrong
169 $matched[] = $regexps[$i];
174 // To overcome ANCHORED:
175 // We could sort by longest match and iterate over these.
176 if (empty($matched)) return false;
178 $match = new RegexpSet_match;
180 // Optimization: if the matches are only "$" and another, then omit "$"
181 if (!_INLINE_OPTIMIZATION or count($matched) > 2) {
182 assert(!empty($repeat));
183 assert(!empty($regexps));
184 // We could do much better, if we would know the matching markup for the
185 // longest regexp match:
186 $hugepat = "/ ( . $repeat ) ( (" . join(')|(', $regexps) . ") ) /Asx";
187 // Proposed premature optimization 1:
188 //$hugepat= "/ ( . $repeat ) ( (" . join(')|(', array_values($matched)) . ") ) /Asx";
189 if (!preg_match($hugepat, $text, $m)) {
192 // Proposed premature optimization 1:
193 //$match->regexp_ind = $matched_ind[count($m) - 4];
194 $match->regexp_ind = count($m) - 4;
196 $match->regexp_ind = $regexp_ind;
199 $match->postmatch = substr($text, strlen($m[0]));
200 $match->prematch = $m[1];
201 $match->match = $m[2];
204 if (DEBUG & _DEBUG_PARSER) {
205 static $_already_dumped = 0;
206 if (!$_already_dumped) {
208 if (_INLINE_OPTIMIZATION)
210 var_dump($matched_ind);
212 $_already_dumped = 1;
213 PrintXML(HTML::dl(HTML::dt("input"),
214 HTML::dd(HTML::pre($text)),
216 HTML::dd(HTML::pre($match->regexp_ind, ":", $regexps[$match->regexp_ind])),
217 HTML::dt("prematch"),
218 HTML::dd(HTML::pre($match->prematch)),
220 HTML::dd(HTML::pre($match->match)),
221 HTML::dt("postmatch"),
222 HTML::dd(HTML::pre($match->postmatch))
230 * A simple markup rule (i.e. terminal token).
232 * These are defined by a regexp.
234 * When a match is found for the regexp, the matching text is replaced.
235 * The replacement content is obtained by calling the SimpleMarkup::markup method.
239 public $_match_regexp;
243 * @return string Regexp which matches this token.
245 function getMatchRegexp()
247 return $this->_match_regexp;
250 /** Markup matching text.
252 * @param string $match The text which matched the regexp
253 * (obtained from getMatchRegexp).
255 * @return mixed The expansion of the matched text.
257 function markup($match /*, $body */)
259 trigger_error("pure virtual", E_USER_ERROR);
264 * A balanced markup rule.
266 * These are defined by a start regexp, and an end regexp.
270 public $_start_regexp;
272 /** Get the starting regexp for this rule.
274 * @return string The starting regexp.
276 function getStartRegexp()
278 return $this->_start_regexp;
281 /** Get the ending regexp for this rule.
283 * @param string $match The text which matched the starting regexp.
285 * @return string The ending regexp.
287 function getEndRegexp($match)
289 return $this->_end_regexp;
292 /** Get expansion for matching input.
294 * @param string $match The text which matched the starting regexp.
296 * @param mixed $body Transformed text found between the starting
297 * and ending regexps.
299 * @return mixed The expansion of the matched text.
301 function markup($match, $body)
303 trigger_error("pure virtual", E_USER_ERROR);
307 class Markup_escape extends SimpleMarkup
309 function getMatchRegexp()
311 return ESCAPE_CHAR . '(?: [[:alnum:]]+ | .)';
314 function markup($match)
316 assert(strlen($match) >= 2);
317 return substr($match, 1);
322 * [image.jpg size=50% border=5], [image.jpg size=50x30]
323 * Support for the following attributes: see stdlib.php:LinkImage()
324 * size=<percent>%, size=<width>x<height>
325 * border=n, align=\w+, hspace=n, vspace=n
327 * title, lang, id, alt
329 function isImageLink($link)
331 if (!$link) return false;
332 assert(defined('INLINE_IMAGES'));
333 return preg_match("/\\.(" . INLINE_IMAGES . ")$/i", $link)
334 or preg_match("/\\.(" . INLINE_IMAGES . ")\s+(size|border|align|hspace|vspace|type|data|width|height|title|lang|id|alt)=/i", $link);
337 function LinkBracketLink($bracketlink)
340 // $bracketlink will start and end with brackets; in between will
341 // be either a page name, a URL or both separated by a pipe.
343 $wikicreolesyntax = false;
345 if (string_starts_with($bracketlink, "[[") or string_starts_with($bracketlink, "#[[")) {
346 $wikicreolesyntax = true;
347 $bracketlink = str_replace("[[", "[", $bracketlink);
348 $bracketlink = str_replace("]]", "]", $bracketlink);
351 // Strip brackets and leading space
352 // bug#1904088 Some brackets links on 2 lines cause the parser to crash
353 preg_match('/(\#?) \[\s* (?: (.*?) \s* (?<!' . ESCAPE_CHAR . ')(\|) )? \s* (.+?) \s*\]/x',
354 str_replace("\n", " ", $bracketlink), $matches);
355 if (count($matches) < 4) {
356 // "[ personal\ninformation manager | PhpWiki:PersonalWiki ]"
357 trigger_error(_("Invalid [] syntax ignored") . _(": ") . $bracketlink, E_USER_WARNING);
358 return new Cached_Link;
360 list (, $hash, $label, $bar, $rawlink) = $matches;
362 if ($wikicreolesyntax and $label) {
368 // Mediawiki compatibility: allow "Image:" and "File:"
369 // as synonyms of "Upload:"
370 // Allow "upload:", "image:" and "file:" also
371 // Remove spaces before and after ":", if any
372 if (string_starts_with($rawlink, "Upload")) {
373 $rawlink = preg_replace("/^Upload\\s*:\\s*/", "Upload:", $rawlink);
374 } elseif (string_starts_with($rawlink, "upload")) {
375 $rawlink = preg_replace("/^upload\\s*:\\s*/", "Upload:", $rawlink);
376 } elseif (string_starts_with($rawlink, "Image")) {
377 $rawlink = preg_replace("/^Image\\s*:\\s*/", "Upload:", $rawlink);
378 } elseif (string_starts_with($rawlink, "image")) {
379 $rawlink = preg_replace("/^image\\s*:\\s*/", "Upload:", $rawlink);
380 } elseif (string_starts_with($rawlink, "File")) {
381 $rawlink = preg_replace("/^File\\s*:\\s*/", "Upload:", $rawlink);
382 } elseif (string_starts_with($rawlink, "file")) {
383 $rawlink = preg_replace("/^file\\s*:\\s*/", "Upload:", $rawlink);
386 $label = UnWikiEscape($label);
388 * Check if the user has typed a explicit URL. This solves the
389 * problem where the URLs have a ~ character, which would be stripped away.
390 * "[http:/server/~name/]" will work as expected
391 * "http:/server/~name/" will NOT work as expected, will remove the ~
393 if (string_starts_with($rawlink, "http://")
394 or string_starts_with($rawlink, "https://")
397 // Mozilla Browser URI Obfuscation Weakness 2004-06-14
398 // http://www.securityfocus.com/bid/10532/
399 // goodurl+"%2F%20%20%20."+badurl
400 if (preg_match("/%2F(%20)+\./i", $rawlink)) {
401 $rawlink = preg_replace("/%2F(%20)+\./i", "%2F.", $rawlink);
404 // Check page name lenght
405 if (!string_starts_with($rawlink, "Upload:")) {
406 if (strlen($rawlink) > MAX_PAGENAME_LENGTH) {
407 return HTML::span(array('class' => 'error'),
408 _('Page name too long'));
411 // Check illegal characters in page names: <>[]{}|"
412 if (preg_match("/[<\[\{\|\"\}\]>]/", $rawlink, $matches) > 0) {
413 return HTML::span(array('class' => 'error'),
414 sprintf(_("Illegal character “%s” in page name."),
417 $link = UnWikiEscape($rawlink);
420 /* Relatives links by Joel Schaubert.
421 * Recognize [../bla] or [/bla] as relative links, without needing http://
422 * but [ /link ] only if SUBPAGE_SEPERATOR is not "/".
423 * Normally /Page links to the subpage /Page.
425 if (SUBPAGE_SEPARATOR == '/') {
426 if (preg_match('/^\.\.\//', $link)) {
427 return new Cached_ExternalLink($link, $label);
429 } elseif (preg_match('/^(\.\.\/|\/)/', $link)) {
430 return new Cached_ExternalLink($link, $label);
433 // Handle "[[SandBox|{{image.jpg}}]]" and "[[SandBox|{{image.jpg|alt text}}]]"
434 if (string_starts_with($label, "{{")) {
435 $imgurl = substr($label, 2, -2); // Remove "{{" and "}}"
436 $pipe = strpos($imgurl, '|');
437 if ($pipe === false) {
438 $label = LinkImage(getUploadDataPath() . $imgurl, $link);
440 list($img, $alt) = explode("|", $imgurl);
441 $label = LinkImage(getUploadDataPath() . $img, $alt);
446 // If label looks like a url to an image or object, we want an image link.
447 if (isImageLink($label)) {
449 $intermap = getInterwikiMap();
450 if (preg_match("/^" . $intermap->getRegexp() . ":/", $label)) {
451 $imgurl = $intermap->link($label);
452 $imgurl = $imgurl->getAttr('href');
453 } elseif (!preg_match("#^(" . ALLOWED_PROTOCOLS . "):#", $imgurl)) {
454 // local theme linkname like 'images/next.gif'.
456 $imgurl = $WikiTheme->getImageURL($imgurl);
458 // for objects (non-images) the link is taken as alt tag,
459 // which is in return taken as alternative img
460 $label = LinkImage($imgurl, $link);
464 // It's an anchor, not a link...
465 $id = MangleXmlIdentifier($link);
466 return HTML::a(array('id' => $id), $bar ? $label : $link);
469 if (preg_match("#^(" . ALLOWED_PROTOCOLS . "):#", $link)) {
470 // if it's an image, embed it; otherwise, it's a regular link
471 if (isImageLink($link) and empty($label)) // patch #1348996 by Robert Litwiniec
472 return LinkImage($link, $label);
474 return new Cached_ExternalLink($link, $label);
475 } elseif (substr($link, 0, 8) == 'phpwiki:')
476 return new Cached_PhpwikiURL($link, $label); /* Semantic relations and attributes.
477 * Relation and attribute names must be word chars only, no space.
478 * Links and Attributes may contain everything. word, nums, units, space, groupsep, numsep, ...
480 elseif (preg_match("/^ (\w+) (:[:=]) (.*) $/x", $link) and !isImageLink($link))
481 return new Cached_SemanticLink($link, $label); /* Do not store the link */
482 elseif (substr($link, 0, 1) == ':')
483 return new Cached_WikiLink($link, $label); /*
484 * Inline images in Interwiki urls's:
485 * [File:my_image.gif] inlines the image,
486 * File:my_image.gif shows a plain inter-wiki link,
487 * [what a pic|File:my_image.gif] shows a named inter-wiki link to the gif
488 * [File:my_image.gif|what a pic] shows an inlined image linked to the page "what a pic"
490 * Note that for simplicity we will accept embedded object tags (non-images)
491 * here also, and separate them later in LinkImage()
493 elseif (strstr($link, ':')
494 and ($intermap = getInterwikiMap())
495 and preg_match("/^" . $intermap->getRegexp() . ":/", $link)
497 // trigger_error("label: $label link: $link", E_USER_WARNING);
498 if (empty($label) and isImageLink($link)) {
499 // if without label => inlined image [File:xx.gif]
500 $imgurl = $intermap->link($link);
501 return LinkImage($imgurl->getAttr('href'));
503 return new Cached_InterwikiLink($link, $label);
505 // Split anchor off end of pagename.
506 if (preg_match('/\A(.*)(?<!' . ESCAPE_CHAR . ')#(.*?)\Z/', $rawlink, $m)) {
507 list(, $rawlink, $anchor) = $m;
508 $pagename = UnWikiEscape($rawlink);
509 $anchor = UnWikiEscape($anchor);
516 return new Cached_WikiLink($pagename, $label, $anchor);
520 class Markup_wikicreolebracketlink extends SimpleMarkup
522 public $_match_regexp = "\\#? \\[\\[ .*? [^]\\s] .*? \\]\\]";
524 function markup($match)
526 $link = LinkBracketLink($match);
527 assert($link->isInlineElement());
532 class Markup_bracketlink extends SimpleMarkup
534 public $_match_regexp = "\\#? \\[ .*? [^]\\s] .*? \\]";
536 function markup($match)
538 $link = LinkBracketLink($match);
539 assert($link->isInlineElement());
544 class Markup_spellcheck extends SimpleMarkup
546 function __construct()
548 $this->suggestions = $GLOBALS['request']->getArg('suggestions');
551 function getMatchRegexp()
553 if (empty($this->suggestions))
554 return "(?# false )";
555 $words = array_keys($this->suggestions);
556 return "(?<= \W ) (?:" . join('|', $words) . ") (?= \W )";
559 function markup($match)
561 if (empty($this->suggestions) or empty($this->suggestions[$match]))
563 return new Cached_SpellCheck(UnWikiEscape($match), $this->suggestions[$match]);
567 class Markup_searchhighlight extends SimpleMarkup
569 function __construct()
571 $result = $GLOBALS['request']->_searchhighlight;
572 require_once 'lib/TextSearchQuery.php';
573 $query = new TextSearchQuery($result['query']);
574 $this->hilight_re = $query->getHighlightRegexp();
575 $this->engine = $result['engine'];
578 function getMatchRegexp()
580 return $this->hilight_re;
583 function markup($match)
585 return new Cached_SearchHighlight(UnWikiEscape($match), $this->engine);
589 class Markup_url extends SimpleMarkup
591 function getMatchRegexp()
593 return "(?<![[:alnum:]]) (?:" . ALLOWED_PROTOCOLS . ") : [^\s<>\"']+ (?<![ ,.?; \] \) ])";
596 function markup($match)
598 return new Cached_ExternalLink(UnWikiEscape($match));
602 class Markup_interwiki extends SimpleMarkup
604 function getMatchRegexp()
606 $map = getInterwikiMap();
607 return "(?<! [[:alnum:]])" . $map->getRegexp() . ": [^:=]\S+ (?<![ ,.?;! \] \) \" \' ])";
610 function markup($match)
612 return new Cached_InterwikiLink(UnWikiEscape($match));
616 class Markup_semanticlink extends SimpleMarkup
618 // No units separated by space allowed here
619 // For :: (relations) only words, no comma,
620 // but for := (attributes) comma and dots are allowed. Units with groupsep.
621 // Ending dots or comma are not part of the link.
622 public $_match_regexp = "(?: \w+:=\S+(?<![\.,]))|(?: \w+::[\w\.]+(?<!\.))";
624 function markup($match)
626 return new Cached_SemanticLink(UnWikiEscape($match));
630 class Markup_wikiword extends SimpleMarkup
632 function getMatchRegexp()
634 global $WikiNameRegexp;
635 if (!trim($WikiNameRegexp)) return " " . WIKI_NAME_REGEXP;
636 return " $WikiNameRegexp";
639 function markup($match)
641 if (!$match) return false;
642 if ($this->_isWikiUserPage($match))
643 return new Cached_UserLink($match); //$this->_UserLink($match);
645 return new Cached_WikiLink($match);
648 // FIXME: there's probably a more useful place to put these two functions
649 function _isWikiUserPage($page)
652 $dbi = $request->getDbh();
653 $page_handle = $dbi->getPage($page);
654 if ($page_handle and $page_handle->get('pref'))
660 function _UserLink($PageName)
662 $link = HTML::a(array('href' => $PageName));
663 $link->pushContent(PossiblyGlueIconToText('wikiuser', $PageName));
664 $link->setAttr('class', 'wikiuser');
669 class Markup_linebreak extends SimpleMarkup
671 public $_match_regexp = "(?: (?<! %) %%% (?! %) | \\\\\\\\ | <\s*(?:br|BR)\s*> | <\s*(?:br|BR)\s*\/\s*> )";
673 function markup($match)
679 class Markup_wikicreole_italics extends BalancedMarkup
681 public $_start_regexp = "\\/\\/";
683 function getEndRegexp($match)
688 function markup($match, $body)
691 return new HtmlElement($tag, $body);
695 class Markup_wikicreole_bold extends BalancedMarkup
697 public $_start_regexp = "\\*\\*";
699 function getEndRegexp($match)
704 function markup($match, $body)
707 return new HtmlElement($tag, $body);
711 class Markup_wikicreole_monospace extends BalancedMarkup
713 public $_start_regexp = "\\#\\#";
715 function getEndRegexp($match)
720 function markup($match, $body)
722 return new HtmlElement('span', array('class' => 'tt'), $body);
726 class Markup_wikicreole_underline extends BalancedMarkup
728 public $_start_regexp = "\\_\\_";
730 function getEndRegexp($match)
735 function markup($match, $body)
738 return new HtmlElement($tag, $body);
742 class Markup_wikicreole_superscript extends BalancedMarkup
744 public $_start_regexp = "\\^\\^";
746 function getEndRegexp($match)
751 function markup($match, $body)
754 return new HtmlElement($tag, $body);
758 class Markup_wikicreole_subscript extends BalancedMarkup
760 public $_start_regexp = ",,";
762 function getEndRegexp($match)
767 function markup($match, $body)
770 return new HtmlElement($tag, $body);
774 class Markup_old_emphasis extends BalancedMarkup
776 public $_start_regexp = "''";
778 function getEndRegexp($match)
783 function markup($match, $body)
786 return new HtmlElement($tag, $body);
790 class Markup_nestled_emphasis extends BalancedMarkup
792 function getStartRegexp()
794 static $start_regexp = false;
796 if (!$start_regexp) {
797 // The three possible delimiters
798 // (none of which can be followed by itself.)
803 $any = "(?: ${i}|${b}|${tt})"; // any of the three.
805 // Any of [_*=] is okay if preceded by space or one of [-"'/:]
806 $start[] = "(?<= \\s|^|[-\"'\\/:]) ${any}";
808 // _ or * is okay after = as long as not immediately followed by =
809 $start[] = "(?<= =) (?: ${i}|${b}) (?! =)";
811 $start[] = "(?<= _) (?: ${b}|${tt}) (?! _)";
812 $start[] = "(?<= \\*) (?: ${i}|${tt}) (?! \\*)";
814 // any delimiter okay after an opening brace ( [{<(] )
815 // as long as it's not immediately followed by the matching closing
817 $start[] = "(?<= { ) ${any} (?! } )";
818 $start[] = "(?<= < ) ${any} (?! > )";
819 $start[] = "(?<= \\( ) ${any} (?! \\) )";
821 $start = "(?:" . join('|', $start) . ")";
823 // Any of the above must be immediately followed by non-whitespace.
824 $start_regexp = $start . "(?= \S)";
827 return $start_regexp;
830 function getEndRegexp($match)
832 $chr = preg_quote($match);
833 return "(?<= \S | ^ ) (?<! $chr) $chr (?! $chr) (?= \s | [-)}>\"'\\/:.,;!? _*=] | $)";
836 function markup($match, $body)
840 return new HtmlElement('b', $body);
842 return new HtmlElement('span', array('class' => 'tt'), $body);
844 return new HtmlElement('i', $body);
849 class Markup_html_emphasis extends BalancedMarkup
851 public $_start_regexp =
852 "<(?: b|big|i|small|tt|em|strong|cite|code|dfn|kbd|samp|s|strike|del|var|sup|sub )>";
854 function getEndRegexp($match)
856 return "<\\/" . substr($match, 1);
859 function markup($match, $body)
861 $tag = substr($match, 1, -1);
862 if (($tag == 'big') || ($tag == 'strike') || ($tag == 'tt')) {
863 return new HtmlElement('span', array('class' => $tag), $body);
865 return new HtmlElement($tag, $body);
869 class Markup_html_divspan extends BalancedMarkup
871 public $_start_regexp =
872 "<(?: div|span )(?: \s[^>]*)?>";
874 function getEndRegexp($match)
876 if (substr($match, 1, 4) == 'span')
880 return "<\\/" . $tag . '>';
883 function markup($match, $body)
885 if (substr($match, 1, 4) == 'span')
889 $rest = substr($match, 1 + strlen($tag), -1);
891 $args = parse_attributes($rest);
895 return new HtmlElement($tag, $args, $body);
899 class Markup_html_abbr extends BalancedMarkup
901 //rurban: abbr|acronym need an optional title tag.
903 public $_start_regexp = "<(?: abbr|acronym )(?: [^>]*)?>";
905 function getEndRegexp($match)
907 if (substr($match, 1, 4) == 'abbr')
911 return "<\\/" . $tag . '>';
914 function markup($match, $body)
916 // 'acronym' is deprecated in HTML 5, replace by 'abbr'
918 $rest = substr($match, 1 + strlen($tag), -1);
919 $attrs = parse_attributes($rest);
920 // Remove attributes other than title and lang
921 $allowedargs = array();
922 foreach ($attrs as $key => $value) {
923 if (in_array($key, array("title", "lang"))) {
924 $allowedargs[$key] = $value;
927 return new HtmlElement($tag, $allowedargs, $body);
931 /** ENABLE_MARKUP_COLOR
932 * See http://www.pmwiki.org/wiki/PmWiki/WikiStyles and
933 * http://www.flexwiki.com/default.aspx/FlexWiki/FormattingRules.html
935 class Markup_color extends BalancedMarkup
937 // %color=blue% blue text %% and back to normal
938 public $_start_regexp = "%color=(?: [^%]*)%";
939 public $_end_regexp = "%%";
941 function markup($match, $body)
943 $color = strtolower(substr($match, 7, -1));
945 $morecolors = array('beige' => '#f5f5dc',
946 'brown' => '#a52a2a',
947 'chocolate' => '#d2691e',
950 'ivory' => '#fffff0',
951 'indigo' => '#4b0082',
952 'magenta' => '#ff00ff',
953 'orange' => '#ffa500',
955 'salmon' => '#fa8072',
957 'turquoise' => '#40e0d0',
958 'violet' => '#ee82ee',
961 if (isset($morecolors[$color])) {
962 $color = $morecolors[$color];
965 // HTML 4 defines the following 16 colors
966 if (in_array($color, array('aqua', 'black', 'blue', 'fuchsia',
967 'gray', 'green', 'lime', 'maroon',
968 'navy', 'olive', 'purple', 'red',
969 'silver', 'teal', 'white', 'yellow'))
970 or ((substr($color, 0, 1) == '#')
971 and ((strlen($color) == 4) or (strlen($color) == 7))
972 and (strspn(substr($color, 1), '0123456789abcdef') == strlen($color) - 1))
974 return new HtmlElement('span', array('style' => "color: $color"), $body);
976 return new HtmlElement('span', array('class' => 'error'),
977 sprintf(_("unknown color %s ignored"), substr($match, 7, -1)));
982 // Wikicreole placeholder
984 class Markup_placeholder extends SimpleMarkup
986 public $_match_regexp = '<<<.*?>>>';
988 function markup($match)
990 return HTML::span($match);
994 // Single-line HTML comment
995 // <!-- This is a comment -->
996 class Markup_html_comment extends SimpleMarkup
998 public $_match_regexp = '<!--.*?-->';
1000 function markup($match)
1002 return HTML::raw('');
1006 // Special version for single-line plugins formatting,
1007 // like: '<small>< ?plugin PopularNearby ? ></small>'
1008 class Markup_plugin extends SimpleMarkup
1010 public $_match_regexp = '<\?plugin(?:-form)?\s[^\n]+?\?>';
1012 function markup($match)
1014 return new Cached_PluginInvocation($match);
1018 // Special version for single-line Wikicreole plugins formatting.
1019 class Markup_plugin_wikicreole extends SimpleMarkup
1021 public $_match_regexp = '<<[^\n]+?>>';
1023 function markup($match)
1025 $pi = str_replace("<<", "<?plugin ", $match);
1026 $pi = str_replace(">>", " ?>", $pi);
1027 return new Cached_PluginInvocation($pi);
1031 // Special version for plugins in xml syntax, mediawiki-style
1032 // <name arg=value>body</name> or <name /> => < ? plugin pluginname arg=value body ? >
1033 // PLUGIN_MARKUP_MAP = "html:RawHtml dot:GraphViz toc:CreateToc amath:AsciiMath richtable:RichTable include:IncludePage tex:TexToPng"
1034 class Markup_xml_plugin extends BalancedMarkup
1036 //public $_start_regexp = "<(?: ".join('|',PLUGIN_MARKUP_MAP)." )(?: \s[^>]*)>";
1038 function getStartRegexp()
1040 global $PLUGIN_MARKUP_MAP;
1041 static $_start_regexp;
1042 if ($_start_regexp) return $_start_regexp;
1043 if (empty($PLUGIN_MARKUP_MAP)) return '';
1044 //"<(?: html|search|extsearch|dot|toc|math|richtable|include|tex )(?: \s[^>]*)>"
1045 $_start_regexp = "<(?: " . join('|', array_keys($PLUGIN_MARKUP_MAP)) . " )(?: \s[^>]*|\\/ )>";
1046 return $_start_regexp;
1049 function getEndRegexp($match)
1051 return "<\\/" . $match . '>';
1054 function markup($match, $body)
1056 global $PLUGIN_MARKUP_MAP;
1057 $name = substr($match, 2, -2);
1059 if (preg_match('/^(\S+)\|(.*)$/', $name, $_m)) {
1061 $vars = $_m[2]; //str_replace(' ', '&', $_m[2]);
1063 if (!isset($PLUGIN_MARKUP_MAP[$name])) {
1064 trigger_error("No plugin for $name $vars defined.", E_USER_WARNING);
1067 $plugin = $PLUGIN_MARKUP_MAP[$name];
1068 return new Cached_PluginInvocation("<" . "?plugin $plugin $vars $body ?" . ">");
1073 * Mediawiki <nowiki>
1074 * <nowiki>...</nowiki>
1076 class Markup_nowiki extends SimpleMarkup
1078 public $_match_regexp = '<nowiki>.*?<\/nowiki>';
1080 function markup($match)
1082 // Remove <nowiki> and </nowiki>
1083 return HTML::raw(substr($match, 8, -9));
1088 * Wikicreole preformatted
1092 class Markup_wikicreole_preformatted extends SimpleMarkup
1094 public $_match_regexp = '\{\{\{.*?\}\}\}';
1096 function markup($match)
1098 // Remove {{{ and }}}
1099 return new HtmlElement('span', array('class' => 'tt'), substr($match, 3, -3));
1103 /** ENABLE_MARKUP_TEMPLATE
1104 * Template syntax similar to Mediawiki
1106 * => < ? plugin Template page=template ? >
1107 * {{template|var1=value1|var2=value|...}}
1108 * => < ? plugin Template page=template var=value ... ? >
1110 * The {{...}} syntax is also used for:
1111 * - Wikicreole images
1113 * - predefined icons
1115 class Markup_template_plugin extends SimpleMarkup
1117 // patch #1732793: allow \n, mult. {{ }} in one line, and single letters
1118 public $_match_regexp = '\{\{.*?\}\}';
1120 function markup($match)
1123 $page = substr($match, 2, -2);
1124 $page = trim($page);
1126 // Check for predefined icons.
1127 $predefinedicons = array(":)" => "ic_smile.png",
1128 ":(" => "ic_sad.png",
1129 ":P" => "ic_tongue.png",
1130 ":D" => "ic_biggrin.png",
1131 ";)" => "ic_wink.png",
1132 "(y)" => "ic_handyes.png",
1133 "(n)" => "ic_handno.png",
1134 "(i)" => "ic_info.png",
1135 "(/)" => "ic_check.png",
1136 "(x)" => "ic_cross.png",
1137 "(!)" => "ic_danger.png",
1138 "(+)" => "ic_plus.png",
1139 "(-)" => "ic_minus.png",
1140 "(?)" => "ic_help.png",
1141 "(on)" => "ic_lighton.png",
1142 "(off)" => "ic_lightoff.png",
1143 "(*)" => "ic_yellowstar.png",
1144 "(*r)" => "ic_redstar.png",
1145 "(*g)" => "ic_greenstar.png",
1146 "(*b)" => "ic_bluestar.png",
1147 "(*y)" => "ic_yellowstar.png",
1149 foreach ($predefinedicons as $ascii => $icon) {
1150 if ($page == $ascii) {
1151 return LinkImage(DATA_PATH . "/themes/default/images/$icon", $page);
1155 if (strpos($page, "|") === false) {
1159 $imagename = substr($page, 0, strpos($page, "|"));
1160 $alt = ltrim(strstr($page, "|"), "|");
1163 // It's not a Mediawiki template, it's a Wikicreole image
1164 if (is_image($imagename)) {
1165 if ((strpos($imagename, "http://") === 0) || (strpos($imagename, "https://") === 0)) {
1166 return LinkImage($imagename, $alt);
1167 } elseif ($imagename[0] == '/') {
1168 return LinkImage(DATA_PATH . '/' . $imagename, $alt);
1170 return LinkImage(getUploadDataPath() . $imagename, $alt);
1175 if (is_video($imagename)) {
1176 $s = '<' . '?plugin Video file="' . $imagename . '" ?' . '>';
1177 return new Cached_PluginInvocation($s);
1180 $page = str_replace("\n", "", $page);
1182 // The argument value might contain a double quote (")
1183 // We have to encode that.
1184 $page = htmlspecialchars($page);
1188 if (preg_match('/^(\S+?)\|(.*)$/', $page, $_m)) {
1190 $vars = '"' . preg_replace('/\|/', '" "', $_m[2]) . '"';
1191 $vars = preg_replace('/"(\S+)=([^"]*)"/', '\\1="\\2"', $vars);
1194 // page may contain a version number
1195 // {{foo?version=5}}
1196 // in that case, output is "page=foo rev=5"
1197 if (strstr($page, "?")) {
1198 $page = str_replace("?version=", "\" rev=\"", $page);
1202 $s = '<' . '?plugin Template page="' . $page . '" ' . $vars . ' ?' . '>';
1204 $s = '<' . '?plugin Template page="' . $page . '" ?' . '>';
1205 return new Cached_PluginInvocation($s);
1209 // "..." => "…" browser specific display (not cached?)
1210 // Support some HTML::Entities: (C) for copy, --- for mdash, -- for ndash
1211 // TODO: "--" => "&emdash;" browser specific display (not cached?)
1213 class Markup_html_entities extends SimpleMarkup
1215 //public $_match_regexp = '(: \.\.\.|\-\-|\-\-\-|\(C\) )';
1217 function __construct()
1219 $this->_entities = array('...' => '…',
1223 '©' => '©',
1224 '™' => '™',
1226 $this->_match_regexp =
1228 join('|', array_map('preg_quote', array_keys($this->_entities))) .
1232 function markup($match)
1234 return HTML::Raw($this->_entities[$match]);
1238 class Markup_isonumchars extends SimpleMarkup
1240 public $_match_regexp = '\&\#\d{2,5};';
1242 function markup($match)
1244 return HTML::Raw($match);
1248 class Markup_isohexchars extends SimpleMarkup
1250 // hexnums, like ¤ <=> ¤
1251 public $_match_regexp = '\&\#x[0-9a-fA-F]{2,4};';
1253 function markup($match)
1255 return HTML::Raw($match);
1259 // FIXME: Do away with magic phpwiki forms. (Maybe phpwiki: links too?)
1261 class InlineTransformer
1263 public $_regexps = array();
1264 public $_markup = array();
1266 function InlineTransformer($markup_types = false)
1269 // We need to extend the inline parsers by certain actions, like SearchHighlight,
1270 // SpellCheck and maybe CreateToc.
1271 if (!$markup_types) {
1272 $non_default = false;
1273 $markup_types = array
1274 ('escape', 'wikicreolebracketlink', 'bracketlink', 'url',
1275 'html_comment', 'placeholder',
1276 'interwiki', 'semanticlink', 'wikiword', 'linebreak',
1277 'wikicreole_superscript',
1278 'wikicreole_subscript',
1279 'wikicreole_italics', 'wikicreole_bold',
1280 'wikicreole_monospace',
1281 'wikicreole_underline',
1282 'old_emphasis', 'nestled_emphasis',
1283 'html_emphasis', 'html_abbr', 'plugin', 'plugin_wikicreole',
1284 'isonumchars', 'isohexchars', /*'html_entities'*/
1286 if (DISABLE_MARKUP_WIKIWORD)
1287 $markup_types = array_remove($markup_types, 'wikiword');
1289 $action = $request->getArg('action');
1290 if ($action == 'SpellCheck' and $request->getArg('suggestions')) { // insert it after url
1291 array_splice($markup_types, 2, 1, array('url', 'spellcheck'));
1293 if (isset($request->_searchhighlight)) { // insert it after url
1294 array_splice($markup_types, 2, 1, array('url', 'searchhighlight'));
1295 //$request->setArg('searchhighlight', false);
1298 $non_default = true;
1300 foreach ($markup_types as $mtype) {
1301 $class = "Markup_$mtype";
1302 $this->_addMarkup(new $class);
1304 $this->_addMarkup(new Markup_nowiki);
1305 if (ENABLE_MARKUP_DIVSPAN and !$non_default)
1306 $this->_addMarkup(new Markup_html_divspan);
1307 if (ENABLE_MARKUP_COLOR and !$non_default)
1308 $this->_addMarkup(new Markup_color);
1309 // Markup_wikicreole_preformatted must be before Markup_template_plugin
1310 $this->_addMarkup(new Markup_wikicreole_preformatted);
1311 if (ENABLE_MARKUP_TEMPLATE and !$non_default)
1312 $this->_addMarkup(new Markup_template_plugin);
1313 // This does not work yet
1314 if (PLUGIN_MARKUP_MAP and !$non_default)
1315 $this->_addMarkup(new Markup_xml_plugin);
1318 function _addMarkup($markup)
1320 if (isa($markup, 'SimpleMarkup'))
1321 $regexp = $markup->getMatchRegexp();
1323 $regexp = $markup->getStartRegexp();
1325 assert(!isset($this->_markup[$regexp]));
1326 assert(strlen(trim($regexp)) > 0);
1327 $this->_regexps[] = $regexp;
1328 $this->_markup[] = $markup;
1331 function parse(&$text, $end_regexps = array('$'))
1333 $regexps = $this->_regexps;
1335 // $end_re takes precedence: "favor reduce over shift"
1336 array_unshift($regexps, $end_regexps[0]);
1337 //array_push($regexps, $end_regexps[0]);
1338 $regexps = new RegexpSet($regexps);
1341 $output = new XmlContent;
1343 $match = $regexps->match($input);
1346 if ($match->regexp_ind == 0) {
1347 // No start pattern found before end pattern.
1349 if (isset($markup) and is_object($markup)
1350 and isa($markup, 'Markup_plugin')
1352 $current =& $output->_content[count($output->_content) - 1];
1353 $current->setTightness(true, true);
1355 $output->pushContent($match->prematch);
1356 $text = $match->postmatch;
1360 $markup = $this->_markup[$match->regexp_ind - 1];
1361 $body = $this->_parse_markup_body($markup, $match->match,
1362 $match->postmatch, $end_regexps);
1364 // Couldn't match balanced expression.
1365 // Ignore and look for next matching start regexp.
1366 $match = $regexps->nextMatch($input, $match);
1370 // Matched markup. Eat input, push output.
1371 // FIXME: combine adjacent strings.
1372 if (isa($markup, 'SimpleMarkup'))
1373 $current = $markup->markup($match->match);
1375 $current = $markup->markup($match->match, $body);
1376 $input = $match->postmatch;
1377 if (isset($markup) and is_object($markup)
1378 and isa($markup, 'Markup_plugin')
1380 $current->setTightness(true, true);
1382 $output->pushContent($match->prematch, $current);
1384 $match = $regexps->match($input);
1387 // No pattern matched, not even the end pattern.
1392 function _parse_markup_body($markup, $match, &$text, $end_regexps)
1394 if (isa($markup, 'SimpleMarkup')) {
1395 return true; // Done. SimpleMarkup is simple.
1398 if (!is_object($markup)) {
1399 return false; // Some error: Should assert
1401 array_unshift($end_regexps, $markup->getEndRegexp($match));
1403 // Optimization: if no end pattern in text, we know the
1404 // parse will fail. This is an important optimization,
1405 // e.g. when text is "*lots *of *start *delims *with
1406 // *no *matching *end *delims".
1407 $ends_pat = "/(?:" . join(").*(?:", $end_regexps) . ")/xs";
1408 if (!@preg_match($ends_pat, $text)) { // Add "@" to avoid warning with "{{(*y)}}"
1411 return $this->parse($text, $end_regexps);
1415 class LinkTransformer extends InlineTransformer
1417 function __construct()
1419 parent::__construct(array('escape', 'wikicreolebracketlink', 'bracketlink', 'url',
1420 'semanticlink', 'interwiki', 'wikiword',
1425 class NowikiTransformer extends InlineTransformer
1427 function __construct()
1431 'html_emphasis', 'html_abbr', 'plugin', 'plugin_wikicreole',
1432 'isonumchars', 'isohexchars', /*'html_entities',*/
1437 function TransformInline($text, $basepage = false)
1440 $action = $GLOBALS['request']->getArg('action');
1441 if (empty($trfm) or $action == 'SpellCheck') {
1442 $trfm = new InlineTransformer;
1446 return new CacheableMarkup($trfm->parse($text), $basepage);
1448 return $trfm->parse($text);
1451 function TransformLinks($text, $basepage = false)
1456 $trfm = new LinkTransformer;
1460 return new CacheableMarkup($trfm->parse($text), $basepage);
1462 return $trfm->parse($text);
1466 * Transform only html markup and entities.
1468 function TransformInlineNowiki($text, $basepage = false)
1473 $trfm = new NowikiTransformer;
1476 return new CacheableMarkup($trfm->parse($text), $basepage);
1478 return $trfm->parse($text);
1484 // c-basic-offset: 4
1485 // c-hanging-comment-ender-p: nil
1486 // indent-tabs-mode: nil