]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/InlineParser.php
Implement Wikicreole syntax for subscript
[SourceForge/phpwiki.git] / lib / InlineParser.php
1 <?php 
2 rcs_id('$Id: InlineParser.php,v 1.100 2008-08-03 15:52:31 vargenau Exp $');
3 /* Copyright (C) 2002 Geoffrey T. Dairiki <dairiki@dairiki.org>
4  * Copyright (C) 2004-2008 Reini Urban
5  * Copyright (C) 2008 Marc-Etienne Vargenau
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
20  * along with PhpWiki; if not, write to the Free Software
21  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  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
33 /**
34  * This is the character used in wiki markup to escape characters with
35  * special meaning.
36  */
37 define('ESCAPE_CHAR', '~');
38
39 require_once(dirname(__FILE__).'/HtmlElement.php');
40 require_once('lib/CachedMarkup.php');
41 require_once(dirname(__FILE__).'/stdlib.php');
42
43
44 function WikiEscape($text) {
45     return str_replace('#', ESCAPE_CHAR . '#', $text);
46 }
47
48 function UnWikiEscape($text) {
49     return preg_replace('/' . ESCAPE_CHAR . '(.)/', '\1', $text);
50 }
51
52 /**
53  * Return type from RegexpSet::match and RegexpSet::nextMatch.
54  *
55  * @see RegexpSet
56  */
57 class RegexpSet_match {
58     /**
59      * The text leading up the the next match.
60      */
61     var $prematch;
62     /**
63      * The matched text.
64      */
65     var $match;
66     /**
67      * The text following the matched text.
68      */
69     var $postmatch;
70     /**
71      * Index of the regular expression which matched.
72      */
73     var $regexp_ind;
74 }
75
76 /**
77  * A set of regular expressions.
78  *
79  * This class is probably only useful for InlineTransformer.
80  */
81 class RegexpSet
82 {
83     /** Constructor
84      *
85      * @param array $regexps A list of regular expressions.  The
86      * regular expressions should not include any sub-pattern groups
87      * "(...)".  (Anonymous groups, like "(?:...)", as well as
88      * look-ahead and look-behind assertions are okay.)
89      */
90     function RegexpSet ($regexps) {
91         assert($regexps);
92         $this->_regexps = array_unique($regexps);
93         if (!defined('_INLINE_OPTIMIZATION')) define('_INLINE_OPTIMIZATION',0);
94     }
95
96     /**
97      * Search text for the next matching regexp from the Regexp Set.
98      *
99      * @param string $text The text to search.
100      *
101      * @return RegexpSet_match  A RegexpSet_match object, or false if no match.
102      */
103     function match ($text) {
104         return $this->_match($text, $this->_regexps, '*?');
105     }
106
107     /**
108      * Search for next matching regexp.
109      *
110      * Here, 'next' has two meanings:
111      *
112      * Match the next regexp(s) in the set, at the same position as the last match.
113      *
114      * If that fails, match the whole RegexpSet, starting after the position of the
115      * previous match.
116      *
117      * @param string $text Text to search.
118      *
119      * @param RegexpSet_match $prevMatch A RegexpSet_match object.
120      * $prevMatch should be a match object obtained by a previous
121      * match upon the same value of $text.
122      *
123      * @return RegexpSet_match A RegexpSet_match object, or false if no match.
124      */
125     function nextMatch ($text, $prevMatch) {
126         // Try to find match at same position.
127         $pos = strlen($prevMatch->prematch);
128         $regexps = array_slice($this->_regexps, $prevMatch->regexp_ind + 1);
129         if ($regexps) {
130             $repeat = sprintf('{%d}', $pos);
131             if ( ($match = $this->_match($text, $regexps, $repeat)) ) {
132                 $match->regexp_ind += $prevMatch->regexp_ind + 1;
133                 return $match;
134             }
135             
136         }
137         
138         // Failed.  Look for match after current position.
139         $repeat = sprintf('{%d,}?', $pos + 1);
140         return $this->_match($text, $this->_regexps, $repeat);
141     }
142
143     // Syntax: http://www.pcre.org/pcre.txt
144     //   x - EXTENDED, ignore whitespace
145     //   s - DOTALL
146     //   A - ANCHORED
147     //   S - STUDY
148     function _match ($text, $regexps, $repeat) {
149         // If one of the regexps is an empty string, php will crash here: 
150         // sf.net: Fatal error: Allowed memory size of 8388608 bytes exhausted 
151         //         (tried to allocate 634 bytes)
152         if (_INLINE_OPTIMIZATION) { // disabled, wrong
153             // So we try to minize memory usage, by looping explicitly,
154             // and storing only those regexp which actually match. 
155             // There may be more than one, so we have to find the longest, 
156             // and match inside until the shortest is empty.
157             $matched = array(); $matched_ind = array();
158             for ($i=0; $i<count($regexps); $i++) {
159                 if (!trim($regexps[$i])) {
160                     trigger_error("empty regexp $i", E_USER_WARNING);
161                     continue;
162                 }
163                 $pat= "/ ( . $repeat ) ( " . $regexps[$i] . " ) /x";
164                 if (preg_match($pat, $text, $_m)) {
165                     $m = $_m; // FIXME: prematch, postmatch is wrong
166                     $matched[] = $regexps[$i];
167                     $matched_ind[] = $i;
168                     $regexp_ind = $i;
169                 }
170             }
171             // To overcome ANCHORED:
172             // We could sort by longest match and iterate over these.
173             if (empty($matched)) return false;
174         }
175         $match = new RegexpSet_match;
176         
177         // Optimization: if the matches are only "$" and another, then omit "$"
178         if (! _INLINE_OPTIMIZATION or count($matched) > 2) {
179             assert(!empty($repeat));
180             assert(!empty($regexps));
181             // We could do much better, if we would know the matching markup for the 
182             // longest regexp match:
183             $hugepat= "/ ( . $repeat ) ( (" . join(')|(', $regexps) . ") ) /Asx";
184             // Proposed premature optimization 1:
185             //$hugepat= "/ ( . $repeat ) ( (" . join(')|(', array_values($matched)) . ") ) /Asx";
186             if (! preg_match($hugepat, $text, $m)) {
187                 return false;
188             }
189             // Proposed premature optimization 1:
190             //$match->regexp_ind = $matched_ind[count($m) - 4];
191             $match->regexp_ind = count($m) - 4;
192         } else {
193             $match->regexp_ind = $regexp_ind;
194         }
195         
196         $match->postmatch = substr($text, strlen($m[0]));
197         $match->prematch = $m[1];
198         $match->match = $m[2];
199
200         /* DEBUGGING */
201         if (DEBUG & _DEBUG_PARSER) {
202           static $_already_dumped = 0;
203           if (!$_already_dumped) {
204             var_dump($regexps); 
205             if (_INLINE_OPTIMIZATION)
206                 var_dump($matched);
207             var_dump($matched_inc); 
208           }
209           $_already_dumped = 1;
210           PrintXML(HTML::dl(HTML::dt("input"),
211                           HTML::dd(HTML::pre($text)),
212                           HTML::dt("regexp"),
213                           HTML::dd(HTML::pre($match->regexp_ind, ":", $regexps[$match->regexp_ind])),
214                           HTML::dt("prematch"),
215                           HTML::dd(HTML::pre($match->prematch)),
216                           HTML::dt("match"),
217                           HTML::dd(HTML::pre($match->match)),
218                           HTML::dt("postmatch"),
219                           HTML::dd(HTML::pre($match->postmatch))
220                           ));
221         }
222         return $match;
223     }
224 }
225
226
227
228 /**
229  * A simple markup rule (i.e. terminal token).
230  *
231  * These are defined by a regexp.
232  *
233  * When a match is found for the regexp, the matching text is replaced.
234  * The replacement content is obtained by calling the SimpleMarkup::markup method.
235  */ 
236 class SimpleMarkup
237 {
238     var $_match_regexp;
239
240     /** Get regexp.
241      *
242      * @return string Regexp which matches this token.
243      */
244     function getMatchRegexp () {
245         return $this->_match_regexp;
246     }
247
248     /** Markup matching text.
249      *
250      * @param string $match The text which matched the regexp
251      * (obtained from getMatchRegexp).
252      *
253      * @return mixed The expansion of the matched text.
254      */
255     function markup ($match /*, $body */) {
256         trigger_error("pure virtual", E_USER_ERROR);
257     }
258 }
259
260 /**
261  * A balanced markup rule.
262  *
263  * These are defined by a start regexp, and an end regexp.
264  */ 
265 class BalancedMarkup
266 {
267     var $_start_regexp;
268
269     /** Get the starting regexp for this rule.
270      *
271      * @return string The starting regexp.
272      */
273     function getStartRegexp () {
274         return $this->_start_regexp;
275     }
276     
277     /** Get the ending regexp for this rule.
278      *
279      * @param string $match The text which matched the starting regexp.
280      *
281      * @return string The ending regexp.
282      */
283     function getEndRegexp ($match) {
284         return $this->_end_regexp;
285     }
286
287     /** Get expansion for matching input.
288      *
289      * @param string $match The text which matched the starting regexp.
290      *
291      * @param mixed $body Transformed text found between the starting
292      * and ending regexps.
293      *
294      * @return mixed The expansion of the matched text.
295      */
296     function markup ($match, $body) {
297         trigger_error("pure virtual", E_USER_ERROR);
298     }
299 }
300
301 class Markup_escape  extends SimpleMarkup
302 {
303     function getMatchRegexp () {
304         return ESCAPE_CHAR . '(?: [[:alnum:]]+ | .)';
305     }
306     
307     function markup ($match) {
308         assert(strlen($match) >= 2);
309         return substr($match, 1);
310     }
311 }
312
313 /**
314  * [image.jpg size=50% border=5], [image.jpg size=50x30]
315  * Support for the following attributes: see stdlib.php:LinkImage()
316  *   size=<precent>%, size=<width>x<height>
317  *   border=n, align=\w+, hspace=n, vspace=n
318  */
319 function isImageLink($link) {
320     if (!$link) return false;
321     assert(defined('INLINE_IMAGES'));
322     return preg_match("/\\.(" . INLINE_IMAGES . ")$/i", $link)
323         or preg_match("/\\.(" . INLINE_IMAGES . ")\s+(size|border|align|hspace|vspace|type|data|width|height)=/i", $link);
324 }
325
326 function LinkBracketLink($bracketlink) {
327
328     // $bracketlink will start and end with brackets; in between will
329     // be either a page name, a URL or both separated by a pipe.
330     
331     // Strip brackets and leading space
332     // bug#1904088  Some brackets links on 2 lines cause the parser to crash
333     preg_match('/(\#?) \[\s* (?: (.*?) \s* (?<!' . ESCAPE_CHAR . ')(\|) )? \s* (.+?) \s*\]/x',
334                str_replace("\n", " ", $bracketlink), $matches);
335     if (count($matches) < 4) {
336         // "[ personal\ninformation manager | PhpWiki:PersonalWiki ]"
337         trigger_error(_("Invalid [] syntax ignored").": ".$bracketlink, E_USER_WARNING);
338         return new Cached_Link;
339     }
340     list (, $hash, $label, $bar, $rawlink) = $matches;
341
342     $label = UnWikiEscape($label);
343     /*
344      * Check if the user has typed a explicit URL. This solves the
345      * problem where the URLs have a ~ character, which would be stripped away.
346      *   "[http:/server/~name/]" will work as expected
347      *   "http:/server/~name/"   will NOT work as expected, will remove the ~
348      */
349     if (   string_starts_with ($rawlink, "http://")
350         or string_starts_with ($rawlink, "https://") ) 
351     {
352         $link = $rawlink;
353         // Mozilla Browser URI Obfuscation Weakness 2004-06-14
354         //   http://www.securityfocus.com/bid/10532/
355         //   goodurl+"%2F%20%20%20."+badurl
356         if (preg_match("/%2F(%20)+\./i", $rawlink)) {
357             $rawlink = preg_replace("/%2F(%20)+\./i","%2F.",$rawlink);
358         }
359     } else
360         $link  = UnWikiEscape($rawlink);
361
362     /* Relatives links by Joel Schaubert.
363      * Recognize [../bla] or [/bla] as relative links, without needing http://
364      * but [ /link ] only if SUBPAGE_SEPERATOR is not "/". 
365      * Normally /Page links to the subpage /Page.
366      */
367     if (SUBPAGE_SEPARATOR == '/') {
368         if (preg_match('/^\.\.\//', $link)) {
369             return new Cached_ExternalLink($link, $label);
370         }
371     } else if (preg_match('/^(\.\.\/|\/)/', $link)) {
372         return new Cached_ExternalLink($link, $label);
373     }
374     // [label|link]
375     // If label looks like a url to an image or object, we want an image link.
376     if (isImageLink($label)) {
377         $imgurl = $label;
378         $intermap = getInterwikiMap();
379         if (preg_match("/^" . $intermap->getRegexp() . ":/", $label)) {
380             $imgurl = $intermap->link($label);
381             $imgurl = $imgurl->getAttr('href');
382         } elseif (! preg_match("#^(" . ALLOWED_PROTOCOLS . "):#", $imgurl)) {
383             // local theme linkname like 'images/next.gif'.
384             global $WikiTheme;
385             $imgurl = $WikiTheme->getImageURL($imgurl);
386         }
387         // for objects (non-images) the link is taken as alt tag, 
388         // which is in return taken as alternative img
389         $label = LinkImage($imgurl, $link);
390     }
391
392     if ($hash) {
393         // It's an anchor, not a link...
394         $id = MangleXmlIdentifier($link);
395         return HTML::a(array('name' => $id, 'id' => $id),
396                        $bar ? $label : $link);
397     }
398
399     if (preg_match("#^(" . ALLOWED_PROTOCOLS . "):#", $link)) {
400         // if it's an image, embed it; otherwise, it's a regular link
401         if (isImageLink($link) and empty($label)) // patch #1348996 by Robert Litwiniec
402             return LinkImage($link, $label);
403         else
404             return new Cached_ExternalLink($link, $label);
405     }
406     elseif (substr($link,0,8) == 'phpwiki:')
407         return new Cached_PhpwikiURL($link, $label);
408
409     /* Semantic relations and attributes. 
410      * Relation and attribute names must be word chars only, no space.
411      * Links and Attributes may contain everything. word, nums, units, space, groupsep, numsep, ...
412      */
413     elseif (preg_match("/^ (\w+) (:[:=]) (.*) $/x", $link) and !isImageLink($link))
414         return new Cached_SemanticLink($link, $label);
415
416     /* Do not store the link */    
417     elseif (substr($link,0,1) == ':')
418         return new Cached_WikiLink($link, $label);
419
420     /*
421      * Inline images in Interwiki urls's:
422      * [File:my_image.gif] inlines the image,
423      * File:my_image.gif shows a plain inter-wiki link,
424      * [what a pic|File:my_image.gif] shows a named inter-wiki link to the gif
425      * [File:my_image.gif|what a pic] shows a inlimed image linked to the page "what a pic"
426      *
427      * Note that for simplicity we will accept embedded object tags (non-images) 
428      * here also, and seperate them later in LinkImage()
429      */
430     elseif (strstr($link,':')
431             and ($intermap = getInterwikiMap()) 
432             and preg_match("/^" . $intermap->getRegexp() . ":/", $link)) 
433     {
434         // trigger_error("label: $label link: $link", E_USER_WARNING);
435         if (empty($label) and isImageLink($link)) {
436             // if without label => inlined image [File:xx.gif]
437             $imgurl = $intermap->link($link);
438             return LinkImage($imgurl->getAttr('href'), $link);
439         }
440         return new Cached_InterwikiLink($link, $label);
441     } else {
442         // Split anchor off end of pagename.
443         if (preg_match('/\A(.*)(?<!'.ESCAPE_CHAR.')#(.*?)\Z/', $rawlink, $m)) {
444             list(,$rawlink,$anchor) = $m;
445             $pagename = UnWikiEscape($rawlink);
446             $anchor = UnWikiEscape($anchor);
447             if (!$label)
448                 $label = $link;
449         }
450         else {
451             $pagename = $link;
452             $anchor = false;
453         }
454         return new Cached_WikiLink($pagename, $label, $anchor);
455     }
456 }
457
458 class Markup_bracketlink  extends SimpleMarkup
459 {
460     var $_match_regexp = "\\#? \\[ .*? [^]\\s] .*? \\]";
461     
462     function markup ($match) {
463         $link = LinkBracketLink($match);
464         assert($link->isInlineElement());
465         return $link;
466     }
467 }
468
469 class Markup_spellcheck extends SimpleMarkup
470 {
471     function Markup_spellcheck () {
472         $this->suggestions = $GLOBALS['request']->getArg('suggestions');
473     }
474     function getMatchRegexp () {
475         if (empty($this->suggestions))
476             return "(?# false )";
477         $words = array_keys($this->suggestions);
478         return "(?<= \W ) (?:" . join('|', $words) . ") (?= \W )";
479     }
480     
481     function markup ($match) {
482         if (empty($this->suggestions) or empty($this->suggestions[$match]))
483             return $match;
484         return new Cached_SpellCheck(UnWikiEscape($match), $this->suggestions[$match]);
485     }
486 }
487
488 class Markup_searchhighlight extends SimpleMarkup
489 {
490     function Markup_searchhighlight () {
491         $result = $GLOBALS['request']->_searchhighlight;
492         require_once("lib/TextSearchQuery.php");
493         $query = new TextSearchQuery($result['query']);
494         $this->hilight_re = $query->getHighlightRegexp();
495         $this->engine = $result['engine'];
496     }
497     function getMatchRegexp () {
498         return $this->hilight_re;
499     }
500     function markup ($match) {
501         return new Cached_SearchHighlight(UnWikiEscape($match), $this->engine);
502     }
503 }
504
505 class Markup_url extends SimpleMarkup
506 {
507     function getMatchRegexp () {
508         return "(?<![[:alnum:]]) (?:" . ALLOWED_PROTOCOLS . ") : [^\s<>\"']+ (?<![ ,.?; \] \) ])";
509     }
510     
511     function markup ($match) {
512         return new Cached_ExternalLink(UnWikiEscape($match));
513     }
514 }
515
516 class Markup_interwiki extends SimpleMarkup
517 {
518     function getMatchRegexp () {
519         $map = getInterwikiMap();
520         return "(?<! [[:alnum:]])" . $map->getRegexp(). ": [^:=]\S+ (?<![ ,.?;! \] \) \" \' ])";
521     }
522
523     function markup ($match) {
524         return new Cached_InterwikiLink(UnWikiEscape($match));
525     }
526 }
527
528 class Markup_semanticlink extends SimpleMarkup
529 {
530     // No units seperated by space allowed here
531     // For :: (relations) only words, no comma,
532     // but for := (attributes) comma and dots are allowed. Units with groupsep.
533     // Ending dots or comma are not part of the link.
534     var $_match_regexp = "(?: \w+:=\S+(?<![\.,]))|(?: \w+::[\w\.]+(?<!\.))"; 
535
536     function markup ($match) {
537         return new Cached_SemanticLink(UnWikiEscape($match));
538     }
539 }
540
541 class Markup_wikiword extends SimpleMarkup
542 {
543     function getMatchRegexp () {
544         global $WikiNameRegexp;
545         if (!trim($WikiNameRegexp)) return " " . WIKI_NAME_REGEXP;
546         return " $WikiNameRegexp";
547     }
548
549     function markup ($match) {
550         if (!$match) return false;
551         if ($this->_isWikiUserPage($match))
552             return new Cached_UserLink($match); //$this->_UserLink($match);
553         else
554             return new Cached_WikiLink($match);
555     }
556
557     // FIXME: there's probably a more useful place to put these two functions    
558     function _isWikiUserPage ($page) {
559         global $request;
560         $dbi = $request->getDbh();
561         $page_handle = $dbi->getPage($page);
562         if ($page_handle and $page_handle->get('pref'))
563             return true;
564         else
565             return false;
566     }
567
568     function _UserLink($PageName) {
569         $link = HTML::a(array('href' => $PageName));
570         $link->pushContent(PossiblyGlueIconToText('wikiuser', $PageName));
571         $link->setAttr('class', 'wikiuser');
572         return $link;
573     }
574 }
575
576 class Markup_linebreak extends SimpleMarkup
577 {
578     //var $_match_regexp = "(?: (?<! %) %%% (?! %) | <(?:br|BR)> | <(?:br|BR) \/> )";
579     var $_match_regexp = "(?: (?<! %) %%% (?! %) | <(?:br|BR)> )";
580
581     function markup ($match) {
582         return HTML::br();
583     }
584 }
585
586 class Markup_wikicreole_subscript extends BalancedMarkup
587 {
588     var $_start_regexp = ",,";
589  
590     function getEndRegexp ($match) {
591         return $match; 
592     }
593    
594     function markup ($match, $body) {
595         $tag = 'sub';
596         return new HtmlElement($tag, $body);
597     }
598 }
599
600 class Markup_old_emphasis  extends BalancedMarkup
601 {
602     var $_start_regexp = "''|__";
603
604     function getEndRegexp ($match) {
605         return $match;
606     }
607     
608     function markup ($match, $body) {
609         $tag = $match == "''" ? 'em' : 'strong';
610         return new HtmlElement($tag, $body);
611     }
612 }
613
614 class Markup_nestled_emphasis extends BalancedMarkup
615 {
616     function getStartRegexp() {
617         static $start_regexp = false;
618
619         if (!$start_regexp) {
620             // The three possible delimiters
621             // (none of which can be followed by itself.)
622             $i = "_ (?! _)";
623             $b = "\\* (?! \\*)";
624             $tt = "= (?! =)";
625
626             $any = "(?: ${i}|${b}|${tt})"; // any of the three.
627
628             // Any of [_*=] is okay if preceded by space or one of [-"'/:]
629             $start[] = "(?<= \\s|^|[-\"'\\/:]) ${any}";
630
631             // _ or * is okay after = as long as not immediately followed by =
632             $start[] = "(?<= =) (?: ${i}|${b}) (?! =)";
633             // etc...
634             $start[] = "(?<= _) (?: ${b}|${tt}) (?! _)";
635             $start[] = "(?<= \\*) (?: ${i}|${tt}) (?! \\*)";
636
637
638             // any delimiter okay after an opening brace ( [{<(] )
639             // as long as it's not immediately followed by the matching closing
640             // brace.
641             $start[] = "(?<= { ) ${any} (?! } )";
642             $start[] = "(?<= < ) ${any} (?! > )";
643             $start[] = "(?<= \\( ) ${any} (?! \\) )";
644             
645             $start = "(?:" . join('|', $start) . ")";
646             
647             // Any of the above must be immediately followed by non-whitespace.
648             $start_regexp = $start . "(?= \S)";
649         }
650
651         return $start_regexp;
652     }
653
654     function getEndRegexp ($match) {
655         $chr = preg_quote($match);
656         return "(?<= \S | ^ ) (?<! $chr) $chr (?! $chr) (?= \s | [-)}>\"'\\/:.,;!? _*=] | $)";
657     }
658     
659     function markup ($match, $body) {
660         switch ($match) {
661         case '*': return new HtmlElement('b', $body);
662         case '=': return new HtmlElement('tt', $body);
663         case '_': return new HtmlElement('i', $body);
664         }
665     }
666 }
667
668 class Markup_html_emphasis extends BalancedMarkup
669 {
670     var $_start_regexp = 
671         "<(?: b|big|i|small|tt|em|strong|cite|code|dfn|kbd|samp|s|strike|del|var|sup|sub )>";
672
673     function getEndRegexp ($match) {
674         return "<\\/" . substr($match, 1);
675     }
676     
677     function markup ($match, $body) {
678         $tag = substr($match, 1, -1);
679         return new HtmlElement($tag, $body);
680     }
681 }
682
683 class Markup_html_divspan extends BalancedMarkup
684 {
685     var $_start_regexp = 
686         "<(?: div|span )(?: \s[^>]*)?>";
687
688     function getEndRegexp ($match) {
689         if (substr($match,1,4) == 'span')
690             $tag = 'span';
691         else
692             $tag = 'div';
693         return "<\\/" . $tag . '>';
694     }
695     
696     function markup ($match, $body) {
697         if (substr($match,1,4) == 'span')
698             $tag = 'span';
699         else
700             $tag = 'div';
701         $rest = substr($match,1+strlen($tag),-1);
702         if (!empty($rest)) {
703             list($key,$val) = explode("=",$rest);
704             $args = array($key => $val);
705         } else $args = array();
706         return new HtmlElement($tag, $args, $body);
707     }
708 }
709
710
711 class Markup_html_abbr extends BalancedMarkup
712 {
713     //rurban: abbr|acronym need an optional title tag.
714     //sf.net bug #728595
715     var $_start_regexp = "<(?: abbr|acronym )(?: \stitle=[^>]*)?>";
716
717     function getEndRegexp ($match) {
718         if (substr($match,1,4) == 'abbr')
719             $tag = 'abbr';
720         else
721             $tag = 'acronym';
722         return "<\\/" . $tag . '>';
723     }
724     
725     function markup ($match, $body) {
726         if (substr($match,1,4) == 'abbr')
727             $tag = 'abbr';
728         else
729             $tag = 'acronym';
730         $rest = substr($match,1+strlen($tag),-1);
731         if (!empty($rest)) {
732             list($key,$val) = explode("=",$rest);
733             $args = array($key => $val);
734         } else $args = array();
735         return new HtmlElement($tag, $args, $body);
736     }
737 }
738
739 /** ENABLE_MARKUP_COLOR
740  *  See http://www.pmwiki.org/wiki/PmWiki/WikiStyles and
741  *      http://www.flexwiki.com/default.aspx/FlexWiki/FormattingRules.html
742  */
743 class Markup_color extends BalancedMarkup {
744     // %color=blue% blue text %% and back to normal
745     var $_start_regexp = "%color=(?: [^%]*)%";
746     var $_end_regexp = "%%";
747     
748     function markup ($match, $body) {
749         $color = strtoupper(substr($match, 7, -1));
750         if (strlen($color) != 7 
751             and in_array($color, array('RED', 'BLUE', 'GRAY', 'YELLOW', 'GREEN', 'CYAN', 'BLACK'))) 
752         {   // must be a valid color name
753             return new HtmlElement('font', array('color' => $color), $body);
754         } elseif ((substr($color,0,1) == '#') 
755                   and (strspn(substr($color,1),'0123456789ABCDEF') == strlen($color)-1)) {
756             return new HtmlElement('font', array('color' => $color), $body);
757         } else {
758             trigger_error(sprintf(_("unknown color %s ignored"), substr($match, 7, -1)), E_USER_WARNING);
759         }
760                 
761     }
762 }
763
764 // Special version for single-line plugins formatting, 
765 //  like: '<small>< ?plugin PopularNearby ? ></small>'
766 class Markup_plugin extends SimpleMarkup
767 {
768     var $_match_regexp = '<\?plugin(?:-form)?\s[^\n]+?\?>';
769
770     function markup ($match) {
771         //$xml = new Cached_PluginInvocation($match);
772         //$xml->setTightness(true,true);
773         return new Cached_PluginInvocation($match);
774     }
775 }
776
777 // Special version for plugins in xml syntax 
778 // <name arg=value>body</name> or <name /> => < ? plugin pluginname arg=value body ? >
779 // PLUGIN_MARKUP_MAP = "html:RawHtml dot:GraphViz toc:CreateToc amath:AsciiMath richtable:RichTable include:IncludePage tex:TexToPng"
780 class Markup_xml_plugin extends BalancedMarkup
781 {
782     //var $_start_regexp = "<(?: ".join('|',PLUGIN_MARKUP_MAP)." )(?: \s[^>]*)>";
783
784     function getStartRegexp () {
785         global $PLUGIN_MARKUP_MAP;
786         static $_start_regexp;
787         if ($_start_regexp) return $_start_regexp;
788         if (empty($PLUGIN_MARKUP_MAP))
789             return '';
790         //"<(?: html|dot|toc|amath|richtable|include|tex )(?: \s[^>]*)>"
791         $_start_regexp = "<(?: ".join('|',array_keys($PLUGIN_MARKUP_MAP))." )(?: \s[^>]* | / )>";
792         return $_start_regexp;
793     }
794     function getEndRegexp ($match) {
795         return "<\\/" . $match . '>';
796     }
797     function markup ($match, $body) {
798         global $PLUGIN_MARKUP_MAP;
799         $name = substr($match,2,-2); 
800         $vars = '';
801         if (preg_match('/^(\S+)\|(.*)$/', $name, $_m)) {
802             $name = $_m[1];
803             $vars = $_m[2]; //str_replace(' ', '&', $_m[2]);
804         }
805         if (!isset($PLUGIN_MARKUP_MAP[$name])) {
806             trigger_error("No plugin for $name $vars defined.", E_USER_WARNING);
807             return "";
808         }
809         $plugin = $PLUGIN_MARKUP_MAP[$name];
810         return new Cached_PluginInvocation("<"."?plugin $plugin $vars $body ?".">");
811     }
812 }
813
814 /** ENABLE_MARKUP_TEMPLATE
815  *  Template syntax similar to mediawiki
816  *  {{template}}
817  * => < ? plugin Template page=template ? >
818  *  {{template|var1=value1|var2=value|...}}
819  * => < ? plugin Template page=template var=value ... ? >
820  */
821 class Markup_template_plugin  extends SimpleMarkup
822 {
823     // patch #1732793: allow \n, mult. {{ }} in one line, and single letters
824     var $_match_regexp = '\{\{.*?\}\}';
825     
826     function markup ($match) {
827         $page = substr(str_replace("\n", "", $match),2,-2); $vars = '';
828         if (preg_match('/^(\S+?)\|(.*)$/', $page, $_m)) {
829             $page = $_m[1];
830             $vars = '"' . preg_replace('/\|/', '" "', $_m[2]) . '"'; 
831             $vars = preg_replace('/"(\S+)=([^"]*)"/', '\\1="\\2"', $vars);
832         }
833         if ($vars)
834             $s = '<'.'?plugin Template page="'.$page.'" '.$vars.' ?'.'>';
835         else
836             $s = '<'.'?plugin Template page="' . $page . '" ?'.'>';
837         return new Cached_PluginInvocation($s);
838     }
839 }
840
841 /** ENABLE_MARKUP_MEDIAWIKI_TABLE
842  *  Table syntax similar to mediawiki
843  *  {|
844  * => <?plugin MediawikiTable
845  *  |}
846  * => ?>
847  */
848 class Markup_mediawikitable_plugin  extends SimpleMarkup
849 {
850     var $_match_regexp = '\{\|.*?\|\}';
851
852     function markup ($match) {
853         $s = str_replace("{|", "", $match);
854         $s = str_replace("|}", "", $s);
855       $s = '<'.'?plugin MediawikiTable ' . $s . '?'.'>';
856       return new Cached_PluginInvocation($s);
857     }
858 }
859
860 // "..." => "&#133;"  browser specific display (not cached?)
861 // Support some HTML::Entities: (C) for copy, --- for mdash, -- for ndash
862 // TODO: "--" => "&emdash;" browser specific display (not cached?)
863
864 class Markup_html_entities  extends SimpleMarkup {
865     //var $_match_regexp = '(: \.\.\.|\-\-|\-\-\-|\(C\) )';
866
867     function Markup_html_entities() {
868         $this->_entities = array('...'  => '&#133;',
869                                  '--'   => '&ndash;',
870                                  '---'  => '&mdash;',
871                                  '(C)'  => '&copy;',
872                                  '&copy;' => '&copy;',
873                                  '&trade;'  => '&trade;',
874                                  );
875         $this->_match_regexp = 
876             '(: ' . 
877             join('|', array_map('preg_quote', array_keys($this->_entities))) . 
878             ' )';
879     }
880    
881     function markup ($match) {
882         return HTML::Raw($this->_entities[$match]);
883     }
884 }
885
886 class Markup_isonumchars  extends SimpleMarkup {
887     var $_match_regexp = '\&\#\d{2,5};';
888     
889     function markup ($match) {
890         return HTML::Raw($match);
891     }
892 }
893
894 class Markup_isohexchars extends SimpleMarkup {
895     // hexnums, like &#x00A4; <=> &curren;
896     var $_match_regexp = '\&\#x[0-9a-fA-F]{2,4};';
897     
898     function markup ($match) {
899         return HTML::Raw($match);
900     }
901 }
902
903 // FIXME: Do away with magic phpwiki forms.  (Maybe phpwiki: links too?)
904 // FIXME: Do away with plugin-links.  They seem not to be used.
905 //Plugin link
906
907 class InlineTransformer
908 {
909     var $_regexps = array();
910     var $_markup = array();
911     
912     function InlineTransformer ($markup_types = false) {
913         global $request;
914         // We need to extend the inline parsers by certain actions, like SearchHighlight, 
915         // SpellCheck and maybe CreateToc.
916         if (!$markup_types) {
917             $non_default = false;
918             $markup_types = array
919                 ('escape', 'bracketlink', 'url',
920                  'interwiki',  'semanticlink', 'wikiword', 'linebreak',
921                  'wikicreole_subscript', 'old_emphasis', 'nestled_emphasis',
922                  'html_emphasis', 'html_abbr', 'plugin',
923                  'isonumchars', 'isohexchars', /*'html_entities'*/
924                  );
925             if (DISABLE_MARKUP_WIKIWORD)
926                 $markup_types = array_remove($markup_types, 'wikiword');
927
928             $action = $request->getArg('action');
929             if ($action == 'SpellCheck' and $request->getArg('suggestions'))
930             {   // insert it after url
931                 array_splice($markup_types, 2, 1, array('url','spellcheck'));
932             }
933             if (isset($request->_searchhighlight))
934             {   // insert it after url
935                 array_splice($markup_types, 2, 1, array('url','searchhighlight'));
936                 //$request->setArg('searchhighlight', false);
937             }
938         } else {
939             $non_default = true;
940         }
941         foreach ($markup_types as $mtype) {
942             $class = "Markup_$mtype";
943             $this->_addMarkup(new $class);
944         }
945         if (ENABLE_MARKUP_DIVSPAN and !$non_default)
946             $this->_addMarkup(new Markup_html_divspan);
947         if (ENABLE_MARKUP_COLOR and !$non_default)
948             $this->_addMarkup(new Markup_color);
949         if (ENABLE_MARKUP_TEMPLATE and !$non_default)
950             $this->_addMarkup(new Markup_template_plugin);
951         if (ENABLE_MARKUP_MEDIAWIKI_TABLE)
952             $this->_addMarkup(new Markup_mediawikitable_plugin);
953         // This does not work yet
954         if (0 and PLUGIN_MARKUP_MAP and !$non_default)
955             $this->_addMarkup(new Markup_xml_plugin);
956     }
957
958     function _addMarkup ($markup) {
959         if (isa($markup, 'SimpleMarkup'))
960             $regexp = $markup->getMatchRegexp();
961         else
962             $regexp = $markup->getStartRegexp();
963
964         assert( !isset($this->_markup[$regexp]) );
965         assert( strlen(trim($regexp)) > 0 );
966         $this->_regexps[] = $regexp;
967         $this->_markup[] = $markup;
968     }
969         
970     function parse (&$text, $end_regexps = array('$')) {
971         $regexps = $this->_regexps;
972
973         // $end_re takes precedence: "favor reduce over shift"
974         array_unshift($regexps, $end_regexps[0]);
975         //array_push($regexps, $end_regexps[0]);
976         $regexps = new RegexpSet($regexps);
977         
978         $input = $text;
979         $output = new XmlContent;
980
981         $match = $regexps->match($input);
982         
983         while ($match) {
984             if ($match->regexp_ind == 0) {
985                 // No start pattern found before end pattern.
986                 // We're all done!
987                 if (isset($markup) and is_object($markup) 
988                     and isa($markup,'Markup_plugin')) 
989                 {
990                     $current =& $output->_content[count($output->_content)-1];
991                     $current->setTightness(true,true);
992                 }
993                 $output->pushContent($match->prematch);
994                 $text = $match->postmatch;
995                 return $output;
996             }
997
998             $markup = $this->_markup[$match->regexp_ind - 1];
999             $body = $this->_parse_markup_body($markup, $match->match, 
1000                                               $match->postmatch, $end_regexps);
1001             if (!$body) {
1002                 // Couldn't match balanced expression.
1003                 // Ignore and look for next matching start regexp.
1004                 $match = $regexps->nextMatch($input, $match);
1005                 continue;
1006             }
1007
1008             // Matched markup.  Eat input, push output.
1009             // FIXME: combine adjacent strings.
1010             if (isa($markup, 'SimpleMarkup'))
1011                 $current = $markup->markup($match->match);
1012             else
1013                 $current = $markup->markup($match->match, $body);
1014             $input = $match->postmatch;
1015             if (isset($markup) and is_object($markup) 
1016                 and isa($markup,'Markup_plugin')) 
1017             {
1018                 $current->setTightness(true,true);
1019             }
1020             $output->pushContent($match->prematch, $current);
1021
1022             $match = $regexps->match($input);
1023         }
1024
1025         // No pattern matched, not even the end pattern.
1026         // Parse fails.
1027         return false;
1028     }
1029
1030     function _parse_markup_body ($markup, $match, &$text, $end_regexps) {
1031         if (isa($markup, 'SimpleMarkup'))
1032             return true;        // Done. SimpleMarkup is simple.
1033
1034         if (!is_object($markup)) return false; // Some error: Should assert
1035         array_unshift($end_regexps, $markup->getEndRegexp($match));
1036
1037         // Optimization: if no end pattern in text, we know the
1038         // parse will fail.  This is an important optimization,
1039         // e.g. when text is "*lots *of *start *delims *with
1040         // *no *matching *end *delims".
1041         $ends_pat = "/(?:" . join(").*(?:", $end_regexps) . ")/xs";
1042         if (!preg_match($ends_pat, $text))
1043             return false;
1044         return $this->parse($text, $end_regexps);
1045     }
1046 }
1047
1048 class LinkTransformer extends InlineTransformer
1049 {
1050     function LinkTransformer () {
1051         $this->InlineTransformer(array('escape', 'bracketlink', 'url',
1052                                        'semanticlink', 'interwiki', 'wikiword', 
1053                                        ));
1054     }
1055 }
1056
1057 class NowikiTransformer extends InlineTransformer
1058 {
1059     function NowikiTransformer () {
1060         $this->InlineTransformer
1061             (array('linebreak',
1062                    'html_emphasis', 'html_abbr', 'plugin',
1063                    'isonumchars', 'isohexchars', /*'html_entities',*/
1064                    ));
1065     }
1066 }
1067
1068 function TransformInline($text, $markup = 2.0, $basepage=false) {
1069     static $trfm;
1070     $action = $GLOBALS['request']->getArg('action');
1071     if (empty($trfm) or $action == 'SpellCheck') {
1072         $trfm = new InlineTransformer;
1073     }
1074     
1075     if ($markup < 2.0) {
1076         $text = ConvertOldMarkup($text, 'inline');
1077     }
1078
1079     if ($basepage) {
1080         return new CacheableMarkup($trfm->parse($text), $basepage);
1081     }
1082     return $trfm->parse($text);
1083 }
1084
1085 function TransformLinks($text, $markup = 2.0, $basepage = false) {
1086     static $trfm;
1087     
1088     if (empty($trfm)) {
1089         $trfm = new LinkTransformer;
1090     }
1091
1092     if ($markup < 2.0) {
1093         $text = ConvertOldMarkup($text, 'links');
1094     }
1095     
1096     if ($basepage) {
1097         return new CacheableMarkup($trfm->parse($text), $basepage);
1098     }
1099     return $trfm->parse($text);
1100 }
1101
1102 /**
1103  * Transform only html markup and entities.
1104  */
1105 function TransformInlineNowiki($text, $markup = 2.0, $basepage=false) {
1106     static $trfm;
1107     
1108     if (empty($trfm)) {
1109         $trfm = new NowikiTransformer;
1110     }
1111     if ($basepage) {
1112         return new CacheableMarkup($trfm->parse($text), $basepage);
1113     }
1114     return $trfm->parse($text);
1115 }
1116
1117
1118 // $Log: not supported by cvs2svn $
1119 // Revision 1.99  2008/05/06 19:23:17  rurban
1120 // update (c)
1121 //
1122 // Revision 1.98  2008/03/21 20:35:52  rurban
1123 // Improve upon embedded ImgObject, such as [ *.mp3 ], objects.
1124 // Object tags now render as label correctly and param tags are also added.
1125 //
1126 // Revision 1.97  2008/03/18 20:25:49  rurban
1127 // Fixed "\n" => " " in [ link parsing ] by suggestion of Marc-Etienne
1128 //
1129 // Revision 1.96  2008/03/17 19:06:39  rurban
1130 // fix bug#1904088  Some brackets links with \n cause the parser to crash
1131 //
1132 // Revision 1.95  2008/02/15 20:02:49  vargenau
1133 // Allow <s> to strike; update Help for <s> and <strike>
1134 //
1135 // Revision 1.94  2008/01/31 20:40:10  vargenau
1136 // Implemented Mediawiki-like syntax for tables
1137 //
1138 // Revision 1.93  2007/09/26 16:54:34  rurban
1139 // Fix Bug#1802827 Template does not get expanded with {{ }} syntax.
1140 // by vargenau
1141 //
1142 // Revision 1.92  2007/08/10 21:58:01  rurban
1143 // Improve SemanticLink parsings:
1144 //   No units seperated by space allowed without []
1145 //   For :: (relations) only words, no comma,
1146 //   but for := (attributes) comma and dots are allowed. Units with groupsep.
1147 //   Ending dots or comma are not part of the link.
1148 //
1149 // Revision 1.91  2007/06/07 18:56:57  rurban
1150 // patch #1732793: allow \n, mult. {{ }} in one line, and single
1151 // letters (slightly improved) by AlJeux and ReiniUrban
1152 //
1153 // Revision 1.90  2007/03/18 17:35:14  rurban
1154 // Fix :DontStoreLink
1155 //
1156 // Revision 1.89  2007/02/17 14:16:28  rurban
1157 // fix color GREY to GRAY
1158 //
1159 // Revision 1.88  2007/01/21 13:15:50  rurban
1160 // Support spaces in attributes and relation links
1161 //
1162 // Revision 1.87  2007/01/20 15:53:51  rurban
1163 // Rewrite of SearchHighlight: through ActionPage and InlineParser
1164 //
1165 // Revision 1.86  2007/01/20 11:25:07  rurban
1166 // add SpellCheck support
1167 //
1168 // Revision 1.85  2007/01/07 18:42:49  rurban
1169 // Add support for non-bracket semantic relation parsing. Assert empty regex (interwikimap?) earlier. Change {{Template||}} vars handling to new style. Stricter interwikimap matching not to find semantic links
1170 //
1171 // Revision 1.84  2007/01/02 13:18:07  rurban
1172 // fix semantic attributes syntax :=, not :-, disable DIVSPAN and PLUGIN_MARKUP_MAP
1173 //
1174 // Revision 1.83  2006/12/22 00:23:24  rurban
1175 // Fix Bug #1540007 "hardened-php issue, crawlers related"
1176 // Broken str_replace with strings > 200 chars
1177 //
1178 // Revision 1.82  2006/12/02 19:53:05  rurban
1179 // Simplify DISABLE_MARKUP_WIKIWORD handling by adding the new function
1180 // stdlib: array_remove(). Hopefully PHP will not add this natively sooner
1181 // or later.
1182 //
1183 // Revision 1.81  2006/11/19 13:52:52  rurban
1184 // improve debug output: regex only once
1185 //
1186 // Revision 1.80  2006/10/12 06:32:30  rurban
1187 // Optionally support new tags <div>, <span> with ENABLE_MARKUP_DIVSPAN (in work)
1188 //
1189 // Revision 1.79  2006/10/08 12:38:11  rurban
1190 // New special interwiki link markup [:LinkTo] without storing the backlink
1191 //
1192 // Revision 1.78  2006/09/03 09:53:52  rurban
1193 // more colors, case-insensitive color names
1194 //
1195 // Revision 1.77  2006/08/25 19:02:02  rurban
1196 // patch #1348996 by Robert Litwiniec: fix show image semantics if label is given
1197 //
1198 // Revision 1.76  2006/08/19 11:02:35  rurban
1199 // add strike and del to html emphasis: Patch #1542894 by Kai Krakow
1200 //
1201 // Revision 1.75  2006/08/15 13:43:10  rurban
1202 // add Markup_xml_plugin (untested) and fix Markup_template_plugin
1203 //
1204 // Revision 1.74  2006/07/23 14:03:18  rurban
1205 // add new feature: DISABLE_MARKUP_WIKIWORD
1206 //
1207 // Revision 1.73  2006/04/15 12:20:36  rurban
1208 // fix relatives links patch by Joel Schaubert for [/
1209 //
1210 // Revision 1.72  2006/03/07 20:43:29  rurban
1211 // relative external link, if no internal subpage. by joel Schaubert
1212 //
1213 // Revision 1.71  2005/11/14 22:31:12  rurban
1214 // add SemanticWeb support
1215 //
1216 // Revision 1.70  2005/10/31 16:45:23  rurban
1217 // added cfg-able markups only for default TextTransformation, not for links and others
1218 //
1219 // Revision 1.69  2005/09/14 05:57:19  rurban
1220 // make ENABLE_MARKUP_TEMPLATE optional
1221 //
1222 // Revision 1.68  2005/09/10 21:24:32  rurban
1223 // optionally support {{Template|vars}} syntax
1224 //
1225 // Revision 1.67  2005/06/06 17:41:20  rurban
1226 // support new ENABLE_MARKUP_COLOR
1227 //
1228 // Revision 1.66  2005/04/23 11:15:49  rurban
1229 // handle allowed inlined objects within INLINE_IMAGES
1230 //
1231 // Revision 1.65  2005/03/27 18:24:17  rurban
1232 // add Log
1233 //
1234
1235 // (c-file-style: "gnu")
1236 // Local Variables:
1237 // mode: php
1238 // tab-width: 8
1239 // c-basic-offset: 4
1240 // c-hanging-comment-ender-p: nil
1241 // indent-tabs-mode: nil
1242 // End:   
1243 ?>