]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/InlineParser.php
for the previous pcre short-cut
[SourceForge/phpwiki.git] / lib / InlineParser.php
1 <?php 
2 rcs_id('$Id: InlineParser.php,v 1.99 2008-05-06 19:23:17 rurban 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_old_emphasis  extends BalancedMarkup
587 {
588     var $_start_regexp = "''|__";
589
590     function getEndRegexp ($match) {
591         return $match;
592     }
593     
594     function markup ($match, $body) {
595         $tag = $match == "''" ? 'em' : 'strong';
596         return new HtmlElement($tag, $body);
597     }
598 }
599
600 class Markup_nestled_emphasis extends BalancedMarkup
601 {
602     function getStartRegexp() {
603         static $start_regexp = false;
604
605         if (!$start_regexp) {
606             // The three possible delimiters
607             // (none of which can be followed by itself.)
608             $i = "_ (?! _)";
609             $b = "\\* (?! \\*)";
610             $tt = "= (?! =)";
611
612             $any = "(?: ${i}|${b}|${tt})"; // any of the three.
613
614             // Any of [_*=] is okay if preceded by space or one of [-"'/:]
615             $start[] = "(?<= \\s|^|[-\"'\\/:]) ${any}";
616
617             // _ or * is okay after = as long as not immediately followed by =
618             $start[] = "(?<= =) (?: ${i}|${b}) (?! =)";
619             // etc...
620             $start[] = "(?<= _) (?: ${b}|${tt}) (?! _)";
621             $start[] = "(?<= \\*) (?: ${i}|${tt}) (?! \\*)";
622
623
624             // any delimiter okay after an opening brace ( [{<(] )
625             // as long as it's not immediately followed by the matching closing
626             // brace.
627             $start[] = "(?<= { ) ${any} (?! } )";
628             $start[] = "(?<= < ) ${any} (?! > )";
629             $start[] = "(?<= \\( ) ${any} (?! \\) )";
630             
631             $start = "(?:" . join('|', $start) . ")";
632             
633             // Any of the above must be immediately followed by non-whitespace.
634             $start_regexp = $start . "(?= \S)";
635         }
636
637         return $start_regexp;
638     }
639
640     function getEndRegexp ($match) {
641         $chr = preg_quote($match);
642         return "(?<= \S | ^ ) (?<! $chr) $chr (?! $chr) (?= \s | [-)}>\"'\\/:.,;!? _*=] | $)";
643     }
644     
645     function markup ($match, $body) {
646         switch ($match) {
647         case '*': return new HtmlElement('b', $body);
648         case '=': return new HtmlElement('tt', $body);
649         case '_': return new HtmlElement('i', $body);
650         }
651     }
652 }
653
654 class Markup_html_emphasis extends BalancedMarkup
655 {
656     var $_start_regexp = 
657         "<(?: b|big|i|small|tt|em|strong|cite|code|dfn|kbd|samp|s|strike|del|var|sup|sub )>";
658
659     function getEndRegexp ($match) {
660         return "<\\/" . substr($match, 1);
661     }
662     
663     function markup ($match, $body) {
664         $tag = substr($match, 1, -1);
665         return new HtmlElement($tag, $body);
666     }
667 }
668
669 class Markup_html_divspan extends BalancedMarkup
670 {
671     var $_start_regexp = 
672         "<(?: div|span )(?: \s[^>]*)?>";
673
674     function getEndRegexp ($match) {
675         if (substr($match,1,4) == 'span')
676             $tag = 'span';
677         else
678             $tag = 'div';
679         return "<\\/" . $tag . '>';
680     }
681     
682     function markup ($match, $body) {
683         if (substr($match,1,4) == 'span')
684             $tag = 'span';
685         else
686             $tag = 'div';
687         $rest = substr($match,1+strlen($tag),-1);
688         if (!empty($rest)) {
689             list($key,$val) = explode("=",$rest);
690             $args = array($key => $val);
691         } else $args = array();
692         return new HtmlElement($tag, $args, $body);
693     }
694 }
695
696
697 class Markup_html_abbr extends BalancedMarkup
698 {
699     //rurban: abbr|acronym need an optional title tag.
700     //sf.net bug #728595
701     var $_start_regexp = "<(?: abbr|acronym )(?: \stitle=[^>]*)?>";
702
703     function getEndRegexp ($match) {
704         if (substr($match,1,4) == 'abbr')
705             $tag = 'abbr';
706         else
707             $tag = 'acronym';
708         return "<\\/" . $tag . '>';
709     }
710     
711     function markup ($match, $body) {
712         if (substr($match,1,4) == 'abbr')
713             $tag = 'abbr';
714         else
715             $tag = 'acronym';
716         $rest = substr($match,1+strlen($tag),-1);
717         if (!empty($rest)) {
718             list($key,$val) = explode("=",$rest);
719             $args = array($key => $val);
720         } else $args = array();
721         return new HtmlElement($tag, $args, $body);
722     }
723 }
724
725 /** ENABLE_MARKUP_COLOR
726  *  See http://www.pmwiki.org/wiki/PmWiki/WikiStyles and
727  *      http://www.flexwiki.com/default.aspx/FlexWiki/FormattingRules.html
728  */
729 class Markup_color extends BalancedMarkup {
730     // %color=blue% blue text %% and back to normal
731     var $_start_regexp = "%color=(?: [^%]*)%";
732     var $_end_regexp = "%%";
733     
734     function markup ($match, $body) {
735         $color = strtoupper(substr($match, 7, -1));
736         if (strlen($color) != 7 
737             and in_array($color, array('RED', 'BLUE', 'GRAY', 'YELLOW', 'GREEN', 'CYAN', 'BLACK'))) 
738         {   // must be a valid color name
739             return new HtmlElement('font', array('color' => $color), $body);
740         } elseif ((substr($color,0,1) == '#') 
741                   and (strspn(substr($color,1),'0123456789ABCDEF') == strlen($color)-1)) {
742             return new HtmlElement('font', array('color' => $color), $body);
743         } else {
744             trigger_error(sprintf(_("unknown color %s ignored"), substr($match, 7, -1)), E_USER_WARNING);
745         }
746                 
747     }
748 }
749
750 // Special version for single-line plugins formatting, 
751 //  like: '<small>< ?plugin PopularNearby ? ></small>'
752 class Markup_plugin extends SimpleMarkup
753 {
754     var $_match_regexp = '<\?plugin(?:-form)?\s[^\n]+?\?>';
755
756     function markup ($match) {
757         //$xml = new Cached_PluginInvocation($match);
758         //$xml->setTightness(true,true);
759         return new Cached_PluginInvocation($match);
760     }
761 }
762
763 // Special version for plugins in xml syntax 
764 // <name arg=value>body</name> or <name /> => < ? plugin pluginname arg=value body ? >
765 // PLUGIN_MARKUP_MAP = "html:RawHtml dot:GraphViz toc:CreateToc amath:AsciiMath richtable:RichTable include:IncludePage tex:TexToPng"
766 class Markup_xml_plugin extends BalancedMarkup
767 {
768     //var $_start_regexp = "<(?: ".join('|',PLUGIN_MARKUP_MAP)." )(?: \s[^>]*)>";
769
770     function getStartRegexp () {
771         global $PLUGIN_MARKUP_MAP;
772         static $_start_regexp;
773         if ($_start_regexp) return $_start_regexp;
774         if (empty($PLUGIN_MARKUP_MAP))
775             return '';
776         //"<(?: html|dot|toc|amath|richtable|include|tex )(?: \s[^>]*)>"
777         $_start_regexp = "<(?: ".join('|',array_keys($PLUGIN_MARKUP_MAP))." )(?: \s[^>]* | / )>";
778         return $_start_regexp;
779     }
780     function getEndRegexp ($match) {
781         return "<\\/" . $match . '>';
782     }
783     function markup ($match, $body) {
784         global $PLUGIN_MARKUP_MAP;
785         $name = substr($match,2,-2); 
786         $vars = '';
787         if (preg_match('/^(\S+)\|(.*)$/', $name, $_m)) {
788             $name = $_m[1];
789             $vars = $_m[2]; //str_replace(' ', '&', $_m[2]);
790         }
791         if (!isset($PLUGIN_MARKUP_MAP[$name])) {
792             trigger_error("No plugin for $name $vars defined.", E_USER_WARNING);
793             return "";
794         }
795         $plugin = $PLUGIN_MARKUP_MAP[$name];
796         return new Cached_PluginInvocation("<"."?plugin $plugin $vars $body ?".">");
797     }
798 }
799
800 /** ENABLE_MARKUP_TEMPLATE
801  *  Template syntax similar to mediawiki
802  *  {{template}}
803  * => < ? plugin Template page=template ? >
804  *  {{template|var1=value1|var2=value|...}}
805  * => < ? plugin Template page=template var=value ... ? >
806  */
807 class Markup_template_plugin  extends SimpleMarkup
808 {
809     // patch #1732793: allow \n, mult. {{ }} in one line, and single letters
810     var $_match_regexp = '\{\{.*?\}\}';
811     
812     function markup ($match) {
813         $page = substr(str_replace("\n", "", $match),2,-2); $vars = '';
814         if (preg_match('/^(\S+?)\|(.*)$/', $page, $_m)) {
815             $page = $_m[1];
816             $vars = '"' . preg_replace('/\|/', '" "', $_m[2]) . '"'; 
817             $vars = preg_replace('/"(\S+)=([^"]*)"/', '\\1="\\2"', $vars);
818         }
819         if ($vars)
820             $s = '<'.'?plugin Template page="'.$page.'" '.$vars.' ?'.'>';
821         else
822             $s = '<'.'?plugin Template page="' . $page . '" ?'.'>';
823         return new Cached_PluginInvocation($s);
824     }
825 }
826
827 /** ENABLE_MARKUP_MEDIAWIKI_TABLE
828  *  Table syntax similar to mediawiki
829  *  {|
830  * => <?plugin MediawikiTable
831  *  |}
832  * => ?>
833  */
834 class Markup_mediawikitable_plugin  extends SimpleMarkup
835 {
836     var $_match_regexp = '\{\|.*?\|\}';
837
838     function markup ($match) {
839         $s = str_replace("{|", "", $match);
840         $s = str_replace("|}", "", $s);
841       $s = '<'.'?plugin MediawikiTable ' . $s . '?'.'>';
842       return new Cached_PluginInvocation($s);
843     }
844 }
845
846 // "..." => "&#133;"  browser specific display (not cached?)
847 // Support some HTML::Entities: (C) for copy, --- for mdash, -- for ndash
848 // TODO: "--" => "&emdash;" browser specific display (not cached?)
849
850 class Markup_html_entities  extends SimpleMarkup {
851     //var $_match_regexp = '(: \.\.\.|\-\-|\-\-\-|\(C\) )';
852
853     function Markup_html_entities() {
854         $this->_entities = array('...'  => '&#133;',
855                                  '--'   => '&ndash;',
856                                  '---'  => '&mdash;',
857                                  '(C)'  => '&copy;',
858                                  '&copy;' => '&copy;',
859                                  '&trade;'  => '&trade;',
860                                  );
861         $this->_match_regexp = 
862             '(: ' . 
863             join('|', array_map('preg_quote', array_keys($this->_entities))) . 
864             ' )';
865     }
866    
867     function markup ($match) {
868         return HTML::Raw($this->_entities[$match]);
869     }
870 }
871
872 class Markup_isonumchars  extends SimpleMarkup {
873     var $_match_regexp = '\&\#\d{2,5};';
874     
875     function markup ($match) {
876         return HTML::Raw($match);
877     }
878 }
879
880 class Markup_isohexchars extends SimpleMarkup {
881     // hexnums, like &#x00A4; <=> &curren;
882     var $_match_regexp = '\&\#x[0-9a-fA-F]{2,4};';
883     
884     function markup ($match) {
885         return HTML::Raw($match);
886     }
887 }
888
889 // FIXME: Do away with magic phpwiki forms.  (Maybe phpwiki: links too?)
890 // FIXME: Do away with plugin-links.  They seem not to be used.
891 //Plugin link
892
893 class InlineTransformer
894 {
895     var $_regexps = array();
896     var $_markup = array();
897     
898     function InlineTransformer ($markup_types = false) {
899         global $request;
900         // We need to extend the inline parsers by certain actions, like SearchHighlight, 
901         // SpellCheck and maybe CreateToc.
902         if (!$markup_types) {
903             $non_default = false;
904             $markup_types = array
905                 ('escape', 'bracketlink', 'url',
906                  'interwiki',  'semanticlink', 'wikiword', 'linebreak',
907                  'old_emphasis', 'nestled_emphasis',
908                  'html_emphasis', 'html_abbr', 'plugin',
909                  'isonumchars', 'isohexchars', /*'html_entities'*/
910                  );
911             if (DISABLE_MARKUP_WIKIWORD)
912                 $markup_types = array_remove($markup_types, 'wikiword');
913
914             $action = $request->getArg('action');
915             if ($action == 'SpellCheck' and $request->getArg('suggestions'))
916             {   // insert it after url
917                 array_splice($markup_types, 2, 1, array('url','spellcheck'));
918             }
919             if (isset($request->_searchhighlight))
920             {   // insert it after url
921                 array_splice($markup_types, 2, 1, array('url','searchhighlight'));
922                 //$request->setArg('searchhighlight', false);
923             }
924         } else {
925             $non_default = true;
926         }
927         foreach ($markup_types as $mtype) {
928             $class = "Markup_$mtype";
929             $this->_addMarkup(new $class);
930         }
931         if (ENABLE_MARKUP_DIVSPAN and !$non_default)
932             $this->_addMarkup(new Markup_html_divspan);
933         if (ENABLE_MARKUP_COLOR and !$non_default)
934             $this->_addMarkup(new Markup_color);
935         if (ENABLE_MARKUP_TEMPLATE and !$non_default)
936             $this->_addMarkup(new Markup_template_plugin);
937         if (ENABLE_MARKUP_MEDIAWIKI_TABLE)
938             $this->_addMarkup(new Markup_mediawikitable_plugin);
939         // This does not work yet
940         if (0 and PLUGIN_MARKUP_MAP and !$non_default)
941             $this->_addMarkup(new Markup_xml_plugin);
942     }
943
944     function _addMarkup ($markup) {
945         if (isa($markup, 'SimpleMarkup'))
946             $regexp = $markup->getMatchRegexp();
947         else
948             $regexp = $markup->getStartRegexp();
949
950         assert( !isset($this->_markup[$regexp]) );
951         assert( strlen(trim($regexp)) > 0 );
952         $this->_regexps[] = $regexp;
953         $this->_markup[] = $markup;
954     }
955         
956     function parse (&$text, $end_regexps = array('$')) {
957         $regexps = $this->_regexps;
958
959         // $end_re takes precedence: "favor reduce over shift"
960         array_unshift($regexps, $end_regexps[0]);
961         //array_push($regexps, $end_regexps[0]);
962         $regexps = new RegexpSet($regexps);
963         
964         $input = $text;
965         $output = new XmlContent;
966
967         $match = $regexps->match($input);
968         
969         while ($match) {
970             if ($match->regexp_ind == 0) {
971                 // No start pattern found before end pattern.
972                 // We're all done!
973                 if (isset($markup) and is_object($markup) 
974                     and isa($markup,'Markup_plugin')) 
975                 {
976                     $current =& $output->_content[count($output->_content)-1];
977                     $current->setTightness(true,true);
978                 }
979                 $output->pushContent($match->prematch);
980                 $text = $match->postmatch;
981                 return $output;
982             }
983
984             $markup = $this->_markup[$match->regexp_ind - 1];
985             $body = $this->_parse_markup_body($markup, $match->match, 
986                                               $match->postmatch, $end_regexps);
987             if (!$body) {
988                 // Couldn't match balanced expression.
989                 // Ignore and look for next matching start regexp.
990                 $match = $regexps->nextMatch($input, $match);
991                 continue;
992             }
993
994             // Matched markup.  Eat input, push output.
995             // FIXME: combine adjacent strings.
996             if (isa($markup, 'SimpleMarkup'))
997                 $current = $markup->markup($match->match);
998             else
999                 $current = $markup->markup($match->match, $body);
1000             $input = $match->postmatch;
1001             if (isset($markup) and is_object($markup) 
1002                 and isa($markup,'Markup_plugin')) 
1003             {
1004                 $current->setTightness(true,true);
1005             }
1006             $output->pushContent($match->prematch, $current);
1007
1008             $match = $regexps->match($input);
1009         }
1010
1011         // No pattern matched, not even the end pattern.
1012         // Parse fails.
1013         return false;
1014     }
1015
1016     function _parse_markup_body ($markup, $match, &$text, $end_regexps) {
1017         if (isa($markup, 'SimpleMarkup'))
1018             return true;        // Done. SimpleMarkup is simple.
1019
1020         if (!is_object($markup)) return false; // Some error: Should assert
1021         array_unshift($end_regexps, $markup->getEndRegexp($match));
1022
1023         // Optimization: if no end pattern in text, we know the
1024         // parse will fail.  This is an important optimization,
1025         // e.g. when text is "*lots *of *start *delims *with
1026         // *no *matching *end *delims".
1027         $ends_pat = "/(?:" . join(").*(?:", $end_regexps) . ")/xs";
1028         if (!preg_match($ends_pat, $text))
1029             return false;
1030         return $this->parse($text, $end_regexps);
1031     }
1032 }
1033
1034 class LinkTransformer extends InlineTransformer
1035 {
1036     function LinkTransformer () {
1037         $this->InlineTransformer(array('escape', 'bracketlink', 'url',
1038                                        'semanticlink', 'interwiki', 'wikiword', 
1039                                        ));
1040     }
1041 }
1042
1043 class NowikiTransformer extends InlineTransformer
1044 {
1045     function NowikiTransformer () {
1046         $this->InlineTransformer
1047             (array('linebreak',
1048                    'html_emphasis', 'html_abbr', 'plugin',
1049                    'isonumchars', 'isohexchars', /*'html_entities',*/
1050                    ));
1051     }
1052 }
1053
1054 function TransformInline($text, $markup = 2.0, $basepage=false) {
1055     static $trfm;
1056     $action = $GLOBALS['request']->getArg('action');
1057     if (empty($trfm) or $action == 'SpellCheck') {
1058         $trfm = new InlineTransformer;
1059     }
1060     
1061     if ($markup < 2.0) {
1062         $text = ConvertOldMarkup($text, 'inline');
1063     }
1064
1065     if ($basepage) {
1066         return new CacheableMarkup($trfm->parse($text), $basepage);
1067     }
1068     return $trfm->parse($text);
1069 }
1070
1071 function TransformLinks($text, $markup = 2.0, $basepage = false) {
1072     static $trfm;
1073     
1074     if (empty($trfm)) {
1075         $trfm = new LinkTransformer;
1076     }
1077
1078     if ($markup < 2.0) {
1079         $text = ConvertOldMarkup($text, 'links');
1080     }
1081     
1082     if ($basepage) {
1083         return new CacheableMarkup($trfm->parse($text), $basepage);
1084     }
1085     return $trfm->parse($text);
1086 }
1087
1088 /**
1089  * Transform only html markup and entities.
1090  */
1091 function TransformInlineNowiki($text, $markup = 2.0, $basepage=false) {
1092     static $trfm;
1093     
1094     if (empty($trfm)) {
1095         $trfm = new NowikiTransformer;
1096     }
1097     if ($basepage) {
1098         return new CacheableMarkup($trfm->parse($text), $basepage);
1099     }
1100     return $trfm->parse($text);
1101 }
1102
1103
1104 // $Log: not supported by cvs2svn $
1105 // Revision 1.98  2008/03/21 20:35:52  rurban
1106 // Improve upon embedded ImgObject, such as [ *.mp3 ], objects.
1107 // Object tags now render as label correctly and param tags are also added.
1108 //
1109 // Revision 1.97  2008/03/18 20:25:49  rurban
1110 // Fixed "\n" => " " in [ link parsing ] by suggestion of Marc-Etienne
1111 //
1112 // Revision 1.96  2008/03/17 19:06:39  rurban
1113 // fix bug#1904088  Some brackets links with \n cause the parser to crash
1114 //
1115 // Revision 1.95  2008/02/15 20:02:49  vargenau
1116 // Allow <s> to strike; update Help for <s> and <strike>
1117 //
1118 // Revision 1.94  2008/01/31 20:40:10  vargenau
1119 // Implemented Mediawiki-like syntax for tables
1120 //
1121 // Revision 1.93  2007/09/26 16:54:34  rurban
1122 // Fix Bug#1802827 Template does not get expanded with {{ }} syntax.
1123 // by vargenau
1124 //
1125 // Revision 1.92  2007/08/10 21:58:01  rurban
1126 // Improve SemanticLink parsings:
1127 //   No units seperated by space allowed without []
1128 //   For :: (relations) only words, no comma,
1129 //   but for := (attributes) comma and dots are allowed. Units with groupsep.
1130 //   Ending dots or comma are not part of the link.
1131 //
1132 // Revision 1.91  2007/06/07 18:56:57  rurban
1133 // patch #1732793: allow \n, mult. {{ }} in one line, and single
1134 // letters (slightly improved) by AlJeux and ReiniUrban
1135 //
1136 // Revision 1.90  2007/03/18 17:35:14  rurban
1137 // Fix :DontStoreLink
1138 //
1139 // Revision 1.89  2007/02/17 14:16:28  rurban
1140 // fix color GREY to GRAY
1141 //
1142 // Revision 1.88  2007/01/21 13:15:50  rurban
1143 // Support spaces in attributes and relation links
1144 //
1145 // Revision 1.87  2007/01/20 15:53:51  rurban
1146 // Rewrite of SearchHighlight: through ActionPage and InlineParser
1147 //
1148 // Revision 1.86  2007/01/20 11:25:07  rurban
1149 // add SpellCheck support
1150 //
1151 // Revision 1.85  2007/01/07 18:42:49  rurban
1152 // 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
1153 //
1154 // Revision 1.84  2007/01/02 13:18:07  rurban
1155 // fix semantic attributes syntax :=, not :-, disable DIVSPAN and PLUGIN_MARKUP_MAP
1156 //
1157 // Revision 1.83  2006/12/22 00:23:24  rurban
1158 // Fix Bug #1540007 "hardened-php issue, crawlers related"
1159 // Broken str_replace with strings > 200 chars
1160 //
1161 // Revision 1.82  2006/12/02 19:53:05  rurban
1162 // Simplify DISABLE_MARKUP_WIKIWORD handling by adding the new function
1163 // stdlib: array_remove(). Hopefully PHP will not add this natively sooner
1164 // or later.
1165 //
1166 // Revision 1.81  2006/11/19 13:52:52  rurban
1167 // improve debug output: regex only once
1168 //
1169 // Revision 1.80  2006/10/12 06:32:30  rurban
1170 // Optionally support new tags <div>, <span> with ENABLE_MARKUP_DIVSPAN (in work)
1171 //
1172 // Revision 1.79  2006/10/08 12:38:11  rurban
1173 // New special interwiki link markup [:LinkTo] without storing the backlink
1174 //
1175 // Revision 1.78  2006/09/03 09:53:52  rurban
1176 // more colors, case-insensitive color names
1177 //
1178 // Revision 1.77  2006/08/25 19:02:02  rurban
1179 // patch #1348996 by Robert Litwiniec: fix show image semantics if label is given
1180 //
1181 // Revision 1.76  2006/08/19 11:02:35  rurban
1182 // add strike and del to html emphasis: Patch #1542894 by Kai Krakow
1183 //
1184 // Revision 1.75  2006/08/15 13:43:10  rurban
1185 // add Markup_xml_plugin (untested) and fix Markup_template_plugin
1186 //
1187 // Revision 1.74  2006/07/23 14:03:18  rurban
1188 // add new feature: DISABLE_MARKUP_WIKIWORD
1189 //
1190 // Revision 1.73  2006/04/15 12:20:36  rurban
1191 // fix relatives links patch by Joel Schaubert for [/
1192 //
1193 // Revision 1.72  2006/03/07 20:43:29  rurban
1194 // relative external link, if no internal subpage. by joel Schaubert
1195 //
1196 // Revision 1.71  2005/11/14 22:31:12  rurban
1197 // add SemanticWeb support
1198 //
1199 // Revision 1.70  2005/10/31 16:45:23  rurban
1200 // added cfg-able markups only for default TextTransformation, not for links and others
1201 //
1202 // Revision 1.69  2005/09/14 05:57:19  rurban
1203 // make ENABLE_MARKUP_TEMPLATE optional
1204 //
1205 // Revision 1.68  2005/09/10 21:24:32  rurban
1206 // optionally support {{Template|vars}} syntax
1207 //
1208 // Revision 1.67  2005/06/06 17:41:20  rurban
1209 // support new ENABLE_MARKUP_COLOR
1210 //
1211 // Revision 1.66  2005/04/23 11:15:49  rurban
1212 // handle allowed inlined objects within INLINE_IMAGES
1213 //
1214 // Revision 1.65  2005/03/27 18:24:17  rurban
1215 // add Log
1216 //
1217
1218 // (c-file-style: "gnu")
1219 // Local Variables:
1220 // mode: php
1221 // tab-width: 8
1222 // c-basic-offset: 4
1223 // c-hanging-comment-ender-p: nil
1224 // indent-tabs-mode: nil
1225 // End:   
1226 ?>