]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/BlockParser.php
get_class case-sensitivity issues
[SourceForge/phpwiki.git] / lib / BlockParser.php
1 <?php rcs_id('$Id: BlockParser.php,v 1.47 2004-06-20 15:30:04 rurban Exp $');
2 /* Copyright (C) 2002, Geoffrey T. Dairiki <dairiki@dairiki.org>
3  *
4  * This file is part of PhpWiki.
5  * 
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.
10  * 
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.
15  * 
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
19  */
20 require_once('lib/HtmlElement.php');
21 require_once('lib/CachedMarkup.php');
22 require_once('lib/InlineParser.php');
23
24 ////////////////////////////////////////////////////////////////
25 //
26 //
27
28 /**
29  * Deal with paragraphs and proper, recursive block indents 
30  * for the new style markup (version 2)
31  *
32  * Everything which goes over more than line:
33  * automatic lists, UL, OL, DL, table, blockquote, verbatim, 
34  * p, pre, plugin, ...
35  *
36  * FIXME:
37  *  Still to do:
38  *    (old-style) tables
39  * FIXME: unify this with the RegexpSet in InlineParser.
40  *
41  * FIXME: This is very php5 sensitive: It was fixed for 1.3.9, 
42  *        but is again broken with the 1.3.11 
43  *        allow_call_time_pass_reference clean fixes
44  *
45  * @package Markup
46  * @author: Geoffrey T. Dairiki 
47  */
48
49 /**
50  * Return type from RegexpSet::match and RegexpSet::nextMatch.
51  *
52  * @see RegexpSet
53  */
54 class AnchoredRegexpSet_match {
55     /**
56      * The matched text.
57      */
58     var $match;
59
60     /**
61      * The text following the matched text.
62      */
63     var $postmatch;
64
65     /**
66      * Index of the regular expression which matched.
67      */
68     var $regexp_ind;
69 }
70
71 /**
72  * A set of regular expressions.
73  *
74  * This class is probably only useful for InlineTransformer.
75  */
76 class AnchoredRegexpSet
77 {
78     /** Constructor
79      *
80      * @param $regexps array A list of regular expressions.  The
81      * regular expressions should not include any sub-pattern groups
82      * "(...)".  (Anonymous groups, like "(?:...)", as well as
83      * look-ahead and look-behind assertions are fine.)
84      */
85     function AnchoredRegexpSet ($regexps) {
86         $this->_regexps = $regexps;
87         $this->_re = "/((" . join(")|(", $regexps) . "))/Ax";
88     }
89
90     /**
91      * Search text for the next matching regexp from the Regexp Set.
92      *
93      * @param $text string The text to search.
94      *
95      * @return object  A RegexpSet_match object, or false if no match.
96      */
97     function match ($text) {
98         if (! preg_match($this->_re, $text, $m)) {
99             return false;
100         }
101         
102         $match = new AnchoredRegexpSet_match;
103         $match->postmatch = substr($text, strlen($m[0]));
104         $match->match = $m[1];
105         $match->regexp_ind = count($m) - 3;
106         return $match;
107     }
108
109     /**
110      * Search for next matching regexp.
111      *
112      * Here, 'next' has two meanings:
113      *
114      * Match the next regexp(s) in the set, at the same position as the last match.
115      *
116      * If that fails, match the whole RegexpSet, starting after the position of the
117      * previous match.
118      *
119      * @param $text string Text to search.
120      *
121      * @param $prevMatch A RegexpSet_match object
122      *
123      * $prevMatch should be a match object obtained by a previous
124      * match upon the same value of $text.
125      *
126      * @return object  A RegexpSet_match object, or false if no match.
127      */
128     function nextMatch ($text, $prevMatch) {
129         // Try to find match at same position.
130         $regexps = array_slice($this->_regexps, $prevMatch->regexp_ind + 1);
131         if (!$regexps) {
132             return false;
133         }
134
135         $pat= "/ ( (" . join(')|(', $regexps) . ") ) /Axs";
136
137         if (! preg_match($pat, $text, $m)) {
138             return false;
139         }
140         
141         $match = new AnchoredRegexpSet_match;
142         $match->postmatch = substr($text, strlen($m[0]));
143         $match->match = $m[1];
144         $match->regexp_ind = count($m) - 3 + $prevMatch->regexp_ind + 1;;
145         return $match;
146     }
147 }
148
149
150     
151 class BlockParser_Input {
152
153     function BlockParser_Input ($text) {
154         
155         // Expand leading tabs.
156         // FIXME: do this better.
157         //
158         // We want to ensure the only characters matching \s are ' ' and "\n".
159         //
160         $text = preg_replace('/(?![ \n])\s/', ' ', $text);
161         assert(!preg_match('/(?![ \n])\s/', $text));
162
163         $this->_lines = preg_split('/[^\S\n]*\n/', $text);
164         $this->_pos = 0;
165
166         // Strip leading blank lines.
167         while ($this->_lines and ! $this->_lines[0])
168             array_shift($this->_lines);
169         $this->_atSpace = false;
170     }
171
172     function skipSpace () {
173         $nlines = count($this->_lines);
174         while (1) {
175             if ($this->_pos >= $nlines) {
176                 $this->_atSpace = false;
177                 break;
178             }
179             if ($this->_lines[$this->_pos] != '')
180                 break;
181             $this->_pos++;
182             $this->_atSpace = true;
183         }
184         return $this->_atSpace;
185     }
186         
187     function currentLine () {
188         if ($this->_pos >= count($this->_lines)) {
189             return false;
190         }
191         return $this->_lines[$this->_pos];
192     }
193         
194     function nextLine () {
195         $this->_atSpace = $this->_lines[$this->_pos++] === '';
196         if ($this->_pos >= count($this->_lines)) {
197             return false;
198         }
199         return $this->_lines[$this->_pos];
200     }
201
202     function advance () {
203         $this->_atSpace = $this->_lines[$this->_pos++] === '';
204     }
205     
206     function getPos () {
207         return array($this->_pos, $this->_atSpace);
208     }
209
210     function setPos ($pos) {
211         list($this->_pos, $this->_atSpace) = $pos;
212     }
213
214     function getPrefix () {
215         return '';
216     }
217
218     function getDepth () {
219         return 0;
220     }
221
222     function where () {
223         if ($this->_pos < count($this->_lines))
224             return $this->_lines[$this->_pos];
225         else
226             return "<EOF>";
227     }
228     
229     function _debug ($tab, $msg) {
230         //return ;
231         $where = $this->where();
232         $tab = str_repeat('____', $this->getDepth() ) . $tab;
233         printXML(HTML::div("$tab $msg: at: '",
234                            HTML::tt($where),
235                            "'"));
236     }
237 }
238
239 class BlockParser_InputSubBlock extends BlockParser_Input
240 {
241     function BlockParser_InputSubBlock (&$input, $prefix_re, $initial_prefix = false) {
242         $this->_input = $input;
243         $this->_prefix_pat = "/$prefix_re|\\s*\$/Ax";
244         $this->_atSpace = false;
245
246         if (($line = $input->currentLine()) === false)
247             $this->_line = false;
248         elseif ($initial_prefix) {
249             assert(substr($line, 0, strlen($initial_prefix)) == $initial_prefix);
250             $this->_line = (string) substr($line, strlen($initial_prefix));
251             $this->_atBlank = ! ltrim($line);
252         }
253         elseif (preg_match($this->_prefix_pat, $line, $m)) {
254             $this->_line = (string) substr($line, strlen($m[0]));
255             $this->_atBlank = ! ltrim($line);
256         }
257         else
258             $this->_line = false;
259     }
260
261     function skipSpace () {
262         // In contrast to the case for top-level blocks,
263         // for sub-blocks, there never appears to be any trailing space.
264         // (The last block in the sub-block should always be of class tight-bottom.)
265         while ($this->_line === '')
266             $this->advance();
267
268         if ($this->_line === false)
269             return $this->_atSpace == 'strong_space';
270         else
271             return $this->_atSpace;
272     }
273         
274     function currentLine () {
275         return $this->_line;
276     }
277
278     function nextLine () {
279         if ($this->_line === '')
280             $this->_atSpace = $this->_atBlank ? 'weak_space' : 'strong_space';
281         else
282             $this->_atSpace = false;
283
284         $line = $this->_input->nextLine();
285         if ($line !== false && preg_match($this->_prefix_pat, $line, $m)) {
286             $this->_line = (string) substr($line, strlen($m[0]));
287             $this->_atBlank = ! ltrim($line);
288         }
289         else
290             $this->_line = false;
291
292         return $this->_line;
293     }
294
295     function advance () {
296         $this->nextLine();
297     }
298         
299     function getPos () {
300         return array($this->_line, $this->_atSpace, $this->_input->getPos());
301     }
302
303     function setPos ($pos) {
304         $this->_line = $pos[0];
305         $this->_atSpace = $pos[1];
306         $this->_input->setPos($pos[2]);
307     }
308     
309     function getPrefix () {
310         assert ($this->_line !== false);
311         $line = $this->_input->currentLine();
312         assert ($line !== false && strlen($line) >= strlen($this->_line));
313         return substr($line, 0, strlen($line) - strlen($this->_line));
314     }
315
316     function getDepth () {
317         return $this->_input->getDepth() + 1;
318     }
319
320     function where () {
321         return $this->_input->where();
322     }
323 }
324     
325
326 class Block_HtmlElement extends HtmlElement
327 {
328     function Block_HtmlElement($tag /*, ... */) {
329         $this->_init(func_get_args());
330     }
331
332     function setTightness($top, $bottom) {
333         $this->setInClass('tightenable');
334         $this->setInClass('top', $top);
335         $this->setInClass('bottom', $bottom);
336     }
337 }
338
339 class ParsedBlock extends Block_HtmlElement {
340     
341     function ParsedBlock (&$input, $tag = 'div', $attr = false) {
342         $this->Block_HtmlElement($tag, $attr);
343         $this->_initBlockTypes();
344         $this->_parse($input);
345     }
346
347     function _parse (&$input) {
348         for ($block = $this->_getBlock($input); $block; $block = $nextBlock) {
349             while ($nextBlock = $this->_getBlock($input)) {
350                 // Attempt to merge current with following block.
351                 if (! ($merged = $block->merge($nextBlock)) ) {
352                     break;      // can't merge
353                 }
354                 $block = $merged;
355             }
356             $this->pushContent($block->finish());
357         }
358     }
359
360     // FIXME: hackish
361     function _initBlockTypes () {
362         foreach (array('oldlists', 'list', 'dl', 'table_dl',
363                        'blockquote', 'heading', 'hr', 'pre', 'email_blockquote',
364                        'plugin', 'p')
365                  as $type) {
366             $class = "Block_$type";
367             $proto = new $class;
368             $this->_block_types[] = $proto;
369             $this->_regexps[] = $proto->_re;
370         }
371         $this->_regexpset = new AnchoredRegexpSet($this->_regexps);
372     }
373
374     function _getBlock (&$input) {
375         $this->_atSpace = $input->skipSpace();
376
377         if (($line = $input->currentLine()) === '')
378             return false;
379
380         $tight_top = !$this->_atSpace;
381         $re_set = &$this->_regexpset;
382         for ($m = $re_set->match($line); $m; $m = $re_set->nextMatch($line, $m)) {
383             $block = $this->_block_types[$m->regexp_ind];
384             if (DEBUG & _DEBUG_PARSER)
385                 $input->_debug('>', get_class($block));
386             
387             if ($block->_match($input, $m)) {
388                 if (DEBUG & _DEBUG_PARSER)
389                     $input->_debug('<', get_class($block));
390                 $tight_bottom = ! $input->skipSpace();
391                 $block->_setTightness($tight_top, $tight_bottom);
392                 return $block;
393             }
394             if (DEBUG & _DEBUG_PARSER)
395                 $input->_debug('[', "_match failed");
396         }
397         if (!$line)
398             return false;
399
400         trigger_error("Couldn't match block: '$line'", E_USER_NOTICE);
401         return false;
402     }
403 }
404
405 class WikiText extends ParsedBlock {
406     function WikiText ($text) {
407         $input = new BlockParser_Input($text);
408         $this->ParsedBlock($input);
409     }
410 }
411
412 class SubBlock extends ParsedBlock {
413     function SubBlock (&$input, $indent_re, $initial_indent = false,
414                        $tag = 'div', $attr = false) {
415         $subinput = new BlockParser_InputSubBlock($input, $indent_re, $initial_indent);
416         $this->ParsedBlock($subinput, $tag, $attr);
417     }
418 }
419
420 /**
421  * TightSubBlock is for use in parsing lists item bodies.
422  *
423  * If the sub-block consists of a single paragraph, it omits
424  * the paragraph element.
425  *
426  * We go to this trouble so that "tight" lists look somewhat reasonable
427  * in older (non-CSS) browsers.  (If you don't do this, then, without
428  * CSS, you only get "loose" lists.
429  */
430 class TightSubBlock extends SubBlock {
431     function TightSubBlock (&$input, $indent_re, $initial_indent = false,
432                             $tag = 'div', $attr = false) {
433         $this->SubBlock($input, $indent_re, $initial_indent, $tag, $attr);
434
435         // If content is a single paragraph, eliminate the paragraph...
436         if (count($this->_content) == 1) {
437             $elem = $this->_content[0];
438             if (isa($elem, 'XmlElement') and $elem->getTag() == 'p') {
439                 assert($elem->getAttr('class') == 'tightenable top bottom');
440                 $this->setContent($elem->getContent());
441             }
442         }
443     }
444 }
445
446 class BlockMarkup {
447     var $_re;
448
449     function _match (&$input, $match) {
450         trigger_error('pure virtual', E_USER_ERROR);
451     }
452
453     function _setTightness ($top, $bot) {
454         $this->_element->setTightness($top, $bot);
455     }
456
457     function merge ($followingBlock) {
458         return false;
459     }
460
461     function finish () {
462         return $this->_element;
463     }
464 }
465
466 class Block_blockquote extends BlockMarkup
467 {
468     var $_depth;
469
470     var $_re = '\ +(?=\S)';
471
472     function _match (&$input, $m) {
473         $this->_depth = strlen($m->match);
474         $indent = sprintf("\\ {%d}", $this->_depth);
475         $this->_element = new SubBlock($input, $indent, $m->match,
476                                        'blockquote');
477         return true;
478     }
479     
480     function merge ($nextBlock) {
481         if (get_class($nextBlock) == get_class($this)) {
482             assert ($nextBlock->_depth < $this->_depth);
483             $nextBlock->_element->unshiftContent($this->_element);
484             $nextBlock->_tight_top = $this->_tight_top;
485             return $nextBlock;
486         }
487         return false;
488     }
489 }
490
491 class Block_list extends BlockMarkup
492 {
493     //var $_tag = 'ol' or 'ul';
494     var $_re = '\ {0,4}
495                 (?: \+
496                   | \\# (?!\[.*\])
497                   | -(?!-)
498                   | [o](?=\ )
499                   | [*] (?!(?=\S)[^*]*(?<=\S)[*](?:\\s|[-)}>"\'\\/:.,;!?_*=]) )
500                 )\ *(?=\S)';
501
502     var $_content = array();
503
504     function _match (&$input, $m) {
505         // A list as the first content in a list is not allowed.
506         // E.g.:
507         //   *  * Item
508         // Should markup as <ul><li>* Item</li></ul>,
509         // not <ul><li><ul><li>Item</li></ul>/li></ul>.
510         //
511         if (preg_match('/[*#+-o]/', $input->getPrefix())) {
512             return false;
513         }
514         
515         $prefix = $m->match;
516         $indent = sprintf("\\ {%d}", strlen($prefix));
517
518         $bullet = trim($m->match);
519         $this->_tag = $bullet == '#' ? 'ol' : 'ul';
520         $this->_content[] = new TightSubBlock($input, $indent, $m->match, 'li');
521         return true;
522     }
523
524     function _setTightness($top, $bot) {
525         $li = &$this->_content[0];
526         $li->setTightness($top, $bot);
527     }
528     
529     function merge ($nextBlock) {
530         if (isa($nextBlock, 'Block_list') and $this->_tag == $nextBlock->_tag) {
531             array_splice($this->_content, count($this->_content), 0,
532                          $nextBlock->_content);
533             return $this;
534         }
535         return false;
536     }
537
538     function finish () {
539         return new Block_HtmlElement($this->_tag, false, $this->_content);
540     }
541 }
542
543 class Block_dl extends Block_list
544 {
545     var $_tag = 'dl';
546
547     function Block_dl () {
548         $this->_re = '\ {0,4}\S.*(?<!'.ESCAPE_CHAR.'):\s*$';
549     }
550
551     function _match (&$input, $m) {
552         if (!($p = $this->_do_match($input, $m)))
553             return false;
554         list ($term, $defn, $loose) = $p;
555
556         $this->_content[] = new Block_HtmlElement('dt', false, $term);
557         $this->_content[] = $defn;
558         $this->_tight_defn = !$loose;
559         return true;
560     }
561
562     function _setTightness($top, $bot) {
563         $dt = &$this->_content[0];
564         $dd = &$this->_content[1];
565
566         $dt->setTightness($top, $this->_tight_defn);
567         $dd->setTightness($this->_tight_defn, $bot);
568     }
569
570     function _do_match (&$input, $m) {
571         $pos = $input->getPos();
572
573         $firstIndent = strspn($m->match, ' ');
574         $pat = sprintf('/\ {%d,%d}(?=\s*\S)/A', $firstIndent + 1, $firstIndent + 5);
575
576         $input->advance();
577         $loose = $input->skipSpace();
578         $line = $input->currentLine();
579
580         if (!$line || !preg_match($pat, $line, $mm)) {
581             $input->setPos($pos);
582             return false;       // No body found.
583         }
584
585         $indent = strlen($mm[0]);
586         $term = TransformInline(rtrim(substr(trim($m->match),0,-1)));
587         $defn = new TightSubBlock($input, sprintf("\\ {%d}", $indent), false, 'dd');
588         return array($term, $defn, $loose);
589     }
590 }
591
592
593
594 class Block_table_dl_defn extends XmlContent
595 {
596     var $nrows;
597     var $ncols;
598     
599     function Block_table_dl_defn ($term, $defn) {
600         $this->XmlContent();
601         if (!is_array($defn))
602             $defn = $defn->getContent();
603
604         $this->_next_tight_top = false; // value irrelevant - gets fixed later
605         $this->_ncols = $this->_ComputeNcols($defn);
606         $this->_nrows = 0;
607
608         foreach ($defn as $item) {
609             if ($this->_IsASubtable($item))
610                 $this->_addSubtable($item);
611             else
612                 $this->_addToRow($item);
613         }
614         $this->_flushRow();
615
616         $th = HTML::th($term);
617         if ($this->_nrows > 1)
618             $th->setAttr('rowspan', $this->_nrows);
619         $this->_setTerm($th);
620     }
621
622     function setTightness($tight_top, $tight_bot) {
623         $this->_tight_top = $tight_top;
624         $this->_tight_bot = $tight_bot;
625         $first =& $this->firstTR();
626         $last  =& $this->lastTR();
627         $first->setInClass('top', $tight_top);
628         if (!empty($last)) {
629             $last->setInClass('bottom', $tight_bot);
630         } else {
631             trigger_error(sprintf("no lastTR: %s",AsXML($this->_content[0])), E_USER_WARNING);
632         }
633     }
634     
635     function _addToRow ($item) {
636         if (empty($this->_accum)) {
637             $this->_accum = HTML::td();
638             if ($this->_ncols > 2)
639                 $this->_accum->setAttr('colspan', $this->_ncols - 1);
640         }
641         $this->_accum->pushContent($item);
642     }
643
644     function _flushRow ($tight_bottom=false) {
645         if (!empty($this->_accum)) {
646             $row = new Block_HtmlElement('tr', false, $this->_accum);
647
648             $row->setTightness($this->_next_tight_top, $tight_bottom);
649             $this->_next_tight_top = $tight_bottom;
650             
651             $this->pushContent($row);
652             $this->_accum = false;
653             $this->_nrows++;
654         }
655     }
656
657     function _addSubtable ($table) {
658         if (!($table_rows = $table->getContent()))
659             return;
660
661         $this->_flushRow($table_rows[0]->_tight_top);
662             
663         foreach ($table_rows as $subdef) {
664             $this->pushContent($subdef);
665             $this->_nrows += $subdef->nrows();
666             $this->_next_tight_top = $subdef->_tight_bot;
667         }
668     }
669
670     function _setTerm ($th) {
671         $first_row = &$this->_content[0];
672         if (isa($first_row, 'Block_table_dl_defn'))
673             $first_row->_setTerm($th);
674         else
675             $first_row->unshiftContent($th);
676     }
677     
678     function _ComputeNcols ($defn) {
679         $ncols = 2;
680         foreach ($defn as $item) {
681             if ($this->_IsASubtable($item)) {
682                 $row = $this->_FirstDefn($item);
683                 $ncols = max($ncols, $row->ncols() + 1);
684             }
685         }
686         return $ncols;
687     }
688
689     function _IsASubtable ($item) {
690         return isa($item, 'HtmlElement')
691             && $item->getTag() == 'table'
692             && $item->getAttr('class') == 'wiki-dl-table';
693     }
694
695     function _FirstDefn ($subtable) {
696         $defs = $subtable->getContent();
697         return $defs[0];
698     }
699
700     function ncols () {
701         return $this->_ncols;
702     }
703
704     function nrows () {
705         return $this->_nrows;
706     }
707
708     function & firstTR() {
709         $first = &$this->_content[0];
710         if (isa($first, 'Block_table_dl_defn'))
711             return $first->firstTR();
712         return $first;
713     }
714
715     function & lastTR() {
716         $last = &$this->_content[$this->_nrows - 1];
717         if (isa($last, 'Block_table_dl_defn'))
718             return $last->lastTR();
719         return $last;
720     }
721
722     function setWidth ($ncols) {
723         assert($ncols >= $this->_ncols);
724         if ($ncols <= $this->_ncols)
725             return;
726         $rows = &$this->_content;
727         for ($i = 0; $i < count($rows); $i++) {
728             $row = &$rows[$i];
729             if (isa($row, 'Block_table_dl_defn'))
730                 $row->setWidth($ncols - 1);
731             else {
732                 $n = count($row->_content);
733                 $lastcol = &$row->_content[$n - 1];
734                 if (!empty($lastcol))
735                   $lastcol->setAttr('colspan', $ncols - 1);
736             }
737         }
738     }
739 }
740
741 class Block_table_dl extends Block_dl
742 {
743     var $_tag = 'dl-table';     // phony.
744
745     function Block_table_dl() {
746         $this->_re = '\ {0,4} (?:\S.*)? (?<!'.ESCAPE_CHAR.') \| \s* $';
747     }
748
749     function _match (&$input, $m) {
750         if (!($p = $this->_do_match($input, $m)))
751             return false;
752         list ($term, $defn, $loose) = $p;
753
754         $this->_content[] = new Block_table_dl_defn($term, $defn);
755         return true;
756     }
757
758     function _setTightness($top, $bot) {
759         $this->_content[0]->setTightness($top, $bot);
760     }
761     
762     function finish () {
763
764         $defs = &$this->_content;
765
766         $ncols = 0;
767         foreach ($defs as $defn)
768             $ncols = max($ncols, $defn->ncols());
769         
770         foreach ($defs as $key => $defn)
771             $defs[$key]->setWidth($ncols);
772
773         return HTML::table(array('class' => 'wiki-dl-table',
774                                  'border' => 1,
775                                  'cellspacing' => 0,
776                                  'cellpadding' => 6),
777                            $defs);
778     }
779 }
780
781 class Block_oldlists extends Block_list
782 {
783     //var $_tag = 'ol', 'ul', or 'dl';
784     var $_re = '(?: [*] (?!(?=\S)[^*]*(?<=\S)[*](?:\\s|[-)}>"\'\\/:.,;!?_*=]))
785                   | [#] (?! \[ .*? \] )
786                   | ; .*? :
787                 ) .*? (?=\S)';
788
789     function _match (&$input, $m) {
790         // FIXME:
791         if (!preg_match('/[*#;]*$/A', $input->getPrefix())) {
792             return false;
793         }
794         
795
796         $prefix = $m->match;
797         $oldindent = '[*#;](?=[#*]|;.*:.*\S)';
798         $newindent = sprintf('\\ {%d}', strlen($prefix));
799         $indent = "(?:$oldindent|$newindent)";
800
801         $bullet = $prefix[0];
802         if ($bullet == '*') {
803             $this->_tag = 'ul';
804             $itemtag = 'li';
805         }
806         elseif ($bullet == '#') {
807             $this->_tag = 'ol';
808             $itemtag = 'li';
809         }
810         else {
811             $this->_tag = 'dl';
812             list ($term,) = explode(':', substr($prefix, 1), 2);
813             $term = trim($term);
814             if ($term)
815                 $this->_content[] = new Block_HtmlElement('dt', false,
816                                                           TransformInline($term));
817             $itemtag = 'dd';
818         }
819
820         $this->_content[] = new TightSubBlock($input, $indent, $m->match, $itemtag);
821         return true;
822     }
823
824     function _setTightness($top, $bot) {
825         if (count($this->_content) == 1) {
826             $li = &$this->_content[0];
827             $li->setTightness($top, $bot);
828         }
829         else {
830             // This is where php5 usually brakes.
831             // wrong duplicated <li> contents
832             if (DEBUG and DEBUG & _DEBUG_PARSER and check_php_version(5)) {
833                 if (count($this->_content) != 2) {
834                     echo "<pre>";
835                     /*
836                     $class = new Reflection_Class('XmlElement');
837                     // Print out basic information
838                     printf(
839                            "===> The %s%s%s %s '%s' [extends %s]\n".
840                            "     declared in %s\n".
841                            "     lines %d to %d\n".
842                            "     having the modifiers %d [%s]\n",
843                            $class->isInternal() ? 'internal' : 'user-defined',
844                            $class->isAbstract() ? ' abstract' : '',
845                            $class->isFinal() ? ' final' : '',
846                            $class->isInterface() ? 'interface' : 'class',
847                            $class->getName(),
848                            var_export($class->getParentClass(), 1),
849                            $class->getFileName(),
850                            $class->getStartLine(),
851                            $class->getEndline(),
852                            $class->getModifiers(),
853                            implode(' ', Reflection::getModifierNames($class->getModifiers()))
854                            );
855                     // Print class properties
856                     printf("---> Properties: %s\n", var_export($class->getProperties(), 1));
857                     */
858                     echo 'count($this->_content): ', count($this->_content),"\n";
859                     echo "\$this->_content[0]: "; var_dump ($this->_content[0]);
860                     
861                     for ($i=1; $i < min(5, count($this->_content)); $i++) {
862                         $c =& $this->_content[$i];
863                         echo '$this->_content[',$i,"]: \n";
864                         echo "_tag: "; var_dump ($c->_tag);
865                         echo "_content: "; var_dump ($c->_content);
866                         echo "_properties: "; var_dump ($c->_properties);
867                     }
868                     debug_print_backtrace();
869                     if (function_exists("xdebug_get_function_stack")) {
870                         var_dump (xdebug_get_function_stack());
871                     }
872                     echo "</pre>";
873                 }
874             }
875             if (!check_php_version(5))
876                 assert(count($this->_content) == 2);
877             $dt = &$this->_content[0];
878             $dd = &$this->_content[1];
879             $dt->setTightness($top, false);
880             $dd->setTightness(false, $bot);
881         }
882     }
883 }
884
885 class Block_pre extends BlockMarkup
886 {
887     var $_re = '<(?:pre|verbatim)>';
888
889     function _match (&$input, $m) {
890         $endtag = '</' . substr($m->match, 1);
891         $text = array();
892         $pos = $input->getPos();
893
894         $line = $m->postmatch;
895         while (ltrim($line) != $endtag) {
896             $text[] = $line;
897             if (($line = $input->nextLine()) === false) {
898                 $input->setPos($pos);
899                 return false;
900             }
901         }
902         $input->advance();
903         
904         $text = join("\n", $text);
905         
906         // FIXME: no <img>, <big>, <small>, <sup>, or <sub>'s allowed
907         // in a <pre>.
908         if ($m->match == '<pre>')
909             $text = TransformInline($text);
910
911         $this->_element = new Block_HtmlElement('pre', false, $text);
912         return true;
913     }
914 }
915
916
917 class Block_plugin extends Block_pre
918 {
919     var $_re = '<\?plugin(?:-form)?(?!\S)';
920
921     // FIXME:
922     /* <?plugin Backlinks
923      *       page=ThisPage ?>
924      *
925      * should work. */
926     function _match (&$input, $m) {
927         $pos = $input->getPos();
928         $pi = $m->match . $m->postmatch;
929         while (!preg_match('/(?<!'.ESCAPE_CHAR.')\?>\s*$/', $pi)) {
930             if (($line = $input->nextLine()) === false) {
931                 $input->setPos($pos);
932                 return false;
933             }
934             $pi .= "\n$line";
935         }
936         $input->advance();
937
938         $this->_element = new Cached_PluginInvocation($pi);
939         return true;
940     }
941 }
942
943 class Block_email_blockquote extends BlockMarkup
944 {
945     var $_attr = array('class' => 'mail-style-quote');
946     var $_re = '>\ ?';
947     
948     function _match (&$input, $m) {
949         //$indent = str_replace(' ', '\\ ', $m->match) . '|>$';
950         $indent = $this->_re;
951         $this->_element = new SubBlock($input, $indent, $m->match,
952                                        'blockquote', $this->_attr);
953         return true;
954     }
955 }
956
957 class Block_hr extends BlockMarkup
958 {
959     var $_re = '-{4,}\s*$';
960
961     function _match (&$input, $m) {
962         $input->advance();
963         $this->_element = new Block_HtmlElement('hr');
964         return true;
965     }
966
967     function _setTightness($top, $bot) {
968         // Don't tighten <hr/>s
969     }
970 }
971
972 class Block_heading extends BlockMarkup
973 {
974     var $_re = '!{1,3}';
975     
976     function _match (&$input, $m) {
977         $tag = "h" . (5 - strlen($m->match));
978         $text = TransformInline(trim($m->postmatch));
979         $input->advance();
980
981         $this->_element = new Block_HtmlElement($tag, false, $text);
982         
983         return true;
984     }
985
986     function _setTightness($top, $bot) {
987         // Don't tighten headers.
988     }
989 }
990
991 class Block_p extends BlockMarkup
992 {
993     var $_tag = 'p';
994     var $_re = '\S.*';
995
996     function _match (&$input, $m) {
997         $this->_text = $m->match;
998         $input->advance();
999         return true;
1000     }
1001
1002     function _setTightness ($top, $bot) {
1003         $this->_tight_top = $top;
1004         $this->_tight_bot = $bot;
1005     }
1006
1007     function merge ($nextBlock) {
1008         $class = get_class($nextBlock);
1009         if (strtolower($class) == 'block_p' && $this->_tight_bot) {
1010             $this->_text .= "\n" . $nextBlock->_text;
1011             $this->_tight_bot = $nextBlock->_tight_bot;
1012             return $this;
1013         }
1014         return false;
1015     }
1016             
1017     function finish () {
1018         $content = TransformInline(trim($this->_text));
1019         $p = new Block_HtmlElement('p', false, $content);
1020         $p->setTightness($this->_tight_top, $this->_tight_bot);
1021         return $p;
1022     }
1023 }
1024
1025 ////////////////////////////////////////////////////////////////
1026 //
1027
1028 function TransformText ($text, $markup = 2.0, $basepage=false) {
1029     if (isa($text, 'WikiDB_PageRevision')) {
1030         $rev = $text;
1031         $text = $rev->getPackedContent();
1032         $markup = $rev->get('markup');
1033     }
1034
1035     if (empty($markup) || $markup < 2.0) {
1036         //include_once("lib/transform.php");
1037         //return do_transform($text);
1038         $text = ConvertOldMarkup($text);
1039     }
1040     
1041     // Expand leading tabs.
1042     $text = expand_tabs($text);
1043
1044     //set_time_limit(3);
1045
1046     $output = new WikiText($text);
1047     if (0 and DEBUG and DEBUG & _DEBUG_VERBOSE and check_php_version(5)) {
1048         echo "<pre>"; var_dump($output); echo "</pre>"; 
1049     }
1050
1051     if ($basepage) {
1052         // This is for immediate consumption.
1053         // We must bind the contents to a base pagename so that
1054         // relative page links can be properly linkified...
1055         return new CacheableMarkup($output->getContent(), $basepage);
1056     }
1057     
1058     return new XmlContent($output->getContent());
1059 }
1060
1061 // $Log: not supported by cvs2svn $
1062 // Revision 1.46  2004/06/20 14:42:53  rurban
1063 // various php5 fixes (still broken at blockparser)
1064 //
1065
1066 // (c-file-style: "gnu")
1067 // Local Variables:
1068 // mode: php
1069 // tab-width: 8
1070 // c-basic-offset: 4
1071 // c-hanging-comment-ender-p: nil
1072 // indent-tabs-mode: nil
1073 // End:   
1074 ?>