3 /* Copyright (C) 2002 Geoffrey T. Dairiki <dairiki@dairiki.org>
4 * Copyright (C) 2004-2010 Reini Urban
5 * Copyright (C) 2008-2010 Marc-Etienne Vargenau, Alcatel-Lucent
7 * This file is part of PhpWiki.
9 * PhpWiki is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
14 * PhpWiki is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
19 * You should have received a copy of the GNU General Public License along
20 * with PhpWiki; if not, write to the Free Software Foundation, Inc.,
21 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
24 * This is the code which deals with the inline part of the (new-style)
28 * @author Geoffrey T. Dairiki, Reini Urban
32 * This is the character used in wiki markup to escape characters with
35 define('ESCAPE_CHAR', '~');
37 require_once('lib/CachedMarkup.php');
38 require_once(dirname(__FILE__).'/stdlib.php');
40 function WikiEscape($text) {
41 return str_replace('#', ESCAPE_CHAR . '#', $text);
44 function UnWikiEscape($text) {
45 return preg_replace('/' . ESCAPE_CHAR . '(.)/', '\1', $text);
49 * Return type from RegexpSet::match and RegexpSet::nextMatch.
53 class RegexpSet_match {
55 * The text leading up the the next match.
63 * The text following the matched text.
67 * Index of the regular expression which matched.
73 * A set of regular expressions.
75 * This class is probably only useful for InlineTransformer.
81 * @param array $regexps A list of regular expressions. The
82 * regular expressions should not include any sub-pattern groups
83 * "(...)". (Anonymous groups, like "(?:...)", as well as
84 * look-ahead and look-behind assertions are okay.)
86 function RegexpSet ($regexps) {
88 $this->_regexps = array_unique($regexps);
89 if (!defined('_INLINE_OPTIMIZATION')) define('_INLINE_OPTIMIZATION',0);
93 * Search text for the next matching regexp from the Regexp Set.
95 * @param string $text The text to search.
97 * @return RegexpSet_match A RegexpSet_match object, or false if no match.
99 function match ($text) {
100 return $this->_match($text, $this->_regexps, '*?');
104 * Search for next matching regexp.
106 * Here, 'next' has two meanings:
108 * Match the next regexp(s) in the set, at the same position as the last match.
110 * If that fails, match the whole RegexpSet, starting after the position of the
113 * @param string $text Text to search.
115 * @param RegexpSet_match $prevMatch A RegexpSet_match object.
116 * $prevMatch should be a match object obtained by a previous
117 * match upon the same value of $text.
119 * @return RegexpSet_match A RegexpSet_match object, or false if no match.
121 function nextMatch ($text, $prevMatch) {
122 // Try to find match at same position.
123 $pos = strlen($prevMatch->prematch);
124 $regexps = array_slice($this->_regexps, $prevMatch->regexp_ind + 1);
126 $repeat = sprintf('{%d}', $pos);
127 if ( ($match = $this->_match($text, $regexps, $repeat)) ) {
128 $match->regexp_ind += $prevMatch->regexp_ind + 1;
134 // Failed. Look for match after current position.
135 $repeat = sprintf('{%d,}?', $pos + 1);
136 return $this->_match($text, $this->_regexps, $repeat);
139 // Syntax: http://www.pcre.org/pcre.txt
140 // x - EXTENDED, ignore whitespace
144 function _match ($text, $regexps, $repeat) {
145 // If one of the regexps is an empty string, php will crash here:
146 // sf.net: Fatal error: Allowed memory size of 8388608 bytes exhausted
147 // (tried to allocate 634 bytes)
148 if (_INLINE_OPTIMIZATION) { // disabled, wrong
149 // So we try to minize memory usage, by looping explicitly,
150 // and storing only those regexp which actually match.
151 // There may be more than one, so we have to find the longest,
152 // and match inside until the shortest is empty.
153 $matched = array(); $matched_ind = array();
154 for ($i=0; $i<count($regexps); $i++) {
155 if (!trim($regexps[$i])) {
156 trigger_error("empty regexp $i", E_USER_WARNING);
159 $pat= "/ ( . $repeat ) ( " . $regexps[$i] . " ) /x";
160 if (preg_match($pat, $text, $_m)) {
161 $m = $_m; // FIXME: prematch, postmatch is wrong
162 $matched[] = $regexps[$i];
167 // To overcome ANCHORED:
168 // We could sort by longest match and iterate over these.
169 if (empty($matched)) return false;
171 $match = new RegexpSet_match;
173 // Optimization: if the matches are only "$" and another, then omit "$"
174 if (! _INLINE_OPTIMIZATION or count($matched) > 2) {
175 assert(!empty($repeat));
176 assert(!empty($regexps));
177 // We could do much better, if we would know the matching markup for the
178 // longest regexp match:
179 $hugepat= "/ ( . $repeat ) ( (" . join(')|(', $regexps) . ") ) /Asx";
180 // Proposed premature optimization 1:
181 //$hugepat= "/ ( . $repeat ) ( (" . join(')|(', array_values($matched)) . ") ) /Asx";
182 if (! preg_match($hugepat, $text, $m)) {
185 // Proposed premature optimization 1:
186 //$match->regexp_ind = $matched_ind[count($m) - 4];
187 $match->regexp_ind = count($m) - 4;
189 $match->regexp_ind = $regexp_ind;
192 $match->postmatch = substr($text, strlen($m[0]));
193 $match->prematch = $m[1];
194 $match->match = $m[2];
197 if (DEBUG & _DEBUG_PARSER) {
198 static $_already_dumped = 0;
199 if (!$_already_dumped) {
201 if (_INLINE_OPTIMIZATION)
203 var_dump($matched_ind);
205 $_already_dumped = 1;
206 PrintXML(HTML::dl(HTML::dt("input"),
207 HTML::dd(HTML::pre($text)),
209 HTML::dd(HTML::pre($match->regexp_ind, ":", $regexps[$match->regexp_ind])),
210 HTML::dt("prematch"),
211 HTML::dd(HTML::pre($match->prematch)),
213 HTML::dd(HTML::pre($match->match)),
214 HTML::dt("postmatch"),
215 HTML::dd(HTML::pre($match->postmatch))
223 * A simple markup rule (i.e. terminal token).
225 * These are defined by a regexp.
227 * When a match is found for the regexp, the matching text is replaced.
228 * The replacement content is obtained by calling the SimpleMarkup::markup method.
236 * @return string Regexp which matches this token.
238 function getMatchRegexp () {
239 return $this->_match_regexp;
242 /** Markup matching text.
244 * @param string $match The text which matched the regexp
245 * (obtained from getMatchRegexp).
247 * @return mixed The expansion of the matched text.
249 function markup ($match /*, $body */) {
250 trigger_error("pure virtual", E_USER_ERROR);
255 * A balanced markup rule.
257 * These are defined by a start regexp, and an end regexp.
263 /** Get the starting regexp for this rule.
265 * @return string The starting regexp.
267 function getStartRegexp () {
268 return $this->_start_regexp;
271 /** Get the ending regexp for this rule.
273 * @param string $match The text which matched the starting regexp.
275 * @return string The ending regexp.
277 function getEndRegexp ($match) {
278 return $this->_end_regexp;
281 /** Get expansion for matching input.
283 * @param string $match The text which matched the starting regexp.
285 * @param mixed $body Transformed text found between the starting
286 * and ending regexps.
288 * @return mixed The expansion of the matched text.
290 function markup ($match, $body) {
291 trigger_error("pure virtual", E_USER_ERROR);
295 class Markup_escape extends SimpleMarkup
297 function getMatchRegexp () {
298 return ESCAPE_CHAR . '(?: [[:alnum:]]+ | .)';
301 function markup ($match) {
302 assert(strlen($match) >= 2);
303 return substr($match, 1);
308 * [image.jpg size=50% border=5], [image.jpg size=50x30]
309 * Support for the following attributes: see stdlib.php:LinkImage()
310 * size=<percent>%, size=<width>x<height>
311 * border=n, align=\w+, hspace=n, vspace=n
313 * title, lang, id, alt
315 function isImageLink($link) {
316 if (!$link) return false;
317 assert(defined('INLINE_IMAGES'));
318 return preg_match("/\\.(" . INLINE_IMAGES . ")$/i", $link)
319 or preg_match("/\\.(" . INLINE_IMAGES . ")\s+(size|border|align|hspace|vspace|type|data|width|height|title|lang|id|alt)=/i", $link);
322 function LinkBracketLink($bracketlink) {
324 // $bracketlink will start and end with brackets; in between will
325 // be either a page name, a URL or both separated by a pipe.
327 $wikicreolesyntax = false;
329 if (string_starts_with($bracketlink, "[[") or string_starts_with($bracketlink, "#[[")) {
330 $wikicreolesyntax = true;
331 $bracketlink = str_replace("[[", "[", $bracketlink);
332 $bracketlink = str_replace("]]", "]", $bracketlink);
335 // Strip brackets and leading space
336 // bug#1904088 Some brackets links on 2 lines cause the parser to crash
337 preg_match('/(\#?) \[\s* (?: (.*?) \s* (?<!' . ESCAPE_CHAR . ')(\|) )? \s* (.+?) \s*\]/x',
338 str_replace("\n", " ", $bracketlink), $matches);
339 if (count($matches) < 4) {
340 // "[ personal\ninformation manager | PhpWiki:PersonalWiki ]"
341 trigger_error(_("Invalid [] syntax ignored")._(": ").$bracketlink, E_USER_WARNING);
342 return new Cached_Link;
344 list (, $hash, $label, $bar, $rawlink) = $matches;
346 if ($wikicreolesyntax and $label) {
352 // Mediawiki compatibility: allow "Image:" and "File:"
353 // as synonyms of "Upload:"
354 // Allow "upload:", "image:" and "file:" also
355 // Remove spaces before and after ":", if any
356 if (string_starts_with($rawlink, "Upload")) {
357 $rawlink = preg_replace("/^Upload\\s*:\\s*/", "Upload:", $rawlink);
358 } elseif (string_starts_with($rawlink, "upload")) {
359 $rawlink = preg_replace("/^upload\\s*:\\s*/", "Upload:", $rawlink);
360 } elseif (string_starts_with($rawlink, "Image")) {
361 $rawlink = preg_replace("/^Image\\s*:\\s*/", "Upload:", $rawlink);
362 } elseif (string_starts_with($rawlink, "image")) {
363 $rawlink = preg_replace("/^image\\s*:\\s*/", "Upload:", $rawlink);
364 } elseif (string_starts_with($rawlink, "File")) {
365 $rawlink = preg_replace("/^File\\s*:\\s*/", "Upload:", $rawlink);
366 } elseif (string_starts_with($rawlink, "file")) {
367 $rawlink = preg_replace("/^file\\s*:\\s*/", "Upload:", $rawlink);
370 $label = UnWikiEscape($label);
372 * Check if the user has typed a explicit URL. This solves the
373 * problem where the URLs have a ~ character, which would be stripped away.
374 * "[http:/server/~name/]" will work as expected
375 * "http:/server/~name/" will NOT work as expected, will remove the ~
377 if ( string_starts_with ($rawlink, "http://")
378 or string_starts_with ($rawlink, "https://") )
381 // Mozilla Browser URI Obfuscation Weakness 2004-06-14
382 // http://www.securityfocus.com/bid/10532/
383 // goodurl+"%2F%20%20%20."+badurl
384 if (preg_match("/%2F(%20)+\./i", $rawlink)) {
385 $rawlink = preg_replace("/%2F(%20)+\./i","%2F.",$rawlink);
388 // Check page name lenght
389 if (!string_starts_with($rawlink, "Upload:")) {
390 if (strlen($rawlink) > MAX_PAGENAME_LENGTH) {
391 return HTML::span(array('class' => 'error'),
392 _('Page name too long'));
395 // Check illegal characters in page names: <>[]{}|"
396 if (preg_match("/[<\[\{\|\"\}\]>]/", $rawlink, $matches) > 0) {
397 return HTML::span(array('class' => 'error'),
398 sprintf(_("Illegal character '%s' in page name."),
401 $link = UnWikiEscape($rawlink);
404 /* Relatives links by Joel Schaubert.
405 * Recognize [../bla] or [/bla] as relative links, without needing http://
406 * but [ /link ] only if SUBPAGE_SEPERATOR is not "/".
407 * Normally /Page links to the subpage /Page.
409 if (SUBPAGE_SEPARATOR == '/') {
410 if (preg_match('/^\.\.\//', $link)) {
411 return new Cached_ExternalLink($link, $label);
413 } elseif (preg_match('/^(\.\.\/|\/)/', $link)) {
414 return new Cached_ExternalLink($link, $label);
417 // Handle "[[SandBox|{{image.jpg}}]]" and "[[SandBox|{{image.jpg|alt text}}]]"
418 if (string_starts_with($label, "{{")) {
419 $imgurl = substr($label, 2, -2); // Remove "{{" and "}}"
420 $pipe = strpos($imgurl, '|');
421 if ($pipe === false) {
422 $label = LinkImage(getUploadDataPath() . $imgurl, $link);
424 list($img, $alt) = explode("|", $imgurl);
425 $label = LinkImage(getUploadDataPath() . $img, $alt);
430 // If label looks like a url to an image or object, we want an image link.
431 if (isImageLink($label)) {
433 $intermap = getInterwikiMap();
434 if (preg_match("/^" . $intermap->getRegexp() . ":/", $label)) {
435 $imgurl = $intermap->link($label);
436 $imgurl = $imgurl->getAttr('href');
437 } elseif (! preg_match("#^(" . ALLOWED_PROTOCOLS . "):#", $imgurl)) {
438 // local theme linkname like 'images/next.gif'.
440 $imgurl = $WikiTheme->getImageURL($imgurl);
442 // for objects (non-images) the link is taken as alt tag,
443 // which is in return taken as alternative img
444 $label = LinkImage($imgurl, $link);
448 // It's an anchor, not a link...
449 $id = MangleXmlIdentifier($link);
450 return HTML::a(array('name' => $id, 'id' => $id),
451 $bar ? $label : $link);
454 if (preg_match("#^(" . ALLOWED_PROTOCOLS . "):#", $link)) {
455 // if it's an image, embed it; otherwise, it's a regular link
456 if (isImageLink($link) and empty($label)) // patch #1348996 by Robert Litwiniec
457 return LinkImage($link, $label);
459 return new Cached_ExternalLink($link, $label);
461 elseif (substr($link,0,8) == 'phpwiki:')
462 return new Cached_PhpwikiURL($link, $label);
464 /* Semantic relations and attributes.
465 * Relation and attribute names must be word chars only, no space.
466 * Links and Attributes may contain everything. word, nums, units, space, groupsep, numsep, ...
468 elseif (preg_match("/^ (\w+) (:[:=]) (.*) $/x", $link) and !isImageLink($link))
469 return new Cached_SemanticLink($link, $label);
471 /* Do not store the link */
472 elseif (substr($link,0,1) == ':')
473 return new Cached_WikiLink($link, $label);
476 * Inline images in Interwiki urls's:
477 * [File:my_image.gif] inlines the image,
478 * File:my_image.gif shows a plain inter-wiki link,
479 * [what a pic|File:my_image.gif] shows a named inter-wiki link to the gif
480 * [File:my_image.gif|what a pic] shows an inlined image linked to the page "what a pic"
482 * Note that for simplicity we will accept embedded object tags (non-images)
483 * here also, and seperate them later in LinkImage()
485 elseif (strstr($link,':')
486 and ($intermap = getInterwikiMap())
487 and preg_match("/^" . $intermap->getRegexp() . ":/", $link))
489 // trigger_error("label: $label link: $link", E_USER_WARNING);
490 if (empty($label) and isImageLink($link)) {
491 // if without label => inlined image [File:xx.gif]
492 $imgurl = $intermap->link($link);
493 return LinkImage($imgurl->getAttr('href'));
495 return new Cached_InterwikiLink($link, $label);
497 // Split anchor off end of pagename.
498 if (preg_match('/\A(.*)(?<!'.ESCAPE_CHAR.')#(.*?)\Z/', $rawlink, $m)) {
499 list(,$rawlink,$anchor) = $m;
500 $pagename = UnWikiEscape($rawlink);
501 $anchor = UnWikiEscape($anchor);
509 return new Cached_WikiLink($pagename, $label, $anchor);
513 class Markup_wikicreolebracketlink extends SimpleMarkup
515 var $_match_regexp = "\\#? \\[\\[ .*? [^]\\s] .*? \\]\\]";
517 function markup ($match) {
518 $link = LinkBracketLink($match);
519 assert($link->isInlineElement());
524 class Markup_bracketlink extends SimpleMarkup
526 var $_match_regexp = "\\#? \\[ .*? [^]\\s] .*? \\]";
528 function markup ($match) {
529 $link = LinkBracketLink($match);
530 assert($link->isInlineElement());
535 class Markup_spellcheck extends SimpleMarkup
537 function Markup_spellcheck () {
538 $this->suggestions = $GLOBALS['request']->getArg('suggestions');
540 function getMatchRegexp () {
541 if (empty($this->suggestions))
542 return "(?# false )";
543 $words = array_keys($this->suggestions);
544 return "(?<= \W ) (?:" . join('|', $words) . ") (?= \W )";
547 function markup ($match) {
548 if (empty($this->suggestions) or empty($this->suggestions[$match]))
550 return new Cached_SpellCheck(UnWikiEscape($match), $this->suggestions[$match]);
554 class Markup_searchhighlight extends SimpleMarkup
556 function Markup_searchhighlight () {
557 $result = $GLOBALS['request']->_searchhighlight;
558 require_once("lib/TextSearchQuery.php");
559 $query = new TextSearchQuery($result['query']);
560 $this->hilight_re = $query->getHighlightRegexp();
561 $this->engine = $result['engine'];
563 function getMatchRegexp () {
564 return $this->hilight_re;
566 function markup ($match) {
567 return new Cached_SearchHighlight(UnWikiEscape($match), $this->engine);
571 class Markup_url extends SimpleMarkup
573 function getMatchRegexp () {
574 return "(?<![[:alnum:]]) (?:" . ALLOWED_PROTOCOLS . ") : [^\s<>\"']+ (?<![ ,.?; \] \) ])";
577 function markup ($match) {
578 return new Cached_ExternalLink(UnWikiEscape($match));
582 class Markup_interwiki extends SimpleMarkup
584 function getMatchRegexp () {
585 $map = getInterwikiMap();
586 return "(?<! [[:alnum:]])" . $map->getRegexp(). ": [^:=]\S+ (?<![ ,.?;! \] \) \" \' ])";
589 function markup ($match) {
590 return new Cached_InterwikiLink(UnWikiEscape($match));
594 class Markup_semanticlink extends SimpleMarkup
596 // No units seperated by space allowed here
597 // For :: (relations) only words, no comma,
598 // but for := (attributes) comma and dots are allowed. Units with groupsep.
599 // Ending dots or comma are not part of the link.
600 var $_match_regexp = "(?: \w+:=\S+(?<![\.,]))|(?: \w+::[\w\.]+(?<!\.))";
602 function markup ($match) {
603 return new Cached_SemanticLink(UnWikiEscape($match));
607 class Markup_wikiword extends SimpleMarkup
609 function getMatchRegexp () {
610 global $WikiNameRegexp;
611 if (!trim($WikiNameRegexp)) return " " . WIKI_NAME_REGEXP;
612 return " $WikiNameRegexp";
615 function markup ($match) {
616 if (!$match) return false;
617 if ($this->_isWikiUserPage($match))
618 return new Cached_UserLink($match); //$this->_UserLink($match);
620 return new Cached_WikiLink($match);
623 // FIXME: there's probably a more useful place to put these two functions
624 function _isWikiUserPage ($page) {
626 $dbi = $request->getDbh();
627 $page_handle = $dbi->getPage($page);
628 if ($page_handle and $page_handle->get('pref'))
634 function _UserLink($PageName) {
635 $link = HTML::a(array('href' => $PageName));
636 $link->pushContent(PossiblyGlueIconToText('wikiuser', $PageName));
637 $link->setAttr('class', 'wikiuser');
642 class Markup_linebreak extends SimpleMarkup
644 var $_match_regexp = "(?: (?<! %) %%% (?! %) | \\\\\\\\ | <\s*(?:br|BR)\s*> | <\s*(?:br|BR)\s*\/\s*> )";
646 function markup ($match) {
651 class Markup_wikicreole_italics extends BalancedMarkup
653 var $_start_regexp = "\\/\\/";
655 function getEndRegexp ($match) {
659 function markup ($match, $body) {
661 return new HtmlElement($tag, $body);
665 class Markup_wikicreole_bold extends BalancedMarkup
667 var $_start_regexp = "\\*\\*";
669 function getEndRegexp ($match) {
673 function markup ($match, $body) {
675 return new HtmlElement($tag, $body);
679 class Markup_wikicreole_monospace extends BalancedMarkup
681 var $_start_regexp = "\\#\\#";
683 function getEndRegexp ($match) {
687 function markup ($match, $body) {
688 return new HtmlElement('span', array('class' => 'tt'), $body);
692 class Markup_wikicreole_underline extends BalancedMarkup
694 var $_start_regexp = "\\_\\_";
696 function getEndRegexp ($match) {
700 function markup ($match, $body) {
702 return new HtmlElement($tag, $body);
706 class Markup_wikicreole_superscript extends BalancedMarkup
708 var $_start_regexp = "\\^\\^";
710 function getEndRegexp ($match) {
714 function markup ($match, $body) {
716 return new HtmlElement($tag, $body);
720 class Markup_wikicreole_subscript extends BalancedMarkup
722 var $_start_regexp = ",,";
724 function getEndRegexp ($match) {
728 function markup ($match, $body) {
730 return new HtmlElement($tag, $body);
734 class Markup_old_emphasis extends BalancedMarkup
736 var $_start_regexp = "''";
738 function getEndRegexp ($match) {
742 function markup ($match, $body) {
744 return new HtmlElement($tag, $body);
748 class Markup_nestled_emphasis extends BalancedMarkup
750 function getStartRegexp() {
751 static $start_regexp = false;
753 if (!$start_regexp) {
754 // The three possible delimiters
755 // (none of which can be followed by itself.)
760 $any = "(?: ${i}|${b}|${tt})"; // any of the three.
762 // Any of [_*=] is okay if preceded by space or one of [-"'/:]
763 $start[] = "(?<= \\s|^|[-\"'\\/:]) ${any}";
765 // _ or * is okay after = as long as not immediately followed by =
766 $start[] = "(?<= =) (?: ${i}|${b}) (?! =)";
768 $start[] = "(?<= _) (?: ${b}|${tt}) (?! _)";
769 $start[] = "(?<= \\*) (?: ${i}|${tt}) (?! \\*)";
771 // any delimiter okay after an opening brace ( [{<(] )
772 // as long as it's not immediately followed by the matching closing
774 $start[] = "(?<= { ) ${any} (?! } )";
775 $start[] = "(?<= < ) ${any} (?! > )";
776 $start[] = "(?<= \\( ) ${any} (?! \\) )";
778 $start = "(?:" . join('|', $start) . ")";
780 // Any of the above must be immediately followed by non-whitespace.
781 $start_regexp = $start . "(?= \S)";
784 return $start_regexp;
787 function getEndRegexp ($match) {
788 $chr = preg_quote($match);
789 return "(?<= \S | ^ ) (?<! $chr) $chr (?! $chr) (?= \s | [-)}>\"'\\/:.,;!? _*=] | $)";
792 function markup ($match, $body) {
794 case '*': return new HtmlElement('b', $body);
795 case '=': return new HtmlElement('span', array('class' => 'tt'), $body);
796 case '_': return new HtmlElement('i', $body);
801 class Markup_html_emphasis extends BalancedMarkup
804 "<(?: b|big|i|small|tt|em|strong|cite|code|dfn|kbd|samp|s|strike|del|var|sup|sub )>";
806 function getEndRegexp ($match) {
807 return "<\\/" . substr($match, 1);
810 function markup ($match, $body) {
811 $tag = substr($match, 1, -1);
812 return new HtmlElement($tag, $body);
816 class Markup_html_divspan extends BalancedMarkup
819 "<(?: div|span )(?: \s[^>]*)?>";
821 function getEndRegexp ($match) {
822 if (substr($match,1,4) == 'span')
826 return "<\\/" . $tag . '>';
829 function markup ($match, $body) {
830 if (substr($match,1,4) == 'span')
834 $rest = substr($match,1+strlen($tag),-1);
836 $args = parse_attributes($rest);
840 return new HtmlElement($tag, $args, $body);
845 class Markup_html_abbr extends BalancedMarkup
847 //rurban: abbr|acronym need an optional title tag.
849 var $_start_regexp = "<(?: abbr|acronym )(?: [^>]*)?>";
851 function getEndRegexp ($match) {
852 if (substr($match,1,4) == 'abbr')
856 return "<\\/" . $tag . '>';
859 function markup ($match, $body) {
860 if (substr($match,1,4) == 'abbr')
864 $rest = substr($match,1+strlen($tag),-1);
865 $attrs = parse_attributes($rest);
866 // Remove attributes other than title and lang
867 $allowedargs = array();
868 foreach ($attrs as $key => $value) {
869 if (in_array ($key, array("title", "lang"))) {
870 $allowedargs[$key] = $value;
873 return new HtmlElement($tag, $allowedargs, $body);
877 /** ENABLE_MARKUP_COLOR
878 * See http://www.pmwiki.org/wiki/PmWiki/WikiStyles and
879 * http://www.flexwiki.com/default.aspx/FlexWiki/FormattingRules.html
881 class Markup_color extends BalancedMarkup {
882 // %color=blue% blue text %% and back to normal
883 var $_start_regexp = "%color=(?: [^%]*)%";
884 var $_end_regexp = "%%";
886 function markup ($match, $body) {
887 $color = strtolower(substr($match, 7, -1));
889 $morecolors = array('beige' => '#f5f5dc',
890 'brown' => '#a52a2a',
891 'chocolate' => '#d2691e',
894 'ivory' => '#fffff0',
895 'indigo' => '#4b0082',
896 'magenta' => '#ff00ff',
897 'orange' => '#ffa500',
899 'salmon' => '#fa8072',
901 'turquoise' => '#40e0d0',
902 'violet' => '#ee82ee',
905 if (isset($morecolors[$color])) {
906 $color = $morecolors[$color];
909 // HTML 4 defines the following 16 colors
910 if (in_array($color, array('aqua', 'black', 'blue', 'fuchsia',
911 'gray', 'green', 'lime', 'maroon',
912 'navy', 'olive', 'purple', 'red',
913 'silver', 'teal', 'white', 'yellow'))
914 or ((substr($color,0,1) == '#')
915 and ((strlen($color) == 4) or (strlen($color) == 7))
916 and (strspn(substr($color,1),'0123456789abcdef') == strlen($color)-1))) {
917 return new HtmlElement('span', array('style' => "color: $color"), $body);
919 return new HtmlElement('span', array('class' => 'error'),
920 sprintf(_("unknown color %s ignored"), substr($match, 7, -1)));
925 // Wikicreole placeholder
927 class Markup_placeholder extends SimpleMarkup
929 var $_match_regexp = '<<<.*?>>>';
931 function markup ($match) {
932 return HTML::span($match);
936 // Single-line HTML comment
937 // <!-- This is a comment -->
938 class Markup_html_comment extends SimpleMarkup
940 var $_match_regexp = '<!--.*?-->';
942 function markup ($match) {
943 return HTML::raw('');
947 // Special version for single-line plugins formatting,
948 // like: '<small>< ?plugin PopularNearby ? ></small>'
949 class Markup_plugin extends SimpleMarkup
951 var $_match_regexp = '<\?plugin(?:-form)?\s[^\n]+?\?>';
953 function markup ($match) {
954 return new Cached_PluginInvocation($match);
958 // Special version for single-line Wikicreole plugins formatting.
959 class Markup_plugin_wikicreole extends SimpleMarkup
961 var $_match_regexp = '<<[^\n]+?>>';
963 function markup ($match) {
964 $pi = str_replace("<<", "<?plugin ", $match);
965 $pi = str_replace(">>", " ?>", $pi);
966 return new Cached_PluginInvocation($pi);
970 // Special version for plugins in xml syntax, mediawiki-style
971 // <name arg=value>body</name> or <name /> => < ? plugin pluginname arg=value body ? >
972 // PLUGIN_MARKUP_MAP = "html:RawHtml dot:GraphViz toc:CreateToc amath:AsciiMath richtable:RichTable include:IncludePage tex:TexToPng"
973 class Markup_xml_plugin extends BalancedMarkup
975 //var $_start_regexp = "<(?: ".join('|',PLUGIN_MARKUP_MAP)." )(?: \s[^>]*)>";
977 function getStartRegexp () {
978 global $PLUGIN_MARKUP_MAP;
979 static $_start_regexp;
980 if ($_start_regexp) return $_start_regexp;
981 if (empty($PLUGIN_MARKUP_MAP)) return '';
982 //"<(?: html|search|extsearch|dot|toc|math|richtable|include|tex )(?: \s[^>]*)>"
983 $_start_regexp = "<(?: ".join('|',array_keys($PLUGIN_MARKUP_MAP))." )(?: \s[^>]*|\\/ )>";
984 return $_start_regexp;
986 function getEndRegexp ($match) {
987 return "<\\/" . $match . '>';
989 function markup ($match, $body) {
990 global $PLUGIN_MARKUP_MAP;
991 $name = substr($match,2,-2);
993 if (preg_match('/^(\S+)\|(.*)$/', $name, $_m)) {
995 $vars = $_m[2]; //str_replace(' ', '&', $_m[2]);
997 if (!isset($PLUGIN_MARKUP_MAP[$name])) {
998 trigger_error("No plugin for $name $vars defined.", E_USER_WARNING);
1001 $plugin = $PLUGIN_MARKUP_MAP[$name];
1002 return new Cached_PluginInvocation("<"."?plugin $plugin $vars $body ?".">");
1007 * Mediawiki <nowiki>
1008 * <nowiki>...</nowiki>
1010 class Markup_nowiki extends SimpleMarkup
1012 var $_match_regexp = '<nowiki>.*?<\/nowiki>';
1014 function markup ($match) {
1015 // Remove <nowiki> and </nowiki>
1016 return HTML::raw(substr($match, 8, -9));
1021 * Wikicreole preformatted
1025 class Markup_wikicreole_preformatted extends SimpleMarkup
1027 var $_match_regexp = '\{\{\{.*?\}\}\}';
1029 function markup ($match) {
1030 // Remove {{{ and }}}
1031 return new HtmlElement('span', array('class' => 'tt'), substr($match, 3, -3));
1035 /** ENABLE_MARKUP_TEMPLATE
1036 * Template syntax similar to Mediawiki
1038 * => < ? plugin Template page=template ? >
1039 * {{template|var1=value1|var2=value|...}}
1040 * => < ? plugin Template page=template var=value ... ? >
1042 * The {{...}} syntax is also used for:
1043 * - Wikicreole images
1045 * - predefined icons
1047 class Markup_template_plugin extends SimpleMarkup
1049 // patch #1732793: allow \n, mult. {{ }} in one line, and single letters
1050 var $_match_regexp = '\{\{.*?\}\}';
1052 function markup ($match) {
1054 $page = substr($match,2,-2);
1055 $page = trim($page);
1057 // Check for predefined icons.
1058 $predefinedicons = array(":)" => "ic_smile.png",
1059 ":(" => "ic_sad.png",
1060 ":P" => "ic_tongue.png",
1061 ":D" => "ic_biggrin.png",
1062 ";)" => "ic_wink.png",
1063 "(y)" => "ic_handyes.png",
1064 "(n)" => "ic_handno.png",
1065 "(i)" => "ic_info.png",
1066 "(/)" => "ic_check.png",
1067 "(x)" => "ic_cross.png",
1068 "(!)" => "ic_danger.png",
1069 "(+)" => "ic_plus.png",
1070 "(-)" => "ic_minus.png",
1071 "(?)" => "ic_help.png",
1072 "(on)" => "ic_lighton.png",
1073 "(off)" => "ic_lightoff.png",
1074 "(*)" => "ic_yellowstar.png",
1075 "(*r)" => "ic_redstar.png",
1076 "(*g)" => "ic_greenstar.png",
1077 "(*b)" => "ic_bluestar.png",
1078 "(*y)" => "ic_yellowstar.png",
1080 foreach ($predefinedicons as $ascii => $icon) {
1081 if ($page == $ascii) {
1082 return LinkImage(DATA_PATH . "/themes/default/images/$icon", $page);
1086 if (strpos($page, "|") === false) {
1090 $imagename = substr($page, 0, strpos($page, "|"));
1091 $alt = ltrim(strstr($page, "|"), "|");
1094 // It's not a Mediawiki template, it's a Wikicreole image
1095 if (is_image($imagename)) {
1096 if ((strpos($imagename, "http://") === 0) || (strpos($imagename, "https://") === 0)) {
1097 return LinkImage($imagename, $alt);
1098 } elseif ($imagename[0] == '/') {
1099 return LinkImage(DATA_PATH . '/' . $imagename, $alt);
1101 return LinkImage(getUploadDataPath() . $imagename, $alt);
1106 if (is_video($imagename)) {
1107 $s = '<'.'?plugin Video file="' . $imagename . '" ?'.'>';
1108 return new Cached_PluginInvocation($s);
1111 $page = str_replace("\n", "", $page);
1113 // The argument value might contain a double quote (")
1114 // We have to encode that.
1115 $page = htmlspecialchars($page);
1119 if (preg_match('/^(\S+?)\|(.*)$/', $page, $_m)) {
1121 $vars = '"' . preg_replace('/\|/', '" "', $_m[2]) . '"';
1122 $vars = preg_replace('/"(\S+)=([^"]*)"/', '\\1="\\2"', $vars);
1125 // page may contain a version number
1126 // {{foo?version=5}}
1127 // in that case, output is "page=foo rev=5"
1128 if (strstr($page, "?")) {
1129 $page = str_replace("?version=", "\" rev=\"", $page);
1133 $s = '<'.'?plugin Template page="'.$page.'" '.$vars.' ?'.'>';
1135 $s = '<'.'?plugin Template page="' . $page . '" ?'.'>';
1136 return new Cached_PluginInvocation($s);
1140 // "..." => "…" browser specific display (not cached?)
1141 // Support some HTML::Entities: (C) for copy, --- for mdash, -- for ndash
1142 // TODO: "--" => "&emdash;" browser specific display (not cached?)
1144 class Markup_html_entities extends SimpleMarkup {
1145 //var $_match_regexp = '(: \.\.\.|\-\-|\-\-\-|\(C\) )';
1147 function Markup_html_entities() {
1148 $this->_entities = array('...' => '…',
1152 '©' => '©',
1153 '™' => '™',
1155 $this->_match_regexp =
1157 join('|', array_map('preg_quote', array_keys($this->_entities))) .
1161 function markup ($match) {
1162 return HTML::Raw($this->_entities[$match]);
1166 class Markup_isonumchars extends SimpleMarkup {
1167 var $_match_regexp = '\&\#\d{2,5};';
1169 function markup ($match) {
1170 return HTML::Raw($match);
1174 class Markup_isohexchars extends SimpleMarkup {
1175 // hexnums, like ¤ <=> ¤
1176 var $_match_regexp = '\&\#x[0-9a-fA-F]{2,4};';
1178 function markup ($match) {
1179 return HTML::Raw($match);
1183 // FIXME: Do away with magic phpwiki forms. (Maybe phpwiki: links too?)
1185 class InlineTransformer
1187 var $_regexps = array();
1188 var $_markup = array();
1190 function InlineTransformer ($markup_types = false) {
1192 // We need to extend the inline parsers by certain actions, like SearchHighlight,
1193 // SpellCheck and maybe CreateToc.
1194 if (!$markup_types) {
1195 $non_default = false;
1196 $markup_types = array
1197 ('escape', 'wikicreolebracketlink', 'bracketlink', 'url',
1198 'html_comment', 'placeholder',
1199 'interwiki', 'semanticlink', 'wikiword', 'linebreak',
1200 'wikicreole_superscript',
1201 'wikicreole_subscript',
1202 'wikicreole_italics', 'wikicreole_bold',
1203 'wikicreole_monospace',
1204 'wikicreole_underline',
1205 'old_emphasis', 'nestled_emphasis',
1206 'html_emphasis', 'html_abbr', 'plugin', 'plugin_wikicreole',
1207 'isonumchars', 'isohexchars', /*'html_entities'*/
1209 if (DISABLE_MARKUP_WIKIWORD)
1210 $markup_types = array_remove($markup_types, 'wikiword');
1212 $action = $request->getArg('action');
1213 if ($action == 'SpellCheck' and $request->getArg('suggestions'))
1214 { // insert it after url
1215 array_splice($markup_types, 2, 1, array('url','spellcheck'));
1217 if (isset($request->_searchhighlight))
1218 { // insert it after url
1219 array_splice($markup_types, 2, 1, array('url','searchhighlight'));
1220 //$request->setArg('searchhighlight', false);
1223 $non_default = true;
1225 foreach ($markup_types as $mtype) {
1226 $class = "Markup_$mtype";
1227 $this->_addMarkup(new $class);
1229 $this->_addMarkup(new Markup_nowiki);
1230 if (ENABLE_MARKUP_DIVSPAN and !$non_default)
1231 $this->_addMarkup(new Markup_html_divspan);
1232 if (ENABLE_MARKUP_COLOR and !$non_default)
1233 $this->_addMarkup(new Markup_color);
1234 // Markup_wikicreole_preformatted must be before Markup_template_plugin
1235 $this->_addMarkup(new Markup_wikicreole_preformatted);
1236 if (ENABLE_MARKUP_TEMPLATE and !$non_default)
1237 $this->_addMarkup(new Markup_template_plugin);
1238 // This does not work yet
1239 if (PLUGIN_MARKUP_MAP and !$non_default)
1240 $this->_addMarkup(new Markup_xml_plugin);
1243 function _addMarkup ($markup) {
1244 if (isa($markup, 'SimpleMarkup'))
1245 $regexp = $markup->getMatchRegexp();
1247 $regexp = $markup->getStartRegexp();
1249 assert( !isset($this->_markup[$regexp]) );
1250 assert( strlen(trim($regexp)) > 0 );
1251 $this->_regexps[] = $regexp;
1252 $this->_markup[] = $markup;
1255 function parse (&$text, $end_regexps = array('$')) {
1256 $regexps = $this->_regexps;
1258 // $end_re takes precedence: "favor reduce over shift"
1259 array_unshift($regexps, $end_regexps[0]);
1260 //array_push($regexps, $end_regexps[0]);
1261 $regexps = new RegexpSet($regexps);
1264 $output = new XmlContent;
1266 $match = $regexps->match($input);
1269 if ($match->regexp_ind == 0) {
1270 // No start pattern found before end pattern.
1272 if (isset($markup) and is_object($markup)
1273 and isa($markup,'Markup_plugin'))
1275 $current =& $output->_content[count($output->_content)-1];
1276 $current->setTightness(true,true);
1278 $output->pushContent($match->prematch);
1279 $text = $match->postmatch;
1283 $markup = $this->_markup[$match->regexp_ind - 1];
1284 $body = $this->_parse_markup_body($markup, $match->match,
1285 $match->postmatch, $end_regexps);
1287 // Couldn't match balanced expression.
1288 // Ignore and look for next matching start regexp.
1289 $match = $regexps->nextMatch($input, $match);
1293 // Matched markup. Eat input, push output.
1294 // FIXME: combine adjacent strings.
1295 if (isa($markup, 'SimpleMarkup'))
1296 $current = $markup->markup($match->match);
1298 $current = $markup->markup($match->match, $body);
1299 $input = $match->postmatch;
1300 if (isset($markup) and is_object($markup)
1301 and isa($markup,'Markup_plugin'))
1303 $current->setTightness(true,true);
1305 $output->pushContent($match->prematch, $current);
1307 $match = $regexps->match($input);
1310 // No pattern matched, not even the end pattern.
1315 function _parse_markup_body ($markup, $match, &$text, $end_regexps) {
1316 if (isa($markup, 'SimpleMarkup'))
1317 return true; // Done. SimpleMarkup is simple.
1319 if (!is_object($markup)) return false; // Some error: Should assert
1320 array_unshift($end_regexps, $markup->getEndRegexp($match));
1322 // Optimization: if no end pattern in text, we know the
1323 // parse will fail. This is an important optimization,
1324 // e.g. when text is "*lots *of *start *delims *with
1325 // *no *matching *end *delims".
1326 $ends_pat = "/(?:" . join(").*(?:", $end_regexps) . ")/xs";
1327 if (!preg_match($ends_pat, $text))
1329 return $this->parse($text, $end_regexps);
1333 class LinkTransformer extends InlineTransformer
1335 function LinkTransformer () {
1336 $this->InlineTransformer(array('escape', 'wikicreolebracketlink', 'bracketlink', 'url',
1337 'semanticlink', 'interwiki', 'wikiword',
1342 class NowikiTransformer extends InlineTransformer
1344 function NowikiTransformer () {
1345 $this->InlineTransformer
1347 'html_emphasis', 'html_abbr', 'plugin', 'plugin_wikicreole',
1348 'isonumchars', 'isohexchars', /*'html_entities',*/
1353 function TransformInline($text, $markup = 2.0, $basepage=false) {
1355 $action = $GLOBALS['request']->getArg('action');
1356 if (empty($trfm) or $action == 'SpellCheck') {
1357 $trfm = new InlineTransformer;
1360 if ($markup < 2.0) {
1361 $text = ConvertOldMarkup($text, 'inline');
1365 return new CacheableMarkup($trfm->parse($text), $basepage);
1367 return $trfm->parse($text);
1370 function TransformLinks($text, $markup = 2.0, $basepage = false) {
1374 $trfm = new LinkTransformer;
1377 if ($markup < 2.0) {
1378 $text = ConvertOldMarkup($text, 'links');
1382 return new CacheableMarkup($trfm->parse($text), $basepage);
1384 return $trfm->parse($text);
1388 * Transform only html markup and entities.
1390 function TransformInlineNowiki($text, $markup = 2.0, $basepage=false) {
1394 $trfm = new NowikiTransformer;
1397 return new CacheableMarkup($trfm->parse($text), $basepage);
1399 return $trfm->parse($text);
1405 // c-basic-offset: 4
1406 // c-hanging-comment-ender-p: nil
1407 // indent-tabs-mode: nil