1 <?php rcs_id('$Id: transform.php,v 1.29 2001-12-12 23:38:53 dairiki Exp $');
2 require_once('lib/WikiPlugin.php');
4 define('WT_SIMPLE_MARKUP', 0);
5 define('WT_TOKENIZER', 1);
6 define('WT_MODE_MARKUP', 2);
8 define("ZERO_LEVEL", 0);
9 define("NESTED_LEVEL", 1);
13 // public variables (only meaningful during do_transform)
14 var $linenumber; // current linenumber
15 var $replacements; // storage for tokenized strings of current line
16 var $user_data; // can be used by the transformer functions
17 // to store miscellaneous data.
20 var $content; // wiki markup, array of lines
21 var $mode_set; // stores if a HTML mode for this line has been set
22 var $trfrm_func; // array of registered functions
23 var $stack; // stack for SetHTMLMode (keeping track of open tags)
26 function WikiTransform()
28 $this->trfrm_func = array();
29 $this->stack = new Stack;
33 * Register transformation functions
35 * This should be done *before* calling do_transform
37 * @param $type enum <dl>
38 * <dt>WT_MODE_MARKUP</dt>
39 * <dd>If one WT_MODE_MARKUP really sets the html mode, then
40 * all successive WT_MODE_MARKUP functions are skipped.</dd>
41 * <dt>WT_TOKENIZER</dt>
42 * <dd> The transformer function is called once for each match
43 * of the $regexp in the line. The matched values are tokenized
44 * to protect them from further transformation.</dd>
46 * @param $function string Function name
47 * @param $regexp string Required for WT_TOKENIZER functions.
48 * Optional for others. If given, the transformer function will only be
49 * called if the line matches the $regexp.
51 function register($type, $function, $regexp = false)
53 $this->trfrm_func[] = array ($type, $function, $regexp);
57 * Sets current mode like list, preformatted text, plain text
59 * Takes care of closing (open) tags
61 * This is a helper function used to keep track of what HTML
62 * block-level element we are currently processing.
63 * Block-level elements are things like paragraphs "<p>",
64 * pre-formatted text "<pre>", and the various list elements:
65 * "<ul>", "<ol>" and "<dl>". Now, SetHTMLMode is also used to
66 * keep track of "<li>" and "<dd>" elements. Note that some of these elements
67 * can be nested, while others can not. (In particular, according to
68 * the HTML 4.01 specification, a paragraph "<p>" element is not
69 * allowed to contain any other block-level elements. Also <pre>,
70 * <li>, <dt>, <dd>, <h1> ... have this same restriction.)
72 * SetHTMLMode generates whatever HTML is necessary to get us into
73 * the requested element type at the requested nesting level.
75 * @param $tag string Type of HTML element to open.
77 * If $tag is an array, $tag[0] gives the element type,
78 * and $tag[1] should be a hash containing attribute-value
79 * pairs for the element.
81 * If $tag is the empty string, all open elements (down to the
82 * level requested by $level) are closed. Use
83 * SetHTMLMode('',0) to close all open block-level elements.
85 * @param $level string Rrequested nesting level for current element.
86 * The nesting level for top level block is one (which is
88 * Nesting is arbitrary limited to 20 levels.
90 * @return string Returns the HTML markup to open the specified element.
92 function SetHTMLMode($tag, $level = 1)
102 $this->mode_set = 1; // in order to prevent other mode markup
107 // arbitrarily limit tag nesting
108 ExitWiki(gettext ("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>" . StartTag($tag, $args) . "\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 $el = $this->stack->cnt() % 2 == 0 ? 'dl' : 'dd';
159 $this->stack->push($el);
162 $retvar .= StartTag($tag, $args) . "\n";
163 $this->stack->push($tag);
167 return $this->token($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 .= Element('dt', $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 for (reset($this->trfrm_func);
243 list($flags, $func, $regexp) = current($this->trfrm_func);
244 next($this->trfrm_func)) {
246 // if HTMLmode is already set then skip all following
247 // WT_MODE_MARKUP functions
248 if ($this->mode_set && ($flags & WT_MODE_MARKUP) != 0)
251 if (!empty($regexp) && !preg_match("/$regexp/", $line))
254 // call registered function
255 if (($flags & WT_TOKENIZER) != 0)
256 $line = $this->tokenize($line, $regexp, $func);
258 $line = $func($line, $this);
261 $html .= $line . "\n";
264 $html .= $this->SetHTMLMode('', 0);
266 return $this->untokenize($html);
268 // end do_transfrom()
270 // Register a new token.
271 function token($repl) {
272 global $FieldSeparator;
273 $tok = $FieldSeparator . sizeof($this->replacements) . $FieldSeparator;
274 $this->replacements[] = $repl;
278 // helper function which does actual tokenizing
279 function tokenize($str, $pattern, $func) {
280 // Find any strings in $str that match $pattern and
281 // store them in $orig, replacing them with tokens
282 // starting at number $ntokens - returns tokenized string
284 while (preg_match("/^(.*?)($pattern)/", $str, $matches)) {
285 $str = substr($str, strlen($matches[0]));
286 $new .= $matches[1] . $this->token($func($matches[2], $this));
291 function untokenize($line) {
292 global $FieldSeparator;
294 $chunks = explode ($FieldSeparator, "$line ");
296 for ($i = 1; $i < count($chunks); $i += 2)
299 $line .= $this->replacements[$tok] . $chunks[$i + 1];
304 // end class WikiTransform
307 //////////////////////////////////////////////////////////
309 function do_transform ($lines) {
310 global $WikiNameRegexp, $AllowedProtocols, $InterWikiLinkRegexp;
312 if (is_string($lines))
313 $lines = preg_split('/[ \t\r]*\n/', trim($lines));
316 $transform = new WikiTransform;
318 // register functions
319 // functions are applied in order of registering
321 $transform->register(WT_SIMPLE_MARKUP, 'wtm_plugin_link');
322 $transform->register(WT_MODE_MARKUP, 'wtm_plugin');
324 $transform->register(WT_TOKENIZER, 'wtt_doublebrackets', '\[\[');
325 $transform->register(WT_TOKENIZER, 'wtt_footnotes', '^\[\d+\]');
326 $transform->register(WT_TOKENIZER, 'wtt_footnoterefs', '\[\d+\]');
327 $transform->register(WT_TOKENIZER, 'wtt_bracketlinks', '\[.+?\]');
328 $transform->register(WT_TOKENIZER, 'wtt_urls',
329 "!?\b($AllowedProtocols):[^\s<>\[\]\"'()]*[^\s<>\[\]\"'(),.?]");
331 if (function_exists('wtt_interwikilinks')) {
332 $transform->register(WT_TOKENIZER, 'wtt_interwikilinks',
333 pcre_fix_posix_classes("!?(?<![[:alnum:]])") .
334 "$InterWikiLinkRegexp:[^\\s.,;?()]+");
336 $transform->register(WT_TOKENIZER, 'wtt_bumpylinks', "!?$WikiNameRegexp");
338 if (function_exists('wtm_table')) {
339 $transform->register(WT_MODE_MARKUP, 'wtm_table', '^\|');
341 $transform->register(WT_SIMPLE_MARKUP, 'wtm_htmlchars');
342 $transform->register(WT_SIMPLE_MARKUP, 'wtm_linebreak');
343 $transform->register(WT_SIMPLE_MARKUP, 'wtm_bold_italics');
345 $transform->register(WT_MODE_MARKUP, 'wtm_list_ul');
346 $transform->register(WT_MODE_MARKUP, 'wtm_list_ol');
347 $transform->register(WT_MODE_MARKUP, 'wtm_list_dl');
348 $transform->register(WT_MODE_MARKUP, 'wtm_preformatted');
349 $transform->register(WT_MODE_MARKUP, 'wtm_headings');
350 $transform->register(WT_MODE_MARKUP, 'wtm_hr');
351 $transform->register(WT_MODE_MARKUP, 'wtm_paragraph');
353 //$html = $transform->do_transform($html, $pagehash['content']);
354 return $transform->do_transform('', $lines);
358 Requirements for functions registered to WikiTransform:
360 Signature: function wtm_xxxx($line, &$transform)
362 $line ... current line containing wiki markup
363 (Note: it may already contain HTML from other transform functions)
364 &$transform ... WikiTransform object -- public variables of this
365 object and their use see above.
367 Functions have to return $line (doesn't matter if modified or not)
368 All conversion should take place inside $line.
370 Tokenizer functions should use $transform->replacements to store
371 the replacement strings. Also, they have to keep track of
372 $transform->tokencounter. See functions below. Back substitution
373 of tokenized strings is done by do_transform().
378 //////////////////////////////////////////////////////////
379 // Tokenizer functions
382 function wtt_doublebrackets($match, &$trfrm)
387 function wtt_footnotes($match, &$trfrm)
389 // FIXME: should this set HTML mode?
390 $ftnt = trim(substr($match,1,-1)) + 0;
392 $html = Element('br');
394 $fnlist = $trfrm->user_data['footnotes'][$ftnt];
395 if (!is_array($fnlist))
396 return $html . $fntext;
398 $trfrm->user_data['footnotes'][$ftnt] = 'footnote_seen';
400 while (list($k, $anchor) = each($fnlist))
402 $html .= Element("a", array("name" => "footnote-$ftnt",
403 "href" => "#$anchor",
404 "class" => "footnote-rev"),
411 function wtt_footnoterefs($match, &$trfrm)
413 $ftnt = trim(substr($match,1,-1)) + 0;
415 $footnote_definition_seen = false;
417 if (empty($trfrm->user_data['footnotes']))
418 $trfrm->user_data['footnotes'] = array();
419 if (empty($trfrm->user_data['footnotes'][$ftnt]))
420 $trfrm->user_data['footnotes'][$ftnt] = array();
421 else if (!is_array($trfrm->user_data['footnotes'][$ftnt]))
422 $footnote_definition_seen = true;
425 $args['href'] = "#footnote-$ftnt";
426 if (!$footnote_definition_seen)
428 $args['name'] = "footrev-$ftnt-" .
429 count($trfrm->user_data['footnotes'][$ftnt]);
430 $trfrm->user_data['footnotes'][$ftnt][] = $args['name'];
433 return Element('sup', array('class' => 'footnote'),
434 QElement("a", $args, "[$ftnt]"));
437 function wtt_bracketlinks($match, &$trfrm)
439 $link = ParseAndLink($match);
440 if (strstr($link['link'], "</form>")) {
441 // FIXME: BIG HACK: see note in wtm_plugin.
442 return "</p>" . $link['link'] . "<p>";
444 return $link["link"];
449 // replace all URL's with tokens, so we don't confuse them
450 // with Wiki words later. Wiki words in URL's break things.
451 // URLs preceeded by a '!' are not linked
452 function wtt_urls($match, &$trfrm)
454 if ($match[0] == "!")
455 return htmlspecialchars(substr($match,1));
456 return LinkURL($match);
459 // Link Wiki words (BumpyText)
460 // Wikiwords preceeded by a '!' are not linked
461 function wtt_bumpylinks($match, &$trfrm)
464 if ($match[0] == "!")
465 return htmlspecialchars(substr($match,1));
466 return LinkWikiWord($match);
469 // end of tokenizer functions
470 //////////////////////////////////////////////////////////
473 //////////////////////////////////////////////////////////
474 // basic simple markup functions
476 // escape HTML metachars
477 function wtm_htmlchars($line, &$transformer)
479 $line = str_replace('&', '&', $line);
480 $line = str_replace('>', '>', $line);
481 $line = str_replace('<', '<', $line);
486 // %%% are linebreaks
487 function wtm_linebreak($line, &$transformer) {
488 return str_replace('%%%', Element('br'), $line);
492 function wtm_bold_italics($line, &$transformer) {
493 $line = preg_replace('|(__)(.*?)(__)|', '<strong>\2</strong>', $line);
494 $line = preg_replace("|('')(.*?)('')|", '<em>\2</em>', $line);
500 //////////////////////////////////////////////////////////
501 // some tokens to be replaced by (dynamic) content
503 // FIXME: some plugins are in-line (maybe?) and some are block level.
504 // Here we treat them all as inline, which will probably
505 // generate some minorly invalid HTML in some cases.
507 function wtm_plugin_link($line, &$transformer) {
508 // FIXME: is this good syntax?
509 global $dbi, $request; // FIXME: make these non-global?
511 if (preg_match('/^(.*?)(<\?plugin-link\s+.*?\?>)(.*)$/', $line, $m)) {
512 list(, $prematch, $plugin_pi, $postmatch) = $m;
513 $loader = new WikiPluginLoader;
514 $html = $loader->expandPI($plugin_pi, $dbi, $request);
515 $line = $prematch . $transformer->token($html) . $postmatch;
520 function wtm_plugin($line, &$transformer) {
521 // FIXME: is this good syntax?
522 global $dbi, $request; // FIXME: make these non-global?
524 if (preg_match('/^<\?plugin(-form)?\s.*\?>\s*$/', $line)) {
525 $loader = new WikiPluginLoader;
526 $html = $loader->expandPI($line, $dbi, $request);
527 $line = $transformer->SetHTMLMode('', 0) . $transformer->token($html);
533 //////////////////////////////////////////////////////////
534 // mode markup functions
537 // tabless markup for unordered, ordered, and dictionary lists
538 // ul/ol list types can be mixed, so we only look at the last
539 // character. Changes e.g. from "**#*" to "###*" go unnoticed.
540 // and wouldn't make a difference to the HTML layout anyway.
542 // unordered lists <UL>: "*"
543 // has to be registereed before list OL
544 function wtm_list_ul($line, &$trfrm) {
545 if (preg_match("/^([#*;]*\*)[^#]/", $line, $matches)) {
546 $numtabs = strlen($matches[1]);
547 $line = preg_replace("/^([#*]*\*)/", '', $line);
548 $line = $trfrm->ListItem('ul', $numtabs) . $line;
553 // ordered lists <OL>: "#"
554 function wtm_list_ol($line, &$trfrm) {
555 if (preg_match("/^([#*;]*\#)/", $line, $matches)) {
556 $numtabs = strlen($matches[1]);
557 $line = preg_replace("/^([#*]*\#)/", "", $line);
558 $line = $trfrm->ListItem('ol', $numtabs) . $line;
564 // definition lists <DL>: ";text:text"
565 function wtm_list_dl($line, &$trfrm) {
566 if (preg_match("/^([#*;]*;)(.*?):(.*$)/", $line, $matches)) {
567 $numtabs = strlen($matches[1]);
568 $line = $trfrm->ListItem('dl', $numtabs, $matches[2]) . $matches[3];
573 // mode: preformatted text, i.e. <pre>
574 function wtm_preformatted($line, &$trfrm) {
575 if (preg_match("/^\s+/", $line)) {
576 $line = $trfrm->SetHTMLMode('pre') . $line;
581 // mode: headings, i.e. <h1>, <h2>, <h3>
582 // lines starting with !,!!,!!! are headings
583 // Patch from steph/tara <tellme@climbtothestars.org>:
584 // use <h2>, <h3>, <h4> since <h1> is page title.
585 function wtm_headings($line, &$trfrm) {
586 if (preg_match("/^(!{1,3})[^!]/", $line, $whichheading)) {
587 if($whichheading[1] == '!') $heading = 'h4';
588 elseif($whichheading[1] == '!!') $heading = 'h3';
589 elseif($whichheading[1] == '!!!') $heading = 'h2';
590 $line = preg_replace("/^!+/", '', $line);
591 $line = $trfrm->SetHTMLMode($heading) . $line;
597 function wtm_table($line, &$trfrm)
600 while (preg_match('/^(\|+)(v*)([<>^]?)([^|]*)/', $line, $m))
602 $line = substr($line, strlen($m[0]));
605 if (strlen($m[1]) > 1)
606 $td['colspan'] = strlen($m[1]);
607 if (strlen($m[2]) > 0)
608 $td['rowspan'] = strlen($m[2]) + 1;
611 $td['align'] = 'center';
612 else if ($m[3] == '>')
613 $td['align'] = 'right';
615 $td['align'] = 'left';
617 $row .= $trfrm->token(StartTag('td', $td) . " ");
619 $row .= $trfrm->token(" </td>");
621 assert(empty($line));
622 $row = $trfrm->token("<tr>") . $row . $trfrm->token("</tr>");
624 return $trfrm->SetHTMLMode(array('table',
625 array(//'align' => 'left',
632 // four or more dashes to <hr>
633 // Note this is of type WT_MODE_MARKUP becuase <hr>'s aren't
634 // allowed within <p>'s. (e.g. "<p><hr></p>" is not valid HTML.)
635 function wtm_hr($line, &$trfrm) {
636 if (preg_match('/^-{4,}(.*)$/', $line, $m)) {
637 $line = $trfrm->SetHTMLMode('', 0) . Element('hr');
639 $line .= $trfrm->SetHTMLMode('p') . $m[1];
644 // default mode: simple text paragraph
645 function wtm_paragraph($line, &$trfrm) {
646 $line = $trfrm->SetHTMLMode('p') . $line;
650 // (c-file-style: "gnu")
655 // c-hanging-comment-ender-p: nil
656 // indent-tabs-mode: nil