]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/InlineParser.php
var --> public
[SourceForge/phpwiki.git] / lib / InlineParser.php
1 <?php
2
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
6  *
7  * This file is part of PhpWiki.
8  *
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.
13  *
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.
18  *
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.
22  */
23 /**
24  * This is the code which deals with the inline part of the (new-style)
25  * wiki-markup.
26  *
27  * @package Markup
28  * @author Geoffrey T. Dairiki, Reini Urban
29  */
30
31 /**
32  * This is the character used in wiki markup to escape characters with
33  * special meaning.
34  */
35 define('ESCAPE_CHAR', '~');
36
37 require_once 'lib/CachedMarkup.php';
38 require_once(dirname(__FILE__) . '/stdlib.php');
39
40 function WikiEscape($text)
41 {
42     return str_replace('#', ESCAPE_CHAR . '#', $text);
43 }
44
45 function UnWikiEscape($text)
46 {
47     return preg_replace('/' . ESCAPE_CHAR . '(.)/', '\1', $text);
48 }
49
50 /**
51  * Return type from RegexpSet::match and RegexpSet::nextMatch.
52  *
53  * @see RegexpSet
54  */
55 class RegexpSet_match
56 {
57     /**
58      * The text leading up the the next match.
59      */
60     public $prematch;
61     /**
62      * The matched text.
63      */
64     public $match;
65     /**
66      * The text following the matched text.
67      */
68     public $postmatch;
69     /**
70      * Index of the regular expression which matched.
71      */
72     public $regexp_ind;
73 }
74
75 /**
76  * A set of regular expressions.
77  *
78  * This class is probably only useful for InlineTransformer.
79  */
80 class RegexpSet
81 {
82     /** Constructor
83      *
84      * @param array $regexps A list of regular expressions.  The
85      * regular expressions should not include any sub-pattern groups
86      * "(...)".  (Anonymous groups, like "(?:...)", as well as
87      * look-ahead and look-behind assertions are okay.)
88      */
89     function RegexpSet($regexps)
90     {
91         assert($regexps);
92         $this->_regexps = array_unique($regexps);
93         if (!defined('_INLINE_OPTIMIZATION')) define('_INLINE_OPTIMIZATION', 0);
94     }
95
96     /**
97      * Search text for the next matching regexp from the Regexp Set.
98      *
99      * @param string $text The text to search.
100      *
101      * @return RegexpSet_match A RegexpSet_match object, or false if no match.
102      */
103     function match($text)
104     {
105         return $this->_match($text, $this->_regexps, '*?');
106     }
107
108     /**
109      * Search for next matching regexp.
110      *
111      * Here, 'next' has two meanings:
112      *
113      * Match the next regexp(s) in the set, at the same position as the last match.
114      *
115      * If that fails, match the whole RegexpSet, starting after the position of the
116      * previous match.
117      *
118      * @param string $text Text to search.
119      *
120      * @param RegexpSet_match $prevMatch A RegexpSet_match object.
121      * $prevMatch should be a match object obtained by a previous
122      * match upon the same value of $text.
123      *
124      * @return RegexpSet_match A RegexpSet_match object, or false if no match.
125      */
126     function nextMatch($text, $prevMatch)
127     {
128         // Try to find match at same position.
129         $pos = strlen($prevMatch->prematch);
130         $regexps = array_slice($this->_regexps, $prevMatch->regexp_ind + 1);
131         if ($regexps) {
132             $repeat = sprintf('{%d}', $pos);
133             if (($match = $this->_match($text, $regexps, $repeat))) {
134                 $match->regexp_ind += $prevMatch->regexp_ind + 1;
135                 return $match;
136             }
137
138         }
139
140         // Failed.  Look for match after current position.
141         $repeat = sprintf('{%d,}?', $pos + 1);
142         return $this->_match($text, $this->_regexps, $repeat);
143     }
144
145     // Syntax: http://www.pcre.org/pcre.txt
146     //   x - EXTENDED, ignore whitespace
147     //   s - DOTALL
148     //   A - ANCHORED
149     //   S - STUDY
150     function _match($text, $regexps, $repeat)
151     {
152         // If one of the regexps is an empty string, php will crash here:
153         // sf.net: Fatal error: Allowed memory size of 8388608 bytes exhausted
154         //         (tried to allocate 634 bytes)
155         if (_INLINE_OPTIMIZATION) { // disabled, wrong
156             // So we try to minize memory usage, by looping explicitly,
157             // and storing only those regexp which actually match.
158             // There may be more than one, so we have to find the longest,
159             // and match inside until the shortest is empty.
160             $matched = array();
161             $matched_ind = array();
162             for ($i = 0; $i < count($regexps); $i++) {
163                 if (!trim($regexps[$i])) {
164                     trigger_error("empty regexp $i", E_USER_WARNING);
165                     continue;
166                 }
167                 $pat = "/ ( . $repeat ) ( " . $regexps[$i] . " ) /x";
168                 if (preg_match($pat, $text, $_m)) {
169                     $m = $_m; // FIXME: prematch, postmatch is wrong
170                     $matched[] = $regexps[$i];
171                     $matched_ind[] = $i;
172                     $regexp_ind = $i;
173                 }
174             }
175             // To overcome ANCHORED:
176             // We could sort by longest match and iterate over these.
177             if (empty($matched)) return false;
178         }
179         $match = new RegexpSet_match;
180
181         // Optimization: if the matches are only "$" and another, then omit "$"
182         if (!_INLINE_OPTIMIZATION or count($matched) > 2) {
183             assert(!empty($repeat));
184             assert(!empty($regexps));
185             // We could do much better, if we would know the matching markup for the
186             // longest regexp match:
187             $hugepat = "/ ( . $repeat ) ( (" . join(')|(', $regexps) . ") ) /Asx";
188             // Proposed premature optimization 1:
189             //$hugepat= "/ ( . $repeat ) ( (" . join(')|(', array_values($matched)) . ") ) /Asx";
190             if (!preg_match($hugepat, $text, $m)) {
191                 return false;
192             }
193             // Proposed premature optimization 1:
194             //$match->regexp_ind = $matched_ind[count($m) - 4];
195             $match->regexp_ind = count($m) - 4;
196         } else {
197             $match->regexp_ind = $regexp_ind;
198         }
199
200         $match->postmatch = substr($text, strlen($m[0]));
201         $match->prematch = $m[1];
202         $match->match = $m[2];
203
204         /* DEBUGGING */
205         if (DEBUG & _DEBUG_PARSER) {
206             static $_already_dumped = 0;
207             if (!$_already_dumped) {
208                 var_dump($regexps);
209                 if (_INLINE_OPTIMIZATION)
210                     var_dump($matched);
211                 var_dump($matched_ind);
212             }
213             $_already_dumped = 1;
214             PrintXML(HTML::dl(HTML::dt("input"),
215                 HTML::dd(HTML::pre($text)),
216                 HTML::dt("regexp"),
217                 HTML::dd(HTML::pre($match->regexp_ind, ":", $regexps[$match->regexp_ind])),
218                 HTML::dt("prematch"),
219                 HTML::dd(HTML::pre($match->prematch)),
220                 HTML::dt("match"),
221                 HTML::dd(HTML::pre($match->match)),
222                 HTML::dt("postmatch"),
223                 HTML::dd(HTML::pre($match->postmatch))
224             ));
225         }
226         return $match;
227     }
228 }
229
230 /**
231  * A simple markup rule (i.e. terminal token).
232  *
233  * These are defined by a regexp.
234  *
235  * When a match is found for the regexp, the matching text is replaced.
236  * The replacement content is obtained by calling the SimpleMarkup::markup method.
237  */
238 class SimpleMarkup
239 {
240     public $_match_regexp;
241
242     /** Get regexp.
243      *
244      * @return string Regexp which matches this token.
245      */
246     function getMatchRegexp()
247     {
248         return $this->_match_regexp;
249     }
250
251     /** Markup matching text.
252      *
253      * @param string $match The text which matched the regexp
254      * (obtained from getMatchRegexp).
255      *
256      * @return mixed The expansion of the matched text.
257      */
258     function markup($match /*, $body */)
259     {
260         trigger_error("pure virtual", E_USER_ERROR);
261     }
262 }
263
264 /**
265  * A balanced markup rule.
266  *
267  * These are defined by a start regexp, and an end regexp.
268  */
269 class BalancedMarkup
270 {
271     public $_start_regexp;
272
273     /** Get the starting regexp for this rule.
274      *
275      * @return string The starting regexp.
276      */
277     function getStartRegexp()
278     {
279         return $this->_start_regexp;
280     }
281
282     /** Get the ending regexp for this rule.
283      *
284      * @param string $match The text which matched the starting regexp.
285      *
286      * @return string The ending regexp.
287      */
288     function getEndRegexp($match)
289     {
290         return $this->_end_regexp;
291     }
292
293     /** Get expansion for matching input.
294      *
295      * @param string $match The text which matched the starting regexp.
296      *
297      * @param mixed $body Transformed text found between the starting
298      * and ending regexps.
299      *
300      * @return mixed The expansion of the matched text.
301      */
302     function markup($match, $body)
303     {
304         trigger_error("pure virtual", E_USER_ERROR);
305     }
306 }
307
308 class Markup_escape extends SimpleMarkup
309 {
310     function getMatchRegexp()
311     {
312         return ESCAPE_CHAR . '(?: [[:alnum:]]+ | .)';
313     }
314
315     function markup($match)
316     {
317         assert(strlen($match) >= 2);
318         return substr($match, 1);
319     }
320 }
321
322 /**
323  * [image.jpg size=50% border=5], [image.jpg size=50x30]
324  * Support for the following attributes: see stdlib.php:LinkImage()
325  *   size=<percent>%, size=<width>x<height>
326  *   border=n, align=\w+, hspace=n, vspace=n
327  *   width=n, height=n
328  *   title, lang, id, alt
329  */
330 function isImageLink($link)
331 {
332     if (!$link) return false;
333     assert(defined('INLINE_IMAGES'));
334     return preg_match("/\\.(" . INLINE_IMAGES . ")$/i", $link)
335         or preg_match("/\\.(" . INLINE_IMAGES . ")\s+(size|border|align|hspace|vspace|type|data|width|height|title|lang|id|alt)=/i", $link);
336 }
337
338 function LinkBracketLink($bracketlink)
339 {
340
341     // $bracketlink will start and end with brackets; in between will
342     // be either a page name, a URL or both separated by a pipe.
343
344     $wikicreolesyntax = false;
345
346     if (string_starts_with($bracketlink, "[[") or string_starts_with($bracketlink, "#[[")) {
347         $wikicreolesyntax = true;
348         $bracketlink = str_replace("[[", "[", $bracketlink);
349         $bracketlink = str_replace("]]", "]", $bracketlink);
350     }
351
352     // Strip brackets and leading space
353     // bug#1904088  Some brackets links on 2 lines cause the parser to crash
354     preg_match('/(\#?) \[\s* (?: (.*?) \s* (?<!' . ESCAPE_CHAR . ')(\|) )? \s* (.+?) \s*\]/x',
355         str_replace("\n", " ", $bracketlink), $matches);
356     if (count($matches) < 4) {
357         // "[ personal\ninformation manager | PhpWiki:PersonalWiki ]"
358         trigger_error(_("Invalid [] syntax ignored") . _(": ") . $bracketlink, E_USER_WARNING);
359         return new Cached_Link;
360     }
361     list (, $hash, $label, $bar, $rawlink) = $matches;
362
363     if ($wikicreolesyntax and $label) {
364         $temp = $label;
365         $label = $rawlink;
366         $rawlink = $temp;
367     }
368
369     // Mediawiki compatibility: allow "Image:" and "File:"
370     // as synonyms of "Upload:"
371     // Allow "upload:", "image:" and "file:" also
372     // Remove spaces before and after ":", if any
373     if (string_starts_with($rawlink, "Upload")) {
374         $rawlink = preg_replace("/^Upload\\s*:\\s*/", "Upload:", $rawlink);
375     } elseif (string_starts_with($rawlink, "upload")) {
376         $rawlink = preg_replace("/^upload\\s*:\\s*/", "Upload:", $rawlink);
377     } elseif (string_starts_with($rawlink, "Image")) {
378         $rawlink = preg_replace("/^Image\\s*:\\s*/", "Upload:", $rawlink);
379     } elseif (string_starts_with($rawlink, "image")) {
380         $rawlink = preg_replace("/^image\\s*:\\s*/", "Upload:", $rawlink);
381     } elseif (string_starts_with($rawlink, "File")) {
382         $rawlink = preg_replace("/^File\\s*:\\s*/", "Upload:", $rawlink);
383     } elseif (string_starts_with($rawlink, "file")) {
384         $rawlink = preg_replace("/^file\\s*:\\s*/", "Upload:", $rawlink);
385     }
386
387     $label = UnWikiEscape($label);
388     /*
389      * Check if the user has typed a explicit URL. This solves the
390      * problem where the URLs have a ~ character, which would be stripped away.
391      *   "[http:/server/~name/]" will work as expected
392      *   "http:/server/~name/"   will NOT work as expected, will remove the ~
393      */
394     if (string_starts_with($rawlink, "http://")
395         or string_starts_with($rawlink, "https://")
396     ) {
397         $link = $rawlink;
398         // Mozilla Browser URI Obfuscation Weakness 2004-06-14
399         //   http://www.securityfocus.com/bid/10532/
400         //   goodurl+"%2F%20%20%20."+badurl
401         if (preg_match("/%2F(%20)+\./i", $rawlink)) {
402             $rawlink = preg_replace("/%2F(%20)+\./i", "%2F.", $rawlink);
403         }
404     } else {
405         // Check page name lenght
406         if (!string_starts_with($rawlink, "Upload:")) {
407             if (strlen($rawlink) > MAX_PAGENAME_LENGTH) {
408                 return HTML::span(array('class' => 'error'),
409                     _('Page name too long'));
410             }
411         }
412         // Check illegal characters in page names: <>[]{}|"
413         if (preg_match("/[<\[\{\|\"\}\]>]/", $rawlink, $matches) > 0) {
414             return HTML::span(array('class' => 'error'),
415                 sprintf(_("Illegal character “%s” in page name."),
416                     $matches[0]));
417         }
418         $link = UnWikiEscape($rawlink);
419     }
420
421     /* Relatives links by Joel Schaubert.
422      * Recognize [../bla] or [/bla] as relative links, without needing http://
423      * but [ /link ] only if SUBPAGE_SEPERATOR is not "/".
424      * Normally /Page links to the subpage /Page.
425      */
426     if (SUBPAGE_SEPARATOR == '/') {
427         if (preg_match('/^\.\.\//', $link)) {
428             return new Cached_ExternalLink($link, $label);
429         }
430     } elseif (preg_match('/^(\.\.\/|\/)/', $link)) {
431         return new Cached_ExternalLink($link, $label);
432     }
433
434     // Handle "[[SandBox|{{image.jpg}}]]" and "[[SandBox|{{image.jpg|alt text}}]]"
435     if (string_starts_with($label, "{{")) {
436         $imgurl = substr($label, 2, -2); // Remove "{{" and "}}"
437         $pipe = strpos($imgurl, '|');
438         if ($pipe === false) {
439             $label = LinkImage(getUploadDataPath() . $imgurl, $link);
440         } else {
441             list($img, $alt) = explode("|", $imgurl);
442             $label = LinkImage(getUploadDataPath() . $img, $alt);
443         }
444     } else
445
446         // [label|link]
447         // If label looks like a url to an image or object, we want an image link.
448         if (isImageLink($label)) {
449             $imgurl = $label;
450             $intermap = getInterwikiMap();
451             if (preg_match("/^" . $intermap->getRegexp() . ":/", $label)) {
452                 $imgurl = $intermap->link($label);
453                 $imgurl = $imgurl->getAttr('href');
454             } elseif (!preg_match("#^(" . ALLOWED_PROTOCOLS . "):#", $imgurl)) {
455                 // local theme linkname like 'images/next.gif'.
456                 global $WikiTheme;
457                 $imgurl = $WikiTheme->getImageURL($imgurl);
458             }
459             // for objects (non-images) the link is taken as alt tag,
460             // which is in return taken as alternative img
461             $label = LinkImage($imgurl, $link);
462         }
463
464     if ($hash) {
465         // It's an anchor, not a link...
466         $id = MangleXmlIdentifier($link);
467         return HTML::a(array('name' => $id, 'id' => $id),
468             $bar ? $label : $link);
469     }
470
471     if (preg_match("#^(" . ALLOWED_PROTOCOLS . "):#", $link)) {
472         // if it's an image, embed it; otherwise, it's a regular link
473         if (isImageLink($link) and empty($label)) // patch #1348996 by Robert Litwiniec
474             return LinkImage($link, $label);
475         else
476             return new Cached_ExternalLink($link, $label);
477     } elseif (substr($link, 0, 8) == 'phpwiki:')
478         return new Cached_PhpwikiURL($link, $label); /* Semantic relations and attributes.
479      * Relation and attribute names must be word chars only, no space.
480      * Links and Attributes may contain everything. word, nums, units, space, groupsep, numsep, ...
481      */
482     elseif (preg_match("/^ (\w+) (:[:=]) (.*) $/x", $link) and !isImageLink($link))
483         return new Cached_SemanticLink($link, $label); /* Do not store the link */
484     elseif (substr($link, 0, 1) == ':')
485         return new Cached_WikiLink($link, $label); /*
486      * Inline images in Interwiki urls's:
487      * [File:my_image.gif] inlines the image,
488      * File:my_image.gif shows a plain inter-wiki link,
489      * [what a pic|File:my_image.gif] shows a named inter-wiki link to the gif
490      * [File:my_image.gif|what a pic] shows an inlined image linked to the page "what a pic"
491      *
492      * Note that for simplicity we will accept embedded object tags (non-images)
493      * here also, and separate them later in LinkImage()
494      */
495     elseif (strstr($link, ':')
496         and ($intermap = getInterwikiMap())
497             and preg_match("/^" . $intermap->getRegexp() . ":/", $link)
498     ) {
499         // trigger_error("label: $label link: $link", E_USER_WARNING);
500         if (empty($label) and isImageLink($link)) {
501             // if without label => inlined image [File:xx.gif]
502             $imgurl = $intermap->link($link);
503             return LinkImage($imgurl->getAttr('href'));
504         }
505         return new Cached_InterwikiLink($link, $label);
506     } else {
507         // Split anchor off end of pagename.
508         if (preg_match('/\A(.*)(?<!' . ESCAPE_CHAR . ')#(.*?)\Z/', $rawlink, $m)) {
509             list(, $rawlink, $anchor) = $m;
510             $pagename = UnWikiEscape($rawlink);
511             $anchor = UnWikiEscape($anchor);
512             if (!$label)
513                 $label = $link;
514         } else {
515             $pagename = $link;
516             $anchor = false;
517         }
518         return new Cached_WikiLink($pagename, $label, $anchor);
519     }
520 }
521
522 class Markup_wikicreolebracketlink extends SimpleMarkup
523 {
524     public $_match_regexp = "\\#? \\[\\[ .*? [^]\\s] .*? \\]\\]";
525
526     function markup($match)
527     {
528         $link = LinkBracketLink($match);
529         assert($link->isInlineElement());
530         return $link;
531     }
532 }
533
534 class Markup_bracketlink extends SimpleMarkup
535 {
536     public $_match_regexp = "\\#? \\[ .*? [^]\\s] .*? \\]";
537
538     function markup($match)
539     {
540         $link = LinkBracketLink($match);
541         assert($link->isInlineElement());
542         return $link;
543     }
544 }
545
546 class Markup_spellcheck extends SimpleMarkup
547 {
548     function Markup_spellcheck()
549     {
550         $this->suggestions = $GLOBALS['request']->getArg('suggestions');
551     }
552
553     function getMatchRegexp()
554     {
555         if (empty($this->suggestions))
556             return "(?# false )";
557         $words = array_keys($this->suggestions);
558         return "(?<= \W ) (?:" . join('|', $words) . ") (?= \W )";
559     }
560
561     function markup($match)
562     {
563         if (empty($this->suggestions) or empty($this->suggestions[$match]))
564             return $match;
565         return new Cached_SpellCheck(UnWikiEscape($match), $this->suggestions[$match]);
566     }
567 }
568
569 class Markup_searchhighlight extends SimpleMarkup
570 {
571     function Markup_searchhighlight()
572     {
573         $result = $GLOBALS['request']->_searchhighlight;
574         require_once 'lib/TextSearchQuery.php';
575         $query = new TextSearchQuery($result['query']);
576         $this->hilight_re = $query->getHighlightRegexp();
577         $this->engine = $result['engine'];
578     }
579
580     function getMatchRegexp()
581     {
582         return $this->hilight_re;
583     }
584
585     function markup($match)
586     {
587         return new Cached_SearchHighlight(UnWikiEscape($match), $this->engine);
588     }
589 }
590
591 class Markup_url extends SimpleMarkup
592 {
593     function getMatchRegexp()
594     {
595         return "(?<![[:alnum:]]) (?:" . ALLOWED_PROTOCOLS . ") : [^\s<>\"']+ (?<![ ,.?; \] \) ])";
596     }
597
598     function markup($match)
599     {
600         return new Cached_ExternalLink(UnWikiEscape($match));
601     }
602 }
603
604 class Markup_interwiki extends SimpleMarkup
605 {
606     function getMatchRegexp()
607     {
608         $map = getInterwikiMap();
609         return "(?<! [[:alnum:]])" . $map->getRegexp() . ": [^:=]\S+ (?<![ ,.?;! \] \) \" \' ])";
610     }
611
612     function markup($match)
613     {
614         return new Cached_InterwikiLink(UnWikiEscape($match));
615     }
616 }
617
618 class Markup_semanticlink extends SimpleMarkup
619 {
620     // No units separated by space allowed here
621     // For :: (relations) only words, no comma,
622     // but for := (attributes) comma and dots are allowed. Units with groupsep.
623     // Ending dots or comma are not part of the link.
624     public $_match_regexp = "(?: \w+:=\S+(?<![\.,]))|(?: \w+::[\w\.]+(?<!\.))";
625
626     function markup($match)
627     {
628         return new Cached_SemanticLink(UnWikiEscape($match));
629     }
630 }
631
632 class Markup_wikiword extends SimpleMarkup
633 {
634     function getMatchRegexp()
635     {
636         global $WikiNameRegexp;
637         if (!trim($WikiNameRegexp)) return " " . WIKI_NAME_REGEXP;
638         return " $WikiNameRegexp";
639     }
640
641     function markup($match)
642     {
643         if (!$match) return false;
644         if ($this->_isWikiUserPage($match))
645             return new Cached_UserLink($match); //$this->_UserLink($match);
646         else
647             return new Cached_WikiLink($match);
648     }
649
650     // FIXME: there's probably a more useful place to put these two functions
651     function _isWikiUserPage($page)
652     {
653         global $request;
654         $dbi = $request->getDbh();
655         $page_handle = $dbi->getPage($page);
656         if ($page_handle and $page_handle->get('pref'))
657             return true;
658         else
659             return false;
660     }
661
662     function _UserLink($PageName)
663     {
664         $link = HTML::a(array('href' => $PageName));
665         $link->pushContent(PossiblyGlueIconToText('wikiuser', $PageName));
666         $link->setAttr('class', 'wikiuser');
667         return $link;
668     }
669 }
670
671 class Markup_linebreak extends SimpleMarkup
672 {
673     public $_match_regexp = "(?: (?<! %) %%% (?! %) | \\\\\\\\ | <\s*(?:br|BR)\s*> | <\s*(?:br|BR)\s*\/\s*> )";
674
675     function markup($match)
676     {
677         return HTML::br();
678     }
679 }
680
681 class Markup_wikicreole_italics extends BalancedMarkup
682 {
683     public $_start_regexp = "\\/\\/";
684
685     function getEndRegexp($match)
686     {
687         return "\\/\\/";
688     }
689
690     function markup($match, $body)
691     {
692         $tag = 'em';
693         return new HtmlElement($tag, $body);
694     }
695 }
696
697 class Markup_wikicreole_bold extends BalancedMarkup
698 {
699     public $_start_regexp = "\\*\\*";
700
701     function getEndRegexp($match)
702     {
703         return "\\*\\*";
704     }
705
706     function markup($match, $body)
707     {
708         $tag = 'strong';
709         return new HtmlElement($tag, $body);
710     }
711 }
712
713 class Markup_wikicreole_monospace extends BalancedMarkup
714 {
715     public $_start_regexp = "\\#\\#";
716
717     function getEndRegexp($match)
718     {
719         return "\\#\\#";
720     }
721
722     function markup($match, $body)
723     {
724         return new HtmlElement('span', array('class' => 'tt'), $body);
725     }
726 }
727
728 class Markup_wikicreole_underline extends BalancedMarkup
729 {
730     public $_start_regexp = "\\_\\_";
731
732     function getEndRegexp($match)
733     {
734         return "\\_\\_";
735     }
736
737     function markup($match, $body)
738     {
739         $tag = 'u';
740         return new HtmlElement($tag, $body);
741     }
742 }
743
744 class Markup_wikicreole_superscript extends BalancedMarkup
745 {
746     public $_start_regexp = "\\^\\^";
747
748     function getEndRegexp($match)
749     {
750         return "\\^\\^";
751     }
752
753     function markup($match, $body)
754     {
755         $tag = 'sup';
756         return new HtmlElement($tag, $body);
757     }
758 }
759
760 class Markup_wikicreole_subscript extends BalancedMarkup
761 {
762     public $_start_regexp = ",,";
763
764     function getEndRegexp($match)
765     {
766         return $match;
767     }
768
769     function markup($match, $body)
770     {
771         $tag = 'sub';
772         return new HtmlElement($tag, $body);
773     }
774 }
775
776 class Markup_old_emphasis extends BalancedMarkup
777 {
778     public $_start_regexp = "''";
779
780     function getEndRegexp($match)
781     {
782         return $match;
783     }
784
785     function markup($match, $body)
786     {
787         $tag = 'em';
788         return new HtmlElement($tag, $body);
789     }
790 }
791
792 class Markup_nestled_emphasis extends BalancedMarkup
793 {
794     function getStartRegexp()
795     {
796         static $start_regexp = false;
797
798         if (!$start_regexp) {
799             // The three possible delimiters
800             // (none of which can be followed by itself.)
801             $i = "_ (?! _)";
802             $b = "\\* (?! \\*)";
803             $tt = "= (?! =)";
804
805             $any = "(?: ${i}|${b}|${tt})"; // any of the three.
806
807             // Any of [_*=] is okay if preceded by space or one of [-"'/:]
808             $start[] = "(?<= \\s|^|[-\"'\\/:]) ${any}";
809
810             // _ or * is okay after = as long as not immediately followed by =
811             $start[] = "(?<= =) (?: ${i}|${b}) (?! =)";
812             // etc...
813             $start[] = "(?<= _) (?: ${b}|${tt}) (?! _)";
814             $start[] = "(?<= \\*) (?: ${i}|${tt}) (?! \\*)";
815
816             // any delimiter okay after an opening brace ( [{<(] )
817             // as long as it's not immediately followed by the matching closing
818             // brace.
819             $start[] = "(?<= { ) ${any} (?! } )";
820             $start[] = "(?<= < ) ${any} (?! > )";
821             $start[] = "(?<= \\( ) ${any} (?! \\) )";
822
823             $start = "(?:" . join('|', $start) . ")";
824
825             // Any of the above must be immediately followed by non-whitespace.
826             $start_regexp = $start . "(?= \S)";
827         }
828
829         return $start_regexp;
830     }
831
832     function getEndRegexp($match)
833     {
834         $chr = preg_quote($match);
835         return "(?<= \S | ^ ) (?<! $chr) $chr (?! $chr) (?= \s | [-)}>\"'\\/:.,;!? _*=] | $)";
836     }
837
838     function markup($match, $body)
839     {
840         switch ($match) {
841             case '*':
842                 return new HtmlElement('b', $body);
843             case '=':
844                 return new HtmlElement('span', array('class' => 'tt'), $body);
845             case '_':
846                 return new HtmlElement('i', $body);
847         }
848     }
849 }
850
851 class Markup_html_emphasis extends BalancedMarkup
852 {
853     public $_start_regexp =
854         "<(?: b|big|i|small|tt|em|strong|cite|code|dfn|kbd|samp|s|strike|del|var|sup|sub )>";
855
856     function getEndRegexp($match)
857     {
858         return "<\\/" . substr($match, 1);
859     }
860
861     function markup($match, $body)
862     {
863         $tag = substr($match, 1, -1);
864         return new HtmlElement($tag, $body);
865     }
866 }
867
868 class Markup_html_divspan extends BalancedMarkup
869 {
870     public $_start_regexp =
871         "<(?: div|span )(?: \s[^>]*)?>";
872
873     function getEndRegexp($match)
874     {
875         if (substr($match, 1, 4) == 'span')
876             $tag = 'span';
877         else
878             $tag = 'div';
879         return "<\\/" . $tag . '>';
880     }
881
882     function markup($match, $body)
883     {
884         if (substr($match, 1, 4) == 'span')
885             $tag = 'span';
886         else
887             $tag = 'div';
888         $rest = substr($match, 1 + strlen($tag), -1);
889         if (!empty($rest)) {
890             $args = parse_attributes($rest);
891         } else {
892             $args = array();
893         }
894         return new HtmlElement($tag, $args, $body);
895     }
896 }
897
898 class Markup_html_abbr extends BalancedMarkup
899 {
900     //rurban: abbr|acronym need an optional title tag.
901     //sf.net bug #728595
902     public $_start_regexp = "<(?: abbr|acronym )(?: [^>]*)?>";
903
904     function getEndRegexp($match)
905     {
906         if (substr($match, 1, 4) == 'abbr')
907             $tag = 'abbr';
908         else
909             $tag = 'acronym';
910         return "<\\/" . $tag . '>';
911     }
912
913     function markup($match, $body)
914     {
915         if (substr($match, 1, 4) == 'abbr')
916             $tag = 'abbr';
917         else
918             $tag = 'acronym';
919         $rest = substr($match, 1 + strlen($tag), -1);
920         $attrs = parse_attributes($rest);
921         // Remove attributes other than title and lang
922         $allowedargs = array();
923         foreach ($attrs as $key => $value) {
924             if (in_array($key, array("title", "lang"))) {
925                 $allowedargs[$key] = $value;
926             }
927         }
928         return new HtmlElement($tag, $allowedargs, $body);
929     }
930 }
931
932 /** ENABLE_MARKUP_COLOR
933  *  See http://www.pmwiki.org/wiki/PmWiki/WikiStyles and
934  *      http://www.flexwiki.com/default.aspx/FlexWiki/FormattingRules.html
935  */
936 class Markup_color extends BalancedMarkup
937 {
938     // %color=blue% blue text %% and back to normal
939     public $_start_regexp = "%color=(?: [^%]*)%";
940     public $_end_regexp = "%%";
941
942     function markup($match, $body)
943     {
944         $color = strtolower(substr($match, 7, -1));
945
946         $morecolors = array('beige' => '#f5f5dc',
947             'brown' => '#a52a2a',
948             'chocolate' => '#d2691e',
949             'cyan' => '#00ffff',
950             'gold' => '#ffd700',
951             'ivory' => '#fffff0',
952             'indigo' => '#4b0082',
953             'magenta' => '#ff00ff',
954             'orange' => '#ffa500',
955             'pink' => '#ffc0cb',
956             'salmon' => '#fa8072',
957             'snow' => '#fffafa',
958             'turquoise' => '#40e0d0',
959             'violet' => '#ee82ee',
960         );
961
962         if (isset($morecolors[$color])) {
963             $color = $morecolors[$color];
964         }
965
966         // HTML 4 defines the following 16 colors
967         if (in_array($color, array('aqua', 'black', 'blue', 'fuchsia',
968             'gray', 'green', 'lime', 'maroon',
969             'navy', 'olive', 'purple', 'red',
970             'silver', 'teal', 'white', 'yellow'))
971             or ((substr($color, 0, 1) == '#')
972                 and ((strlen($color) == 4) or (strlen($color) == 7))
973                     and (strspn(substr($color, 1), '0123456789abcdef') == strlen($color) - 1))
974         ) {
975             return new HtmlElement('span', array('style' => "color: $color"), $body);
976         } else {
977             return new HtmlElement('span', array('class' => 'error'),
978                 sprintf(_("unknown color %s ignored"), substr($match, 7, -1)));
979         }
980     }
981 }
982
983 // Wikicreole placeholder
984 // <<<placeholder>>>
985 class Markup_placeholder extends SimpleMarkup
986 {
987     public $_match_regexp = '<<<.*?>>>';
988
989     function markup($match)
990     {
991         return HTML::span($match);
992     }
993 }
994
995 // Single-line HTML comment
996 // <!-- This is a comment -->
997 class Markup_html_comment extends SimpleMarkup
998 {
999     public $_match_regexp = '<!--.*?-->';
1000
1001     function markup($match)
1002     {
1003         return HTML::raw('');
1004     }
1005 }
1006
1007 // Special version for single-line plugins formatting,
1008 //  like: '<small>< ?plugin PopularNearby ? ></small>'
1009 class Markup_plugin extends SimpleMarkup
1010 {
1011     public $_match_regexp = '<\?plugin(?:-form)?\s[^\n]+?\?>';
1012
1013     function markup($match)
1014     {
1015         return new Cached_PluginInvocation($match);
1016     }
1017 }
1018
1019 // Special version for single-line Wikicreole plugins formatting.
1020 class Markup_plugin_wikicreole extends SimpleMarkup
1021 {
1022     public $_match_regexp = '<<[^\n]+?>>';
1023
1024     function markup($match)
1025     {
1026         $pi = str_replace("<<", "<?plugin ", $match);
1027         $pi = str_replace(">>", " ?>", $pi);
1028         return new Cached_PluginInvocation($pi);
1029     }
1030 }
1031
1032 // Special version for plugins in xml syntax, mediawiki-style
1033 // <name arg=value>body</name> or <name /> => < ? plugin pluginname arg=value body ? >
1034 // PLUGIN_MARKUP_MAP = "html:RawHtml dot:GraphViz toc:CreateToc amath:AsciiMath richtable:RichTable include:IncludePage tex:TexToPng"
1035 class Markup_xml_plugin extends BalancedMarkup
1036 {
1037     //public $_start_regexp = "<(?: ".join('|',PLUGIN_MARKUP_MAP)." )(?: \s[^>]*)>";
1038
1039     function getStartRegexp()
1040     {
1041         global $PLUGIN_MARKUP_MAP;
1042         static $_start_regexp;
1043         if ($_start_regexp) return $_start_regexp;
1044         if (empty($PLUGIN_MARKUP_MAP)) return '';
1045         //"<(?: html|search|extsearch|dot|toc|math|richtable|include|tex )(?: \s[^>]*)>"
1046         $_start_regexp = "<(?: " . join('|', array_keys($PLUGIN_MARKUP_MAP)) . " )(?: \s[^>]*|\\/ )>";
1047         return $_start_regexp;
1048     }
1049
1050     function getEndRegexp($match)
1051     {
1052         return "<\\/" . $match . '>';
1053     }
1054
1055     function markup($match, $body)
1056     {
1057         global $PLUGIN_MARKUP_MAP;
1058         $name = substr($match, 2, -2);
1059         $vars = '';
1060         if (preg_match('/^(\S+)\|(.*)$/', $name, $_m)) {
1061             $name = $_m[1];
1062             $vars = $_m[2]; //str_replace(' ', '&', $_m[2]);
1063         }
1064         if (!isset($PLUGIN_MARKUP_MAP[$name])) {
1065             trigger_error("No plugin for $name $vars defined.", E_USER_WARNING);
1066             return "";
1067         }
1068         $plugin = $PLUGIN_MARKUP_MAP[$name];
1069         return new Cached_PluginInvocation("<" . "?plugin $plugin $vars $body ?" . ">");
1070     }
1071 }
1072
1073 /**
1074  *  Mediawiki <nowiki>
1075  *  <nowiki>...</nowiki>
1076  */
1077 class Markup_nowiki extends SimpleMarkup
1078 {
1079     public $_match_regexp = '<nowiki>.*?<\/nowiki>';
1080
1081     function markup($match)
1082     {
1083         // Remove <nowiki> and </nowiki>
1084         return HTML::raw(substr($match, 8, -9));
1085     }
1086 }
1087
1088 /**
1089  *  Wikicreole preformatted
1090  *  {{{
1091  *  }}}
1092  */
1093 class Markup_wikicreole_preformatted extends SimpleMarkup
1094 {
1095     public $_match_regexp = '\{\{\{.*?\}\}\}';
1096
1097     function markup($match)
1098     {
1099         // Remove {{{ and }}}
1100         return new HtmlElement('span', array('class' => 'tt'), substr($match, 3, -3));
1101     }
1102 }
1103
1104 /** ENABLE_MARKUP_TEMPLATE
1105  *  Template syntax similar to Mediawiki
1106  *  {{template}}
1107  * => < ? plugin Template page=template ? >
1108  *  {{template|var1=value1|var2=value|...}}
1109  * => < ? plugin Template page=template var=value ... ? >
1110  *
1111  * The {{...}} syntax is also used for:
1112  *  - Wikicreole images
1113  *  - videos
1114  *  - predefined icons
1115  */
1116 class Markup_template_plugin extends SimpleMarkup
1117 {
1118     // patch #1732793: allow \n, mult. {{ }} in one line, and single letters
1119     public $_match_regexp = '\{\{.*?\}\}';
1120
1121     function markup($match)
1122     {
1123
1124         $page = substr($match, 2, -2);
1125         $page = trim($page);
1126
1127         // Check for predefined icons.
1128         $predefinedicons = array(":)" => "ic_smile.png",
1129             ":(" => "ic_sad.png",
1130             ":P" => "ic_tongue.png",
1131             ":D" => "ic_biggrin.png",
1132             ";)" => "ic_wink.png",
1133             "(y)" => "ic_handyes.png",
1134             "(n)" => "ic_handno.png",
1135             "(i)" => "ic_info.png",
1136             "(/)" => "ic_check.png",
1137             "(x)" => "ic_cross.png",
1138             "(!)" => "ic_danger.png",
1139             "(+)" => "ic_plus.png",
1140             "(-)" => "ic_minus.png",
1141             "(?)" => "ic_help.png",
1142             "(on)" => "ic_lighton.png",
1143             "(off)" => "ic_lightoff.png",
1144             "(*)" => "ic_yellowstar.png",
1145             "(*r)" => "ic_redstar.png",
1146             "(*g)" => "ic_greenstar.png",
1147             "(*b)" => "ic_bluestar.png",
1148             "(*y)" => "ic_yellowstar.png",
1149         );
1150         foreach ($predefinedicons as $ascii => $icon) {
1151             if ($page == $ascii) {
1152                 return LinkImage(DATA_PATH . "/themes/default/images/$icon", $page);
1153             }
1154         }
1155
1156         if (strpos($page, "|") === false) {
1157             $imagename = $page;
1158             $alt = "";
1159         } else {
1160             $imagename = substr($page, 0, strpos($page, "|"));
1161             $alt = ltrim(strstr($page, "|"), "|");
1162         }
1163
1164         // It's not a Mediawiki template, it's a Wikicreole image
1165         if (is_image($imagename)) {
1166             if ((strpos($imagename, "http://") === 0) || (strpos($imagename, "https://") === 0)) {
1167                 return LinkImage($imagename, $alt);
1168             } elseif ($imagename[0] == '/') {
1169                 return LinkImage(DATA_PATH . '/' . $imagename, $alt);
1170             } else {
1171                 return LinkImage(getUploadDataPath() . $imagename, $alt);
1172             }
1173         }
1174
1175         // It's a video
1176         if (is_video($imagename)) {
1177             $s = '<' . '?plugin Video file="' . $imagename . '" ?' . '>';
1178             return new Cached_PluginInvocation($s);
1179         }
1180
1181         $page = str_replace("\n", "", $page);
1182
1183         // The argument value might contain a double quote (")
1184         // We have to encode that.
1185         $page = htmlspecialchars($page);
1186
1187         $vars = '';
1188
1189         if (preg_match('/^(\S+?)\|(.*)$/', $page, $_m)) {
1190             $page = $_m[1];
1191             $vars = '"' . preg_replace('/\|/', '" "', $_m[2]) . '"';
1192             $vars = preg_replace('/"(\S+)=([^"]*)"/', '\\1="\\2"', $vars);
1193         }
1194
1195         // page may contain a version number
1196         // {{foo?version=5}}
1197         // in that case, output is "page=foo rev=5"
1198         if (strstr($page, "?")) {
1199             $page = str_replace("?version=", "\" rev=\"", $page);
1200         }
1201
1202         if ($vars)
1203             $s = '<' . '?plugin Template page="' . $page . '" ' . $vars . ' ?' . '>';
1204         else
1205             $s = '<' . '?plugin Template page="' . $page . '" ?' . '>';
1206         return new Cached_PluginInvocation($s);
1207     }
1208 }
1209
1210 // "..." => "&#133;"  browser specific display (not cached?)
1211 // Support some HTML::Entities: (C) for copy, --- for mdash, -- for ndash
1212 // TODO: "--" => "&emdash;" browser specific display (not cached?)
1213
1214 class Markup_html_entities extends SimpleMarkup
1215 {
1216     //public $_match_regexp = '(: \.\.\.|\-\-|\-\-\-|\(C\) )';
1217
1218     function Markup_html_entities()
1219     {
1220         $this->_entities = array('...' => '&#133;',
1221             '--' => '&ndash;',
1222             '---' => '&mdash;',
1223             '(C)' => '&copy;',
1224             '&copy;' => '&copy;',
1225             '&trade;' => '&trade;',
1226         );
1227         $this->_match_regexp =
1228             '(: ' .
1229                 join('|', array_map('preg_quote', array_keys($this->_entities))) .
1230                 ' )';
1231     }
1232
1233     function markup($match)
1234     {
1235         return HTML::Raw($this->_entities[$match]);
1236     }
1237 }
1238
1239 class Markup_isonumchars extends SimpleMarkup
1240 {
1241     public $_match_regexp = '\&\#\d{2,5};';
1242
1243     function markup($match)
1244     {
1245         return HTML::Raw($match);
1246     }
1247 }
1248
1249 class Markup_isohexchars extends SimpleMarkup
1250 {
1251     // hexnums, like &#x00A4; <=> &curren;
1252     public $_match_regexp = '\&\#x[0-9a-fA-F]{2,4};';
1253
1254     function markup($match)
1255     {
1256         return HTML::Raw($match);
1257     }
1258 }
1259
1260 // FIXME: Do away with magic phpwiki forms.  (Maybe phpwiki: links too?)
1261
1262 class InlineTransformer
1263 {
1264     public $_regexps = array();
1265     public $_markup = array();
1266
1267     function InlineTransformer($markup_types = false)
1268     {
1269         global $request;
1270         // We need to extend the inline parsers by certain actions, like SearchHighlight,
1271         // SpellCheck and maybe CreateToc.
1272         if (!$markup_types) {
1273             $non_default = false;
1274             $markup_types = array
1275             ('escape', 'wikicreolebracketlink', 'bracketlink', 'url',
1276                 'html_comment', 'placeholder',
1277                 'interwiki', 'semanticlink', 'wikiword', 'linebreak',
1278                 'wikicreole_superscript',
1279                 'wikicreole_subscript',
1280                 'wikicreole_italics', 'wikicreole_bold',
1281                 'wikicreole_monospace',
1282                 'wikicreole_underline',
1283                 'old_emphasis', 'nestled_emphasis',
1284                 'html_emphasis', 'html_abbr', 'plugin', 'plugin_wikicreole',
1285                 'isonumchars', 'isohexchars', /*'html_entities'*/
1286             );
1287             if (DISABLE_MARKUP_WIKIWORD)
1288                 $markup_types = array_remove($markup_types, 'wikiword');
1289
1290             $action = $request->getArg('action');
1291             if ($action == 'SpellCheck' and $request->getArg('suggestions')) { // insert it after url
1292                 array_splice($markup_types, 2, 1, array('url', 'spellcheck'));
1293             }
1294             if (isset($request->_searchhighlight)) { // insert it after url
1295                 array_splice($markup_types, 2, 1, array('url', 'searchhighlight'));
1296                 //$request->setArg('searchhighlight', false);
1297             }
1298         } else {
1299             $non_default = true;
1300         }
1301         foreach ($markup_types as $mtype) {
1302             $class = "Markup_$mtype";
1303             $this->_addMarkup(new $class);
1304         }
1305         $this->_addMarkup(new Markup_nowiki);
1306         if (ENABLE_MARKUP_DIVSPAN and !$non_default)
1307             $this->_addMarkup(new Markup_html_divspan);
1308         if (ENABLE_MARKUP_COLOR and !$non_default)
1309             $this->_addMarkup(new Markup_color);
1310         // Markup_wikicreole_preformatted must be before Markup_template_plugin
1311         $this->_addMarkup(new Markup_wikicreole_preformatted);
1312         if (ENABLE_MARKUP_TEMPLATE and !$non_default)
1313             $this->_addMarkup(new Markup_template_plugin);
1314         // This does not work yet
1315         if (PLUGIN_MARKUP_MAP and !$non_default)
1316             $this->_addMarkup(new Markup_xml_plugin);
1317     }
1318
1319     function _addMarkup($markup)
1320     {
1321         if (isa($markup, 'SimpleMarkup'))
1322             $regexp = $markup->getMatchRegexp();
1323         else
1324             $regexp = $markup->getStartRegexp();
1325
1326         assert(!isset($this->_markup[$regexp]));
1327         assert(strlen(trim($regexp)) > 0);
1328         $this->_regexps[] = $regexp;
1329         $this->_markup[] = $markup;
1330     }
1331
1332     function parse(&$text, $end_regexps = array('$'))
1333     {
1334         $regexps = $this->_regexps;
1335
1336         // $end_re takes precedence: "favor reduce over shift"
1337         array_unshift($regexps, $end_regexps[0]);
1338         //array_push($regexps, $end_regexps[0]);
1339         $regexps = new RegexpSet($regexps);
1340
1341         $input = $text;
1342         $output = new XmlContent;
1343
1344         $match = $regexps->match($input);
1345
1346         while ($match) {
1347             if ($match->regexp_ind == 0) {
1348                 // No start pattern found before end pattern.
1349                 // We're all done!
1350                 if (isset($markup) and is_object($markup)
1351                     and isa($markup, 'Markup_plugin')
1352                 ) {
1353                     $current =& $output->_content[count($output->_content) - 1];
1354                     $current->setTightness(true, true);
1355                 }
1356                 $output->pushContent($match->prematch);
1357                 $text = $match->postmatch;
1358                 return $output;
1359             }
1360
1361             $markup = $this->_markup[$match->regexp_ind - 1];
1362             $body = $this->_parse_markup_body($markup, $match->match,
1363                 $match->postmatch, $end_regexps);
1364             if (!$body) {
1365                 // Couldn't match balanced expression.
1366                 // Ignore and look for next matching start regexp.
1367                 $match = $regexps->nextMatch($input, $match);
1368                 continue;
1369             }
1370
1371             // Matched markup.  Eat input, push output.
1372             // FIXME: combine adjacent strings.
1373             if (isa($markup, 'SimpleMarkup'))
1374                 $current = $markup->markup($match->match);
1375             else
1376                 $current = $markup->markup($match->match, $body);
1377             $input = $match->postmatch;
1378             if (isset($markup) and is_object($markup)
1379                 and isa($markup, 'Markup_plugin')
1380             ) {
1381                 $current->setTightness(true, true);
1382             }
1383             $output->pushContent($match->prematch, $current);
1384
1385             $match = $regexps->match($input);
1386         }
1387
1388         // No pattern matched, not even the end pattern.
1389         // Parse fails.
1390         return false;
1391     }
1392
1393     function _parse_markup_body($markup, $match, &$text, $end_regexps)
1394     {
1395         if (isa($markup, 'SimpleMarkup')) {
1396             return true; // Done. SimpleMarkup is simple.
1397         }
1398
1399         if (!is_object($markup)) {
1400            return false; // Some error: Should assert
1401         }
1402         array_unshift($end_regexps, $markup->getEndRegexp($match));
1403
1404         // Optimization: if no end pattern in text, we know the
1405         // parse will fail.  This is an important optimization,
1406         // e.g. when text is "*lots *of *start *delims *with
1407         // *no *matching *end *delims".
1408         $ends_pat = "/(?:" . join(").*(?:", $end_regexps) . ")/xs";
1409         if (!@preg_match($ends_pat, $text)) { // Add "@" to avoid warning with "{{(*y)}}"
1410             return false;
1411         }
1412         return $this->parse($text, $end_regexps);
1413     }
1414 }
1415
1416 class LinkTransformer extends InlineTransformer
1417 {
1418     function LinkTransformer()
1419     {
1420         $this->InlineTransformer(array('escape', 'wikicreolebracketlink', 'bracketlink', 'url',
1421             'semanticlink', 'interwiki', 'wikiword',
1422         ));
1423     }
1424 }
1425
1426 class NowikiTransformer extends InlineTransformer
1427 {
1428     function NowikiTransformer()
1429     {
1430         $this->InlineTransformer
1431         (array('linebreak',
1432             'html_emphasis', 'html_abbr', 'plugin', 'plugin_wikicreole',
1433             'isonumchars', 'isohexchars', /*'html_entities',*/
1434         ));
1435     }
1436 }
1437
1438 function TransformInline($text, $markup = 2.0, $basepage = false)
1439 {
1440     static $trfm;
1441     $action = $GLOBALS['request']->getArg('action');
1442     if (empty($trfm) or $action == 'SpellCheck') {
1443         $trfm = new InlineTransformer;
1444     }
1445
1446     if ($markup < 2.0) {
1447         $text = ConvertOldMarkup($text, 'inline');
1448     }
1449
1450     if ($basepage) {
1451         return new CacheableMarkup($trfm->parse($text), $basepage);
1452     }
1453     return $trfm->parse($text);
1454 }
1455
1456 function TransformLinks($text, $markup = 2.0, $basepage = false)
1457 {
1458     static $trfm;
1459
1460     if (empty($trfm)) {
1461         $trfm = new LinkTransformer;
1462     }
1463
1464     if ($markup < 2.0) {
1465         $text = ConvertOldMarkup($text, 'links');
1466     }
1467
1468     if ($basepage) {
1469         return new CacheableMarkup($trfm->parse($text), $basepage);
1470     }
1471     return $trfm->parse($text);
1472 }
1473
1474 /**
1475  * Transform only html markup and entities.
1476  */
1477 function TransformInlineNowiki($text, $markup = 2.0, $basepage = false)
1478 {
1479     static $trfm;
1480
1481     if (empty($trfm)) {
1482         $trfm = new NowikiTransformer;
1483     }
1484     if ($basepage) {
1485         return new CacheableMarkup($trfm->parse($text), $basepage);
1486     }
1487     return $trfm->parse($text);
1488 }
1489
1490 // Local Variables:
1491 // mode: php
1492 // tab-width: 8
1493 // c-basic-offset: 4
1494 // c-hanging-comment-ender-p: nil
1495 // indent-tabs-mode: nil
1496 // End: