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');
41 function WikiEscape($text) {
42 return str_replace('#', ESCAPE_CHAR . '#', $text);
45 function UnWikiEscape($text) {
46 return preg_replace('/' . ESCAPE_CHAR . '(.)/', '\1', $text);
50 * Return type from RegexpSet::match and RegexpSet::nextMatch.
54 class RegexpSet_match {
56 * The text leading up the the next match.
64 * The text following the matched text.
68 * Index of the regular expression which matched.
74 * A set of regular expressions.
76 * This class is probably only useful for InlineTransformer.
82 * @param array $regexps A list of regular expressions. The
83 * regular expressions should not include any sub-pattern groups
84 * "(...)". (Anonymous groups, like "(?:...)", as well as
85 * look-ahead and look-behind assertions are okay.)
87 function RegexpSet ($regexps) {
89 $this->_regexps = array_unique($regexps);
90 if (!defined('_INLINE_OPTIMIZATION')) define('_INLINE_OPTIMIZATION',0);
94 * Search text for the next matching regexp from the Regexp Set.
96 * @param string $text The text to search.
98 * @return RegexpSet_match A RegexpSet_match object, or false if no match.
100 function match ($text) {
101 return $this->_match($text, $this->_regexps, '*?');
105 * Search for next matching regexp.
107 * Here, 'next' has two meanings:
109 * Match the next regexp(s) in the set, at the same position as the last match.
111 * If that fails, match the whole RegexpSet, starting after the position of the
114 * @param string $text Text to search.
116 * @param RegexpSet_match $prevMatch A RegexpSet_match object.
117 * $prevMatch should be a match object obtained by a previous
118 * match upon the same value of $text.
120 * @return RegexpSet_match A RegexpSet_match object, or false if no match.
122 function nextMatch ($text, $prevMatch) {
123 // Try to find match at same position.
124 $pos = strlen($prevMatch->prematch);
125 $regexps = array_slice($this->_regexps, $prevMatch->regexp_ind + 1);
127 $repeat = sprintf('{%d}', $pos);
128 if ( ($match = $this->_match($text, $regexps, $repeat)) ) {
129 $match->regexp_ind += $prevMatch->regexp_ind + 1;
135 // Failed. Look for match after current position.
136 $repeat = sprintf('{%d,}?', $pos + 1);
137 return $this->_match($text, $this->_regexps, $repeat);
140 // Syntax: http://www.pcre.org/pcre.txt
141 // x - EXTENDED, ignore whitespace
145 function _match ($text, $regexps, $repeat) {
146 // If one of the regexps is an empty string, php will crash here:
147 // sf.net: Fatal error: Allowed memory size of 8388608 bytes exhausted
148 // (tried to allocate 634 bytes)
149 if (_INLINE_OPTIMIZATION) { // disabled, wrong
150 // So we try to minize memory usage, by looping explicitly,
151 // and storing only those regexp which actually match.
152 // There may be more than one, so we have to find the longest,
153 // and match inside until the shortest is empty.
154 $matched = array(); $matched_ind = array();
155 for ($i=0; $i<count($regexps); $i++) {
156 if (!trim($regexps[$i])) {
157 trigger_error("empty regexp $i", E_USER_WARNING);
160 $pat= "/ ( . $repeat ) ( " . $regexps[$i] . " ) /x";
161 if (preg_match($pat, $text, $_m)) {
162 $m = $_m; // FIXME: prematch, postmatch is wrong
163 $matched[] = $regexps[$i];
168 // To overcome ANCHORED:
169 // We could sort by longest match and iterate over these.
170 if (empty($matched)) return false;
172 $match = new RegexpSet_match;
174 // Optimization: if the matches are only "$" and another, then omit "$"
175 if (! _INLINE_OPTIMIZATION or count($matched) > 2) {
176 assert(!empty($repeat));
177 assert(!empty($regexps));
178 // We could do much better, if we would know the matching markup for the
179 // longest regexp match:
180 $hugepat= "/ ( . $repeat ) ( (" . join(')|(', $regexps) . ") ) /Asx";
181 // Proposed premature optimization 1:
182 //$hugepat= "/ ( . $repeat ) ( (" . join(')|(', array_values($matched)) . ") ) /Asx";
183 if (! preg_match($hugepat, $text, $m)) {
186 // Proposed premature optimization 1:
187 //$match->regexp_ind = $matched_ind[count($m) - 4];
188 $match->regexp_ind = count($m) - 4;
190 $match->regexp_ind = $regexp_ind;
193 $match->postmatch = substr($text, strlen($m[0]));
194 $match->prematch = $m[1];
195 $match->match = $m[2];
198 if (DEBUG & _DEBUG_PARSER) {
199 static $_already_dumped = 0;
200 if (!$_already_dumped) {
202 if (_INLINE_OPTIMIZATION)
204 var_dump($matched_ind);
206 $_already_dumped = 1;
207 PrintXML(HTML::dl(HTML::dt("input"),
208 HTML::dd(HTML::pre($text)),
210 HTML::dd(HTML::pre($match->regexp_ind, ":", $regexps[$match->regexp_ind])),
211 HTML::dt("prematch"),
212 HTML::dd(HTML::pre($match->prematch)),
214 HTML::dd(HTML::pre($match->match)),
215 HTML::dt("postmatch"),
216 HTML::dd(HTML::pre($match->postmatch))
226 * A simple markup rule (i.e. terminal token).
228 * These are defined by a regexp.
230 * When a match is found for the regexp, the matching text is replaced.
231 * The replacement content is obtained by calling the SimpleMarkup::markup method.
239 * @return string Regexp which matches this token.
241 function getMatchRegexp () {
242 return $this->_match_regexp;
245 /** Markup matching text.
247 * @param string $match The text which matched the regexp
248 * (obtained from getMatchRegexp).
250 * @return mixed The expansion of the matched text.
252 function markup ($match /*, $body */) {
253 trigger_error("pure virtual", E_USER_ERROR);
258 * A balanced markup rule.
260 * These are defined by a start regexp, and an end regexp.
266 /** Get the starting regexp for this rule.
268 * @return string The starting regexp.
270 function getStartRegexp () {
271 return $this->_start_regexp;
274 /** Get the ending regexp for this rule.
276 * @param string $match The text which matched the starting regexp.
278 * @return string The ending regexp.
280 function getEndRegexp ($match) {
281 return $this->_end_regexp;
284 /** Get expansion for matching input.
286 * @param string $match The text which matched the starting regexp.
288 * @param mixed $body Transformed text found between the starting
289 * and ending regexps.
291 * @return mixed The expansion of the matched text.
293 function markup ($match, $body) {
294 trigger_error("pure virtual", E_USER_ERROR);
298 class Markup_escape extends SimpleMarkup
300 function getMatchRegexp () {
301 return ESCAPE_CHAR . '(?: [[:alnum:]]+ | .)';
304 function markup ($match) {
305 assert(strlen($match) >= 2);
306 return substr($match, 1);
311 * [image.jpg size=50% border=5], [image.jpg size=50x30]
312 * Support for the following attributes: see stdlib.php:LinkImage()
313 * size=<percent>%, size=<width>x<height>
314 * border=n, align=\w+, hspace=n, vspace=n
316 * title, lang, id, alt
318 function isImageLink($link) {
319 if (!$link) return false;
320 assert(defined('INLINE_IMAGES'));
321 return preg_match("/\\.(" . INLINE_IMAGES . ")$/i", $link)
322 or preg_match("/\\.(" . INLINE_IMAGES . ")\s+(size|border|align|hspace|vspace|type|data|width|height|title|lang|id|alt)=/i", $link);
325 function LinkBracketLink($bracketlink) {
327 // $bracketlink will start and end with brackets; in between will
328 // be either a page name, a URL or both separated by a pipe.
330 $wikicreolesyntax = false;
332 if (string_starts_with($bracketlink, "[[") or string_starts_with($bracketlink, "#[[")) {
333 $wikicreolesyntax = true;
334 $bracketlink = str_replace("[[", "[", $bracketlink);
335 $bracketlink = str_replace("]]", "]", $bracketlink);
338 // Strip brackets and leading space
339 // bug#1904088 Some brackets links on 2 lines cause the parser to crash
340 preg_match('/(\#?) \[\s* (?: (.*?) \s* (?<!' . ESCAPE_CHAR . ')(\|) )? \s* (.+?) \s*\]/x',
341 str_replace("\n", " ", $bracketlink), $matches);
342 if (count($matches) < 4) {
343 // "[ personal\ninformation manager | PhpWiki:PersonalWiki ]"
344 trigger_error(_("Invalid [] syntax ignored")._(": ").$bracketlink, E_USER_WARNING);
345 return new Cached_Link;
347 list (, $hash, $label, $bar, $rawlink) = $matches;
349 if ($wikicreolesyntax and $label) {
355 // Mediawiki compatibility: allow "Image:" and "File:"
356 // as synonyms of "Upload:"
357 // Allow "upload:", "image:" and "file:" also
358 // Remove spaces before and after ":", if any
359 if (string_starts_with($rawlink, "Upload")) {
360 $rawlink = preg_replace("/^Upload\\s*:\\s*/", "Upload:", $rawlink);
361 } else if (string_starts_with($rawlink, "upload")) {
362 $rawlink = preg_replace("/^upload\\s*:\\s*/", "Upload:", $rawlink);
363 } else if (string_starts_with($rawlink, "Image")) {
364 $rawlink = preg_replace("/^Image\\s*:\\s*/", "Upload:", $rawlink);
365 } else if (string_starts_with($rawlink, "image")) {
366 $rawlink = preg_replace("/^image\\s*:\\s*/", "Upload:", $rawlink);
367 } else if (string_starts_with($rawlink, "File")) {
368 $rawlink = preg_replace("/^File\\s*:\\s*/", "Upload:", $rawlink);
369 } else if (string_starts_with($rawlink, "file")) {
370 $rawlink = preg_replace("/^file\\s*:\\s*/", "Upload:", $rawlink);
373 $label = UnWikiEscape($label);
375 * Check if the user has typed a explicit URL. This solves the
376 * problem where the URLs have a ~ character, which would be stripped away.
377 * "[http:/server/~name/]" will work as expected
378 * "http:/server/~name/" will NOT work as expected, will remove the ~
380 if ( string_starts_with ($rawlink, "http://")
381 or string_starts_with ($rawlink, "https://") )
384 // Mozilla Browser URI Obfuscation Weakness 2004-06-14
385 // http://www.securityfocus.com/bid/10532/
386 // goodurl+"%2F%20%20%20."+badurl
387 if (preg_match("/%2F(%20)+\./i", $rawlink)) {
388 $rawlink = preg_replace("/%2F(%20)+\./i","%2F.",$rawlink);
391 // Check page name lenght
392 if (strlen($rawlink) > MAX_PAGENAME_LENGTH) {
393 return HTML::span(array('class' => 'error'),
394 _('Page name too long'));
396 // Check illegal characters in page names: <>[]{}|"
397 if (preg_match("/[<\[\{\|\"\}\]>]/", $rawlink, $matches) > 0) {
398 return HTML::span(array('class' => 'error'),
399 sprintf(_("Illegal character '%s' in page name."),
402 $link = UnWikiEscape($rawlink);
405 /* Relatives links by Joel Schaubert.
406 * Recognize [../bla] or [/bla] as relative links, without needing http://
407 * but [ /link ] only if SUBPAGE_SEPERATOR is not "/".
408 * Normally /Page links to the subpage /Page.
410 if (SUBPAGE_SEPARATOR == '/') {
411 if (preg_match('/^\.\.\//', $link)) {
412 return new Cached_ExternalLink($link, $label);
414 } else if (preg_match('/^(\.\.\/|\/)/', $link)) {
415 return new Cached_ExternalLink($link, $label);
418 // Handle "[[SandBox|{{image.jpg}}]]" and "[[SandBox|{{image.jpg|alt text}}]]"
419 if (string_starts_with($label, "{{")) {
420 $imgurl = substr($label, 2, -2); // Remove "{{" and "}}"
421 $pipe = strpos($imgurl, '|');
422 if ($pipe === false) {
423 $label = LinkImage(getUploadDataPath() . $imgurl, $link);
425 list($img, $alt) = explode("|", $imgurl);
426 $label = LinkImage(getUploadDataPath() . $img, $alt);
431 // If label looks like a url to an image or object, we want an image link.
432 if (isImageLink($label)) {
434 $intermap = getInterwikiMap();
435 if (preg_match("/^" . $intermap->getRegexp() . ":/", $label)) {
436 $imgurl = $intermap->link($label);
437 $imgurl = $imgurl->getAttr('href');
438 } elseif (! preg_match("#^(" . ALLOWED_PROTOCOLS . "):#", $imgurl)) {
439 // local theme linkname like 'images/next.gif'.
441 $imgurl = $WikiTheme->getImageURL($imgurl);
443 // for objects (non-images) the link is taken as alt tag,
444 // which is in return taken as alternative img
445 $label = LinkImage($imgurl, $link);
449 // It's an anchor, not a link...
450 $id = MangleXmlIdentifier($link);
451 return HTML::a(array('name' => $id, 'id' => $id),
452 $bar ? $label : $link);
455 if (preg_match("#^(" . ALLOWED_PROTOCOLS . "):#", $link)) {
456 // if it's an image, embed it; otherwise, it's a regular link
457 if (isImageLink($link) and empty($label)) // patch #1348996 by Robert Litwiniec
458 return LinkImage($link, $label);
460 return new Cached_ExternalLink($link, $label);
462 elseif (substr($link,0,8) == 'phpwiki:')
463 return new Cached_PhpwikiURL($link, $label);
465 /* Semantic relations and attributes.
466 * Relation and attribute names must be word chars only, no space.
467 * Links and Attributes may contain everything. word, nums, units, space, groupsep, numsep, ...
469 elseif (preg_match("/^ (\w+) (:[:=]) (.*) $/x", $link) and !isImageLink($link))
470 return new Cached_SemanticLink($link, $label);
472 /* Do not store the link */
473 elseif (substr($link,0,1) == ':')
474 return new Cached_WikiLink($link, $label);
477 * Inline images in Interwiki urls's:
478 * [File:my_image.gif] inlines the image,
479 * File:my_image.gif shows a plain inter-wiki link,
480 * [what a pic|File:my_image.gif] shows a named inter-wiki link to the gif
481 * [File:my_image.gif|what a pic] shows an inlined image linked to the page "what a pic"
483 * Note that for simplicity we will accept embedded object tags (non-images)
484 * here also, and seperate them later in LinkImage()
486 elseif (strstr($link,':')
487 and ($intermap = getInterwikiMap())
488 and preg_match("/^" . $intermap->getRegexp() . ":/", $link))
490 // trigger_error("label: $label link: $link", E_USER_WARNING);
491 if (empty($label) and isImageLink($link)) {
492 // if without label => inlined image [File:xx.gif]
493 $imgurl = $intermap->link($link);
494 return LinkImage($imgurl->getAttr('href'));
496 return new Cached_InterwikiLink($link, $label);
498 // Split anchor off end of pagename.
499 if (preg_match('/\A(.*)(?<!'.ESCAPE_CHAR.')#(.*?)\Z/', $rawlink, $m)) {
500 list(,$rawlink,$anchor) = $m;
501 $pagename = UnWikiEscape($rawlink);
502 $anchor = UnWikiEscape($anchor);
510 return new Cached_WikiLink($pagename, $label, $anchor);
514 class Markup_wikicreolebracketlink extends SimpleMarkup
516 var $_match_regexp = "\\#? \\[\\[ .*? [^]\\s] .*? \\]\\]";
518 function markup ($match) {
519 $link = LinkBracketLink($match);
520 assert($link->isInlineElement());
525 class Markup_bracketlink extends SimpleMarkup
527 var $_match_regexp = "\\#? \\[ .*? [^]\\s] .*? \\]";
529 function markup ($match) {
530 $link = LinkBracketLink($match);
531 assert($link->isInlineElement());
536 class Markup_spellcheck extends SimpleMarkup
538 function Markup_spellcheck () {
539 $this->suggestions = $GLOBALS['request']->getArg('suggestions');
541 function getMatchRegexp () {
542 if (empty($this->suggestions))
543 return "(?# false )";
544 $words = array_keys($this->suggestions);
545 return "(?<= \W ) (?:" . join('|', $words) . ") (?= \W )";
548 function markup ($match) {
549 if (empty($this->suggestions) or empty($this->suggestions[$match]))
551 return new Cached_SpellCheck(UnWikiEscape($match), $this->suggestions[$match]);
555 class Markup_searchhighlight extends SimpleMarkup
557 function Markup_searchhighlight () {
558 $result = $GLOBALS['request']->_searchhighlight;
559 require_once("lib/TextSearchQuery.php");
560 $query = new TextSearchQuery($result['query']);
561 $this->hilight_re = $query->getHighlightRegexp();
562 $this->engine = $result['engine'];
564 function getMatchRegexp () {
565 return $this->hilight_re;
567 function markup ($match) {
568 return new Cached_SearchHighlight(UnWikiEscape($match), $this->engine);
572 class Markup_url extends SimpleMarkup
574 function getMatchRegexp () {
575 return "(?<![[:alnum:]]) (?:" . ALLOWED_PROTOCOLS . ") : [^\s<>\"']+ (?<![ ,.?; \] \) ])";
578 function markup ($match) {
579 return new Cached_ExternalLink(UnWikiEscape($match));
583 class Markup_interwiki extends SimpleMarkup
585 function getMatchRegexp () {
586 $map = getInterwikiMap();
587 return "(?<! [[:alnum:]])" . $map->getRegexp(). ": [^:=]\S+ (?<![ ,.?;! \] \) \" \' ])";
590 function markup ($match) {
591 return new Cached_InterwikiLink(UnWikiEscape($match));
595 class Markup_semanticlink extends SimpleMarkup
597 // No units seperated by space allowed here
598 // For :: (relations) only words, no comma,
599 // but for := (attributes) comma and dots are allowed. Units with groupsep.
600 // Ending dots or comma are not part of the link.
601 var $_match_regexp = "(?: \w+:=\S+(?<![\.,]))|(?: \w+::[\w\.]+(?<!\.))";
603 function markup ($match) {
604 return new Cached_SemanticLink(UnWikiEscape($match));
608 class Markup_wikiword extends SimpleMarkup
610 function getMatchRegexp () {
611 global $WikiNameRegexp;
612 if (!trim($WikiNameRegexp)) return " " . WIKI_NAME_REGEXP;
613 return " $WikiNameRegexp";
616 function markup ($match) {
617 if (!$match) return false;
618 if ($this->_isWikiUserPage($match))
619 return new Cached_UserLink($match); //$this->_UserLink($match);
621 return new Cached_WikiLink($match);
624 // FIXME: there's probably a more useful place to put these two functions
625 function _isWikiUserPage ($page) {
627 $dbi = $request->getDbh();
628 $page_handle = $dbi->getPage($page);
629 if ($page_handle and $page_handle->get('pref'))
635 function _UserLink($PageName) {
636 $link = HTML::a(array('href' => $PageName));
637 $link->pushContent(PossiblyGlueIconToText('wikiuser', $PageName));
638 $link->setAttr('class', 'wikiuser');
643 class Markup_linebreak extends SimpleMarkup
645 var $_match_regexp = "(?: (?<! %) %%% (?! %) | \\\\\\\\ | <\s*(?:br|BR)\s*> | <\s*(?:br|BR)\s*\/\s*> )";
647 function markup ($match) {
652 class Markup_wikicreole_italics extends BalancedMarkup
654 var $_start_regexp = "\\/\\/";
656 function getEndRegexp ($match) {
660 function markup ($match, $body) {
662 return new HtmlElement($tag, $body);
666 class Markup_wikicreole_bold extends BalancedMarkup
668 var $_start_regexp = "\\*\\*";
670 function getEndRegexp ($match) {
674 function markup ($match, $body) {
676 return new HtmlElement($tag, $body);
680 class Markup_wikicreole_monospace extends BalancedMarkup
682 var $_start_regexp = "\\#\\#";
684 function getEndRegexp ($match) {
688 function markup ($match, $body) {
690 return new HtmlElement($tag, $body);
694 class Markup_wikicreole_underline extends BalancedMarkup
696 var $_start_regexp = "\\_\\_";
698 function getEndRegexp ($match) {
702 function markup ($match, $body) {
704 return new HtmlElement($tag, $body);
708 class Markup_wikicreole_superscript extends BalancedMarkup
710 var $_start_regexp = "\\^\\^";
712 function getEndRegexp ($match) {
716 function markup ($match, $body) {
718 return new HtmlElement($tag, $body);
722 class Markup_wikicreole_subscript extends BalancedMarkup
724 var $_start_regexp = ",,";
726 function getEndRegexp ($match) {
730 function markup ($match, $body) {
732 return new HtmlElement($tag, $body);
736 class Markup_old_emphasis extends BalancedMarkup
738 var $_start_regexp = "''";
740 function getEndRegexp ($match) {
744 function markup ($match, $body) {
746 return new HtmlElement($tag, $body);
750 class Markup_nestled_emphasis extends BalancedMarkup
752 function getStartRegexp() {
753 static $start_regexp = false;
755 if (!$start_regexp) {
756 // The three possible delimiters
757 // (none of which can be followed by itself.)
762 $any = "(?: ${i}|${b}|${tt})"; // any of the three.
764 // Any of [_*=] is okay if preceded by space or one of [-"'/:]
765 $start[] = "(?<= \\s|^|[-\"'\\/:]) ${any}";
767 // _ or * is okay after = as long as not immediately followed by =
768 $start[] = "(?<= =) (?: ${i}|${b}) (?! =)";
770 $start[] = "(?<= _) (?: ${b}|${tt}) (?! _)";
771 $start[] = "(?<= \\*) (?: ${i}|${tt}) (?! \\*)";
774 // any delimiter okay after an opening brace ( [{<(] )
775 // as long as it's not immediately followed by the matching closing
777 $start[] = "(?<= { ) ${any} (?! } )";
778 $start[] = "(?<= < ) ${any} (?! > )";
779 $start[] = "(?<= \\( ) ${any} (?! \\) )";
781 $start = "(?:" . join('|', $start) . ")";
783 // Any of the above must be immediately followed by non-whitespace.
784 $start_regexp = $start . "(?= \S)";
787 return $start_regexp;
790 function getEndRegexp ($match) {
791 $chr = preg_quote($match);
792 return "(?<= \S | ^ ) (?<! $chr) $chr (?! $chr) (?= \s | [-)}>\"'\\/:.,;!? _*=] | $)";
795 function markup ($match, $body) {
797 case '*': return new HtmlElement('b', $body);
798 case '=': return new HtmlElement('tt', $body);
799 case '_': return new HtmlElement('i', $body);
804 class Markup_html_emphasis extends BalancedMarkup
807 "<(?: b|big|i|small|tt|em|strong|cite|code|dfn|kbd|samp|s|strike|del|var|sup|sub )>";
809 function getEndRegexp ($match) {
810 return "<\\/" . substr($match, 1);
813 function markup ($match, $body) {
814 $tag = substr($match, 1, -1);
815 return new HtmlElement($tag, $body);
819 class Markup_html_divspan extends BalancedMarkup
822 "<(?: div|span )(?: \s[^>]*)?>";
824 function getEndRegexp ($match) {
825 if (substr($match,1,4) == 'span')
829 return "<\\/" . $tag . '>';
832 function markup ($match, $body) {
833 if (substr($match,1,4) == 'span')
837 $rest = substr($match,1+strlen($tag),-1);
839 $args = parse_attributes($rest);
843 return new HtmlElement($tag, $args, $body);
848 class Markup_html_abbr extends BalancedMarkup
850 //rurban: abbr|acronym need an optional title tag.
852 var $_start_regexp = "<(?: abbr|acronym )(?: [^>]*)?>";
854 function getEndRegexp ($match) {
855 if (substr($match,1,4) == 'abbr')
859 return "<\\/" . $tag . '>';
862 function markup ($match, $body) {
863 if (substr($match,1,4) == 'abbr')
867 $rest = substr($match,1+strlen($tag),-1);
868 $attrs = parse_attributes($rest);
869 // Remove attributes other than title and lang
870 $allowedargs = array();
871 foreach ($attrs as $key => $value) {
872 if (in_array ($key, array("title", "lang"))) {
873 $allowedargs[$key] = $value;
876 return new HtmlElement($tag, $allowedargs, $body);
880 /** ENABLE_MARKUP_COLOR
881 * See http://www.pmwiki.org/wiki/PmWiki/WikiStyles and
882 * http://www.flexwiki.com/default.aspx/FlexWiki/FormattingRules.html
884 class Markup_color extends BalancedMarkup {
885 // %color=blue% blue text %% and back to normal
886 var $_start_regexp = "%color=(?: [^%]*)%";
887 var $_end_regexp = "%%";
889 function markup ($match, $body) {
890 $color = strtolower(substr($match, 7, -1));
892 $morecolors = array('beige' => '#f5f5dc',
893 'brown' => '#a52a2a',
894 'chocolate' => '#d2691e',
897 'ivory' => '#fffff0',
898 'indigo' => '#4b0082',
899 'magenta' => '#ff00ff',
900 'orange' => '#ffa500',
902 'salmon' => '#fa8072',
904 'turquoise' => '#40e0d0',
905 'violet' => '#ee82ee',
908 if (isset($morecolors[$color])) {
909 $color = $morecolors[$color];
912 // HTML 4 defines the following 16 colors
913 if (in_array($color, array('aqua', 'black', 'blue', 'fuchsia',
914 'gray', 'green', 'lime', 'maroon',
915 'navy', 'olive', 'purple', 'red',
916 'silver', 'teal', 'white', 'yellow'))
917 or ((substr($color,0,1) == '#')
918 and ((strlen($color) == 4) or (strlen($color) == 7))
919 and (strspn(substr($color,1),'0123456789abcdef') == strlen($color)-1))) {
920 return new HtmlElement('span', array('style' => "color: $color"), $body);
922 return new HtmlElement('span', array('class' => 'error'),
923 sprintf(_("unknown color %s ignored"), substr($match, 7, -1)));
928 // Wikicreole placeholder
930 class Markup_placeholder extends SimpleMarkup
932 var $_match_regexp = '<<<.*?>>>';
934 function markup ($match) {
935 return HTML::span($match);
939 // Single-line HTML comment
940 // <!-- This is a comment -->
941 class Markup_html_comment extends SimpleMarkup
943 var $_match_regexp = '<!--.*?-->';
945 function markup ($match) {
946 return HTML::raw('');
950 // Special version for single-line plugins formatting,
951 // like: '<small>< ?plugin PopularNearby ? ></small>'
952 class Markup_plugin extends SimpleMarkup
954 var $_match_regexp = '<\?plugin(?:-form)?\s[^\n]+?\?>';
956 function markup ($match) {
957 return new Cached_PluginInvocation($match);
961 // Special version for single-line Wikicreole plugins formatting.
962 class Markup_plugin_wikicreole extends SimpleMarkup
964 var $_match_regexp = '<<[^\n]+?>>';
966 function markup ($match) {
967 $pi = str_replace("<<", "<?plugin ", $match);
968 $pi = str_replace(">>", " ?>", $pi);
969 return new Cached_PluginInvocation($pi);
973 // Special version for plugins in xml syntax, mediawiki-style
974 // <name arg=value>body</name> or <name /> => < ? plugin pluginname arg=value body ? >
975 // PLUGIN_MARKUP_MAP = "html:RawHtml dot:GraphViz toc:CreateToc amath:AsciiMath richtable:RichTable include:IncludePage tex:TexToPng"
976 class Markup_xml_plugin extends BalancedMarkup
978 //var $_start_regexp = "<(?: ".join('|',PLUGIN_MARKUP_MAP)." )(?: \s[^>]*)>";
980 function getStartRegexp () {
981 global $PLUGIN_MARKUP_MAP;
982 static $_start_regexp;
983 if ($_start_regexp) return $_start_regexp;
984 if (empty($PLUGIN_MARKUP_MAP)) return '';
985 //"<(?: html|search|extsearch|dot|toc|math|richtable|include|tex )(?: \s[^>]*)>"
986 $_start_regexp = "<(?: ".join('|',array_keys($PLUGIN_MARKUP_MAP))." )(?: \s[^>]*|\\/ )>";
987 return $_start_regexp;
989 function getEndRegexp ($match) {
990 return "<\\/" . $match . '>';
992 function markup ($match, $body) {
993 global $PLUGIN_MARKUP_MAP;
994 $name = substr($match,2,-2);
996 if (preg_match('/^(\S+)\|(.*)$/', $name, $_m)) {
998 $vars = $_m[2]; //str_replace(' ', '&', $_m[2]);
1000 if (!isset($PLUGIN_MARKUP_MAP[$name])) {
1001 trigger_error("No plugin for $name $vars defined.", E_USER_WARNING);
1004 $plugin = $PLUGIN_MARKUP_MAP[$name];
1005 return new Cached_PluginInvocation("<"."?plugin $plugin $vars $body ?".">");
1010 * Mediawiki <nowiki>
1011 * <nowiki>...</nowiki>
1013 class Markup_nowiki extends SimpleMarkup
1015 var $_match_regexp = '<nowiki>.*?<\/nowiki>';
1017 function markup ($match) {
1018 // Remove <nowiki> and </nowiki>
1019 return HTML::raw(substr($match, 8, -9));
1024 * Wikicreole preformatted
1028 class Markup_wikicreole_preformatted extends SimpleMarkup
1030 var $_match_regexp = '\{\{\{.*?\}\}\}';
1032 function markup ($match) {
1033 // Remove {{{ and }}}
1034 return new HtmlElement('tt', substr($match, 3, -3));
1038 /** ENABLE_MARKUP_TEMPLATE
1039 * Template syntax similar to Mediawiki
1041 * => < ? plugin Template page=template ? >
1042 * {{template|var1=value1|var2=value|...}}
1043 * => < ? plugin Template page=template var=value ... ? >
1045 * The {{...}} syntax is also used for:
1046 * - Wikicreole images
1048 * - predefined icons
1050 class Markup_template_plugin extends SimpleMarkup
1052 // patch #1732793: allow \n, mult. {{ }} in one line, and single letters
1053 var $_match_regexp = '\{\{.*?\}\}';
1055 function markup ($match) {
1057 $page = substr($match,2,-2);
1058 $page = trim($page);
1060 // Check for predefined icons.
1061 $predefinedicons = array(":)" => "ic_smile.png",
1062 ":(" => "ic_sad.png",
1063 ":P" => "ic_tongue.png",
1064 ":D" => "ic_biggrin.png",
1065 ";)" => "ic_wink.png",
1066 "(y)" => "ic_handyes.png",
1067 "(n)" => "ic_handno.png",
1068 "(i)" => "ic_info.png",
1069 "(/)" => "ic_check.png",
1070 "(x)" => "ic_cross.png",
1071 "(!)" => "ic_danger.png",
1072 "(+)" => "ic_plus.png",
1073 "(-)" => "ic_minus.png",
1074 "(?)" => "ic_help.png",
1075 "(on)" => "ic_lighton.png",
1076 "(off)" => "ic_lightoff.png",
1077 "(*)" => "ic_yellowstar.png",
1078 "(*r)" => "ic_redstar.png",
1079 "(*g)" => "ic_greenstar.png",
1080 "(*b)" => "ic_bluestar.png",
1081 "(*y)" => "ic_yellowstar.png",
1083 foreach ($predefinedicons as $ascii => $icon) {
1084 if ($page == $ascii) {
1085 return LinkImage(DATA_PATH . "/themes/default/images/$icon", $page);
1089 if (strpos($page, "|") === false) {
1093 $imagename = substr($page, 0, strpos($page, "|"));
1094 $alt = ltrim(strstr($page, "|"), "|");
1097 // It's not a Mediawiki template, it's a Wikicreole image
1098 if (is_image($imagename)) {
1099 if ((strpos($imagename, "http://") === 0) || (strpos($imagename, "https://") === 0)) {
1100 return LinkImage($imagename, $alt);
1101 } else if ($imagename[0] == '/') {
1102 return LinkImage(DATA_PATH . '/' . $imagename, $alt);
1104 return LinkImage(getUploadDataPath() . $imagename, $alt);
1109 if (is_video($imagename)) {
1110 $s = '<'.'?plugin Video file="' . $imagename . '" ?'.'>';
1111 return new Cached_PluginInvocation($s);
1114 $page = str_replace("\n", "", $page);
1116 // The argument value might contain a double quote (")
1117 // We have to encode that.
1118 $page = htmlspecialchars($page);
1122 if (preg_match('/^(\S+?)\|(.*)$/', $page, $_m)) {
1124 $vars = '"' . preg_replace('/\|/', '" "', $_m[2]) . '"';
1125 $vars = preg_replace('/"(\S+)=([^"]*)"/', '\\1="\\2"', $vars);
1128 // page may contain a version number
1129 // {{foo?version=5}}
1130 // in that case, output is "page=foo rev=5"
1131 if (strstr($page, "?")) {
1132 $page = str_replace("?version=", "\" rev=\"", $page);
1136 $s = '<'.'?plugin Template page="'.$page.'" '.$vars.' ?'.'>';
1138 $s = '<'.'?plugin Template page="' . $page . '" ?'.'>';
1139 return new Cached_PluginInvocation($s);
1143 // "..." => "…" browser specific display (not cached?)
1144 // Support some HTML::Entities: (C) for copy, --- for mdash, -- for ndash
1145 // TODO: "--" => "&emdash;" browser specific display (not cached?)
1147 class Markup_html_entities extends SimpleMarkup {
1148 //var $_match_regexp = '(: \.\.\.|\-\-|\-\-\-|\(C\) )';
1150 function Markup_html_entities() {
1151 $this->_entities = array('...' => '…',
1155 '©' => '©',
1156 '™' => '™',
1158 $this->_match_regexp =
1160 join('|', array_map('preg_quote', array_keys($this->_entities))) .
1164 function markup ($match) {
1165 return HTML::Raw($this->_entities[$match]);
1169 class Markup_isonumchars extends SimpleMarkup {
1170 var $_match_regexp = '\&\#\d{2,5};';
1172 function markup ($match) {
1173 return HTML::Raw($match);
1177 class Markup_isohexchars extends SimpleMarkup {
1178 // hexnums, like ¤ <=> ¤
1179 var $_match_regexp = '\&\#x[0-9a-fA-F]{2,4};';
1181 function markup ($match) {
1182 return HTML::Raw($match);
1186 // FIXME: Do away with magic phpwiki forms. (Maybe phpwiki: links too?)
1188 class InlineTransformer
1190 var $_regexps = array();
1191 var $_markup = array();
1193 function InlineTransformer ($markup_types = false) {
1195 // We need to extend the inline parsers by certain actions, like SearchHighlight,
1196 // SpellCheck and maybe CreateToc.
1197 if (!$markup_types) {
1198 $non_default = false;
1199 $markup_types = array
1200 ('escape', 'wikicreolebracketlink', 'bracketlink', 'url',
1201 'html_comment', 'placeholder',
1202 'interwiki', 'semanticlink', 'wikiword', 'linebreak',
1203 'wikicreole_superscript',
1204 'wikicreole_subscript',
1205 'wikicreole_italics', 'wikicreole_bold',
1206 'wikicreole_monospace',
1207 'wikicreole_underline',
1208 'old_emphasis', 'nestled_emphasis',
1209 'html_emphasis', 'html_abbr', 'plugin', 'plugin_wikicreole',
1210 'isonumchars', 'isohexchars', /*'html_entities'*/
1212 if (DISABLE_MARKUP_WIKIWORD)
1213 $markup_types = array_remove($markup_types, 'wikiword');
1215 $action = $request->getArg('action');
1216 if ($action == 'SpellCheck' and $request->getArg('suggestions'))
1217 { // insert it after url
1218 array_splice($markup_types, 2, 1, array('url','spellcheck'));
1220 if (isset($request->_searchhighlight))
1221 { // insert it after url
1222 array_splice($markup_types, 2, 1, array('url','searchhighlight'));
1223 //$request->setArg('searchhighlight', false);
1226 $non_default = true;
1228 foreach ($markup_types as $mtype) {
1229 $class = "Markup_$mtype";
1230 $this->_addMarkup(new $class);
1232 $this->_addMarkup(new Markup_nowiki);
1233 if (ENABLE_MARKUP_DIVSPAN and !$non_default)
1234 $this->_addMarkup(new Markup_html_divspan);
1235 if (ENABLE_MARKUP_COLOR and !$non_default)
1236 $this->_addMarkup(new Markup_color);
1237 // Markup_wikicreole_preformatted must be before Markup_template_plugin
1238 $this->_addMarkup(new Markup_wikicreole_preformatted);
1239 if (ENABLE_MARKUP_TEMPLATE and !$non_default)
1240 $this->_addMarkup(new Markup_template_plugin);
1241 // This does not work yet
1242 if (PLUGIN_MARKUP_MAP and !$non_default)
1243 $this->_addMarkup(new Markup_xml_plugin);
1246 function _addMarkup ($markup) {
1247 if (isa($markup, 'SimpleMarkup'))
1248 $regexp = $markup->getMatchRegexp();
1250 $regexp = $markup->getStartRegexp();
1252 assert( !isset($this->_markup[$regexp]) );
1253 assert( strlen(trim($regexp)) > 0 );
1254 $this->_regexps[] = $regexp;
1255 $this->_markup[] = $markup;
1258 function parse (&$text, $end_regexps = array('$')) {
1259 $regexps = $this->_regexps;
1261 // $end_re takes precedence: "favor reduce over shift"
1262 array_unshift($regexps, $end_regexps[0]);
1263 //array_push($regexps, $end_regexps[0]);
1264 $regexps = new RegexpSet($regexps);
1267 $output = new XmlContent;
1269 $match = $regexps->match($input);
1272 if ($match->regexp_ind == 0) {
1273 // No start pattern found before end pattern.
1275 if (isset($markup) and is_object($markup)
1276 and isa($markup,'Markup_plugin'))
1278 $current =& $output->_content[count($output->_content)-1];
1279 $current->setTightness(true,true);
1281 $output->pushContent($match->prematch);
1282 $text = $match->postmatch;
1286 $markup = $this->_markup[$match->regexp_ind - 1];
1287 $body = $this->_parse_markup_body($markup, $match->match,
1288 $match->postmatch, $end_regexps);
1290 // Couldn't match balanced expression.
1291 // Ignore and look for next matching start regexp.
1292 $match = $regexps->nextMatch($input, $match);
1296 // Matched markup. Eat input, push output.
1297 // FIXME: combine adjacent strings.
1298 if (isa($markup, 'SimpleMarkup'))
1299 $current = $markup->markup($match->match);
1301 $current = $markup->markup($match->match, $body);
1302 $input = $match->postmatch;
1303 if (isset($markup) and is_object($markup)
1304 and isa($markup,'Markup_plugin'))
1306 $current->setTightness(true,true);
1308 $output->pushContent($match->prematch, $current);
1310 $match = $regexps->match($input);
1313 // No pattern matched, not even the end pattern.
1318 function _parse_markup_body ($markup, $match, &$text, $end_regexps) {
1319 if (isa($markup, 'SimpleMarkup'))
1320 return true; // Done. SimpleMarkup is simple.
1322 if (!is_object($markup)) return false; // Some error: Should assert
1323 array_unshift($end_regexps, $markup->getEndRegexp($match));
1325 // Optimization: if no end pattern in text, we know the
1326 // parse will fail. This is an important optimization,
1327 // e.g. when text is "*lots *of *start *delims *with
1328 // *no *matching *end *delims".
1329 $ends_pat = "/(?:" . join(").*(?:", $end_regexps) . ")/xs";
1330 if (!preg_match($ends_pat, $text))
1332 return $this->parse($text, $end_regexps);
1336 class LinkTransformer extends InlineTransformer
1338 function LinkTransformer () {
1339 $this->InlineTransformer(array('escape', 'wikicreolebracketlink', 'bracketlink', 'url',
1340 'semanticlink', 'interwiki', 'wikiword',
1345 class NowikiTransformer extends InlineTransformer
1347 function NowikiTransformer () {
1348 $this->InlineTransformer
1350 'html_emphasis', 'html_abbr', 'plugin', 'plugin_wikicreole',
1351 'isonumchars', 'isohexchars', /*'html_entities',*/
1356 function TransformInline($text, $markup = 2.0, $basepage=false) {
1358 $action = $GLOBALS['request']->getArg('action');
1359 if (empty($trfm) or $action == 'SpellCheck') {
1360 $trfm = new InlineTransformer;
1363 if ($markup < 2.0) {
1364 $text = ConvertOldMarkup($text, 'inline');
1368 return new CacheableMarkup($trfm->parse($text), $basepage);
1370 return $trfm->parse($text);
1373 function TransformLinks($text, $markup = 2.0, $basepage = false) {
1377 $trfm = new LinkTransformer;
1380 if ($markup < 2.0) {
1381 $text = ConvertOldMarkup($text, 'links');
1385 return new CacheableMarkup($trfm->parse($text), $basepage);
1387 return $trfm->parse($text);
1391 * Transform only html markup and entities.
1393 function TransformInlineNowiki($text, $markup = 2.0, $basepage=false) {
1397 $trfm = new NowikiTransformer;
1400 return new CacheableMarkup($trfm->parse($text), $basepage);
1402 return $trfm->parse($text);
1408 // c-basic-offset: 4
1409 // c-hanging-comment-ender-p: nil
1410 // indent-tabs-mode: nil