]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/InlineParser.php
New FSF address
[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         $link  = UnWikiEscape($rawlink);
392
393     /* Relatives links by Joel Schaubert.
394      * Recognize [../bla] or [/bla] as relative links, without needing http://
395      * but [ /link ] only if SUBPAGE_SEPERATOR is not "/".
396      * Normally /Page links to the subpage /Page.
397      */
398     if (SUBPAGE_SEPARATOR == '/') {
399         if (preg_match('/^\.\.\//', $link)) {
400             return new Cached_ExternalLink($link, $label);
401         }
402     } else if (preg_match('/^(\.\.\/|\/)/', $link)) {
403         return new Cached_ExternalLink($link, $label);
404     }
405
406     // Handle "[[SandBox|{{image.jpg}}]]" and "[[SandBox|{{image.jpg|alt text}}]]"
407     if (string_starts_with($label, "{{")) {
408         $imgurl = substr($label, 2, -2); // Remove "{{" and "}}"
409         $pipe = strpos($imgurl, '|');
410         if ($pipe === false) {
411             $label = LinkImage(getUploadDataPath() . $imgurl, $link);
412         } else {
413             list($img, $alt) = explode("|", $imgurl);
414             $label = LinkImage(getUploadDataPath() . $img, $alt);
415         }
416     } else
417
418     // [label|link]
419     // If label looks like a url to an image or object, we want an image link.
420     if (isImageLink($label)) {
421         $imgurl = $label;
422         $intermap = getInterwikiMap();
423         if (preg_match("/^" . $intermap->getRegexp() . ":/", $label)) {
424             $imgurl = $intermap->link($label);
425             $imgurl = $imgurl->getAttr('href');
426         } elseif (! preg_match("#^(" . ALLOWED_PROTOCOLS . "):#", $imgurl)) {
427             // local theme linkname like 'images/next.gif'.
428             global $WikiTheme;
429             $imgurl = $WikiTheme->getImageURL($imgurl);
430         }
431         // for objects (non-images) the link is taken as alt tag,
432         // which is in return taken as alternative img
433         $label = LinkImage($imgurl, $link);
434     }
435
436     if ($hash) {
437         // It's an anchor, not a link...
438         $id = MangleXmlIdentifier($link);
439         return HTML::a(array('name' => $id, 'id' => $id),
440                        $bar ? $label : $link);
441     }
442
443     if (preg_match("#^(" . ALLOWED_PROTOCOLS . "):#", $link)) {
444         // if it's an image, embed it; otherwise, it's a regular link
445         if (isImageLink($link) and empty($label)) // patch #1348996 by Robert Litwiniec
446             return LinkImage($link, $label);
447         else
448             return new Cached_ExternalLink($link, $label);
449     }
450     elseif (substr($link,0,8) == 'phpwiki:')
451         return new Cached_PhpwikiURL($link, $label);
452
453     /* Semantic relations and attributes.
454      * Relation and attribute names must be word chars only, no space.
455      * Links and Attributes may contain everything. word, nums, units, space, groupsep, numsep, ...
456      */
457     elseif (preg_match("/^ (\w+) (:[:=]) (.*) $/x", $link) and !isImageLink($link))
458         return new Cached_SemanticLink($link, $label);
459
460     /* Do not store the link */
461     elseif (substr($link,0,1) == ':')
462         return new Cached_WikiLink($link, $label);
463
464     /*
465      * Inline images in Interwiki urls's:
466      * [File:my_image.gif] inlines the image,
467      * File:my_image.gif shows a plain inter-wiki link,
468      * [what a pic|File:my_image.gif] shows a named inter-wiki link to the gif
469      * [File:my_image.gif|what a pic] shows an inlined image linked to the page "what a pic"
470      *
471      * Note that for simplicity we will accept embedded object tags (non-images)
472      * here also, and seperate them later in LinkImage()
473      */
474     elseif (strstr($link,':')
475             and ($intermap = getInterwikiMap())
476             and preg_match("/^" . $intermap->getRegexp() . ":/", $link))
477     {
478         // trigger_error("label: $label link: $link", E_USER_WARNING);
479         if (empty($label) and isImageLink($link)) {
480             // if without label => inlined image [File:xx.gif]
481             $imgurl = $intermap->link($link);
482             return LinkImage($imgurl->getAttr('href'));
483         }
484         return new Cached_InterwikiLink($link, $label);
485     } else {
486         // Split anchor off end of pagename.
487         if (preg_match('/\A(.*)(?<!'.ESCAPE_CHAR.')#(.*?)\Z/', $rawlink, $m)) {
488             list(,$rawlink,$anchor) = $m;
489             $pagename = UnWikiEscape($rawlink);
490             $anchor = UnWikiEscape($anchor);
491             if (!$label)
492                 $label = $link;
493         }
494         else {
495             $pagename = $link;
496             $anchor = false;
497         }
498         return new Cached_WikiLink($pagename, $label, $anchor);
499     }
500 }
501
502 class Markup_wikicreolebracketlink  extends SimpleMarkup
503 {
504     var $_match_regexp = "\\#? \\[\\[ .*? [^]\\s] .*? \\]\\]";
505
506     function markup ($match) {
507         $link = LinkBracketLink($match);
508         assert($link->isInlineElement());
509         return $link;
510     }
511 }
512
513 class Markup_bracketlink  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_spellcheck extends SimpleMarkup
525 {
526     function Markup_spellcheck () {
527     $this->suggestions = $GLOBALS['request']->getArg('suggestions');
528     }
529     function getMatchRegexp () {
530         if (empty($this->suggestions))
531             return "(?# false )";
532     $words = array_keys($this->suggestions);
533         return "(?<= \W ) (?:" . join('|', $words) . ") (?= \W )";
534     }
535
536     function markup ($match) {
537         if (empty($this->suggestions) or empty($this->suggestions[$match]))
538             return $match;
539         return new Cached_SpellCheck(UnWikiEscape($match), $this->suggestions[$match]);
540     }
541 }
542
543 class Markup_searchhighlight extends SimpleMarkup
544 {
545     function Markup_searchhighlight () {
546         $result = $GLOBALS['request']->_searchhighlight;
547         require_once("lib/TextSearchQuery.php");
548         $query = new TextSearchQuery($result['query']);
549         $this->hilight_re = $query->getHighlightRegexp();
550         $this->engine = $result['engine'];
551     }
552     function getMatchRegexp () {
553         return $this->hilight_re;
554     }
555     function markup ($match) {
556         return new Cached_SearchHighlight(UnWikiEscape($match), $this->engine);
557     }
558 }
559
560 class Markup_url extends SimpleMarkup
561 {
562     function getMatchRegexp () {
563         return "(?<![[:alnum:]]) (?:" . ALLOWED_PROTOCOLS . ") : [^\s<>\"']+ (?<![ ,.?; \] \) ])";
564     }
565
566     function markup ($match) {
567         return new Cached_ExternalLink(UnWikiEscape($match));
568     }
569 }
570
571 class Markup_interwiki extends SimpleMarkup
572 {
573     function getMatchRegexp () {
574         $map = getInterwikiMap();
575         return "(?<! [[:alnum:]])" . $map->getRegexp(). ": [^:=]\S+ (?<![ ,.?;! \] \) \" \' ])";
576     }
577
578     function markup ($match) {
579         return new Cached_InterwikiLink(UnWikiEscape($match));
580     }
581 }
582
583 class Markup_semanticlink extends SimpleMarkup
584 {
585     // No units seperated by space allowed here
586     // For :: (relations) only words, no comma,
587     // but for := (attributes) comma and dots are allowed. Units with groupsep.
588     // Ending dots or comma are not part of the link.
589     var $_match_regexp = "(?: \w+:=\S+(?<![\.,]))|(?: \w+::[\w\.]+(?<!\.))";
590
591     function markup ($match) {
592         return new Cached_SemanticLink(UnWikiEscape($match));
593     }
594 }
595
596 class Markup_wikiword extends SimpleMarkup
597 {
598     function getMatchRegexp () {
599         global $WikiNameRegexp;
600         if (!trim($WikiNameRegexp)) return " " . WIKI_NAME_REGEXP;
601         return " $WikiNameRegexp";
602     }
603
604     function markup ($match) {
605         if (!$match) return false;
606         if ($this->_isWikiUserPage($match))
607             return new Cached_UserLink($match); //$this->_UserLink($match);
608         else
609             return new Cached_WikiLink($match);
610     }
611
612     // FIXME: there's probably a more useful place to put these two functions
613     function _isWikiUserPage ($page) {
614         global $request;
615         $dbi = $request->getDbh();
616         $page_handle = $dbi->getPage($page);
617         if ($page_handle and $page_handle->get('pref'))
618             return true;
619         else
620             return false;
621     }
622
623     function _UserLink($PageName) {
624         $link = HTML::a(array('href' => $PageName));
625         $link->pushContent(PossiblyGlueIconToText('wikiuser', $PageName));
626         $link->setAttr('class', 'wikiuser');
627         return $link;
628     }
629 }
630
631 class Markup_linebreak extends SimpleMarkup
632 {
633     var $_match_regexp = "(?: (?<! %) %%% (?! %) | \\\\\\\\ | <\s*(?:br|BR)\s*> | <\s*(?:br|BR)\s*\/\s*> )";
634
635     function markup ($match) {
636         return HTML::br();
637     }
638 }
639
640 class Markup_wikicreole_italics extends BalancedMarkup
641 {
642     var $_start_regexp = "\\/\\/";
643
644     function getEndRegexp ($match) {
645         return "\\/\\/";
646     }
647
648     function markup ($match, $body) {
649         $tag = 'em';
650         return new HtmlElement($tag, $body);
651     }
652 }
653
654 class Markup_wikicreole_bold extends BalancedMarkup
655 {
656     var $_start_regexp = "\\*\\*";
657
658     function getEndRegexp ($match) {
659         return "\\*\\*";
660     }
661
662     function markup ($match, $body) {
663         $tag = 'strong';
664         return new HtmlElement($tag, $body);
665     }
666 }
667
668 class Markup_wikicreole_monospace extends BalancedMarkup
669 {
670     var $_start_regexp = "\\#\\#";
671
672     function getEndRegexp ($match) {
673         return "\\#\\#";
674     }
675
676     function markup ($match, $body) {
677         $tag = 'tt';
678         return new HtmlElement($tag, $body);
679     }
680 }
681
682 class Markup_wikicreole_underline extends BalancedMarkup
683 {
684     var $_start_regexp = "\\_\\_";
685
686     function getEndRegexp ($match) {
687         return "\\_\\_";
688     }
689
690     function markup ($match, $body) {
691         $tag = 'u';
692         return new HtmlElement($tag, $body);
693     }
694 }
695
696 class Markup_wikicreole_superscript extends BalancedMarkup
697 {
698     var $_start_regexp = "\\^\\^";
699
700     function getEndRegexp ($match) {
701         return "\\^\\^";
702     }
703
704     function markup ($match, $body) {
705         $tag = 'sup';
706         return new HtmlElement($tag, $body);
707     }
708 }
709
710 class Markup_wikicreole_subscript extends BalancedMarkup
711 {
712     var $_start_regexp = ",,";
713
714     function getEndRegexp ($match) {
715         return $match;
716     }
717
718     function markup ($match, $body) {
719         $tag = 'sub';
720         return new HtmlElement($tag, $body);
721     }
722 }
723
724 class Markup_old_emphasis  extends BalancedMarkup
725 {
726     var $_start_regexp = "''";
727
728     function getEndRegexp ($match) {
729         return $match;
730     }
731
732     function markup ($match, $body) {
733         $tag = 'em';
734         return new HtmlElement($tag, $body);
735     }
736 }
737
738 class Markup_nestled_emphasis extends BalancedMarkup
739 {
740     function getStartRegexp() {
741     static $start_regexp = false;
742
743     if (!$start_regexp) {
744         // The three possible delimiters
745             // (none of which can be followed by itself.)
746         $i = "_ (?! _)";
747         $b = "\\* (?! \\*)";
748         $tt = "= (?! =)";
749
750         $any = "(?: ${i}|${b}|${tt})"; // any of the three.
751
752         // Any of [_*=] is okay if preceded by space or one of [-"'/:]
753         $start[] = "(?<= \\s|^|[-\"'\\/:]) ${any}";
754
755         // _ or * is okay after = as long as not immediately followed by =
756         $start[] = "(?<= =) (?: ${i}|${b}) (?! =)";
757         // etc...
758         $start[] = "(?<= _) (?: ${b}|${tt}) (?! _)";
759         $start[] = "(?<= \\*) (?: ${i}|${tt}) (?! \\*)";
760
761
762         // any delimiter okay after an opening brace ( [{<(] )
763         // as long as it's not immediately followed by the matching closing
764         // brace.
765         $start[] = "(?<= { ) ${any} (?! } )";
766         $start[] = "(?<= < ) ${any} (?! > )";
767         $start[] = "(?<= \\( ) ${any} (?! \\) )";
768
769         $start = "(?:" . join('|', $start) . ")";
770
771         // Any of the above must be immediately followed by non-whitespace.
772         $start_regexp = $start . "(?= \S)";
773     }
774
775     return $start_regexp;
776     }
777
778     function getEndRegexp ($match) {
779         $chr = preg_quote($match);
780         return "(?<= \S | ^ ) (?<! $chr) $chr (?! $chr) (?= \s | [-)}>\"'\\/:.,;!? _*=] | $)";
781     }
782
783     function markup ($match, $body) {
784         switch ($match) {
785         case '*': return new HtmlElement('b', $body);
786         case '=': return new HtmlElement('tt', $body);
787         case '_': return new HtmlElement('i', $body);
788         }
789     }
790 }
791
792 class Markup_html_emphasis extends BalancedMarkup
793 {
794     var $_start_regexp =
795         "<(?: b|big|i|small|tt|em|strong|cite|code|dfn|kbd|samp|s|strike|del|var|sup|sub )>";
796
797     function getEndRegexp ($match) {
798         return "<\\/" . substr($match, 1);
799     }
800
801     function markup ($match, $body) {
802         $tag = substr($match, 1, -1);
803         return new HtmlElement($tag, $body);
804     }
805 }
806
807 class Markup_html_divspan extends BalancedMarkup
808 {
809     var $_start_regexp =
810         "<(?: div|span )(?: \s[^>]*)?>";
811
812     function getEndRegexp ($match) {
813         if (substr($match,1,4) == 'span')
814             $tag = 'span';
815         else
816             $tag = 'div';
817         return "<\\/" . $tag . '>';
818     }
819
820     function markup ($match, $body) {
821         if (substr($match,1,4) == 'span')
822             $tag = 'span';
823         else
824             $tag = 'div';
825         $rest = substr($match,1+strlen($tag),-1);
826         if (!empty($rest)) {
827             $args = parse_attributes($rest);
828         } else {
829             $args = array();
830         }
831         return new HtmlElement($tag, $args, $body);
832     }
833 }
834
835
836 class Markup_html_abbr extends BalancedMarkup
837 {
838     //rurban: abbr|acronym need an optional title tag.
839     //sf.net bug #728595
840     var $_start_regexp = "<(?: abbr|acronym )(?: [^>]*)?>";
841
842     function getEndRegexp ($match) {
843         if (substr($match,1,4) == 'abbr')
844             $tag = 'abbr';
845         else
846             $tag = 'acronym';
847         return "<\\/" . $tag . '>';
848     }
849
850     function markup ($match, $body) {
851         if (substr($match,1,4) == 'abbr')
852             $tag = 'abbr';
853         else
854             $tag = 'acronym';
855         $rest = substr($match,1+strlen($tag),-1);
856         $attrs = parse_attributes($rest);
857         // Remove attributes other than title and lang
858         $allowedargs = array();
859         foreach ($attrs as $key => $value) {
860             if (in_array ($key, array("title", "lang"))) {
861                 $allowedargs[$key] = $value;
862             }
863         }
864         return new HtmlElement($tag, $allowedargs, $body);
865     }
866 }
867
868 /** ENABLE_MARKUP_COLOR
869  *  See http://www.pmwiki.org/wiki/PmWiki/WikiStyles and
870  *      http://www.flexwiki.com/default.aspx/FlexWiki/FormattingRules.html
871  */
872 class Markup_color extends BalancedMarkup {
873     // %color=blue% blue text %% and back to normal
874     var $_start_regexp = "%color=(?: [^%]*)%";
875     var $_end_regexp = "%%";
876
877     function markup ($match, $body) {
878         $color = strtolower(substr($match, 7, -1));
879
880         $morecolors = array('beige' => '#f5f5dc',
881                             'brown' => '#a52a2a',
882                             'chocolate' => '#d2691e',
883                             'cyan' => '#00ffff',
884                             'gold' => '#ffd700',
885                             'ivory' => '#fffff0',
886                             'indigo' => '#4b0082',
887                             'magenta' => '#ff00ff',
888                             'orange' => '#ffa500',
889                             'pink' => '#ffc0cb',
890                             'salmon' => '#fa8072',
891                             'snow' => '#fffafa',
892                             'turquoise' => '#40e0d0',
893                             'violet' => '#ee82ee',
894                            );
895
896         if (isset($morecolors[$color])) {
897             $color = $morecolors[$color];
898         }
899
900         // HTML 4 defines the following 16 colors
901         if (in_array($color, array('aqua', 'black', 'blue', 'fuchsia',
902                                    'gray', 'green', 'lime', 'maroon',
903                                    'navy', 'olive', 'purple', 'red',
904                                    'silver', 'teal', 'white', 'yellow'))
905               or ((substr($color,0,1) == '#')
906                   and ((strlen($color) == 4) or (strlen($color) == 7))
907                   and (strspn(substr($color,1),'0123456789abcdef') == strlen($color)-1))) {
908             return new HtmlElement('span', array('style' => "color: $color"), $body);
909         } else {
910             return new HtmlElement('span', array('class' => 'error'),
911                                    sprintf(_("unknown color %s ignored"), substr($match, 7, -1)));
912         }
913     }
914 }
915
916 // Wikicreole placeholder
917 // <<<placeholder>>>
918 class Markup_placeholder extends SimpleMarkup
919 {
920     var $_match_regexp = '<<<.*?>>>';
921
922     function markup ($match) {
923         return HTML::span($match);
924     }
925 }
926
927 // Single-line HTML comment
928 // <!-- This is a comment -->
929 class Markup_html_comment extends SimpleMarkup
930 {
931     var $_match_regexp = '<!--.*?-->';
932
933     function markup ($match) {
934         return HTML::raw('');
935     }
936 }
937
938 // Special version for single-line plugins formatting,
939 //  like: '<small>< ?plugin PopularNearby ? ></small>'
940 class Markup_plugin extends SimpleMarkup
941 {
942     var $_match_regexp = '<\?plugin(?:-form)?\s[^\n]+?\?>';
943
944     function markup ($match) {
945     return new Cached_PluginInvocation($match);
946     }
947 }
948
949 // Special version for single-line Wikicreole plugins formatting.
950 class Markup_plugin_wikicreole extends SimpleMarkup
951 {
952     var $_match_regexp = '<<[^\n]+?>>';
953
954     function markup ($match) {
955         $pi = str_replace("<<", "<?plugin ", $match);
956         $pi = str_replace(">>", " ?>", $pi);
957     return new Cached_PluginInvocation($pi);
958     }
959 }
960
961 // Special version for plugins in xml syntax, mediawiki-style
962 // <name arg=value>body</name> or <name /> => < ? plugin pluginname arg=value body ? >
963 // PLUGIN_MARKUP_MAP = "html:RawHtml dot:GraphViz toc:CreateToc amath:AsciiMath richtable:RichTable include:IncludePage tex:TexToPng"
964 class Markup_xml_plugin extends BalancedMarkup
965 {
966     //var $_start_regexp = "<(?: ".join('|',PLUGIN_MARKUP_MAP)." )(?: \s[^>]*)>";
967
968     function getStartRegexp () {
969     global $PLUGIN_MARKUP_MAP;
970         static $_start_regexp;
971         if ($_start_regexp) return $_start_regexp;
972         if (empty($PLUGIN_MARKUP_MAP)) return '';
973         //"<(?: html|search|extsearch|dot|toc|math|richtable|include|tex )(?: \s[^>]*)>"
974     $_start_regexp = "<(?: ".join('|',array_keys($PLUGIN_MARKUP_MAP))." )(?: \s[^>]*|\\/ )>";
975         return $_start_regexp;
976     }
977     function getEndRegexp ($match) {
978         return "<\\/" . $match . '>';
979     }
980     function markup ($match, $body) {
981     global $PLUGIN_MARKUP_MAP;
982         $name = substr($match,2,-2);
983     $vars = '';
984         if (preg_match('/^(\S+)\|(.*)$/', $name, $_m)) {
985             $name = $_m[1];
986             $vars = $_m[2]; //str_replace(' ', '&', $_m[2]);
987         }
988         if (!isset($PLUGIN_MARKUP_MAP[$name])) {
989             trigger_error("No plugin for $name $vars defined.", E_USER_WARNING);
990             return "";
991         }
992         $plugin = $PLUGIN_MARKUP_MAP[$name];
993     return new Cached_PluginInvocation("<"."?plugin $plugin $vars $body ?".">");
994     }
995 }
996
997 /**
998  *  Mediawiki <nowiki>
999  *  <nowiki>...</nowiki>
1000  */
1001 class Markup_nowiki extends SimpleMarkup
1002 {
1003     var $_match_regexp = '<nowiki>.*?<\/nowiki>';
1004
1005     function markup ($match) {
1006         // Remove <nowiki> and </nowiki>
1007         return HTML::raw(substr($match, 8, -9));
1008     }
1009 }
1010
1011 /**
1012  *  Wikicreole preformatted
1013  *  {{{
1014  *  }}}
1015  */
1016 class Markup_wikicreole_preformatted extends SimpleMarkup
1017 {
1018     var $_match_regexp = '\{\{\{.*?\}\}\}';
1019
1020     function markup ($match) {
1021         // Remove {{{ and }}}
1022         return new HtmlElement('tt', substr($match, 3, -3));
1023     }
1024 }
1025
1026 /** ENABLE_MARKUP_TEMPLATE
1027  *  Template syntax similar to Mediawiki
1028  *  {{template}}
1029  * => < ? plugin Template page=template ? >
1030  *  {{template|var1=value1|var2=value|...}}
1031  * => < ? plugin Template page=template var=value ... ? >
1032  *
1033  * The {{...}} syntax is also used for:
1034  *  - Wikicreole images
1035  *  - videos
1036  *  - predefined icons
1037  */
1038 class Markup_template_plugin  extends SimpleMarkup
1039 {
1040     // patch #1732793: allow \n, mult. {{ }} in one line, and single letters
1041     var $_match_regexp = '\{\{.*?\}\}';
1042
1043     function markup ($match) {
1044
1045         $page = substr($match,2,-2);
1046         $page = trim($page);
1047
1048         // Check for predefined icons.
1049         $predefinedicons = array(":)" => "ic_smile.png",
1050                                  ":(" => "ic_sad.png",
1051                                  ":P" => "ic_tongue.png",
1052                                  ":D" => "ic_biggrin.png",
1053                                  ";)" => "ic_wink.png",
1054                                  "(y)" => "ic_handyes.png",
1055                                  "(n)" => "ic_handno.png",
1056                                  "(i)" => "ic_info.png",
1057                                  "(/)" => "ic_check.png",
1058                                  "(x)" => "ic_cross.png",
1059                                  "(!)" => "ic_danger.png",
1060                                  "(+)" => "ic_plus.png",
1061                                  "(-)" => "ic_minus.png",
1062                                  "(?)" => "ic_help.png",
1063                                  "(on)" => "ic_lighton.png",
1064                                  "(off)" => "ic_lightoff.png",
1065                                  "(*)" => "ic_yellowstar.png",
1066                                  "(*r)" => "ic_redstar.png",
1067                                  "(*g)" => "ic_greenstar.png",
1068                                  "(*b)" => "ic_bluestar.png",
1069                                  "(*y)" => "ic_yellowstar.png",
1070                                 );
1071         foreach ($predefinedicons as $ascii => $icon) {
1072             if ($page == $ascii) {
1073                 return LinkImage(DATA_PATH . "/themes/default/images/$icon", $page);
1074             }
1075         }
1076
1077         if (strpos($page, "|") === false) {
1078             $imagename = $page;
1079             $alt = "";
1080         } else {
1081             $imagename = substr($page, 0, strpos($page, "|"));
1082             $alt = ltrim(strstr($page, "|"), "|");
1083         }
1084
1085         // It's not a Mediawiki template, it's a Wikicreole image
1086         if (is_image($imagename)) {
1087             if ($imagename[0] == '/') {
1088                 return LinkImage(DATA_PATH . '/' . $imagename, $alt);
1089             } else {
1090                 return LinkImage(getUploadDataPath() . $imagename, $alt);
1091             }
1092         }
1093
1094         // It's a video
1095         if (is_video($imagename)) {
1096             $s = '<'.'?plugin Video file="' . $imagename . '" ?'.'>';
1097         return new Cached_PluginInvocation($s);
1098         }
1099
1100         $page = str_replace("\n", "", $page);
1101
1102         // The argument value might contain a double quote (")
1103         // We have to encode that.
1104         $page = htmlspecialchars($page);
1105
1106         $vars = '';
1107
1108         if (preg_match('/^(\S+?)\|(.*)$/', $page, $_m)) {
1109             $page = $_m[1];
1110             $vars = '"' . preg_replace('/\|/', '" "', $_m[2]) . '"';
1111             $vars = preg_replace('/"(\S+)=([^"]*)"/', '\\1="\\2"', $vars);
1112         }
1113
1114         // page may contain a version number
1115         // {{foo?version=5}}
1116         // in that case, output is "page=foo rev=5"
1117         if (strstr($page, "?")) {
1118             $page = str_replace("?version=", "\" rev=\"", $page);
1119         }
1120
1121         if ($vars)
1122             $s = '<'.'?plugin Template page="'.$page.'" '.$vars.' ?'.'>';
1123         else
1124             $s = '<'.'?plugin Template page="' . $page . '" ?'.'>';
1125     return new Cached_PluginInvocation($s);
1126     }
1127 }
1128
1129 // "..." => "&#133;"  browser specific display (not cached?)
1130 // Support some HTML::Entities: (C) for copy, --- for mdash, -- for ndash
1131 // TODO: "--" => "&emdash;" browser specific display (not cached?)
1132
1133 class Markup_html_entities  extends SimpleMarkup {
1134     //var $_match_regexp = '(: \.\.\.|\-\-|\-\-\-|\(C\) )';
1135
1136     function Markup_html_entities() {
1137         $this->_entities = array('...'  => '&#133;',
1138                                  '--'   => '&ndash;',
1139                                  '---'  => '&mdash;',
1140                                  '(C)'  => '&copy;',
1141                                  '&copy;' => '&copy;',
1142                                  '&trade;'  => '&trade;',
1143                                  );
1144         $this->_match_regexp =
1145             '(: ' .
1146             join('|', array_map('preg_quote', array_keys($this->_entities))) .
1147             ' )';
1148     }
1149
1150     function markup ($match) {
1151         return HTML::Raw($this->_entities[$match]);
1152     }
1153 }
1154
1155 class Markup_isonumchars  extends SimpleMarkup {
1156     var $_match_regexp = '\&\#\d{2,5};';
1157
1158     function markup ($match) {
1159         return HTML::Raw($match);
1160     }
1161 }
1162
1163 class Markup_isohexchars extends SimpleMarkup {
1164     // hexnums, like &#x00A4; <=> &curren;
1165     var $_match_regexp = '\&\#x[0-9a-fA-F]{2,4};';
1166
1167     function markup ($match) {
1168         return HTML::Raw($match);
1169     }
1170 }
1171
1172 // FIXME: Do away with magic phpwiki forms.  (Maybe phpwiki: links too?)
1173
1174 class InlineTransformer
1175 {
1176     var $_regexps = array();
1177     var $_markup = array();
1178
1179     function InlineTransformer ($markup_types = false) {
1180         global $request;
1181     // We need to extend the inline parsers by certain actions, like SearchHighlight,
1182     // SpellCheck and maybe CreateToc.
1183         if (!$markup_types) {
1184             $non_default = false;
1185             $markup_types = array
1186                 ('escape', 'wikicreolebracketlink', 'bracketlink', 'url',
1187                  'html_comment', 'placeholder',
1188                  'interwiki',  'semanticlink', 'wikiword', 'linebreak',
1189                  'wikicreole_superscript',
1190                  'wikicreole_subscript',
1191                  'wikicreole_italics', 'wikicreole_bold',
1192                  'wikicreole_monospace',
1193                  'wikicreole_underline',
1194                  'old_emphasis', 'nestled_emphasis',
1195                  'html_emphasis', 'html_abbr', 'plugin', 'plugin_wikicreole',
1196                  'isonumchars', 'isohexchars', /*'html_entities'*/
1197                  );
1198         if (DISABLE_MARKUP_WIKIWORD)
1199                 $markup_types = array_remove($markup_types, 'wikiword');
1200
1201         $action = $request->getArg('action');
1202         if ($action == 'SpellCheck' and $request->getArg('suggestions'))
1203         {   // insert it after url
1204         array_splice($markup_types, 2, 1, array('url','spellcheck'));
1205         }
1206         if (isset($request->_searchhighlight))
1207         {   // insert it after url
1208         array_splice($markup_types, 2, 1, array('url','searchhighlight'));
1209                 //$request->setArg('searchhighlight', false);
1210         }
1211         } else {
1212             $non_default = true;
1213     }
1214         foreach ($markup_types as $mtype) {
1215             $class = "Markup_$mtype";
1216             $this->_addMarkup(new $class);
1217         }
1218         $this->_addMarkup(new Markup_nowiki);
1219         if (ENABLE_MARKUP_DIVSPAN and !$non_default)
1220             $this->_addMarkup(new Markup_html_divspan);
1221         if (ENABLE_MARKUP_COLOR and !$non_default)
1222             $this->_addMarkup(new Markup_color);
1223         // Markup_wikicreole_preformatted must be before Markup_template_plugin
1224         $this->_addMarkup(new Markup_wikicreole_preformatted);
1225         if (ENABLE_MARKUP_TEMPLATE and !$non_default)
1226             $this->_addMarkup(new Markup_template_plugin);
1227         // This does not work yet
1228         if (PLUGIN_MARKUP_MAP and !$non_default)
1229             $this->_addMarkup(new Markup_xml_plugin);
1230     }
1231
1232     function _addMarkup ($markup) {
1233         if (isa($markup, 'SimpleMarkup'))
1234             $regexp = $markup->getMatchRegexp();
1235         else
1236             $regexp = $markup->getStartRegexp();
1237
1238         assert( !isset($this->_markup[$regexp]) );
1239         assert( strlen(trim($regexp)) > 0 );
1240         $this->_regexps[] = $regexp;
1241         $this->_markup[] = $markup;
1242     }
1243
1244     function parse (&$text, $end_regexps = array('$')) {
1245         $regexps = $this->_regexps;
1246
1247         // $end_re takes precedence: "favor reduce over shift"
1248         array_unshift($regexps, $end_regexps[0]);
1249         //array_push($regexps, $end_regexps[0]);
1250         $regexps = new RegexpSet($regexps);
1251
1252         $input = $text;
1253         $output = new XmlContent;
1254
1255         $match = $regexps->match($input);
1256
1257         while ($match) {
1258             if ($match->regexp_ind == 0) {
1259                 // No start pattern found before end pattern.
1260                 // We're all done!
1261                 if (isset($markup) and is_object($markup)
1262                     and isa($markup,'Markup_plugin'))
1263                 {
1264                     $current =& $output->_content[count($output->_content)-1];
1265                     $current->setTightness(true,true);
1266                 }
1267                 $output->pushContent($match->prematch);
1268                 $text = $match->postmatch;
1269                 return $output;
1270             }
1271
1272             $markup = $this->_markup[$match->regexp_ind - 1];
1273             $body = $this->_parse_markup_body($markup, $match->match,
1274                                               $match->postmatch, $end_regexps);
1275             if (!$body) {
1276                 // Couldn't match balanced expression.
1277                 // Ignore and look for next matching start regexp.
1278                 $match = $regexps->nextMatch($input, $match);
1279                 continue;
1280             }
1281
1282             // Matched markup.  Eat input, push output.
1283             // FIXME: combine adjacent strings.
1284             if (isa($markup, 'SimpleMarkup'))
1285                 $current = $markup->markup($match->match);
1286             else
1287                 $current = $markup->markup($match->match, $body);
1288             $input = $match->postmatch;
1289             if (isset($markup) and is_object($markup)
1290                 and isa($markup,'Markup_plugin'))
1291             {
1292                 $current->setTightness(true,true);
1293             }
1294             $output->pushContent($match->prematch, $current);
1295
1296             $match = $regexps->match($input);
1297         }
1298
1299         // No pattern matched, not even the end pattern.
1300         // Parse fails.
1301         return false;
1302     }
1303
1304     function _parse_markup_body ($markup, $match, &$text, $end_regexps) {
1305         if (isa($markup, 'SimpleMarkup'))
1306             return true;        // Done. SimpleMarkup is simple.
1307
1308         if (!is_object($markup)) return false; // Some error: Should assert
1309         array_unshift($end_regexps, $markup->getEndRegexp($match));
1310
1311         // Optimization: if no end pattern in text, we know the
1312         // parse will fail.  This is an important optimization,
1313         // e.g. when text is "*lots *of *start *delims *with
1314         // *no *matching *end *delims".
1315         $ends_pat = "/(?:" . join(").*(?:", $end_regexps) . ")/xs";
1316         if (!preg_match($ends_pat, $text))
1317             return false;
1318         return $this->parse($text, $end_regexps);
1319     }
1320 }
1321
1322 class LinkTransformer extends InlineTransformer
1323 {
1324     function LinkTransformer () {
1325         $this->InlineTransformer(array('escape', 'wikicreolebracketlink', 'bracketlink', 'url',
1326                                        'semanticlink', 'interwiki', 'wikiword',
1327                                        ));
1328     }
1329 }
1330
1331 class NowikiTransformer extends InlineTransformer
1332 {
1333     function NowikiTransformer () {
1334         $this->InlineTransformer
1335             (array('linebreak',
1336                    'html_emphasis', 'html_abbr', 'plugin', 'plugin_wikicreole',
1337                    'isonumchars', 'isohexchars', /*'html_entities',*/
1338                    ));
1339     }
1340 }
1341
1342 function TransformInline($text, $markup = 2.0, $basepage=false) {
1343     static $trfm;
1344     $action = $GLOBALS['request']->getArg('action');
1345     if (empty($trfm) or $action == 'SpellCheck') {
1346         $trfm = new InlineTransformer;
1347     }
1348
1349     if ($markup < 2.0) {
1350         $text = ConvertOldMarkup($text, 'inline');
1351     }
1352
1353     if ($basepage) {
1354         return new CacheableMarkup($trfm->parse($text), $basepage);
1355     }
1356     return $trfm->parse($text);
1357 }
1358
1359 function TransformLinks($text, $markup = 2.0, $basepage = false) {
1360     static $trfm;
1361
1362     if (empty($trfm)) {
1363         $trfm = new LinkTransformer;
1364     }
1365
1366     if ($markup < 2.0) {
1367         $text = ConvertOldMarkup($text, 'links');
1368     }
1369
1370     if ($basepage) {
1371         return new CacheableMarkup($trfm->parse($text), $basepage);
1372     }
1373     return $trfm->parse($text);
1374 }
1375
1376 /**
1377  * Transform only html markup and entities.
1378  */
1379 function TransformInlineNowiki($text, $markup = 2.0, $basepage=false) {
1380     static $trfm;
1381
1382     if (empty($trfm)) {
1383         $trfm = new NowikiTransformer;
1384     }
1385     if ($basepage) {
1386         return new CacheableMarkup($trfm->parse($text), $basepage);
1387     }
1388     return $trfm->parse($text);
1389 }
1390
1391 // Local Variables:
1392 // mode: php
1393 // tab-width: 8
1394 // c-basic-offset: 4
1395 // c-hanging-comment-ender-p: nil
1396 // indent-tabs-mode: nil
1397 // End:
1398 ?>