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