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