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