1 <?php rcs_id('$Id: transform.php,v 1.40 2002-01-31 05:10:28 dairiki Exp $');
2 require_once('lib/WikiPlugin.php');
3 require_once('lib/HtmlElement.php');
4 require_once('lib/interwiki.php');
6 define('WT_SIMPLE_MARKUP', 0);
7 define('WT_TOKENIZER', 1);
8 define('WT_MODE_MARKUP', 2);
10 define("ZERO_LEVEL", 0);
11 define("NESTED_LEVEL", 1);
15 // public variables (only meaningful during do_transform)
16 var $linenumber; // current linenumber
17 var $replacements; // storage for tokenized strings of current line
18 var $user_data; // can be used by the transformer functions
19 // to store miscellaneous data.
22 var $content; // wiki markup, array of lines
23 var $mode_set; // stores if a HTML mode for this line has been set
24 var $trfrm_func; // array of registered functions
25 var $stack; // stack for SetHTMLMode (keeping track of open tags)
28 function WikiTransform()
30 $this->trfrm_func = array();
31 $this->stack = new Stack;
35 * Register transformation functions
37 * This should be done *before* calling do_transform
39 * @param $type enum <dl>
40 * <dt>WT_MODE_MARKUP</dt>
41 * <dd>If one WT_MODE_MARKUP really sets the html mode, then
42 * all successive WT_MODE_MARKUP functions are skipped.</dd>
43 * <dt>WT_TOKENIZER</dt>
44 * <dd> The transformer function is called once for each match
45 * of the $regexp in the line. The matched values are tokenized
46 * to protect them from further transformation.</dd>
48 * @param $function string Function name
49 * @param $regexp string Required for WT_TOKENIZER functions.
50 * Optional for others. If given, the transformer function will only be
51 * called if the line matches the $regexp.
53 function register($type, $function, $regexp = false)
55 $this->trfrm_func[] = array ($type, $function, $regexp);
59 * Sets current mode like list, preformatted text, plain text
61 * Takes care of closing (open) tags
63 * This is a helper function used to keep track of what HTML
64 * block-level element we are currently processing.
65 * Block-level elements are things like paragraphs "<p>",
66 * pre-formatted text "<pre>", and the various list elements:
67 * "<ul>", "<ol>" and "<dl>". Now, SetHTMLMode is also used to
68 * keep track of "<li>" and "<dd>" elements. Note that some of these elements
69 * can be nested, while others can not. (In particular, according to
70 * the HTML 4.01 specification, a paragraph "<p>" element is not
71 * allowed to contain any other block-level elements. Also <pre>,
72 * <li>, <dt>, <dd>, <h1> ... have this same restriction.)
74 * SetHTMLMode generates whatever HTML is necessary to get us into
75 * the requested element type at the requested nesting level.
77 * @param $tag string Type of HTML element to open.
79 * If $tag is an array, $tag[0] gives the element type,
80 * and $tag[1] should be a hash containing attribute-value
81 * pairs for the element.
83 * If $tag is the empty string, all open elements (down to the
84 * level requested by $level) are closed. Use
85 * SetHTMLMode('',0) to close all open block-level elements.
87 * @param $level string Rrequested nesting level for current element.
88 * The nesting level for top level block is one (which is
90 * Nesting is arbitrary limited to 20 levels.
92 * @return string Returns the HTML markup to open the specified element.
94 function SetHTMLMode($tag, $level = 1)
97 $el = new HtmlElement($tag[0], $tag[1]);
99 $el = new HtmlElement($tag);
101 $this->mode_set = 1; // in order to prevent other mode markup
106 // arbitrarily limit tag nesting
108 $request->finish(_("Lists nested too deep in SetHTMLOutputMode"));
111 if ($level <= $this->stack->cnt()) {
112 // $tag has fewer nestings (old: tabs) than stack,
113 // reduce stack to that tab count
114 while ($this->stack->cnt() > $level) {
115 $closetag = $this->stack->pop();
116 assert('$closetag != false');
117 $retvar .= "</$closetag>\n";
120 // if list type isn't the same,
121 // back up one more and push new tag
122 if ($tag && $tag != $this->stack->top()) {
123 $closetag = $this->stack->pop();
124 $retvar .= "</$closetag>" . $el->startTag() . "\n";
125 $this->stack->push($tag);
129 else {// $level > $this->stack->cnt()
130 // Test for and close top level elements which are not allowed to contain
131 // other block-level elements.
132 if ($this->stack->cnt() == 1 and
133 preg_match('/^(p|pre|h\d)$/i', $this->stack->top()))
135 $closetag = $this->stack->pop();
136 $retvar .= "</$closetag>";
139 // we add the diff to the stack
140 // stack might be zero
141 if ($this->stack->cnt() < $level) {
142 while ($this->stack->cnt() < $level - 1) {
143 // This is a bit of a hack:
145 // We're not nested deep enough, and have to make up some kind of block
146 // element to nest within.
148 // Currently, this can only happen for nested list element
149 // (either <ul> <ol> or <dl>). What we used to do here is
150 // to open extra lists of whatever type was requested.
151 // This would result in invalid HTML, since and list is
152 // not allowed to contain another list without first containing
153 // a list item. ("<ul><ul><li>Item</ul></ul>" is invalid.)
155 // So now, when we need extra list elements, we use a <dl>, and
156 // open it with an empty <dd>.
157 $stuff = $this->stack->cnt() % 2 == 0 ? 'dl' : 'dd';
158 $retvar .= "<$stuff>";
159 $this->stack->push($stuff);
162 $retvar .= $el->startTag() . "\n";
163 $this->stack->push($tag);
167 return $this->rawtoken($retvar);
171 * Start new list item element.
173 * This closes any currently open list items at the specified level or deeper,
174 * then opens a new list item element.
176 * @param $list_type string Type of list element to open. This should
177 * be one of 'dl', 'ol', or 'ul'.
179 * @param $level integer Nesting depth for list item. Should be a positive integer.
181 * @param $defn_term string Definition term. Specifies the contents for the
182 * <dt> element. Only used if $list_type is 'dl'.
184 * @return string HTML
186 function ListItem($list_type, $level, $defn_term = '')
188 $level = min($level, 10);
190 $retval = $this->SetHTMLMode($list_type, 2 * $level - 1);
191 if ($list_type == 'dl') {
192 $retval .= AsXML(HTML::dt(HTML::raw($defn_term)));
193 $retval .= $this->SetHTMLMode('dd', 2 * $level);
196 $retval .= $this->SetHTMLMode('li', 2 * $level);
202 /** Work horse and main loop.
204 * This function does the transform from wiki markup to HTML.
206 * Contains main-loop and calls transformer functions.
208 * @param $html string HTML header (if needed, otherwise '')
209 * (This string is prepended to the return value.)
211 * @param $content array Wiki markup as array of lines
213 * @return string HTML
215 function do_transform($html, $content)
217 global $FieldSeparator;
219 $this->content = $content;
220 $this->replacements = array();
221 $this->user_data = array();
223 // Loop over all lines of the page and apply transformation rules
224 $numlines = count($this->content);
225 for ($lnum = 0; $lnum < $numlines; $lnum++)
228 $this->linenumber = $lnum;
229 $line = $this->content[$lnum];
231 // blank lines clear the current mode (to force new paragraph)
232 if (!strlen($line) || $line == "\r") {
233 $html .= $this->SetHTMLMode('', 0);
239 // main loop applying all registered functions
240 // tokenizers, markup, html mode, ...
241 // functions are executed in order of registering
242 foreach ($this->trfrm_func as $trfrm) {
243 list($flags, $func, $regexp) = $trfrm;
245 // if HTMLmode is already set then skip all following
246 // WT_MODE_MARKUP functions
247 if ($this->mode_set && ($flags & WT_MODE_MARKUP) != 0)
250 if (!empty($regexp) && !preg_match("/$regexp/", $line))
253 // call registered function
254 if (($flags & WT_TOKENIZER) != 0)
255 $line = $this->tokenize($line, $regexp, $func);
257 $line = $func($line, $this);
260 $html .= $line . "\n";
263 $html .= $this->SetHTMLMode('', 0);
265 return new RawXml($this->untokenize($html));
267 // end do_transfrom()
269 // Register a new token.
270 function rawtoken($repl) {
271 global $FieldSeparator;
272 $tok = $FieldSeparator . sizeof($this->replacements) . $FieldSeparator;
273 $this->replacements[] = $repl;
277 // Register a new token.
278 function token($repl) {
279 return $this->rawtoken(AsXML($repl));
282 // helper function which does actual tokenizing
283 function tokenize($str, $pattern, $func) {
284 // Find any strings in $str that match $pattern and
285 // store them in $orig, replacing them with tokens
286 // starting at number $ntokens - returns tokenized string
288 while (preg_match("/^(.*?)($pattern)/", $str, $matches)) {
289 $str = substr($str, strlen($matches[0]));
290 $new .= $matches[1] . $this->token($func($matches[2], $this));
295 function untokenize($line) {
296 global $FieldSeparator;
298 $chunks = explode ($FieldSeparator, "$line ");
300 for ($i = 1; $i < count($chunks); $i += 2)
303 $line .= $this->replacements[$tok] . $chunks[$i + 1];
308 // end class WikiTransform
311 //////////////////////////////////////////////////////////
313 class WikiPageTransform
314 extends WikiTransform {
315 function WikiPageTransform() {
316 global $WikiNameRegexp, $AllowedProtocols, $request;
318 $this->WikiTransform();
320 // register functions
321 // functions are applied in order of registering
323 $this->register(WT_SIMPLE_MARKUP, 'wtm_plugin_link');
324 $this->register(WT_MODE_MARKUP, 'wtm_plugin');
326 $this->register(WT_TOKENIZER, 'wtt_doublebrackets', '\[\[');
327 $this->register(WT_TOKENIZER, 'wtt_footnotes', '^\[\d+\]');
328 $this->register(WT_TOKENIZER, 'wtt_footnoterefs', '\[\d+\]');
329 $this->register(WT_TOKENIZER, 'wtt_bracketlinks', '\[.+?\]');
330 $this->register(WT_TOKENIZER, 'wtt_urls',
331 "!?\b($AllowedProtocols):[^\s<>\[\]\"'()]*[^\s<>\[\]\"'(),.?]");
333 $map = InterWikiMap::GetMap($request);
334 $this->register(WT_TOKENIZER, 'wtt_interwikilinks',
335 pcre_fix_posix_classes("!?(?<![[:alnum:]])")
336 . $map->getRegexp() . ":[^\\s.,;?()]+");
338 $this->register(WT_TOKENIZER, 'wtt_bumpylinks', "!?$WikiNameRegexp");
340 if (function_exists('wtm_table')) {
341 $this->register(WT_MODE_MARKUP, 'wtm_table', '^\|');
343 $this->register(WT_SIMPLE_MARKUP, 'wtm_htmlchars');
344 $this->register(WT_SIMPLE_MARKUP, 'wtm_linebreak');
345 $this->register(WT_SIMPLE_MARKUP, 'wtm_bold_italics');
347 $this->register(WT_MODE_MARKUP, 'wtm_list_ul');
348 $this->register(WT_MODE_MARKUP, 'wtm_list_ol');
349 $this->register(WT_MODE_MARKUP, 'wtm_list_dl');
350 $this->register(WT_MODE_MARKUP, 'wtm_preformatted');
351 $this->register(WT_MODE_MARKUP, 'wtm_headings');
352 $this->register(WT_MODE_MARKUP, 'wtm_hr');
353 $this->register(WT_MODE_MARKUP, 'wtm_paragraph');
357 function do_transform ($lines, $class = 'WikiPageTransform') {
358 if (is_string($lines))
359 $lines = preg_split('/[ \t\r]*\n/', trim($lines));
362 return $trfm->do_transform('', $lines);
366 extends WikiTransform {
367 function LinkTransform() {
368 global $WikiNameRegexp, $AllowedProtocols, $request;
370 $this->WikiTransform();
372 // register functions
373 // functions are applied in order of registering
375 $this->register(WT_TOKENIZER, 'wtt_doublebrackets', '\[\[');
376 $this->register(WT_TOKENIZER, 'wtt_quotetoken', '\[\d+\]');
377 $this->register(WT_TOKENIZER, 'wtt_bracketlinks', '\[.+?\]');
378 $this->register(WT_TOKENIZER, 'wtt_urls',
379 "!?\b($AllowedProtocols):[^\s<>\[\]\"'()]*[^\s<>\[\]\"'(),.?]");
381 $map = InterWikiMap::GetMap($request);
382 if (function_exists('wtt_interwikilinks')) {
383 $this->register(WT_TOKENIZER, 'wtt_interwikilinks',
384 pcre_fix_posix_classes("!?(?<![[:alnum:]])")
385 . $map->getRegexp() . ":[^\\s.,;?()]+");
387 $this->register(WT_TOKENIZER, 'wtt_bumpylinks', "!?$WikiNameRegexp");
388 $this->register(WT_SIMPLE_MARKUP, 'wtm_htmlchars');
393 Requirements for functions registered to WikiTransform:
395 Signature: function wtm_xxxx($line, &$transform)
397 $line ... current line containing wiki markup
398 (Note: it may already contain HTML from other transform functions)
399 &$transform ... WikiTransform object -- public variables of this
400 object and their use see above.
402 Functions have to return $line (doesn't matter if modified or not)
403 All conversion should take place inside $line.
405 Tokenizer functions should use $transform->replacements to store
406 the replacement strings. Also, they have to keep track of
407 $transform->tokencounter. See functions below. Back substitution
408 of tokenized strings is done by do_transform().
413 //////////////////////////////////////////////////////////
414 // Tokenizer functions
417 function wtt_doublebrackets($match, &$trfrm)
422 function wtt_footnotes($match, &$trfrm)
424 // FIXME: should this set HTML mode?
425 $ftnt = trim(substr($match,1,-1)) + 0;
427 $html = HTML(HTML::br());
429 $fnlist = $trfrm->user_data['footnotes'][$ftnt];
430 if (!is_array($fnlist)) {
431 $html->pushContent($fntext);
434 $trfrm->user_data['footnotes'][$ftnt] = 'footnote_seen';
436 while (list($k, $anchor) = each($fnlist)) {
437 $html->pushContent(HTML::a(array("name" => "footnote-$ftnt",
438 "href" => "#$anchor",
439 "class" => "footnote-rev"),
447 function wtt_footnoterefs($match, &$trfrm)
449 $ftnt = trim(substr($match,1,-1)) + 0;
451 $footnote_definition_seen = false;
453 if (empty($trfrm->user_data['footnotes']))
454 $trfrm->user_data['footnotes'] = array();
455 if (empty($trfrm->user_data['footnotes'][$ftnt]))
456 $trfrm->user_data['footnotes'][$ftnt] = array();
457 else if (!is_array($trfrm->user_data['footnotes'][$ftnt]))
458 $footnote_definition_seen = true;
461 $link = HTML::a(array('href' => "#footnote-$ftnt"), "[$ftnt]");
462 if (!$footnote_definition_seen) {
463 $name = "footrev-$ftnt-" . count($trfrm->user_data['footnotes'][$ftnt]);
464 $link->setAttr('name', $name);
465 $trfrm->user_data['footnotes'][$ftnt][] = $name;
467 return HTML::sup(array('class' => 'footnote'), $link);
470 function wtt_bracketlinks($match, &$trfrm)
473 if (preg_match('/^\[\s*\]$/', $match))
476 $link = LinkBracketLink($match);
478 if ($link->isInlineElement())
482 return new RawXml("</p>" . $link->asXML() . "<p>");
486 // replace all URL's with tokens, so we don't confuse them
487 // with Wiki words later. Wiki words in URL's break things.
488 // URLs preceeded by a '!' are not linked
489 function wtt_urls($match, &$trfrm) {
490 return $match[0] == "!"
496 // Link InterWiki links
497 // These can be protected by a '!' like Wiki words.
498 function wtt_interwikilinks($match, &$trfrm) {
499 if ($match[0] == '!')
500 return substr($match, 1);
503 $map = InterWikiMap::GetMap($request);
504 return $map->link($match);
507 // Link Wiki words (BumpyText)
508 // Wikiwords preceeded by a '!' are not linked
509 function wtt_bumpylinks($match, &$trfrm) {
510 return $match[0] == "!" ? substr($match,1) : WikiLink($match, 'auto');
514 // Just quote the token.
515 function wtt_quotetoken($match, &$trfrm) {
521 // end of tokenizer functions
522 //////////////////////////////////////////////////////////
525 //////////////////////////////////////////////////////////
526 // basic simple markup functions
528 // escape HTML metachars
529 function wtm_htmlchars($line, &$transformer) {
530 return XmlElement::_quote($line);
533 // %%% are linebreaks
534 function wtm_linebreak($line, &$transformer) {
535 return str_replace('%%%', '<br />', $line);
539 function wtm_bold_italics($line, &$transformer) {
540 $line = preg_replace('|(__)(.*?)(__)|', '<strong>\2</strong>', $line);
541 $line = preg_replace("|('')(.*?)('')|", '<em>\2</em>', $line);
547 //////////////////////////////////////////////////////////
548 // some tokens to be replaced by (dynamic) content
550 // FIXME: some plugins are in-line (maybe?) and some are block level.
551 // Here we treat them all as inline, which will probably
552 // generate some minorly invalid HTML in some cases.
554 function wtm_plugin_link($line, &$transformer) {
555 // FIXME: is this good syntax?
556 global $request; // FIXME: make these non-global?
558 if (preg_match('/^(.*?)(<\?plugin-link\s+.*?\?>)(.*)$/', $line, $m)) {
559 list(, $prematch, $plugin_pi, $postmatch) = $m;
560 $loader = new WikiPluginLoader;
561 $html = $loader->expandPI($plugin_pi, $request);
562 $line = $prematch . $transformer->token($html) . $postmatch;
567 function wtm_plugin($line, &$transformer) {
568 // FIXME: is this good syntax?
569 global $request; // FIXME: make these non-global?
571 if (preg_match('/^<\?plugin(-form)?\s.*\?>\s*$/', $line)) {
572 $loader = new WikiPluginLoader;
573 $html = $loader->expandPI($line, $request);
574 $line = $transformer->SetHTMLMode('', 0) . $transformer->token($html);
580 //////////////////////////////////////////////////////////
581 // mode markup functions
584 // tabless markup for unordered, ordered, and dictionary lists
585 // ul/ol list types can be mixed, so we only look at the last
586 // character. Changes e.g. from "**#*" to "###*" go unnoticed.
587 // and wouldn't make a difference to the HTML layout anyway.
589 // unordered lists <UL>: "*"
590 // has to be registereed before list OL
591 function wtm_list_ul($line, &$trfrm) {
592 if (preg_match("/^([#*;]*\*)[^#]/", $line, $matches)) {
593 $numtabs = strlen($matches[1]);
594 $line = preg_replace("/^([#*]*\*)/", '', $line);
595 $line = $trfrm->ListItem('ul', $numtabs) . $line;
600 // ordered lists <OL>: "#"
601 function wtm_list_ol($line, &$trfrm) {
602 if (preg_match("/^([#*;]*\#)/", $line, $matches)) {
603 $numtabs = strlen($matches[1]);
604 $line = preg_replace("/^([#*]*\#)/", "", $line);
605 $line = $trfrm->ListItem('ol', $numtabs) . $line;
611 // definition lists <DL>: ";text:text"
612 function wtm_list_dl($line, &$trfrm) {
613 if (preg_match("/^([#*;]*;)(.*?):(.*$)/", $line, $matches)) {
614 $numtabs = strlen($matches[1]);
615 $line = $trfrm->ListItem('dl', $numtabs, $matches[2]) . $matches[3];
620 // mode: preformatted text, i.e. <pre>
621 function wtm_preformatted($line, &$trfrm) {
622 if (preg_match("/^\s+/", $line)) {
623 $line = $trfrm->SetHTMLMode('pre') . $line;
628 // mode: headings, i.e. <h1>, <h2>, <h3>
629 // lines starting with !,!!,!!! are headings
630 // Patch from steph/tara <tellme@climbtothestars.org>:
631 // use <h2>, <h3>, <h4> since <h1> is page title.
632 function wtm_headings($line, &$trfrm) {
633 if (preg_match("/^(!{1,3})[^!]/", $line, $whichheading)) {
634 if($whichheading[1] == '!') $heading = 'h4';
635 elseif($whichheading[1] == '!!') $heading = 'h3';
636 elseif($whichheading[1] == '!!!') $heading = 'h2';
637 $line = preg_replace("/^!+/", '', $line);
638 $line = $trfrm->SetHTMLMode($heading) . $line;
644 function wtm_table($line, &$trfrm)
647 while (preg_match('/^(\|+)(v*)([<>^]?)([^|]*)/', $line, $m))
649 $line = substr($line, strlen($m[0]));
653 if (strlen($m[1]) > 1)
654 $td->setAttr('colspan', strlen($m[1]));
655 if (strlen($m[2]) > 0)
656 $td->setAttr('rowspan', strlen($m[2]) + 1);
659 $td->setAttr('align', 'center');
660 else if ($m[3] == '>')
661 $td->setAttr('align', 'right');
663 $td->setAttr('align', 'left');
665 // FIXME: this is a hack: can't tokenize whole <td></td> since we
666 // haven't marked up italics, etc... yet
667 $row .= $trfrm->rawtoken($td->startTag() . " ");
669 $row .= $trfrm->rawtoken(" " . $td->endTag());
671 assert(empty($line));
672 $row = $trfrm->rawtoken("<tr>") . $row . $trfrm->rawtoken("</tr>");
674 return $trfrm->SetHTMLMode(array('table',
675 array('cellpadding' => 1,
681 // four or more dashes to <hr>
682 // Note this is of type WT_MODE_MARKUP becuase <hr>'s aren't
683 // allowed within <p>'s. (e.g. "<p><hr></p>" is not valid HTML.)
684 function wtm_hr($line, &$trfrm) {
685 if (preg_match('/^-{4,}(.*)$/', $line, $m)) {
686 $line = $trfrm->SetHTMLMode('', 0) . '<hr />';
688 $line .= $trfrm->SetHTMLMode('p') . $m[1];
693 // default mode: simple text paragraph
694 function wtm_paragraph($line, &$trfrm) {
695 return $trfrm->SetHTMLMode('p') . $line;
698 // (c-file-style: "gnu")
703 // c-hanging-comment-ender-p: nil
704 // indent-tabs-mode: nil