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