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