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