File: BlockParser.php

package info (click to toggle)
phpwiki 1.3.14-3
  • links: PTS
  • area: main
  • in suites: lenny
  • size: 15,716 kB
  • ctags: 23,548
  • sloc: php: 88,295; sql: 1,476; sh: 1,378; perl: 765; makefile: 602; awk: 28
file content (1209 lines) | stat: -rwxr-xr-x 36,414 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
<?php rcs_id('$Id: BlockParser.php,v 1.60 2007/01/07 18:41:32 rurban Exp $');
/* Copyright (C) 2002 Geoffrey T. Dairiki <dairiki@dairiki.org>
 * Copyright (C) 2004,2005 Reini Urban
 *
 * This file is part of PhpWiki.
 * 
 * PhpWiki is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 * 
 * PhpWiki is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with PhpWiki; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */
require_once('lib/HtmlElement.php');
require_once('lib/CachedMarkup.php');
require_once('lib/InlineParser.php');

////////////////////////////////////////////////////////////////
//
//

/**
 * Deal with paragraphs and proper, recursive block indents 
 * for the new style markup (version 2)
 *
 * Everything which goes over more than line:
 * automatic lists, UL, OL, DL, table, blockquote, verbatim, 
 * p, pre, plugin, ...
 *
 * FIXME:
 *  Still to do:
 *    (old-style) tables
 * FIXME: unify this with the RegexpSet in InlineParser.
 *
 * FIXME: This is very php5 sensitive: It was fixed for 1.3.9, 
 *        but is again broken with the 1.3.11 
 *        allow_call_time_pass_reference clean fixes
 *
 * @package Markup
 * @author: Geoffrey T. Dairiki 
 */

/**
 * Return type from RegexpSet::match and RegexpSet::nextMatch.
 *
 * @see RegexpSet
 */
class AnchoredRegexpSet_match {
    /**
     * The matched text.
     */
    var $match;

    /**
     * The text following the matched text.
     */
    var $postmatch;

    /**
     * Index of the regular expression which matched.
     */
    var $regexp_ind;
}

/**
 * A set of regular expressions.
 *
 * This class is probably only useful for InlineTransformer.
 */
class AnchoredRegexpSet
{
    /** Constructor
     *
     * @param $regexps array A list of regular expressions.  The
     * regular expressions should not include any sub-pattern groups
     * "(...)".  (Anonymous groups, like "(?:...)", as well as
     * look-ahead and look-behind assertions are fine.)
     */
    function AnchoredRegexpSet ($regexps) {
        $this->_regexps = $regexps;
        $this->_re = "/((" . join(")|(", $regexps) . "))/Ax";
    }

    /**
     * Search text for the next matching regexp from the Regexp Set.
     *
     * @param $text string The text to search.
     *
     * @return object  A RegexpSet_match object, or false if no match.
     */
    function match ($text) {
    	if (!is_string($text)) return false;
        if (! preg_match($this->_re, $text, $m)) {
            return false;
        }
        
        $match = new AnchoredRegexpSet_match;
        $match->postmatch = substr($text, strlen($m[0]));
        $match->match = $m[1];
        $match->regexp_ind = count($m) - 3;
        return $match;
    }

    /**
     * Search for next matching regexp.
     *
     * Here, 'next' has two meanings:
     *
     * Match the next regexp(s) in the set, at the same position as the last match.
     *
     * If that fails, match the whole RegexpSet, starting after the position of the
     * previous match.
     *
     * @param $text string Text to search.
     *
     * @param $prevMatch A RegexpSet_match object
     *
     * $prevMatch should be a match object obtained by a previous
     * match upon the same value of $text.
     *
     * @return object  A RegexpSet_match object, or false if no match.
     */
    function nextMatch ($text, $prevMatch) {
        // Try to find match at same position.
        $regexps = array_slice($this->_regexps, $prevMatch->regexp_ind + 1);
        if (!$regexps) {
            return false;
        }

        $pat= "/ ( (" . join(')|(', $regexps) . ") ) /Axs";

        if (! preg_match($pat, $text, $m)) {
            return false;
        }
        
        $match = new AnchoredRegexpSet_match;
        $match->postmatch = substr($text, strlen($m[0]));
        $match->match = $m[1];
        $match->regexp_ind = count($m) - 3 + $prevMatch->regexp_ind + 1;;
        return $match;
    }
}


    
class BlockParser_Input {

    function BlockParser_Input ($text) {
        
        // Expand leading tabs.
        // FIXME: do this better.
        //
        // We want to ensure the only characters matching \s are ' ' and "\n".
        //
        $text = preg_replace('/(?![ \n])\s/', ' ', $text);
        assert(!preg_match('/(?![ \n])\s/', $text));

        $this->_lines = preg_split('/[^\S\n]*\n/', $text);
        $this->_pos = 0;

        // Strip leading blank lines.
        while ($this->_lines and ! $this->_lines[0])
            array_shift($this->_lines);
        $this->_atSpace = false;
    }

    function skipSpace () {
        $nlines = count($this->_lines);
        while (1) {
            if ($this->_pos >= $nlines) {
                $this->_atSpace = false;
                break;
            }
            if ($this->_lines[$this->_pos] != '')
                break;
            $this->_pos++;
            $this->_atSpace = true;
        }
        return $this->_atSpace;
    }
        
    function currentLine () {
        if ($this->_pos >= count($this->_lines)) {
            return false;
        }
        return $this->_lines[$this->_pos];
    }
        
    function nextLine () {
        $this->_atSpace = $this->_lines[$this->_pos++] === '';
        if ($this->_pos >= count($this->_lines)) {
            return false;
        }
        return $this->_lines[$this->_pos];
    }

    function advance () {
        $this->_atSpace = ($this->_lines[$this->_pos] === '');
        $this->_pos++;
    }
    
    function getPos () {
        return array($this->_pos, $this->_atSpace);
    }

    function setPos ($pos) {
        list($this->_pos, $this->_atSpace) = $pos;
    }

    function getPrefix () {
        return '';
    }

    function getDepth () {
        return 0;
    }

    function where () {
        if ($this->_pos < count($this->_lines))
            return $this->_lines[$this->_pos];
        else
            return "<EOF>";
    }
    
    function _debug ($tab, $msg) {
        //return ;
        $where = $this->where();
        $tab = str_repeat('____', $this->getDepth() ) . $tab;
        printXML(HTML::div("$tab $msg: at: '",
                           HTML::tt($where),
                           "'"));
        flush();                   
    }
}

class BlockParser_InputSubBlock extends BlockParser_Input
{
    function BlockParser_InputSubBlock (&$input, $prefix_re, $initial_prefix = false) {
        $this->_input = &$input;
        $this->_prefix_pat = "/$prefix_re|\\s*\$/Ax";
        $this->_atSpace = false;

        if (($line = $input->currentLine()) === false)
            $this->_line = false;
        elseif ($initial_prefix) {
            assert(substr($line, 0, strlen($initial_prefix)) == $initial_prefix);
            $this->_line = (string) substr($line, strlen($initial_prefix));
            $this->_atBlank = ! ltrim($line);
        }
        elseif (preg_match($this->_prefix_pat, $line, $m)) {
            $this->_line = (string) substr($line, strlen($m[0]));
            $this->_atBlank = ! ltrim($line);
        }
        else
            $this->_line = false;
    }

    function skipSpace () {
        // In contrast to the case for top-level blocks,
        // for sub-blocks, there never appears to be any trailing space.
        // (The last block in the sub-block should always be of class tight-bottom.)
        while ($this->_line === '')
            $this->advance();

        if ($this->_line === false)
            return $this->_atSpace == 'strong_space';
        else
            return $this->_atSpace;
    }
        
    function currentLine () {
        return $this->_line;
    }

    function nextLine () {
        if ($this->_line === '')
            $this->_atSpace = $this->_atBlank ? 'weak_space' : 'strong_space';
        else
            $this->_atSpace = false;

        $line = $this->_input->nextLine();
        if ($line !== false && preg_match($this->_prefix_pat, $line, $m)) {
            $this->_line = (string) substr($line, strlen($m[0]));
            $this->_atBlank = ! ltrim($line);
        }
        else
            $this->_line = false;

        return $this->_line;
    }

    function advance () {
        $this->nextLine();
    }
        
    function getPos () {
        return array($this->_line, $this->_atSpace, $this->_input->getPos());
    }

    function setPos ($pos) {
        $this->_line = $pos[0];
        $this->_atSpace = $pos[1];
        $this->_input->setPos($pos[2]);
    }
    
    function getPrefix () {
        assert ($this->_line !== false);
        $line = $this->_input->currentLine();
        assert ($line !== false && strlen($line) >= strlen($this->_line));
        return substr($line, 0, strlen($line) - strlen($this->_line));
    }

    function getDepth () {
        return $this->_input->getDepth() + 1;
    }

    function where () {
        return $this->_input->where();
    }
}
    

class Block_HtmlElement extends HtmlElement
{
    function Block_HtmlElement($tag /*, ... */) {
        $this->_init(func_get_args());
    }

    function setTightness($top, $bottom) {
	$this->setInClass('tightenable');
	$this->setInClass('top', $top);
	$this->setInClass('bottom', $bottom);
    }
}

class ParsedBlock extends Block_HtmlElement {
    
    function ParsedBlock (&$input, $tag = 'div', $attr = false) {
        $this->Block_HtmlElement($tag, $attr);
        $this->_initBlockTypes();
        $this->_parse($input);
    }

    function _parse (&$input) {
        // php5 failed to advance the block. php5 copies objects by ref.
        // nextBlock == block, both are the same objects. So we have to clone it.
        for ($block = $this->_getBlock($input); 
             $block; 
             $block = (is_object($nextBlock) ? clone($nextBlock) : $nextBlock))
        {
            while ($nextBlock = $this->_getBlock($input)) {
                // Attempt to merge current with following block.
                if (! ($merged = $block->merge($nextBlock)) ) {
                    break;      // can't merge
                }
                $block = $merged;
            }
            $this->pushContent($block->finish());
        }
    }

    // FIXME: hackish. This should only be called once.
    function _initBlockTypes () {
    	// better static or global?
    	static $_regexpset, $_block_types;

    	if (!is_object($_regexpset)) {
	    $Block_types = array
		    ('oldlists', 'list', 'dl', 'table_dl',
                     'blockquote', 'heading', 'hr', 'pre', 'email_blockquote',
		     'plugin', 'p');
            // insert it before p!
            if (ENABLE_MARKUP_DIVSPAN) {
            	array_pop($Block_types);
 		$Block_types[] = 'divspan';
 		$Block_types[] = 'p';
            }
            foreach ($Block_types as $type) {
                $class = "Block_$type";
                $proto = new $class;
                $this->_block_types[] = $proto;
                $this->_regexps[] = $proto->_re;
            }
            $this->_regexpset = new AnchoredRegexpSet($this->_regexps);
            $_regexpset = $this->_regexpset;
            $_block_types = $this->_block_types;
            unset($Block_types);
    	} else {
             $this->_regexpset = $_regexpset;
             $this->_block_types = $_block_types;
        }
    }

    function _getBlock (&$input) {
        $this->_atSpace = $input->skipSpace();

        $line = $input->currentLine();
        if ($line === false or $line === '') { // allow $line === '0' 
            return false;
        }
        $tight_top = !$this->_atSpace;
        $re_set = &$this->_regexpset;
        //FIXME: php5 fails to advance here!
        for ($m = $re_set->match($line); $m; $m = $re_set->nextMatch($line, $m)) {
            $block = clone($this->_block_types[$m->regexp_ind]);
            if (DEBUG & _DEBUG_PARSER)
                $input->_debug('>', get_class($block));
            
            if ($block->_match($input, $m)) {
            	//$block->_text = $line;
                if (DEBUG & _DEBUG_PARSER)
                    $input->_debug('<', get_class($block));
                $tight_bottom = ! $input->skipSpace();
                $block->_setTightness($tight_top, $tight_bottom);
                return $block;
            }
            if (DEBUG & _DEBUG_PARSER)
                $input->_debug('[', "_match failed");
        }
        if ($line === false or $line === '') // allow $line === '0' 
            return false;

        trigger_error("Couldn't match block: '$line'", E_USER_NOTICE);
        return false;
    }
}

class WikiText extends ParsedBlock {
    function WikiText ($text) {
        $input = new BlockParser_Input($text);
        $this->ParsedBlock($input);
    }
}

class SubBlock extends ParsedBlock {
    function SubBlock (&$input, $indent_re, $initial_indent = false,
                       $tag = 'div', $attr = false) {
        $subinput = new BlockParser_InputSubBlock($input, $indent_re, $initial_indent);
        $this->ParsedBlock($subinput, $tag, $attr);
    }
}

/**
 * TightSubBlock is for use in parsing lists item bodies.
 *
 * If the sub-block consists of a single paragraph, it omits
 * the paragraph element.
 *
 * We go to this trouble so that "tight" lists look somewhat reasonable
 * in older (non-CSS) browsers.  (If you don't do this, then, without
 * CSS, you only get "loose" lists.
 */
class TightSubBlock extends SubBlock {
    function TightSubBlock (&$input, $indent_re, $initial_indent = false,
                            $tag = 'div', $attr = false) {
        $this->SubBlock($input, $indent_re, $initial_indent, $tag, $attr);

        // If content is a single paragraph, eliminate the paragraph...
        if (count($this->_content) == 1) {
            $elem = $this->_content[0];
            if (isa($elem, 'XmlElement') and $elem->getTag() == 'p') {
                assert($elem->getAttr('class') == 'tightenable top bottom');
                $this->setContent($elem->getContent());
            }
        }
    }
}

class BlockMarkup {
    var $_re;

    function _match (&$input, $match) {
        trigger_error('pure virtual', E_USER_ERROR);
    }

    function _setTightness ($top, $bot) {
        $this->_element->setTightness($top, $bot);
    }

    function merge ($followingBlock) {
        return false;
    }

    function finish () {
        return $this->_element;
    }
}

class Block_blockquote extends BlockMarkup
{
    var $_depth;
    var $_re = '\ +(?=\S)';

    function _match (&$input, $m) {
        $this->_depth = strlen($m->match);
        $indent = sprintf("\\ {%d}", $this->_depth);
        $this->_element = new SubBlock($input, $indent, $m->match,
                                       'blockquote');
        return true;
    }
    
    function merge ($nextBlock) {
        if (get_class($nextBlock) == get_class($this)) {
            assert ($nextBlock->_depth < $this->_depth);
            $nextBlock->_element->unshiftContent($this->_element);
	    if (!empty($this->_tight_top))
            $nextBlock->_tight_top = $this->_tight_top;
            return $nextBlock;
        }
        return false;
    }
}

class Block_list extends BlockMarkup
{
    //var $_tag = 'ol' or 'ul';
    var $_re = '\ {0,4}
                (?: \+
                  | \\# (?!\[.*\])
                  | -(?!-)
                  | [o](?=\ )
                  | [*] (?!(?=\S)[^*]*(?<=\S)[*](?:\\s|[-)}>"\'\\/:.,;!?_*=]) )
                )\ *(?=\S)';
    var $_content = array();

    function _match (&$input, $m) {
        // A list as the first content in a list is not allowed.
        // E.g.:
        //   *  * Item
        // Should markup as <ul><li>* Item</li></ul>,
        // not <ul><li><ul><li>Item</li></ul>/li></ul>.
        //
        if (preg_match('/[*#+-o]/', $input->getPrefix())) {
            return false;
        }
        
        $prefix = $m->match;
        $indent = sprintf("\\ {%d}", strlen($prefix));

        $bullet = trim($m->match);
        $this->_tag = $bullet == '#' ? 'ol' : 'ul';
        $this->_content[] = new TightSubBlock($input, $indent, $m->match, 'li');
        return true;
    }

    function _setTightness($top, $bot) {
        $li = &$this->_content[0];
        $li->setTightness($top, $bot);
    }
    
    function merge ($nextBlock) {
        if (isa($nextBlock, 'Block_list') and $this->_tag == $nextBlock->_tag) {
            if ($nextBlock->_content === $this->_content) {
            	trigger_error("Internal Error: no block advance", E_USER_NOTICE);
            	return false;
            }
            array_splice($this->_content, count($this->_content), 0,
                         $nextBlock->_content);
            return $this;
        }
        return false;
    }

    function finish () {
        return new Block_HtmlElement($this->_tag, false, $this->_content);
    }
}

class Block_dl extends Block_list
{
    var $_tag = 'dl';

    function Block_dl () {
        $this->_re = '\ {0,4}\S.*(?<!'.ESCAPE_CHAR.'):\s*$';
    }

    function _match (&$input, $m) {
        if (!($p = $this->_do_match($input, $m)))
            return false;
        list ($term, $defn, $loose) = $p;

        $this->_content[] = new Block_HtmlElement('dt', false, $term);
        $this->_content[] = $defn;
        $this->_tight_defn = !$loose;
        return true;
    }

    function _setTightness($top, $bot) {
        $dt = &$this->_content[0];
        $dd = &$this->_content[1];

        $dt->setTightness($top, $this->_tight_defn);
        $dd->setTightness($this->_tight_defn, $bot);
    }

    function _do_match (&$input, $m) {
        $pos = $input->getPos();

        $firstIndent = strspn($m->match, ' ');
        $pat = sprintf('/\ {%d,%d}(?=\s*\S)/A', $firstIndent + 1, $firstIndent + 5);

        $input->advance();
        $loose = $input->skipSpace();
        $line = $input->currentLine();

        if (!$line || !preg_match($pat, $line, $mm)) {
            $input->setPos($pos);
            return false;       // No body found.
        }

        $indent = strlen($mm[0]);
        $term = TransformInline(rtrim(substr(trim($m->match),0,-1)));
        $defn = new TightSubBlock($input, sprintf("\\ {%d}", $indent), false, 'dd');
        return array($term, $defn, $loose);
    }
}



class Block_table_dl_defn extends XmlContent
{
    var $nrows;
    var $ncols;
    
    function Block_table_dl_defn ($term, $defn) {
        $this->XmlContent();
        if (!is_array($defn))
            $defn = $defn->getContent();

	$this->_next_tight_top = false; // value irrelevant - gets fixed later
        $this->_ncols = $this->_ComputeNcols($defn);
        $this->_nrows = 0;

        foreach ($defn as $item) {
            if ($this->_IsASubtable($item))
                $this->_addSubtable($item);
            else
                $this->_addToRow($item);
        }
        $this->_flushRow();

        $th = HTML::th($term);
        if ($this->_nrows > 1)
            $th->setAttr('rowspan', $this->_nrows);
        $this->_setTerm($th);
    }

    function setTightness($tight_top, $tight_bot) {
        $this->_tight_top = $tight_top;
	$this->_tight_bot = $tight_bot;
	$first = &$this->firstTR();
	$last  = &$this->lastTR();
	$first->setInClass('top', $tight_top);
        if (!empty($last)) {
            $last->setInClass('bottom', $tight_bot);
        } else {
            trigger_error(sprintf("no lastTR: %s",AsXML($this->_content[0])), E_USER_WARNING);
        }
    }
    
    function _addToRow ($item) {
        if (empty($this->_accum)) {
            $this->_accum = HTML::td();
            if ($this->_ncols > 2)
                $this->_accum->setAttr('colspan', $this->_ncols - 1);
        }
        $this->_accum->pushContent($item);
    }

    function _flushRow ($tight_bottom=false) {
        if (!empty($this->_accum)) {
            $row = new Block_HtmlElement('tr', false, $this->_accum);

            $row->setTightness($this->_next_tight_top, $tight_bottom);
            $this->_next_tight_top = $tight_bottom;
            
            $this->pushContent($row);
            $this->_accum = false;
            $this->_nrows++;
        }
    }

    function _addSubtable ($table) {
        if (!($table_rows = $table->getContent()))
            return;

        $this->_flushRow($table_rows[0]->_tight_top);
            
        foreach ($table_rows as $subdef) {
            $this->pushContent($subdef);
            $this->_nrows += $subdef->nrows();
            $this->_next_tight_top = $subdef->_tight_bot;
        }
    }

    function _setTerm ($th) {
        $first_row = &$this->_content[0];
        if (isa($first_row, 'Block_table_dl_defn'))
            $first_row->_setTerm($th);
        else
            $first_row->unshiftContent($th);
    }
    
    function _ComputeNcols ($defn) {
        $ncols = 2;
        foreach ($defn as $item) {
            if ($this->_IsASubtable($item)) {
                $row = $this->_FirstDefn($item);
                $ncols = max($ncols, $row->ncols() + 1);
            }
        }
        return $ncols;
    }

    function _IsASubtable ($item) {
        return isa($item, 'HtmlElement')
            && $item->getTag() == 'table'
            && $item->getAttr('class') == 'wiki-dl-table';
    }

    function _FirstDefn ($subtable) {
        $defs = $subtable->getContent();
        return $defs[0];
    }

    function ncols () {
        return $this->_ncols;
    }

    function nrows () {
        return $this->_nrows;
    }

    function & firstTR() {
	$first = &$this->_content[0];
	if (isa($first, 'Block_table_dl_defn'))
	    return $first->firstTR();
	return $first;
    }

    function & lastTR() {
	$last = &$this->_content[$this->_nrows - 1];
	if (isa($last, 'Block_table_dl_defn'))
	    return $last->lastTR();
	return $last;
    }

    function setWidth ($ncols) {
        assert($ncols >= $this->_ncols);
        if ($ncols <= $this->_ncols)
            return;
        $rows = &$this->_content;
        for ($i = 0; $i < count($rows); $i++) {
            $row = &$rows[$i];
            if (isa($row, 'Block_table_dl_defn'))
                $row->setWidth($ncols - 1);
            else {
                $n = count($row->_content);
                $lastcol = &$row->_content[$n - 1];
                if (!empty($lastcol))
                  $lastcol->setAttr('colspan', $ncols - 1);
            }
        }
    }
}

class Block_table_dl extends Block_dl
{
    var $_tag = 'dl-table';     // phony.

    function Block_table_dl() {
        $this->_re = '\ {0,4} (?:\S.*)? (?<!'.ESCAPE_CHAR.') \| \s* $';
    }

    function _match (&$input, $m) {
        if (!($p = $this->_do_match($input, $m)))
            return false;
        list ($term, $defn, $loose) = $p;

        $this->_content[] = new Block_table_dl_defn($term, $defn);
        return true;
    }

    function _setTightness($top, $bot) {
        $this->_content[0]->setTightness($top, $bot);
    }
    
    function finish () {

        $defs = &$this->_content;

        $ncols = 0;
        foreach ($defs as $defn)
            $ncols = max($ncols, $defn->ncols());
        
        foreach ($defs as $key => $defn)
            $defs[$key]->setWidth($ncols);

        return HTML::table(array('class' => 'wiki-dl-table',
                                 'border' => 1,
                                 'cellspacing' => 0,
                                 'cellpadding' => 6),
                           $defs);
    }
}

class Block_oldlists extends Block_list
{
    //var $_tag = 'ol', 'ul', or 'dl';
    var $_re = '(?: [*] (?!(?=\S)[^*]*(?<=\S)[*](?:\\s|[-)}>"\'\\/:.,;!?_*=]))
                  | [#] (?! \[ .*? \] )
                  | ; .*? :
                ) .*? (?=\S)';

    function _match (&$input, $m) {
        // FIXME:
        if (!preg_match('/[*#;]*$/A', $input->getPrefix())) {
            return false;
        }
        

        $prefix = $m->match;
        $oldindent = '[*#;](?=[#*]|;.*:.*\S)';
        $newindent = sprintf('\\ {%d}', strlen($prefix));
        $indent = "(?:$oldindent|$newindent)";

        $bullet = $prefix[0];
        if ($bullet == '*') {
            $this->_tag = 'ul';
            $itemtag = 'li';
        }
        elseif ($bullet == '#') {
            $this->_tag = 'ol';
            $itemtag = 'li';
        }
        else {
            $this->_tag = 'dl';
            list ($term,) = explode(':', substr($prefix, 1), 2);
            $term = trim($term);
            if ($term)
                $this->_content[] = new Block_HtmlElement('dt', false,
                                                          TransformInline($term));
            $itemtag = 'dd';
        }

        $this->_content[] = new TightSubBlock($input, $indent, $m->match, $itemtag);
        return true;
    }

    function _setTightness($top, $bot) {
        if (count($this->_content) == 1) {
            $li = &$this->_content[0];
            $li->setTightness($top, $bot);
        }
        else {
            // This is where php5 usually brakes.
            // wrong duplicated <li> contents
            if (DEBUG and DEBUG & _DEBUG_PARSER and check_php_version(5)) {
                if (count($this->_content) != 2) {
                    echo "<pre>";
                    /*
                    $class = new Reflection_Class('XmlElement');
                    // Print out basic information
                    printf(
                           "===> The %s%s%s %s '%s' [extends %s]\n".
                           "     declared in %s\n".
                           "     lines %d to %d\n".
                           "     having the modifiers %d [%s]\n",
                           $class->isInternal() ? 'internal' : 'user-defined',
                           $class->isAbstract() ? ' abstract' : '',
                           $class->isFinal() ? ' final' : '',
                           $class->isInterface() ? 'interface' : 'class',
                           $class->getName(),
                           var_export($class->getParentClass(), 1),
                           $class->getFileName(),
                           $class->getStartLine(),
                           $class->getEndline(),
                           $class->getModifiers(),
                           implode(' ', Reflection::getModifierNames($class->getModifiers()))
                           );
                    // Print class properties
                    printf("---> Properties: %s\n", var_export($class->getProperties(), 1));
                    */
                    echo 'count($this->_content): ', count($this->_content),"\n";
                    echo "\$this->_content[0]: "; var_dump ($this->_content[0]);
                    
                    for ($i=1; $i < min(5, count($this->_content)); $i++) {
                        $c =& $this->_content[$i];
                        echo '$this->_content[',$i,"]: \n";
                        echo "_tag: "; var_dump ($c->_tag);
                        echo "_content: "; var_dump ($c->_content);
                        echo "_properties: "; var_dump ($c->_properties);
                    }
                    debug_print_backtrace();
                    if (DEBUG & _DEBUG_APD) {
                        if (function_exists("xdebug_get_function_stack")) {
                            var_dump (xdebug_get_function_stack());
                        }
                    }
                    echo "</pre>";
                }
            }
            if (!check_php_version(5))
                assert(count($this->_content) == 2);
            $dt = &$this->_content[0];
            $dd = &$this->_content[1];
            $dt->setTightness($top, false);
            $dd->setTightness(false, $bot);
        }
    }
}

class Block_pre extends BlockMarkup
{
    var $_re = '<(?:pre|verbatim|nowiki)>';

    function _match (&$input, $m) {
        $endtag = '</' . substr($m->match, 1);
        $text = array();
        $pos = $input->getPos();

        $line = $m->postmatch;
        while (ltrim($line) != $endtag) {
            $text[] = $line;
            if (($line = $input->nextLine()) === false) {
                $input->setPos($pos);
                return false;
            }
        }
        $input->advance();
        
	if ($m->match == '<nowiki>')
	    $text = join("<br>\n", $text);
	else
            $text = join("\n", $text);
        
        // FIXME: no <img>, <big>, <small>, <sup>, or <sub>'s allowed
        // in a <pre>.
        if ($m->match == '<pre>')
            $text = TransformInline($text);
	if ($m->match == '<nowiki>') {
            $text = TransformInlineNowiki($text);
	    $this->_element = new Block_HtmlElement('p', false, $text);
	} else {
            $this->_element = new Block_HtmlElement('pre', false, $text);
	}
        return true;
    }
}

class Block_plugin extends Block_pre
{
    var $_re = '<\?plugin(?:-form)?(?!\S)';

    // FIXME:
    /* <?plugin Backlinks
     *       page=ThisPage ?>
    /* <?plugin ListPages pages=<!plugin-list Backlinks!>
     *                    exclude=<!plugin-list TitleSearch s=T*!> ?>
     *
     * should all work.
     */
    function _match (&$input, $m) {
        $pos = $input->getPos();
        $pi = $m->match . $m->postmatch;
        while (!preg_match('/(?<!'.ESCAPE_CHAR.')\?>\s*$/', $pi)) {
            if (($line = $input->nextLine()) === false) {
                $input->setPos($pos);
                return false;
            }
            $pi .= "\n$line";
        }
        $input->advance();

	$this->_element = new Cached_PluginInvocation($pi);
        return true;
    }
}

class Block_email_blockquote extends BlockMarkup
{
    var $_attr = array('class' => 'mail-style-quote');
    var $_re = '>\ ?';
    
    function _match (&$input, $m) {
        //$indent = str_replace(' ', '\\ ', $m->match) . '|>$';
        $indent = $this->_re;
        $this->_element = new SubBlock($input, $indent, $m->match,
                                       'blockquote', $this->_attr);
        return true;
    }
}

class Block_hr extends BlockMarkup
{
    var $_re = '-{4,}\s*$';

    function _match (&$input, $m) {
        $input->advance();
        $this->_element = new Block_HtmlElement('hr');
        return true;
    }

    function _setTightness($top, $bot) {
	// Don't tighten <hr/>s
    }
}

class Block_heading extends BlockMarkup
{
    var $_re = '!{1,3}';
    
    function _match (&$input, $m) {
        $tag = "h" . (5 - strlen($m->match));
        $text = TransformInline(trim($m->postmatch));
        $input->advance();

        $this->_element = new Block_HtmlElement($tag, false, $text);
        
        return true;
    }

    function _setTightness($top, $bot) {
	// Don't tighten headers.
    }
}

class Block_p extends BlockMarkup
{
    var $_tag = 'p';
    var $_re = '\S.*';
    var $_text = '';

    function _match (&$input, $m) {
        $this->_text = $m->match;
        $input->advance();
        return true;
    }

    function _setTightness ($top, $bot) {
        $this->_tight_top = $top;
        $this->_tight_bot = $bot;
    }

    function merge ($nextBlock) {
        $class = get_class($nextBlock);
        if (strtolower($class) == 'block_p' and $this->_tight_bot) {
            $this->_text .= "\n" . $nextBlock->_text;
            $this->_tight_bot = $nextBlock->_tight_bot;
            return $this;
        }
        return false;
    }
            
    function finish () {
        $content = TransformInline(trim($this->_text));
        $p = new Block_HtmlElement('p', false, $content);
        $p->setTightness($this->_tight_top, $this->_tight_bot);
        return $p;
    }
}

class Block_divspan extends BlockMarkup
{
    var $_re = '<(?im)(?: div|span)(?:[^>]*)?>';

    function _match (&$input, $m) {
    	if (substr($m->match,1,4) == 'span') {
    	    $tag = 'span';
	} else {
    	    $tag = 'div';
	}
	// without last >
        $argstr = substr(trim(substr($m->match,strlen($tag)+1)),0,-1); 
        $pos = $input->getPos();
        $pi  = $content = $m->postmatch;
        while (!preg_match('/^(.*)\<\/'.$tag.'\>(.*)$/i', $pi, $me)) {
            $content .= "\n$pi";;
            if (($pi = $input->nextLine()) === false) {
                $input->setPos($pos);
                return false;
            }
        }
        $content .= $me[1]; // prematch
        $input->advance();
        $content = TransformInline(trim($content));
        if (!$argstr) $args = false;
        else {
            foreach (preg_split("/\s+/", $argstr) as $a) {
                @list($k, $v) = preg_split("/\s*=\s*/", $a);
                if ($v) $v = preg_replace(array("/^[\"']/","/['\"]$/"), array('',''), $v);
                if (trim($k) and trim($v)) $args[$k] = $v;
            }
        }
        $this->_element = new Block_HtmlElement($tag, $args, $content);
        //$this->_element->setTightness($tag == 'span', $tag == 'span');
        return true;
    }
    function _setTightness($top, $bot) {
	// Don't tighten user <div|span>
    }
}


////////////////////////////////////////////////////////////////
//

/**
 * Transform the text of a page, and return a parse tree.
 */
function TransformTextPre ($text, $markup = 2.0, $basepage=false) {
    if (isa($text, 'WikiDB_PageRevision')) {
        $rev = $text;
        $text = $rev->getPackedContent();
        $markup = $rev->get('markup');
    }
    // NEW: default markup is new, to increase stability
    if (!empty($markup) && $markup < 2.0) {
        $text = ConvertOldMarkup($text);
    }
    
    // Expand leading tabs.
    $text = expand_tabs($text);
    //set_time_limit(3);
    $output = new WikiText($text);

    return $output;
}

/**
 * Transform the text of a page, and return an XmlContent,
 * suitable for printXml()-ing.
 */
function TransformText ($text, $markup = 2.0, $basepage=false) {
    $output = TransformTextPre($text, $markup, $basepage);
    if ($basepage) {
        // This is for immediate consumption.
        // We must bind the contents to a base pagename so that
        // relative page links can be properly linkified...
        return new CacheableMarkup($output->getContent(), $basepage);
    }
    return new XmlContent($output->getContent());
}

// $Log: BlockParser.php,v $
// Revision 1.60  2007/01/07 18:41:32  rurban
// Fix ENABLE_DIVSPAN
//
// Revision 1.59  2006/12/22 16:21:29  rurban
// silence one BlockParser use-case
//
// Revision 1.58  2006/11/19 13:57:14  rurban
// fix Regex Syntax Error
//
// Revision 1.57  2006/10/12 06:32:30  rurban
// Optionally support new tags <div>, <span> with ENABLE_MARKUP_DIVSPAN (in work)
//
// Revision 1.56  2006/07/23 14:03:18  rurban
// add new feature: DISABLE_MARKUP_WIKIWORD
//
// Revision 1.55  2005/01/29 21:08:41  rurban
// update (C)
//
// Revision 1.54  2005/01/29 21:00:54  rurban
// do not warn on empty nextBlock
//
// Revision 1.53  2005/01/29 20:36:44  rurban
// very important php5 fix! clone objects
//
// Revision 1.52  2004/10/21 19:52:10  rurban
// Patch #994487: Allow callers to get the parse tree for a page (danfr)
//
// Revision 1.51  2004/09/14 09:54:04  rurban
// cache ParsedBlock::_initBlockTypes
//
// Revision 1.50  2004/09/08 13:38:00  rurban
// improve loadfile stability by using markup=2 as default for undefined markup-style.
// use more refs for huge objects.
// fix debug=static issue in WikiPluginCached
//
// Revision 1.49  2004/07/02 09:55:58  rurban
// more stability fixes: new DISABLE_GETIMAGESIZE if your php crashes when loading LinkIcons: failing getimagesize in old phps; blockparser stabilized
//
// Revision 1.48  2004/06/21 06:30:16  rurban
// revert to prev references
//
// Revision 1.47  2004/06/20 15:30:04  rurban
// get_class case-sensitivity issues
//
// Revision 1.46  2004/06/20 14:42:53  rurban
// various php5 fixes (still broken at blockparser)
//

// (c-file-style: "gnu")
// Local Variables:
// mode: php
// tab-width: 8
// c-basic-offset: 4
// c-hanging-comment-ender-p: nil
// indent-tabs-mode: nil
// End:   
?>