1 <?php rcs_id('$Id: BlockParser.php,v 1.9 2002-01-28 18:49:08 dairiki Exp $');
2 /* Copyright (C) 2002, Geoffrey T. Dairiki <dairiki@dairiki.org>
4 * This file is part of PhpWiki.
6 * PhpWiki is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
11 * PhpWiki is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with PhpWiki; if not, write to the Free Software
18 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20 require_once('lib/HtmlElement.php');
22 require_once('lib/transform.php');
25 extends WikiTransform {
26 function InlineTransform() {
27 global $WikiNameRegexp, $AllowedProtocols, $InterWikiLinkRegexp;
29 $this->WikiTransform();
32 // functions are applied in order of registering
34 $this->register(WT_SIMPLE_MARKUP, 'wtm_plugin_link');
36 $this->register(WT_TOKENIZER, 'wtt_doublebrackets', '\[\[');
37 //$this->register(WT_TOKENIZER, 'wtt_footnotes', '^\[\d+\]');
38 //$this->register(WT_TOKENIZER, 'wtt_footnoterefs', '\[\d+\]');
39 $this->register(WT_TOKENIZER, 'wtt_bracketlinks', '\[.+?\]');
40 $this->register(WT_TOKENIZER, 'wtt_urls',
41 "!?\b($AllowedProtocols):[^\s<>\[\]\"'()]*[^\s<>\[\]\"'(),.?]");
43 if (function_exists('wtt_interwikilinks')) {
44 $this->register(WT_TOKENIZER, 'wtt_interwikilinks',
45 pcre_fix_posix_classes("!?(?<![[:alnum:]])") .
46 "$InterWikiLinkRegexp:[^\\s.,;?()]+");
48 $this->register(WT_TOKENIZER, 'wtt_bumpylinks', "!?$WikiNameRegexp");
50 $this->register(WT_SIMPLE_MARKUP, 'wtm_htmlchars');
51 $this->register(WT_SIMPLE_MARKUP, 'wtm_linebreak');
52 $this->register(WT_SIMPLE_MARKUP, 'wtm_bold_italics');
56 function TransformInline ($text) {
57 // The old transform code does funny things with trailing
60 $trfm = new InlineTransform;
61 preg_match('/\s*$/', $text, $m);
63 // This "\n" -> "\r" hackage is to fool the old transform code
64 // into continuing italics across lines.
65 $in = str_replace("\n", "\r", $text);
66 $out = preg_replace('/\s*$/', '', AsXML($trfm->do_transform('', array($in))));
67 $out = str_replace("\r", "\n", $out);
71 if (false && $out != $text) {
72 echo(" IN <pre>'" . htmlspecialchars($text) . "'</pre><br>\n");
73 echo("OUT <pre>'" . htmlspecialchars($out) . "'</pre><br>\n");
75 return new RawXml($out);
79 ////////////////////////////////////////////////////////////////
82 define("BLOCK_NEVER_TIGHTEN", 0);
83 define("BLOCK_NOTIGHTEN_AFTER", 1);
84 define("BLOCK_NOTIGHTEN_BEFORE", 2);
85 define("BLOCK_NOTIGHTEN_EITHER", 3);
94 function parse (&$input, $tighten_mode = BLOCK_NEVER_TIGHTEN) {
97 for ($block = BlockParser::_nextBlock($input); $block; $block = $nextBlock) {
98 while ($nextBlock = BlockParser::_nextBlock($input)) {
99 // Attempt to merge current with following block.
100 if (! $block->merge($nextBlock))
101 break; // can't merge
104 $content->pushContent($block->finish($tighten_mode));
109 function _nextBlock (&$input) {
110 global $Block_BlockTypes;
115 foreach ($Block_BlockTypes as $type) {
116 if ($m = $input->match($type->_re)) {
117 BlockParser::_debug('>', get_class($type), $input);
120 $block->_followsBreak = $input->atBreak();
121 if (!$block->_parse($input, $m)) {
122 BlockParser::_debug('[', "_parse failed", $input);
125 $block->_preceedsBreak = $input->eatSpace();
126 BlockParser::_debug('<', get_class($type), $input);
131 if ($input->getDepth() == 0) {
132 // We should never get here.
133 //preg_match('/.*/A', substr($this->_text, $this->_pos), $m);// get first line
134 trigger_error("Couldn't match block: '".rawurlencode($m[0])."'", E_USER_NOTICE);
136 //FIXME:$this->_debug("no match");
140 function _debug ($tab, $msg, $input) {
143 $tab = str_repeat($tab, $input->getDepth() + 1);
144 printXML(HTML::div("$tab $msg: at: '",
145 HTML::tt($input->where()),
151 class BlockParser_Match {
152 function BlockParser_Match ($match_data) {
153 $this->_m = $match_data;
156 function getPrefix () {
160 function getMatch ($n = 0) {
161 $text = $this->_m[$n + 2];
162 //if (preg_match('/\n./s', $text)) {
163 $prefix = $this->getPrefix();
164 $text = str_replace("\n$prefix", "\n", $text);
171 class BlockParser_Input {
173 function BlockParser_Input ($text) {
174 $this->_text = $text;
178 // Expand leading tabs.
179 // FIXME: do this better.
181 // We want to ensure the only characters matching \s are ' ' and "\n".
183 $this->_text = preg_replace('/(?![ \n])\s/', ' ', $this->_text);
184 assert(!preg_match('/(?![ \n])\s/', $this->_text));
185 if (!preg_match('/\n$/', $this->_text))
186 $this->_text .= "\n";
188 $this->_set_prefix ('');
189 $this->_atBreak = false;
193 function _set_prefix ($prefix, $next_prefix = false) {
194 if ($next_prefix === false)
195 $next_prefix = $prefix;
197 $this->_prefix = $prefix;
198 $this->_next_prefix = $next_prefix;
200 $this->_regexp_cache = array();
202 $blank = "(:?$prefix)?\s*\n";
203 $this->_blank_pat = "/$blank/A";
204 $this->_eof_pat = "/\\Z|(?!$blank|${prefix}.)/A";
208 return preg_match($this->_eof_pat, substr($this->_text, $this->_pos));
211 function match ($regexp) {
212 $cache = &$this->_regexp_cache;
213 if (!isset($cache[$regexp])) {
214 // Fix up any '^'s in pattern (add our prefix)
215 $re = preg_replace('/(?<! [ [ \\\\ ]) \^ /x',
216 '^' . $this->_next_prefix, $regexp);
218 // Fix any match backreferences (like '\1').
219 $re = preg_replace('/(?<= [^ \\\\ ] [ \\\\ ] )( \\d+ )/ex', "'\\1' + 2", $re);
221 $re = "/(" . $this->_prefix . ")($re)/Am";
222 $cache[$regexp] = $re;
225 $re = $cache[$regexp];
227 if (preg_match($re, substr($this->_text, $this->_pos), $m)) {
228 return new BlockParser_Match($m);
233 function accept ($match) {
234 $text = $match->_m[0];
236 assert(substr($this->_text, $this->_pos, strlen($text)) == $text);
237 $this->_pos += strlen($text);
240 assert(preg_match("/\n$/", $text));
242 if ($this->_next_prefix != $this->_prefix)
243 $this->_set_prefix($this->_next_prefix);
245 $this->_atBreak = false;
250 * Consume blank lines.
252 * @return bool True if any blank lines where comsumed.
254 function eatSpace () {
255 if (preg_match($this->_blank_pat, substr($this->_text, $this->_pos), $m)) {
256 $this->_pos += strlen($m[0]);
257 if ($this->_next_prefix != $this->_prefix)
258 $this->_set_prefix($this->_next_prefix);
259 $this->_atBreak = true;
261 while (preg_match($this->_blank_pat, substr($this->_text, $this->_pos), $m)) {
262 $this->_pos += strlen($m[0]);
266 return $this->_atBreak;
269 function atBreak () {
270 return $this->_atBreak;
273 function getDepth () {
274 return $this->_depth;
279 if (($m = $this->match('.*\n')))
280 return sprintf('[%s]%s', $m->getPrefix(), $m->getMatch());
284 function subBlock ($initial_prefix, $subsequent_prefix = false) {
285 if ($subsequent_prefix === false)
286 $subsequent_prefix = $initial_prefix;
288 return new BlockParser_InputSubBlock ($this, $initial_prefix, $subsequent_prefix);
292 class BlockParser_InputSubBlock extends BlockParser_Input
294 function BlockParser_InputSubBlock (&$block, $initial_prefix, $subsequent_prefix) {
295 $this->_text = &$block->_text;
296 $this->_pos = &$block->_pos;
297 $this->_atBreak = &$block->_atBreak;
299 $this->_depth = $block->_depth + 1;
301 $this->_set_prefix($block->_prefix . $initial_prefix,
302 $block->_next_prefix . $subsequent_prefix);
312 var $_followsBreak = false;
313 var $_preceedsBreak = false;
314 var $_content = array();
317 function _parse (&$input, $match) {
318 trigger_error('pure virtual', E_USER_ERROR);
321 function _pushContent ($c) {
323 $c = func_get_args();
325 $this->_content[] = $x;
328 function isTerminal () {
332 function merge ($followingBlock) {
336 function finish (/*$tighten*/) {
337 return new HtmlElement($this->_tag, $this->_attr, $this->_content);
342 class CompoundBlock extends Block
344 function isTerminal () {
350 class Block_blockquote extends CompoundBlock
352 var $_tag ='blockquote';
354 var $_re = '\ +(?=\S)';
356 function _parse (&$input, $m) {
357 $indent = $m->getMatch();
358 $this->_depth = strlen($indent);
359 $this->_content = BlockParser::parse($input->subBlock($indent),
360 BLOCK_NOTIGHTEN_EITHER);
364 function merge ($nextBlock) {
365 if (get_class($nextBlock) != 'block_blockquote')
367 assert ($nextBlock->_depth < $this->_depth);
369 $content = $nextBlock->_content;
370 array_unshift($content, $this->finish());
371 $this->_content = $content;
376 class Block_list extends CompoundBlock
378 //var $_tag = 'ol' or 'ul';
379 var $_re = '\ {0,4}([*+#]|-(?!-)|o(?=\ ))\ *(?=\S)';
381 function _parse (&$input, $m) {
382 // A list as the first content in a list is not allowed.
385 // Should markup as <ul><li>* Item</li></ul>,
386 // not <ul><li><ul><li>Item</li></ul>/li></ul>.
388 if (preg_match('/[-*o+#;]\s*$/', $m->getPrefix()))
391 $prefix = $m->getMatch();
392 $leader = preg_quote($prefix, '/');
393 $indent = sprintf("\\ {%d}", strlen($prefix));
395 $bullet = $m->getMatch(1);
396 $this->_tag = $bullet == '#' ? 'ol' : 'ul';
398 $text = $input->subBlock($leader, $indent);
399 $content = BlockParser::parse($text, BLOCK_NOTIGHTEN_AFTER);
400 $this->_pushContent(HTML::li(false, $content));
404 function merge ($nextBlock) {
405 if (!isa($nextBlock, 'Block_list') || $this->_tag != $nextBlock->_tag)
408 $this->_pushContent($nextBlock->_content);
414 class Block_dl extends Block_list
417 var $_re = '(\ {0,4})([^\s!].*):\s*?\n(?=(?:\s*^)+(\1\ +)\S)';
418 // 1-------12--------2 3-----3
420 function _parse (&$input, $m) {
421 $term = TransformInline(rtrim($m->getMatch(2)));
422 $indent = $m->getMatch(3);
426 $this->_pushContent(HTML::dt(false, $term),
428 BlockParser::parse($input->subBlock($indent),
429 BLOCK_NOTIGHTEN_AFTER)));
434 class Block_table_dl_row extends HtmlElement
436 function Block_table_dl_row ($defn) {
437 $this->HtmlElement('tr', /*array('valign' => 'top'), */
438 HTML::td(false, $defn));
442 function setWidth ($ncols) {
443 assert ($ncols >= $this->_ncols);
444 if ($ncols <= $this->_ncols)
446 $last_td = &$this->_content[count($this->_content) - 1];
447 $span = max(1, (int)$last_td->getAttr('colspan'));
448 $last_td->setAttr('colspan', $span + $ncols - $this->_ncols);
449 $this->_ncols = $ncols;
452 function setTerm ($term, $rowspan = 1) {
453 if ($term->isEmpty())
456 $th = HTML::th(/*array('align' => 'right'),*/ $term);
458 $th->setAttr('rowspan', $rowspan);
459 $this->unshiftContent($th);
463 class Block_table_dl extends Block_list
466 var $_attr = array('class' => 'wiki-dl-table',
467 'border' => 2, // FIXME: CSS?
472 var $_re = '(\ {0,4})((?![\s!]).*)?[|]\s*?\n(?=(?:\s*^)+(\1\ +)\S)';
473 // 1-------12-----------2 3-----3
475 function _parse (&$input, $m) {
476 $term = TransformInline(rtrim($m->getMatch(2)));
477 $indent = $m->getMatch(3);
480 $defn = BlockParser::parse($input->subBlock($indent),
481 BLOCK_NOTIGHTEN_AFTER);
483 $this->_pushDefinition($term, $defn);
487 function _pushDefinition ($term, $defn) {
488 if (!is_array($defn))
489 $defn = array($defn);
494 foreach ($defn as $item) {
495 if (! isa($item, 'HtmlElement')
496 || $item->getTag() != 'table'
497 || $item->getAttr('class') != 'wiki-dl-table') {
504 $rows[] = new Block_table_dl_row($grp);
509 foreach ($subtable->getContent() as $tr) {
516 $rows[] = new Block_table_dl_row($grp);
518 $nrows = count($rows);
519 $rows[0]->setTerm($term, $nrows);
520 $this->_pushContent($rows);
524 $rows = &$this->_content;
527 foreach ($rows as $tr)
528 $ncols = max($ncols, $tr->_ncols);
529 foreach ($rows as $key => $tr)
530 $rows[$key]->setWidth($ncols);
532 return parent::finish();
536 class Block_oldlists extends Block_list
538 //var $_tag = 'ol', 'ul', or 'dl';
539 var $_re = '(?:([*#])|;(.*):).*?(?=\S)';
542 function _parse (&$input, $m) {
543 if (!preg_match('/[*#;]*$/A', $m->getPrefix()))
546 $prefix = $m->getMatch();
548 $leader = preg_quote($prefix, '/');
550 $oldindent = '[*#;](?=[#*]|;.*:.*?\S)';
551 $newindent = sprintf('\\ {%d}', strlen($prefix));
552 $indent = "(?:$oldindent|$newindent)";
554 $bullet = $m->getMatch(1);
556 $this->_tag = $bullet == '*' ? 'ul' : 'ol';
561 $term = trim($m->getMatch(2));
563 $this->_pushContent(HTML::dt(false, TransformInline($term)));
567 $item->pushContent(BlockParser::parse($input->subBlock($leader, $indent),
568 BLOCK_NOTIGHTEN_AFTER));
569 $this->_pushContent($item);
574 class Block_pre extends Block
577 var $_re = '<(pre|verbatim)>(.*?(?:\s*\n^.*?)*?)(?<!~)<\/\1>\s*?\n';
578 // 1------------1 2------------------2
580 function _parse (&$input, $m) {
583 $text = $m->getMatch(2);
584 $tag = $m->getMatch(1);
587 $text = TransformInline($text);
589 $this->_pushContent($text);
594 class Block_plugin extends Block
597 var $_attr = array('class' => 'plugin');
598 var $_re = '<\?plugin(?:-form)?.*?(?:\n^.*?)*?(?<!~)\?>\s*?\n';
600 function _parse (&$input, $m) {
602 $loader = new WikiPluginLoader;
604 $this->_pushContent($loader->expandPI($m->getMatch(), $request));
609 class Block_hr extends Block
612 var $_re = '-{4,}\s*?\n';
614 function _parse (&$input, $m) {
620 class Block_heading extends Block
622 var $_re = '(!{1,3})(.*)\n';
624 function _parse (&$input, $m) {
626 $this->_tag = "h" . (5 - strlen($m->getMatch(1)));
627 $this->_pushContent(TransformInline(trim($m->getMatch(2))));
632 class Block_p extends Block
637 function _parse (&$input, $m) {
638 $this->_text = $m->getMatch();
643 function merge ($nextBlock) {
644 if ($this->_preceedsBreak || get_class($nextBlock) != 'block_p')
647 $this->_text .= $nextBlock->_text;
648 $this->_preceedsBreak = $nextBlock->_preceedsBreak;
652 function finish ($tighten) {
653 $this->_pushContent(TransformInline(trim($this->_text)));
655 if ($this->_followsBreak && ($tighten & BLOCK_NOTIGHTEN_AFTER) != 0)
657 elseif ($this->_preceedsBreak && ($tighten & BLOCK_NOTIGHTEN_BEFORE) != 0)
660 return $tighten ? $this->_content : parent::finish();
664 class Block_email_blockquote extends CompoundBlock
666 // FIXME: move CSS to CSS.
667 var $_tag ='blockquote';
668 var $_attr = array('style' => 'border-left-width: medium; border-left-color: #0f0; border-left-style: ridge; padding-left: 1em; margin-left: 0em; margin-right: 0em;');
672 function _parse (&$input, $m) {
673 $prefix = $m->getMatch();
674 $indent = "(?:$prefix|>(?=\s*?\n))";
675 $this->_content = BlockParser::parse($input->subBlock($indent),
676 BLOCK_NOTIGHTEN_EITHER);
681 ////////////////////////////////////////////////////////////////
686 $GLOBALS['Block_BlockTypes'] = array(new Block_oldlists,
690 new Block_blockquote,
694 new Block_email_blockquote,
698 // FIXME: This is temporary, too...
699 function NewTransform ($text) {
703 // Expand leading tabs.
704 // FIXME: do this better. also move it...
705 $text = preg_replace('/^\ *[^\ \S\n][^\S\n]*/me', "str_repeat(' ', strlen('\\0'))", $text);
706 assert(!preg_match('/^\ *\t/', $text));
708 $input = new BlockParser_Input($text);
709 return BlockParser::parse($input);
714 function TransformRevision ($revision) {
715 if ($revision->get('markup') == 'new') {
716 return NewTransform($revision->getPackedContent());
719 return do_transform($revision->getContent());
724 // (c-file-style: "gnu")
729 // c-hanging-comment-ender-p: nil
730 // indent-tabs-mode: nil