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.
237 abstract class SimpleMarkup
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 abstract function markup($match /*, $body */);
261 * A balanced markup rule.
263 * These are defined by a start regexp, and an end regexp.
265 abstract class BalancedMarkup
267 public $_start_regexp;
269 /** Get the starting regexp for this rule.
271 * @return string The starting regexp.
273 function getStartRegexp()
275 return $this->_start_regexp;
278 /** Get the ending regexp for this rule.
280 * @param string $match The text which matched the starting regexp.
282 * @return string The ending regexp.
284 function getEndRegexp($match)
286 return $this->_end_regexp;
289 /** Get expansion for matching input.
291 * @param string $match The text which matched the starting regexp.
293 * @param mixed $body Transformed text found between the starting
294 * and ending regexps.
296 * @return mixed The expansion of the matched text.
298 abstract function markup($match, $body);
301 class Markup_escape extends SimpleMarkup
303 function getMatchRegexp()
305 return ESCAPE_CHAR . '(?: [[:alnum:]]+ | .)';
308 function markup($match)
310 assert(strlen($match) >= 2);
311 return substr($match, 1);
316 * [image.jpg size=50% border=5], [image.jpg size=50x30]
317 * Support for the following attributes: see stdlib.php:LinkImage()
318 * size=<percent>%, size=<width>x<height>
319 * border=n, align=\w+, hspace=n, vspace=n
321 * title, lang, id, alt
323 function isImageLink($link)
325 if (!$link) return false;
326 assert(defined('INLINE_IMAGES'));
327 return preg_match("/\\.(" . INLINE_IMAGES . ")$/i", $link)
328 or preg_match("/\\.(" . INLINE_IMAGES . ")\s+(size|border|align|hspace|vspace|type|data|width|height|title|lang|id|alt)=/i", $link);
331 function LinkBracketLink($bracketlink)
334 // $bracketlink will start and end with brackets; in between will
335 // be either a page name, a URL or both separated by a pipe.
337 $wikicreolesyntax = false;
339 if (string_starts_with($bracketlink, "[[") or string_starts_with($bracketlink, "#[[")) {
340 $wikicreolesyntax = true;
341 $bracketlink = str_replace("[[", "[", $bracketlink);
342 $bracketlink = str_replace("]]", "]", $bracketlink);
345 // Strip brackets and leading space
346 // bug#1904088 Some brackets links on 2 lines cause the parser to crash
347 preg_match('/(\#?) \[\s* (?: (.*?) \s* (?<!' . ESCAPE_CHAR . ')(\|) )? \s* (.+?) \s*\]/x',
348 str_replace("\n", " ", $bracketlink), $matches);
349 if (count($matches) < 4) {
350 // "[ personal\ninformation manager | PhpWiki:PersonalWiki ]"
351 trigger_error(_("Invalid [] syntax ignored") . _(": ") . $bracketlink, E_USER_WARNING);
352 return new Cached_Link;
354 list (, $hash, $label, $bar, $rawlink) = $matches;
356 if ($wikicreolesyntax and $label) {
362 // Mediawiki compatibility: allow "Image:" and "File:"
363 // as synonyms of "Upload:"
364 // Allow "upload:", "image:" and "file:" also
365 // Remove spaces before and after ":", if any
366 if (string_starts_with($rawlink, "Upload")) {
367 $rawlink = preg_replace("/^Upload\\s*:\\s*/", "Upload:", $rawlink);
368 } elseif (string_starts_with($rawlink, "upload")) {
369 $rawlink = preg_replace("/^upload\\s*:\\s*/", "Upload:", $rawlink);
370 } elseif (string_starts_with($rawlink, "Image")) {
371 $rawlink = preg_replace("/^Image\\s*:\\s*/", "Upload:", $rawlink);
372 } elseif (string_starts_with($rawlink, "image")) {
373 $rawlink = preg_replace("/^image\\s*:\\s*/", "Upload:", $rawlink);
374 } elseif (string_starts_with($rawlink, "File")) {
375 $rawlink = preg_replace("/^File\\s*:\\s*/", "Upload:", $rawlink);
376 } elseif (string_starts_with($rawlink, "file")) {
377 $rawlink = preg_replace("/^file\\s*:\\s*/", "Upload:", $rawlink);
380 $label = UnWikiEscape($label);
382 * Check if the user has typed a explicit URL. This solves the
383 * problem where the URLs have a ~ character, which would be stripped away.
384 * "[http:/server/~name/]" will work as expected
385 * "http:/server/~name/" will NOT work as expected, will remove the ~
387 if (string_starts_with($rawlink, "http://")
388 or string_starts_with($rawlink, "https://")
391 // Mozilla Browser URI Obfuscation Weakness 2004-06-14
392 // http://www.securityfocus.com/bid/10532/
393 // goodurl+"%2F%20%20%20."+badurl
394 if (preg_match("/%2F(%20)+\./i", $rawlink)) {
395 $rawlink = preg_replace("/%2F(%20)+\./i", "%2F.", $rawlink);
398 // Check page name lenght
399 if (!string_starts_with($rawlink, "Upload:")) {
400 if (strlen($rawlink) > MAX_PAGENAME_LENGTH) {
401 return HTML::span(array('class' => 'error'),
402 _('Page name too long'));
405 // Check illegal characters in page names: <>[]{}|"
406 if (preg_match("/[<\[\{\|\"\}\]>]/", $rawlink, $matches) > 0) {
407 return HTML::span(array('class' => 'error'),
408 sprintf(_("Illegal character “%s” in page name."),
411 $link = UnWikiEscape($rawlink);
414 /* Relatives links by Joel Schaubert.
415 * Recognize [../bla] or [/bla] as relative links, without needing http://
416 * but [ /link ] only if SUBPAGE_SEPERATOR is not "/".
417 * Normally /Page links to the subpage /Page.
419 if (SUBPAGE_SEPARATOR == '/') {
420 if (preg_match('/^\.\.\//', $link)) {
421 return new Cached_ExternalLink($link, $label);
423 } elseif (preg_match('/^(\.\.\/|\/)/', $link)) {
424 return new Cached_ExternalLink($link, $label);
427 // Handle "[[SandBox|{{image.jpg}}]]" and "[[SandBox|{{image.jpg|alt text}}]]"
428 if (string_starts_with($label, "{{")) {
429 $imgurl = substr($label, 2, -2); // Remove "{{" and "}}"
430 $pipe = strpos($imgurl, '|');
431 if ($pipe === false) {
432 $label = LinkImage(getUploadDataPath() . $imgurl, $link);
434 list($img, $alt) = explode("|", $imgurl);
435 $label = LinkImage(getUploadDataPath() . $img, $alt);
440 // If label looks like a url to an image or object, we want an image link.
441 if (isImageLink($label)) {
443 $intermap = getInterwikiMap();
444 if (preg_match("/^" . $intermap->getRegexp() . ":/", $label)) {
445 $imgurl = $intermap->link($label);
446 $imgurl = $imgurl->getAttr('href');
447 } elseif (!preg_match("#^(" . ALLOWED_PROTOCOLS . "):#", $imgurl)) {
448 // local theme linkname like 'images/next.gif'.
450 $imgurl = $WikiTheme->getImageURL($imgurl);
452 // for objects (non-images) the link is taken as alt tag,
453 // which is in return taken as alternative img
454 $label = LinkImage($imgurl, $link);
458 // It's an anchor, not a link...
459 $id = MangleXmlIdentifier($link);
460 return HTML::a(array('id' => $id), $bar ? $label : $link);
463 if (preg_match("#^(" . ALLOWED_PROTOCOLS . "):#", $link)) {
464 // if it's an image, embed it; otherwise, it's a regular link
465 if (isImageLink($link) and empty($label)) // patch #1348996 by Robert Litwiniec
466 return LinkImage($link, $label);
468 return new Cached_ExternalLink($link, $label);
469 } elseif (substr($link, 0, 8) == 'phpwiki:')
470 return new Cached_PhpwikiURL($link, $label); /* Semantic relations and attributes.
471 * Relation and attribute names must be word chars only, no space.
472 * Links and Attributes may contain everything. word, nums, units, space, groupsep, numsep, ...
474 elseif (preg_match("/^ (\w+) (:[:=]) (.*) $/x", $link) and !isImageLink($link))
475 return new Cached_SemanticLink($link, $label); /* Do not store the link */
476 elseif (substr($link, 0, 1) == ':')
477 return new Cached_WikiLink($link, $label); /*
478 * Inline images in Interwiki urls's:
479 * [File:my_image.gif] inlines the image,
480 * File:my_image.gif shows a plain inter-wiki link,
481 * [what a pic|File:my_image.gif] shows a named inter-wiki link to the gif
482 * [File:my_image.gif|what a pic] shows an inlined image linked to the page "what a pic"
484 * Note that for simplicity we will accept embedded object tags (non-images)
485 * here also, and separate them later in LinkImage()
487 elseif (strstr($link, ':')
488 and ($intermap = getInterwikiMap())
489 and preg_match("/^" . $intermap->getRegexp() . ":/", $link)
491 // trigger_error("label: $label link: $link", E_USER_WARNING);
492 if (empty($label) and isImageLink($link)) {
493 // if without label => inlined image [File:xx.gif]
494 $imgurl = $intermap->link($link);
495 return LinkImage($imgurl->getAttr('href'));
497 return new Cached_InterwikiLink($link, $label);
499 // Split anchor off end of pagename.
500 if (preg_match('/\A(.*)(?<!' . ESCAPE_CHAR . ')#(.*?)\Z/', $rawlink, $m)) {
501 list(, $rawlink, $anchor) = $m;
502 $pagename = UnWikiEscape($rawlink);
503 $anchor = UnWikiEscape($anchor);
512 $backlinks[] = array('linkto' => $pagename, 'relation' => 0);
514 return new Cached_WikiLink($pagename, $label, $anchor);
518 class Markup_wikicreolebracketlink extends SimpleMarkup
520 public $_match_regexp = "\\#? \\[\\[ .*? [^]\\s] .*? \\]\\]";
522 function markup($match)
524 $link = LinkBracketLink($match);
525 assert($link->isInlineElement());
530 class Markup_bracketlink extends SimpleMarkup
532 public $_match_regexp = "\\#? \\[ .*? [^]\\s] .*? \\]";
534 function markup($match)
536 $link = LinkBracketLink($match);
537 assert($link->isInlineElement());
542 class Markup_spellcheck extends SimpleMarkup
544 function __construct()
546 $this->suggestions = $GLOBALS['request']->getArg('suggestions');
549 function getMatchRegexp()
551 if (empty($this->suggestions))
552 return "(?# false )";
553 $words = array_keys($this->suggestions);
554 return "(?<= \W ) (?:" . join('|', $words) . ") (?= \W )";
557 function markup($match)
559 if (empty($this->suggestions) or empty($this->suggestions[$match]))
561 return new Cached_SpellCheck(UnWikiEscape($match), $this->suggestions[$match]);
565 class Markup_searchhighlight extends SimpleMarkup
567 function __construct()
569 $result = $GLOBALS['request']->_searchhighlight;
570 require_once 'lib/TextSearchQuery.php';
571 $query = new TextSearchQuery($result['query']);
572 $this->hilight_re = $query->getHighlightRegexp();
573 $this->engine = $result['engine'];
576 function getMatchRegexp()
578 return $this->hilight_re;
581 function markup($match)
583 return new Cached_SearchHighlight(UnWikiEscape($match), $this->engine);
587 class Markup_url extends SimpleMarkup
589 function getMatchRegexp()
591 return "(?<![[:alnum:]]) (?:" . ALLOWED_PROTOCOLS . ") : [^\s<>\"']+ (?<![ ,.?; \] \) ])";
594 function markup($match)
596 return new Cached_ExternalLink(UnWikiEscape($match));
600 class Markup_interwiki extends SimpleMarkup
602 function getMatchRegexp()
604 $map = getInterwikiMap();
605 return "(?<! [[:alnum:]])" . $map->getRegexp() . ": [^:=]\S+ (?<![ ,.?;! \] \) \" \' ])";
608 function markup($match)
610 return new Cached_InterwikiLink(UnWikiEscape($match));
614 class Markup_semanticlink extends SimpleMarkup
616 // No units separated by space allowed here
617 // For :: (relations) only words, no comma,
618 // but for := (attributes) comma and dots are allowed. Units with groupsep.
619 // Ending dots or comma are not part of the link.
620 public $_match_regexp = "(?: \w+:=\S+(?<![\.,]))|(?: \w+::[\w\.]+(?<!\.))";
622 function markup($match)
624 return new Cached_SemanticLink(UnWikiEscape($match));
628 class Markup_wikiword extends SimpleMarkup
630 function getMatchRegexp()
632 global $WikiNameRegexp;
633 if (!trim($WikiNameRegexp)) return " " . WIKI_NAME_REGEXP;
634 return " $WikiNameRegexp";
637 function markup($match)
639 if (!$match) return false;
640 if ($this->_isWikiUserPage($match))
641 return new Cached_UserLink($match); //$this->_UserLink($match);
643 return new Cached_WikiLink($match);
646 // FIXME: there's probably a more useful place to put these two functions
647 function _isWikiUserPage($page)
650 $dbi = $request->getDbh();
651 $page_handle = $dbi->getPage($page);
652 if ($page_handle and $page_handle->get('pref'))
658 function _UserLink($PageName)
660 $link = HTML::a(array('href' => $PageName));
661 $link->pushContent(PossiblyGlueIconToText('wikiuser', $PageName));
662 $link->setAttr('class', 'wikiuser');
667 class Markup_linebreak extends SimpleMarkup
669 public $_match_regexp = "(?: (?<! %) %%% (?! %) | \\\\\\\\ | <\s*(?:br|BR)\s*> | <\s*(?:br|BR)\s*\/\s*> )";
671 function markup($match)
677 class Markup_wikicreole_italics extends BalancedMarkup
679 public $_start_regexp = "\\/\\/";
681 function getEndRegexp($match)
686 function markup($match, $body)
689 return new HtmlElement($tag, $body);
693 class Markup_wikicreole_bold extends BalancedMarkup
695 public $_start_regexp = "\\*\\*";
697 function getEndRegexp($match)
702 function markup($match, $body)
705 return new HtmlElement($tag, $body);
709 class Markup_wikicreole_monospace extends BalancedMarkup
711 public $_start_regexp = "\\#\\#";
713 function getEndRegexp($match)
718 function markup($match, $body)
720 return new HtmlElement('span', array('class' => 'tt'), $body);
724 class Markup_wikicreole_underline extends BalancedMarkup
726 public $_start_regexp = "\\_\\_";
728 function getEndRegexp($match)
733 function markup($match, $body)
736 return new HtmlElement($tag, $body);
740 class Markup_wikicreole_superscript extends BalancedMarkup
742 public $_start_regexp = "\\^\\^";
744 function getEndRegexp($match)
749 function markup($match, $body)
752 return new HtmlElement($tag, $body);
756 class Markup_wikicreole_subscript extends BalancedMarkup
758 public $_start_regexp = ",,";
760 function getEndRegexp($match)
765 function markup($match, $body)
768 return new HtmlElement($tag, $body);
772 class Markup_old_emphasis extends BalancedMarkup
774 public $_start_regexp = "''";
776 function getEndRegexp($match)
781 function markup($match, $body)
784 return new HtmlElement($tag, $body);
788 class Markup_nestled_emphasis extends BalancedMarkup
790 function getStartRegexp()
792 static $start_regexp = false;
794 if (!$start_regexp) {
795 // The three possible delimiters
796 // (none of which can be followed by itself.)
801 $any = "(?: ${i}|${b}|${tt})"; // any of the three.
803 // Any of [_*=] is okay if preceded by space or one of [-"'/:]
804 $start[] = "(?<= \\s|^|[-\"'\\/:]) ${any}";
806 // _ or * is okay after = as long as not immediately followed by =
807 $start[] = "(?<= =) (?: ${i}|${b}) (?! =)";
809 $start[] = "(?<= _) (?: ${b}|${tt}) (?! _)";
810 $start[] = "(?<= \\*) (?: ${i}|${tt}) (?! \\*)";
812 // any delimiter okay after an opening brace ( [{<(] )
813 // as long as it's not immediately followed by the matching closing
815 $start[] = "(?<= { ) ${any} (?! } )";
816 $start[] = "(?<= < ) ${any} (?! > )";
817 $start[] = "(?<= \\( ) ${any} (?! \\) )";
819 $start = "(?:" . join('|', $start) . ")";
821 // Any of the above must be immediately followed by non-whitespace.
822 $start_regexp = $start . "(?= \S)";
825 return $start_regexp;
828 function getEndRegexp($match)
830 $chr = preg_quote($match);
831 return "(?<= \S | ^ ) (?<! $chr) $chr (?! $chr) (?= \s | [-)}>\"'\\/:.,;!? _*=] | $)";
834 function markup($match, $body)
838 return new HtmlElement('b', $body);
840 return new HtmlElement('span', array('class' => 'tt'), $body);
842 return new HtmlElement('i', $body);
847 class Markup_html_emphasis extends BalancedMarkup
849 public $_start_regexp =
850 "<(?: b|big|i|small|tt|em|strong|cite|code|dfn|kbd|samp|s|strike|del|var|sup|sub )>";
852 function getEndRegexp($match)
854 return "<\\/" . substr($match, 1);
857 function markup($match, $body)
859 $tag = substr($match, 1, -1);
860 if (($tag == 'big') || ($tag == 'strike') || ($tag == 'tt')) {
861 return new HtmlElement('span', array('class' => $tag), $body);
863 return new HtmlElement($tag, $body);
867 class Markup_html_divspan extends BalancedMarkup
869 public $_start_regexp =
870 "<(?: div|span )(?: \s[^>]*)?>";
872 function getEndRegexp($match)
874 if (substr($match, 1, 4) == 'span')
878 return "<\\/" . $tag . '>';
881 function markup($match, $body)
883 if (substr($match, 1, 4) == 'span')
887 $rest = substr($match, 1 + strlen($tag), -1);
889 $args = parse_attributes($rest);
893 return new HtmlElement($tag, $args, $body);
897 class Markup_html_abbr extends BalancedMarkup
899 //rurban: abbr|acronym need an optional title tag.
901 public $_start_regexp = "<(?: abbr|acronym )(?: [^>]*)?>";
903 function getEndRegexp($match)
905 if (substr($match, 1, 4) == 'abbr')
909 return "<\\/" . $tag . '>';
912 function markup($match, $body)
914 // 'acronym' is deprecated in HTML 5, replace by 'abbr'
916 $rest = substr($match, 1 + strlen($tag), -1);
917 $attrs = parse_attributes($rest);
918 // Remove attributes other than title and lang
919 $allowedargs = array();
920 foreach ($attrs as $key => $value) {
921 if (in_array($key, array("title", "lang"))) {
922 $allowedargs[$key] = $value;
925 return new HtmlElement($tag, $allowedargs, $body);
929 /** ENABLE_MARKUP_COLOR
930 * See http://www.pmwiki.org/wiki/PmWiki/WikiStyles and
931 * http://www.flexwiki.com/default.aspx/FlexWiki/FormattingRules.html
933 class Markup_color extends BalancedMarkup
935 // %color=blue% blue text %% and back to normal
936 public $_start_regexp = "%color=(?: [^%]*)%";
937 public $_end_regexp = "%%";
939 function markup($match, $body)
941 $color = strtolower(substr($match, 7, -1));
943 $morecolors = array('beige' => '#f5f5dc',
944 'brown' => '#a52a2a',
945 'chocolate' => '#d2691e',
948 'ivory' => '#fffff0',
949 'indigo' => '#4b0082',
950 'magenta' => '#ff00ff',
951 'orange' => '#ffa500',
953 'salmon' => '#fa8072',
955 'turquoise' => '#40e0d0',
956 'violet' => '#ee82ee',
959 if (isset($morecolors[$color])) {
960 $color = $morecolors[$color];
963 // HTML 4 defines the following 16 colors
964 if (in_array($color, array('aqua', 'black', 'blue', 'fuchsia',
965 'gray', 'green', 'lime', 'maroon',
966 'navy', 'olive', 'purple', 'red',
967 'silver', 'teal', 'white', 'yellow'))
968 or ((substr($color, 0, 1) == '#')
969 and ((strlen($color) == 4) or (strlen($color) == 7))
970 and (strspn(substr($color, 1), '0123456789abcdef') == strlen($color) - 1))
972 return new HtmlElement('span', array('style' => "color: $color"), $body);
974 return new HtmlElement('span', array('class' => 'error'),
975 sprintf(_("unknown color %s ignored"), substr($match, 7, -1)));
980 // Wikicreole placeholder
982 class Markup_placeholder extends SimpleMarkup
984 public $_match_regexp = '<<<.*?>>>';
986 function markup($match)
988 return HTML::span($match);
992 // Single-line HTML comment
993 // <!-- This is a comment -->
994 class Markup_html_comment extends SimpleMarkup
996 public $_match_regexp = '<!--.*?-->';
998 function markup($match)
1000 return HTML::raw('');
1004 // Special version for single-line plugins formatting,
1005 // like: '<small>< ?plugin PopularNearby ? ></small>'
1006 class Markup_plugin extends SimpleMarkup
1008 public $_match_regexp = '<\?plugin(?:-form)?\s[^\n]+?\?>';
1010 function markup($match)
1012 return new Cached_PluginInvocation($match);
1016 // Special version for single-line Wikicreole plugins formatting.
1017 class Markup_plugin_wikicreole extends SimpleMarkup
1019 public $_match_regexp = '<<[^\n]+?>>';
1021 function markup($match)
1023 $pi = str_replace("<<", "<?plugin ", $match);
1024 $pi = str_replace(">>", " ?>", $pi);
1025 return new Cached_PluginInvocation($pi);
1029 // Special version for plugins in xml syntax, mediawiki-style
1030 // <name arg=value>body</name> or <name /> => < ? plugin pluginname arg=value body ? >
1031 // PLUGIN_MARKUP_MAP = "html:RawHtml dot:GraphViz toc:CreateToc amath:AsciiMath richtable:RichTable include:IncludePage tex:TexToPng"
1032 class Markup_xml_plugin extends BalancedMarkup
1034 //public $_start_regexp = "<(?: ".join('|',PLUGIN_MARKUP_MAP)." )(?: \s[^>]*)>";
1036 function getStartRegexp()
1038 global $PLUGIN_MARKUP_MAP;
1039 static $_start_regexp;
1040 if ($_start_regexp) return $_start_regexp;
1041 if (empty($PLUGIN_MARKUP_MAP)) return '';
1042 //"<(?: html|search|extsearch|dot|toc|math|richtable|include|tex )(?: \s[^>]*)>"
1043 $_start_regexp = "<(?: " . join('|', array_keys($PLUGIN_MARKUP_MAP)) . " )(?: \s[^>]*|\\/ )>";
1044 return $_start_regexp;
1047 function getEndRegexp($match)
1049 return "<\\/" . $match . '>';
1052 function markup($match, $body)
1054 global $PLUGIN_MARKUP_MAP;
1055 $name = substr($match, 2, -2);
1057 if (preg_match('/^(\S+)\|(.*)$/', $name, $_m)) {
1059 $vars = $_m[2]; //str_replace(' ', '&', $_m[2]);
1061 if (!isset($PLUGIN_MARKUP_MAP[$name])) {
1062 trigger_error("No plugin for $name $vars defined.", E_USER_WARNING);
1065 $plugin = $PLUGIN_MARKUP_MAP[$name];
1066 return new Cached_PluginInvocation("<" . "?plugin $plugin $vars $body ?" . ">");
1071 * Mediawiki <nowiki>
1072 * <nowiki>...</nowiki>
1074 class Markup_nowiki extends SimpleMarkup
1076 public $_match_regexp = '<nowiki>.*?<\/nowiki>';
1078 function markup($match)
1080 // Remove <nowiki> and </nowiki>
1081 return HTML::raw(substr($match, 8, -9));
1086 * Wikicreole preformatted
1090 class Markup_wikicreole_preformatted extends SimpleMarkup
1092 public $_match_regexp = '\{\{\{.*?\}\}\}';
1094 function markup($match)
1096 // Remove {{{ and }}}
1097 return new HtmlElement('span', array('class' => 'tt'), substr($match, 3, -3));
1101 /** ENABLE_MARKUP_TEMPLATE
1102 * Template syntax similar to Mediawiki
1104 * => < ? plugin Template page=template ? >
1105 * {{template|var1=value1|var2=value|...}}
1106 * => < ? plugin Template page=template var=value ... ? >
1108 * The {{...}} syntax is also used for:
1109 * - Wikicreole images
1111 * - predefined icons
1113 class Markup_template_plugin extends SimpleMarkup
1115 // patch #1732793: allow \n, mult. {{ }} in one line, and single letters
1116 public $_match_regexp = '\{\{.*?\}\}';
1118 function markup($match)
1121 $page = substr($match, 2, -2);
1122 $page = trim($page);
1124 // Check for predefined icons.
1125 $predefinedicons = array(":)" => "ic_smile.png",
1126 ":(" => "ic_sad.png",
1127 ":P" => "ic_tongue.png",
1128 ":D" => "ic_biggrin.png",
1129 ";)" => "ic_wink.png",
1130 "(y)" => "ic_handyes.png",
1131 "(n)" => "ic_handno.png",
1132 "(i)" => "ic_info.png",
1133 "(/)" => "ic_check.png",
1134 "(x)" => "ic_cross.png",
1135 "(!)" => "ic_danger.png",
1136 "(+)" => "ic_plus.png",
1137 "(-)" => "ic_minus.png",
1138 "(?)" => "ic_help.png",
1139 "(on)" => "ic_lighton.png",
1140 "(off)" => "ic_lightoff.png",
1141 "(*)" => "ic_yellowstar.png",
1142 "(*r)" => "ic_redstar.png",
1143 "(*g)" => "ic_greenstar.png",
1144 "(*b)" => "ic_bluestar.png",
1145 "(*y)" => "ic_yellowstar.png",
1147 foreach ($predefinedicons as $ascii => $icon) {
1148 if ($page == $ascii) {
1149 return LinkImage(DATA_PATH . "/themes/default/images/$icon", $page);
1153 if (strpos($page, "|") === false) {
1157 $imagename = substr($page, 0, strpos($page, "|"));
1158 $alt = ltrim(strstr($page, "|"), "|");
1161 // It's not a Mediawiki template, it's a Wikicreole image
1162 if (is_image($imagename)) {
1163 if ((strpos($imagename, "http://") === 0) || (strpos($imagename, "https://") === 0)) {
1164 return LinkImage($imagename, $alt);
1165 } elseif ($imagename[0] == '/') {
1166 return LinkImage(DATA_PATH . '/' . $imagename, $alt);
1168 return LinkImage(getUploadDataPath() . $imagename, $alt);
1173 if (is_video($imagename)) {
1174 $s = '<' . '?plugin Video file="' . $imagename . '" ?' . '>';
1175 return new Cached_PluginInvocation($s);
1178 $page = str_replace("\n", "", $page);
1180 // The argument value might contain a double quote (")
1181 // We have to encode that.
1182 $page = htmlspecialchars($page);
1186 if (preg_match('/^(\S+?)\|(.*)$/', $page, $_m)) {
1188 $vars = '"' . preg_replace('/\|/', '" "', $_m[2]) . '"';
1189 $vars = preg_replace('/"(\S+)=([^"]*)"/', '\\1="\\2"', $vars);
1192 // page may contain a version number
1193 // {{foo?version=5}}
1194 // in that case, output is "page=foo rev=5"
1195 if (strstr($page, "?")) {
1196 $page = str_replace("?version=", "\" rev=\"", $page);
1200 $s = '<' . '?plugin Template page="' . $page . '" ' . $vars . ' ?' . '>';
1202 $s = '<' . '?plugin Template page="' . $page . '" ?' . '>';
1203 return new Cached_PluginInvocation($s);
1207 // "..." => "…" browser specific display (not cached?)
1208 // Support some HTML::Entities: (C) for copy, --- for mdash, -- for ndash
1209 // TODO: "--" => "&emdash;" browser specific display (not cached?)
1211 class Markup_html_entities extends SimpleMarkup
1213 //public $_match_regexp = '(: \.\.\.|\-\-|\-\-\-|\(C\) )';
1215 function __construct()
1217 $this->_entities = array('...' => '…',
1221 '©' => '©',
1222 '™' => '™',
1224 $this->_match_regexp =
1226 join('|', array_map('preg_quote', array_keys($this->_entities))) .
1230 function markup($match)
1232 return HTML::Raw($this->_entities[$match]);
1236 class Markup_isonumchars extends SimpleMarkup
1238 public $_match_regexp = '\&\#\d{2,5};';
1240 function markup($match)
1242 return HTML::Raw($match);
1246 class Markup_isohexchars extends SimpleMarkup
1248 // hexnums, like ¤ <=> ¤
1249 public $_match_regexp = '\&\#x[0-9a-fA-F]{2,4};';
1251 function markup($match)
1253 return HTML::Raw($match);
1257 // FIXME: Do away with magic phpwiki forms. (Maybe phpwiki: links too?)
1259 class InlineTransformer
1261 public $_regexps = array();
1262 public $_markup = array();
1264 function InlineTransformer($markup_types = false)
1267 // We need to extend the inline parsers by certain actions, like SearchHighlight,
1268 // SpellCheck and maybe CreateToc.
1269 if (!$markup_types) {
1270 $non_default = false;
1271 $markup_types = array
1272 ('escape', 'wikicreolebracketlink', 'bracketlink', 'url',
1273 'html_comment', 'placeholder',
1274 'interwiki', 'semanticlink', 'wikiword', 'linebreak',
1275 'wikicreole_superscript',
1276 'wikicreole_subscript',
1277 'wikicreole_italics', 'wikicreole_bold',
1278 'wikicreole_monospace',
1279 'wikicreole_underline',
1280 'old_emphasis', 'nestled_emphasis',
1281 'html_emphasis', 'html_abbr', 'plugin', 'plugin_wikicreole',
1282 'isonumchars', 'isohexchars', /*'html_entities'*/
1284 if (DISABLE_MARKUP_WIKIWORD)
1285 $markup_types = array_remove($markup_types, 'wikiword');
1287 $action = $request->getArg('action');
1288 if ($action == 'SpellCheck' and $request->getArg('suggestions')) { // insert it after url
1289 array_splice($markup_types, 2, 1, array('url', 'spellcheck'));
1291 if (isset($request->_searchhighlight)) { // insert it after url
1292 array_splice($markup_types, 2, 1, array('url', 'searchhighlight'));
1293 //$request->setArg('searchhighlight', false);
1296 $non_default = true;
1298 foreach ($markup_types as $mtype) {
1299 $class = "Markup_$mtype";
1300 $this->_addMarkup(new $class);
1302 $this->_addMarkup(new Markup_nowiki);
1303 if (ENABLE_MARKUP_DIVSPAN and !$non_default)
1304 $this->_addMarkup(new Markup_html_divspan);
1305 if (ENABLE_MARKUP_COLOR and !$non_default)
1306 $this->_addMarkup(new Markup_color);
1307 // Markup_wikicreole_preformatted must be before Markup_template_plugin
1308 $this->_addMarkup(new Markup_wikicreole_preformatted);
1309 if (ENABLE_MARKUP_TEMPLATE and !$non_default)
1310 $this->_addMarkup(new Markup_template_plugin);
1311 // This does not work yet
1312 if (PLUGIN_MARKUP_MAP and !$non_default)
1313 $this->_addMarkup(new Markup_xml_plugin);
1316 function _addMarkup($markup)
1318 if (isa($markup, 'SimpleMarkup'))
1319 $regexp = $markup->getMatchRegexp();
1321 $regexp = $markup->getStartRegexp();
1323 assert(!isset($this->_markup[$regexp]));
1324 assert(strlen(trim($regexp)) > 0);
1325 $this->_regexps[] = $regexp;
1326 $this->_markup[] = $markup;
1329 function parse(&$text, $end_regexps = array('$'))
1331 $regexps = $this->_regexps;
1333 // $end_re takes precedence: "favor reduce over shift"
1334 array_unshift($regexps, $end_regexps[0]);
1335 //array_push($regexps, $end_regexps[0]);
1336 $regexps = new RegexpSet($regexps);
1339 $output = new XmlContent;
1341 $match = $regexps->match($input);
1344 if ($match->regexp_ind == 0) {
1345 // No start pattern found before end pattern.
1347 if (isset($markup) and is_object($markup)
1348 and isa($markup, 'Markup_plugin')
1350 $current =& $output->_content[count($output->_content) - 1];
1351 $current->setTightness(true, true);
1353 $output->pushContent($match->prematch);
1354 $text = $match->postmatch;
1358 $markup = $this->_markup[$match->regexp_ind - 1];
1359 $body = $this->_parse_markup_body($markup, $match->match,
1360 $match->postmatch, $end_regexps);
1362 // Couldn't match balanced expression.
1363 // Ignore and look for next matching start regexp.
1364 $match = $regexps->nextMatch($input, $match);
1368 // Matched markup. Eat input, push output.
1369 // FIXME: combine adjacent strings.
1370 if (isa($markup, 'SimpleMarkup'))
1371 $current = $markup->markup($match->match);
1373 $current = $markup->markup($match->match, $body);
1374 $input = $match->postmatch;
1375 if (isset($markup) and is_object($markup)
1376 and isa($markup, 'Markup_plugin')
1378 $current->setTightness(true, true);
1380 $output->pushContent($match->prematch, $current);
1382 $match = $regexps->match($input);
1385 // No pattern matched, not even the end pattern.
1390 function _parse_markup_body($markup, $match, &$text, $end_regexps)
1392 if (isa($markup, 'SimpleMarkup')) {
1393 return true; // Done. SimpleMarkup is simple.
1396 if (!is_object($markup)) {
1397 return false; // Some error: Should assert
1399 array_unshift($end_regexps, $markup->getEndRegexp($match));
1401 // Optimization: if no end pattern in text, we know the
1402 // parse will fail. This is an important optimization,
1403 // e.g. when text is "*lots *of *start *delims *with
1404 // *no *matching *end *delims".
1405 $ends_pat = "/(?:" . join(").*(?:", $end_regexps) . ")/xs";
1406 if (!@preg_match($ends_pat, $text)) { // Add "@" to avoid warning with "{{(*y)}}"
1409 return $this->parse($text, $end_regexps);
1413 class LinkTransformer extends InlineTransformer
1415 function __construct()
1417 parent::__construct(array('escape', 'wikicreolebracketlink', 'bracketlink', 'url',
1418 'semanticlink', 'interwiki', 'wikiword',
1423 class NowikiTransformer extends InlineTransformer
1425 function __construct()
1429 'html_emphasis', 'html_abbr', 'plugin', 'plugin_wikicreole',
1430 'isonumchars', 'isohexchars', /*'html_entities',*/
1435 function TransformInline($text, $basepage = false)
1438 $action = $GLOBALS['request']->getArg('action');
1439 if (empty($trfm) or $action == 'SpellCheck') {
1440 $trfm = new InlineTransformer;
1444 return new CacheableMarkup($trfm->parse($text), $basepage);
1446 return $trfm->parse($text);
1449 function TransformLinks($text, $basepage = false)
1454 $trfm = new LinkTransformer;
1458 return new CacheableMarkup($trfm->parse($text), $basepage);
1460 return $trfm->parse($text);
1464 * Transform only html markup and entities.
1466 function TransformInlineNowiki($text, $basepage = false)
1471 $trfm = new NowikiTransformer;
1474 return new CacheableMarkup($trfm->parse($text), $basepage);
1476 return $trfm->parse($text);
1482 // c-basic-offset: 4
1483 // c-hanging-comment-ender-p: nil
1484 // indent-tabs-mode: nil