]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/BlockParser.php
Fixed bug #2786559 : Rendering problem in definition list table
[SourceForge/phpwiki.git] / lib / BlockParser.php
1 <?php rcs_id('$Id$');
2 /* Copyright (C) 2002 Geoffrey T. Dairiki <dairiki@dairiki.org>
3  * Copyright (C) 2004,2005 Reini Urban
4  * Copyright (C) 2008-2009 Marc-Etienne Vargenau, Alcatel-Lucent
5  *
6  * This file is part of PhpWiki.
7  * 
8  * PhpWiki is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; either version 2 of the License, or
11  * (at your option) any later version.
12  * 
13  * PhpWiki is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  * 
18  * You should have received a copy of the GNU General Public License
19  * along with PhpWiki; if not, write to the Free Software
20  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
21  */
22 require_once('lib/HtmlElement.php');
23 require_once('lib/CachedMarkup.php');
24 require_once('lib/InlineParser.php');
25
26 /**
27  * Deal with paragraphs and proper, recursive block indents 
28  * for the new style markup (version 2)
29  *
30  * Everything which goes over more than line:
31  * automatic lists, UL, OL, DL, table, blockquote, verbatim, 
32  * p, pre, plugin, ...
33  *
34  * FIXME:
35  *  Still to do:
36  *    (old-style) tables
37  * FIXME: unify this with the RegexpSet in InlineParser.
38  *
39  * FIXME: This is very php5 sensitive: It was fixed for 1.3.9, 
40  *        but is again broken with the 1.3.11 
41  *        allow_call_time_pass_reference clean fixes
42  *
43  * @package Markup
44  * @author: Geoffrey T. Dairiki 
45  */
46
47 /**
48  * Return type from RegexpSet::match and RegexpSet::nextMatch.
49  *
50  * @see RegexpSet
51  */
52 class AnchoredRegexpSet_match {
53     /**
54      * The matched text.
55      */
56     var $match;
57
58     /**
59      * The text following the matched text.
60      */
61     var $postmatch;
62
63     /**
64      * Index of the regular expression which matched.
65      */
66     var $regexp_ind;
67 }
68
69 /**
70  * A set of regular expressions.
71  *
72  * This class is probably only useful for InlineTransformer.
73  */
74 class AnchoredRegexpSet
75 {
76     /** Constructor
77      *
78      * @param $regexps array A list of regular expressions.  The
79      * regular expressions should not include any sub-pattern groups
80      * "(...)".  (Anonymous groups, like "(?:...)", as well as
81      * look-ahead and look-behind assertions are fine.)
82      */
83     function AnchoredRegexpSet ($regexps) {
84         $this->_regexps = $regexps;
85         $this->_re = "/((" . join(")|(", $regexps) . "))/Ax";
86     }
87
88     /**
89      * Search text for the next matching regexp from the Regexp Set.
90      *
91      * @param $text string The text to search.
92      *
93      * @return object  A RegexpSet_match object, or false if no match.
94      */
95     function match ($text) {
96         if (!is_string($text)) return false;
97         if (! preg_match($this->_re, $text, $m)) {
98             return false;
99         }
100         
101         $match = new AnchoredRegexpSet_match;
102         $match->postmatch = substr($text, strlen($m[0]));
103         $match->match = $m[1];
104         $match->regexp_ind = count($m) - 3;
105         return $match;
106     }
107
108     /**
109      * Search for next matching regexp.
110      *
111      * Here, 'next' has two meanings:
112      *
113      * Match the next regexp(s) in the set, at the same position as the last match.
114      *
115      * If that fails, match the whole RegexpSet, starting after the position of the
116      * previous match.
117      *
118      * @param $text string Text to search.
119      *
120      * @param $prevMatch A RegexpSet_match object
121      *
122      * $prevMatch should be a match object obtained by a previous
123      * match upon the same value of $text.
124      *
125      * @return object  A RegexpSet_match object, or false if no match.
126      */
127     function nextMatch ($text, $prevMatch) {
128         // Try to find match at same position.
129         $regexps = array_slice($this->_regexps, $prevMatch->regexp_ind + 1);
130         if (!$regexps) {
131             return false;
132         }
133
134         $pat= "/ ( (" . join(')|(', $regexps) . ") ) /Axs";
135
136         if (! preg_match($pat, $text, $m)) {
137             return false;
138         }
139         
140         $match = new AnchoredRegexpSet_match;
141         $match->postmatch = substr($text, strlen($m[0]));
142         $match->match = $m[1];
143         $match->regexp_ind = count($m) - 3 + $prevMatch->regexp_ind + 1;;
144         return $match;
145     }
146 }
147
148
149     
150 class BlockParser_Input {
151
152     function BlockParser_Input ($text) {
153         
154         // Expand leading tabs.
155         // FIXME: do this better.
156         //
157         // We want to ensure the only characters matching \s are ' ' and "\n".
158         //
159         $text = preg_replace('/(?![ \n])\s/', ' ', $text);
160         assert(!preg_match('/(?![ \n])\s/', $text));
161
162         $this->_lines = preg_split('/[^\S\n]*\n/', $text);
163         $this->_pos = 0;
164
165         // Strip leading blank lines.
166         while ($this->_lines and ! $this->_lines[0])
167             array_shift($this->_lines);
168         $this->_atSpace = false;
169     }
170
171     function skipSpace () {
172         $nlines = count($this->_lines);
173         while (1) {
174             if ($this->_pos >= $nlines) {
175                 $this->_atSpace = false;
176                 break;
177             }
178             if ($this->_lines[$this->_pos] != '')
179                 break;
180             $this->_pos++;
181             $this->_atSpace = true;
182         }
183         return $this->_atSpace;
184     }
185         
186     function currentLine () {
187         if ($this->_pos >= count($this->_lines)) {
188             return false;
189         }
190         return $this->_lines[$this->_pos];
191     }
192         
193     function nextLine () {
194         $this->_atSpace = $this->_lines[$this->_pos++] === '';
195         if ($this->_pos >= count($this->_lines)) {
196             return false;
197         }
198         return $this->_lines[$this->_pos];
199     }
200
201     function advance () {
202         $this->_atSpace = ($this->_lines[$this->_pos] === '');
203         $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         flush();                   
237     }
238 }
239
240 class BlockParser_InputSubBlock extends BlockParser_Input
241 {
242     function BlockParser_InputSubBlock (&$input, $prefix_re, $initial_prefix = false) {
243         $this->_input = &$input;
244         $this->_prefix_pat = "/$prefix_re|\\s*\$/Ax";
245         $this->_atSpace = false;
246
247         if (($line = $input->currentLine()) === false)
248             $this->_line = false;
249         elseif ($initial_prefix) {
250             assert(substr($line, 0, strlen($initial_prefix)) == $initial_prefix);
251             $this->_line = (string) substr($line, strlen($initial_prefix));
252             $this->_atBlank = ! ltrim($line);
253         }
254         elseif (preg_match($this->_prefix_pat, $line, $m)) {
255             $this->_line = (string) substr($line, strlen($m[0]));
256             $this->_atBlank = ! ltrim($line);
257         }
258         else
259             $this->_line = false;
260     }
261
262     function skipSpace () {
263         // In contrast to the case for top-level blocks,
264         // for sub-blocks, there never appears to be any trailing space.
265         // (The last block in the sub-block should always be of class tight-bottom.)
266         while ($this->_line === '')
267             $this->advance();
268
269         if ($this->_line === false)
270             return $this->_atSpace == 'strong_space';
271         else
272             return $this->_atSpace;
273     }
274         
275     function currentLine () {
276         return $this->_line;
277     }
278
279     function nextLine () {
280         if ($this->_line === '')
281             $this->_atSpace = $this->_atBlank ? 'weak_space' : 'strong_space';
282         else
283             $this->_atSpace = false;
284
285         $line = $this->_input->nextLine();
286         if ($line !== false && preg_match($this->_prefix_pat, $line, $m)) {
287             $this->_line = (string) substr($line, strlen($m[0]));
288             $this->_atBlank = ! ltrim($line);
289         }
290         else
291             $this->_line = false;
292
293         return $this->_line;
294     }
295
296     function advance () {
297         $this->nextLine();
298     }
299         
300     function getPos () {
301         return array($this->_line, $this->_atSpace, $this->_input->getPos());
302     }
303
304     function setPos ($pos) {
305         $this->_line = $pos[0];
306         $this->_atSpace = $pos[1];
307         $this->_input->setPos($pos[2]);
308     }
309     
310     function getPrefix () {
311         assert ($this->_line !== false);
312         $line = $this->_input->currentLine();
313         assert ($line !== false && strlen($line) >= strlen($this->_line));
314         return substr($line, 0, strlen($line) - strlen($this->_line));
315     }
316
317     function getDepth () {
318         return $this->_input->getDepth() + 1;
319     }
320
321     function where () {
322         return $this->_input->where();
323     }
324 }
325     
326
327 class Block_HtmlElement extends HtmlElement
328 {
329     function Block_HtmlElement($tag /*, ... */) {
330         $this->_init(func_get_args());
331     }
332
333     function setTightness($top, $bottom) {
334     }
335 }
336
337 class ParsedBlock extends Block_HtmlElement {
338     
339     function ParsedBlock (&$input, $tag = 'div', $attr = false) {
340         $this->Block_HtmlElement($tag, $attr);
341         $this->_initBlockTypes();
342         $this->_parse($input);
343     }
344
345     function _parse (&$input) {
346         // php5 failed to advance the block. php5 copies objects by ref.
347         // nextBlock == block, both are the same objects. So we have to clone it.
348         for ($block = $this->_getBlock($input); 
349              $block; 
350              $block = (is_object($nextBlock) ? clone($nextBlock) : $nextBlock))
351         {
352             while ($nextBlock = $this->_getBlock($input)) {
353                 // Attempt to merge current with following block.
354                 if (! ($merged = $block->merge($nextBlock)) ) {
355                     break;      // can't merge
356                 }
357                 $block = $merged;
358             }
359             $this->pushContent($block->finish());
360         }
361     }
362
363     // FIXME: hackish. This should only be called once.
364     function _initBlockTypes () {
365         // better static or global?
366         static $_regexpset, $_block_types;
367
368         if (!is_object($_regexpset)) {
369             // nowiki_wikicreole must be before template_plugin
370             $Block_types = array
371                     ('nowiki_wikicreole', 'template_plugin', 'placeholder', 'oldlists', 'list', 'dl',
372                      'table_dl', 'table_wikicreole', 'table_mediawiki',
373                      'blockquote', 'heading', 'heading_wikicreole', 'hr', 'pre', 'email_blockquote',
374                      'plugin', 'plugin_wikicreole', 'p');
375             // insert it before p!
376             if (ENABLE_MARKUP_DIVSPAN) {
377                 array_pop($Block_types);
378                 $Block_types[] = 'divspan';
379                 $Block_types[] = 'p';
380             }
381             foreach ($Block_types as $type) {
382                 $class = "Block_$type";
383                 $proto = new $class;
384                 $this->_block_types[] = $proto;
385                 $this->_regexps[] = $proto->_re;
386             }
387             $this->_regexpset = new AnchoredRegexpSet($this->_regexps);
388             $_regexpset = $this->_regexpset;
389             $_block_types = $this->_block_types;
390             unset($Block_types);
391         } else {
392              $this->_regexpset = $_regexpset;
393              $this->_block_types = $_block_types;
394         }
395     }
396
397     function _getBlock (&$input) {
398         $this->_atSpace = $input->skipSpace();
399
400         $line = $input->currentLine();
401         if ($line === false or $line === '') { // allow $line === '0' 
402             return false;
403         }
404         $tight_top = !$this->_atSpace;
405         $re_set = &$this->_regexpset;
406         //FIXME: php5 fails to advance here!
407         for ($m = $re_set->match($line); $m; $m = $re_set->nextMatch($line, $m)) {
408             $block = clone($this->_block_types[$m->regexp_ind]);
409             if (DEBUG & _DEBUG_PARSER)
410                 $input->_debug('>', get_class($block));
411             
412             if ($block->_match($input, $m)) {
413                 //$block->_text = $line;
414                 if (DEBUG & _DEBUG_PARSER)
415                     $input->_debug('<', get_class($block));
416                 $tight_bottom = ! $input->skipSpace();
417                 $block->_setTightness($tight_top, $tight_bottom);
418                 return $block;
419             }
420             if (DEBUG & _DEBUG_PARSER)
421                 $input->_debug('[', "_match failed");
422         }
423         if ($line === false or $line === '') // allow $line === '0' 
424             return false;
425
426         trigger_error("Couldn't match block: '$line'", E_USER_NOTICE);
427         return false;
428     }
429 }
430
431 class WikiText extends ParsedBlock {
432     function WikiText ($text) {
433         $input = new BlockParser_Input($text);
434         $this->ParsedBlock($input);
435     }
436 }
437
438 class SubBlock extends ParsedBlock {
439     function SubBlock (&$input, $indent_re, $initial_indent = false,
440                        $tag = 'div', $attr = false) {
441         $subinput = new BlockParser_InputSubBlock($input, $indent_re, $initial_indent);
442         $this->ParsedBlock($subinput, $tag, $attr);
443     }
444 }
445
446 /**
447  * TightSubBlock is for use in parsing lists item bodies.
448  *
449  * If the sub-block consists of a single paragraph, it omits
450  * the paragraph element.
451  *
452  * We go to this trouble so that "tight" lists look somewhat reasonable
453  * in older (non-CSS) browsers.  (If you don't do this, then, without
454  * CSS, you only get "loose" lists.
455  */
456 class TightSubBlock extends SubBlock {
457     function TightSubBlock (&$input, $indent_re, $initial_indent = false,
458                             $tag = 'div', $attr = false) {
459         $this->SubBlock($input, $indent_re, $initial_indent, $tag, $attr);
460
461         // If content is a single paragraph, eliminate the paragraph...
462         if (count($this->_content) == 1) {
463             $elem = $this->_content[0];
464             if (isa($elem, 'XmlElement') and $elem->getTag() == 'p') {
465                 $this->setContent($elem->getContent());
466             }
467         }
468     }
469 }
470
471 class BlockMarkup {
472     var $_re;
473
474     function _match (&$input, $match) {
475         trigger_error('pure virtual', E_USER_ERROR);
476     }
477
478     function _setTightness ($top, $bot) {
479         // $this->_element->setTightness($top, $bot);
480     }
481
482     function merge ($followingBlock) {
483         return false;
484     }
485
486     function finish () {
487         return $this->_element;
488     }
489 }
490
491 class Block_blockquote extends BlockMarkup
492 {
493     var $_depth;
494     var $_re = '\ +(?=\S)';
495
496     function _match (&$input, $m) {
497         $this->_depth = strlen($m->match);
498         $indent = sprintf("\\ {%d}", $this->_depth);
499         $this->_element = new SubBlock($input, $indent, $m->match,
500                                        'blockquote');
501         return true;
502     }
503     
504     function merge ($nextBlock) {
505         if (get_class($nextBlock) == get_class($this)) {
506             assert ($nextBlock->_depth < $this->_depth);
507             $nextBlock->_element->unshiftContent($this->_element);
508             if (!empty($this->_tight_top))
509             $nextBlock->_tight_top = $this->_tight_top;
510             return $nextBlock;
511         }
512         return false;
513     }
514 }
515
516 class Block_list extends BlockMarkup
517 {
518     //var $_tag = 'ol' or 'ul';
519     var $_re = '\ {0,4}
520                 (?: \+
521                   | \\#\ (?!\[.*\])
522                   | -(?!-)
523                   | [o](?=\ )
524                   | [*]\ (?!(?=\S)[^*]*(?<=\S)[*](?:\\s|[-)}>"\'\\/:.,;!?_*=]) )
525                 )\ *(?=\S)';
526     var $_content = array();
527
528     function _match (&$input, $m) {
529         // A list as the first content in a list is not allowed.
530         // E.g.:
531         //   *  * Item
532         // Should markup as <ul><li>* Item</li></ul>,
533         // not <ul><li><ul><li>Item</li></ul>/li></ul>.
534         //
535         if (preg_match('/[*#+-o]/', $input->getPrefix())) {
536             return false;
537         }
538         
539         $prefix = $m->match;
540         $indent = sprintf("\\ {%d}", strlen($prefix));
541
542         $bullet = trim($m->match);
543         $this->_tag = $bullet == '#' ? 'ol' : 'ul';
544         $this->_content[] = new TightSubBlock($input, $indent, $m->match, 'li');
545         return true;
546     }
547
548     function _setTightness($top, $bot) {
549         $li = &$this->_content[0];
550         $li->setTightness($top, $bot);
551     }
552     
553     function merge ($nextBlock) {
554         if (isa($nextBlock, 'Block_list') and $this->_tag == $nextBlock->_tag) {
555             if ($nextBlock->_content === $this->_content) {
556                 trigger_error("Internal Error: no block advance", E_USER_NOTICE);
557                 return false;
558             }
559             array_splice($this->_content, count($this->_content), 0,
560                          $nextBlock->_content);
561             return $this;
562         }
563         return false;
564     }
565
566     function finish () {
567         return new Block_HtmlElement($this->_tag, false, $this->_content);
568     }
569 }
570
571 class Block_dl extends Block_list
572 {
573     var $_tag = 'dl';
574
575     function Block_dl () {
576         $this->_re = '\ {0,4}\S.*(?<!'.ESCAPE_CHAR.'):\s*$';
577     }
578
579     function _match (&$input, $m) {
580         if (!($p = $this->_do_match($input, $m)))
581             return false;
582         list ($term, $defn, $loose) = $p;
583
584         $this->_content[] = new Block_HtmlElement('dt', false, $term);
585         $this->_content[] = $defn;
586         $this->_tight_defn = !$loose;
587         return true;
588     }
589
590     function _setTightness($top, $bot) {
591         $dt = &$this->_content[0];
592         $dd = &$this->_content[1];
593
594         $dt->setTightness($top, $this->_tight_defn);
595         $dd->setTightness($this->_tight_defn, $bot);
596     }
597
598     function _do_match (&$input, $m) {
599         $pos = $input->getPos();
600
601         $firstIndent = strspn($m->match, ' ');
602         $pat = sprintf('/\ {%d,%d}(?=\s*\S)/A', $firstIndent + 1, $firstIndent + 5);
603
604         $input->advance();
605         $loose = $input->skipSpace();
606         $line = $input->currentLine();
607
608         if (!$line || !preg_match($pat, $line, $mm)) {
609             $input->setPos($pos);
610             return false;       // No body found.
611         }
612
613         $indent = strlen($mm[0]);
614         $term = TransformInline(rtrim(substr(trim($m->match),0,-1)));
615         $defn = new TightSubBlock($input, sprintf("\\ {%d}", $indent), false, 'dd');
616         return array($term, $defn, $loose);
617     }
618 }
619
620
621
622 class Block_table_dl_defn extends XmlContent
623 {
624     var $nrows;
625     var $ncols;
626     
627     function Block_table_dl_defn ($term, $defn) {
628         $this->XmlContent();
629         if (!is_array($defn))
630             $defn = $defn->getContent();
631
632         $this->_next_tight_top = false; // value irrelevant - gets fixed later
633         $this->_ncols = $this->_ComputeNcols($defn);
634         $this->_nrows = 0;
635
636         foreach ($defn as $item) {
637             if ($this->_IsASubtable($item))
638                 $this->_addSubtable($item);
639             else
640                 $this->_addToRow($item);
641         }
642         $this->_flushRow();
643
644         $th = HTML::th($term);
645         if ($this->_nrows > 1)
646             $th->setAttr('rowspan', $this->_nrows);
647         $this->_setTerm($th);
648     }
649
650     function setTightness($tight_top, $tight_bot) {
651         $this->_tight_top = $tight_top;
652         $this->_tight_bot = $tight_bot;
653     }
654     
655     function _addToRow ($item) {
656         if (empty($this->_accum)) {
657             $this->_accum = HTML::td();
658             if ($this->_ncols > 2)
659                 $this->_accum->setAttr('colspan', $this->_ncols - 1);
660         }
661         $this->_accum->pushContent($item);
662     }
663
664     function _flushRow ($tight_bottom=false) {
665         if (!empty($this->_accum)) {
666             $row = new Block_HtmlElement('tr', false, $this->_accum);
667
668             $row->setTightness($this->_next_tight_top, $tight_bottom);
669             $this->_next_tight_top = $tight_bottom;
670             
671             $this->pushContent($row);
672             $this->_accum = false;
673             $this->_nrows++;
674         }
675     }
676
677     function _addSubtable ($table) {
678         if (!($table_rows = $table->getContent()))
679             return;
680
681         $this->_flushRow($table_rows[0]->_tight_top);
682             
683         foreach ($table_rows as $subdef) {
684             $this->pushContent($subdef);
685             $this->_nrows += $subdef->nrows();
686             $this->_next_tight_top = $subdef->_tight_bot;
687         }
688     }
689
690     function _setTerm ($th) {
691         $first_row = &$this->_content[0];
692         if (isa($first_row, 'Block_table_dl_defn'))
693             $first_row->_setTerm($th);
694         else
695             $first_row->unshiftContent($th);
696     }
697     
698     function _ComputeNcols ($defn) {
699         $ncols = 2;
700         foreach ($defn as $item) {
701             if ($this->_IsASubtable($item)) {
702                 $row = $this->_FirstDefn($item);
703                 $ncols = max($ncols, $row->ncols() + 1);
704             }
705         }
706         return $ncols;
707     }
708
709     function _IsASubtable ($item) {
710         return isa($item, 'HtmlElement')
711             && $item->getTag() == 'table'
712             && $item->getAttr('class') == 'wiki-dl-table';
713     }
714
715     function _FirstDefn ($subtable) {
716         $defs = $subtable->getContent();
717         return $defs[0];
718     }
719
720     function ncols () {
721         return $this->_ncols;
722     }
723
724     function nrows () {
725         return $this->_nrows;
726     }
727
728     function & firstTR() {
729         $first = &$this->_content[0];
730         if (isa($first, 'Block_table_dl_defn'))
731             return $first->firstTR();
732         return $first;
733     }
734
735     function & lastTR() {
736         $last = &$this->_content[$this->_nrows - 1];
737         if (isa($last, 'Block_table_dl_defn'))
738             return $last->lastTR();
739         return $last;
740     }
741
742     function setWidth ($ncols) {
743         assert($ncols >= $this->_ncols);
744         if ($ncols <= $this->_ncols)
745             return;
746         $rows = &$this->_content;
747         for ($i = 0; $i < count($rows); $i++) {
748             $row = &$rows[$i];
749             if (isa($row, 'Block_table_dl_defn'))
750                 $row->setWidth($ncols - 1);
751             else {
752                 $n = count($row->_content);
753                 $lastcol = &$row->_content[$n - 1];
754                 if (!empty($lastcol))
755                   $lastcol->setAttr('colspan', $ncols - 1);
756             }
757         }
758     }
759 }
760
761 class Block_table_dl extends Block_dl
762 {
763     var $_tag = 'dl-table';     // phony.
764
765     function Block_table_dl() {
766         $this->_re = '\ {0,4} (?:\S.*)? (?<!'.ESCAPE_CHAR.') \| \s* $';
767     }
768
769     function _match (&$input, $m) {
770         if (!($p = $this->_do_match($input, $m)))
771             return false;
772         list ($term, $defn, $loose) = $p;
773
774         $this->_content[] = new Block_table_dl_defn($term, $defn);
775         return true;
776     }
777
778     function _setTightness($top, $bot) {
779         $this->_content[0]->setTightness($top, $bot);
780     }
781     
782     function finish () {
783
784         $defs = &$this->_content;
785
786         $ncols = 0;
787         foreach ($defs as $defn)
788             $ncols = max($ncols, $defn->ncols());
789         
790         foreach ($defs as $key => $defn)
791             $defs[$key]->setWidth($ncols);
792
793         return HTML::table(array('class' => 'wiki-dl-table',
794                                  'border' => 1,
795                                  'cellspacing' => 0,
796                                  'cellpadding' => 6),
797                            $defs);
798     }
799 }
800
801 class Block_oldlists extends Block_list
802 {
803     //var $_tag = 'ol', 'ul', or 'dl';
804     var $_re = '(?: [*]\ (?!(?=\S)[^*]*(?<=\S)[*](?:\\s|[-)}>"\'\\/:.,;!?_*=]))
805                   | [#]\ (?! \[ .*? \] )
806                   | ; .*? :
807                 ) .*? (?=\S)';
808
809     function _match (&$input, $m) {
810         // FIXME:
811         if (!preg_match('/[*#;]*$/A', $input->getPrefix())) {
812             return false;
813         }
814         
815
816         $prefix = $m->match;
817         $oldindent = '[*#;](?=[#*]|;.*:.*\S)';
818         $newindent = sprintf('\\ {%d}', strlen($prefix));
819         $indent = "(?:$oldindent|$newindent)";
820
821         $bullet = $prefix[0];
822         if ($bullet == '*') {
823             $this->_tag = 'ul';
824             $itemtag = 'li';
825         }
826         elseif ($bullet == '#') {
827             $this->_tag = 'ol';
828             $itemtag = 'li';
829         }
830         else {
831             $this->_tag = 'dl';
832             list ($term,) = explode(':', substr($prefix, 1), 2);
833             $term = trim($term);
834             if ($term)
835                 $this->_content[] = new Block_HtmlElement('dt', false,
836                                                           TransformInline($term));
837             $itemtag = 'dd';
838         }
839
840         $this->_content[] = new TightSubBlock($input, $indent, $m->match, $itemtag);
841         return true;
842     }
843
844     function _setTightness($top, $bot) {
845         if (count($this->_content) == 1) {
846             $li = &$this->_content[0];
847             $li->setTightness($top, $bot);
848         }
849         else {
850             // This is where php5 usually brakes.
851             // wrong duplicated <li> contents
852             if (DEBUG and DEBUG & _DEBUG_PARSER and check_php_version(5)) {
853                 if (count($this->_content) != 2) {
854                     echo "<pre>";
855                     /*
856                     $class = new Reflection_Class('XmlElement');
857                     // Print out basic information
858                     printf(
859                            "===> The %s%s%s %s '%s' [extends %s]\n".
860                            "     declared in %s\n".
861                            "     lines %d to %d\n".
862                            "     having the modifiers %d [%s]\n",
863                            $class->isInternal() ? 'internal' : 'user-defined',
864                            $class->isAbstract() ? ' abstract' : '',
865                            $class->isFinal() ? ' final' : '',
866                            $class->isInterface() ? 'interface' : 'class',
867                            $class->getName(),
868                            var_export($class->getParentClass(), 1),
869                            $class->getFileName(),
870                            $class->getStartLine(),
871                            $class->getEndline(),
872                            $class->getModifiers(),
873                            implode(' ', Reflection::getModifierNames($class->getModifiers()))
874                            );
875                     // Print class properties
876                     printf("---> Properties: %s\n", var_export($class->getProperties(), 1));
877                     */
878                     echo 'count($this->_content): ', count($this->_content),"\n";
879                     echo "\$this->_content[0]: "; var_dump ($this->_content[0]);
880                     
881                     for ($i=1; $i < min(5, count($this->_content)); $i++) {
882                         $c =& $this->_content[$i];
883                         echo '$this->_content[',$i,"]: \n";
884                         echo "_tag: "; var_dump ($c->_tag);
885                         echo "_content: "; var_dump ($c->_content);
886                         echo "_properties: "; var_dump ($c->_properties);
887                     }
888                     debug_print_backtrace();
889                     if (DEBUG & _DEBUG_APD) {
890                         if (function_exists("xdebug_get_function_stack")) {
891                             var_dump (xdebug_get_function_stack());
892                         }
893                     }
894                     echo "</pre>";
895                 }
896             }
897             if (!check_php_version(5))
898                 assert(count($this->_content) == 2);
899             $dt = &$this->_content[0];
900             $dd = &$this->_content[1];
901             $dt->setTightness($top, false);
902             $dd->setTightness(false, $bot);
903         }
904     }
905 }
906
907 class Block_pre extends BlockMarkup
908 {
909     var $_re = '<(?:pre|verbatim|nowiki|noinclude)>';
910
911     function _match (&$input, $m) {
912         $endtag = '</' . substr($m->match, 1);
913         $text = array();
914         $pos = $input->getPos();
915
916         $line = $m->postmatch;
917         while (ltrim($line) != $endtag) {
918             $text[] = $line;
919             if (($line = $input->nextLine()) === false) {
920                 $input->setPos($pos);
921                 return false;
922             }
923         }
924         $input->advance();
925         
926         if ($m->match == '<nowiki>')
927             $text = join("<br>\n", $text);
928         else
929             $text = join("\n", $text);
930         
931         // FIXME: no <img>, <big>, <small>, <sup>, or <sub>'s allowed
932         // in a <pre>.
933         if ($m->match == '<pre>') {
934             $text = TransformInline($text);
935         }
936         if ($m->match == '<noinclude>') {
937             $text = TransformText($text);
938             $this->_element = new Block_HtmlElement('div', false, $text);
939         } else if ($m->match == '<nowiki>') {
940             $text = TransformInlineNowiki($text);
941             $this->_element = new Block_HtmlElement('p', false, $text);
942         } else {
943             $this->_element = new Block_HtmlElement('pre', false, $text);
944         }
945         return true;
946     }
947 }
948
949 // Wikicreole placeholder
950 // <<<placeholder>>>
951 class Block_placeholder extends BlockMarkup
952 {
953     var $_re = '<<<';
954
955     function _match (&$input, $m) {
956         $endtag = '>>>';
957         $text = array();
958         $pos = $input->getPos();
959
960         $line = $m->postmatch;
961         while (ltrim($line) != $endtag) {
962             $text[] = $line;
963             if (($line = $input->nextLine()) === false) {
964                 $input->setPos($pos);
965                 return false;
966             }
967         }
968         $input->advance();
969
970         $text = join("\n", $text);
971         $text = '<<<' . $text . '>>>';
972         $this->_element = new Block_HtmlElement('div', false, $text);
973         return true;
974     }
975 }
976
977 class Block_nowiki_wikicreole extends BlockMarkup
978 {
979     var $_re = '{{{';
980
981     function _match (&$input, $m) {
982         $endtag = '}}}';
983         $text = array();
984         $pos = $input->getPos();
985
986         $line = $m->postmatch;
987         while (ltrim($line) != $endtag) {
988             $text[] = $line;
989             if (($line = $input->nextLine()) === false) {
990                 $input->setPos($pos);
991                 return false;
992             }
993         }
994         $input->advance();
995
996         $text = join("\n", $text);
997         $this->_element = new Block_HtmlElement('pre', false, $text);
998         return true;
999     }
1000 }
1001
1002 class Block_plugin extends Block_pre
1003 {
1004     var $_re = '<\?plugin(?:-form)?(?!\S)';
1005
1006     // FIXME:
1007     /* <?plugin Backlinks
1008      *       page=ThisPage ?>
1009     /* <?plugin ListPages pages=<!plugin-list Backlinks!>
1010      *                    exclude=<!plugin-list TitleSearch s=T*!> ?>
1011      *
1012      * should all work.
1013      */
1014     function _match (&$input, $m) {
1015         $pos = $input->getPos();
1016         $pi = $m->match . $m->postmatch;
1017         while (!preg_match('/(?<!'.ESCAPE_CHAR.')\?>\s*$/', $pi)) {
1018             if (($line = $input->nextLine()) === false) {
1019                 $input->setPos($pos);
1020                 return false;
1021             }
1022             $pi .= "\n$line";
1023         }
1024         $input->advance();
1025
1026         $this->_element = new Cached_PluginInvocation($pi);
1027         return true;
1028     }
1029 }
1030
1031 class Block_plugin_wikicreole extends Block_pre
1032 {
1033     // var $_re = '<<(?!\S)';
1034     var $_re = '<<';
1035
1036     function _match (&$input, $m) {
1037         $pos = $input->getPos();
1038         $pi = $m->postmatch;
1039         if ($pi[0] == '<') {
1040             return false;
1041         }
1042         $pi = "<?plugin " . $pi;
1043         while (!preg_match('/(?<!'.ESCAPE_CHAR.')>>\s*$/', $pi)) {
1044             if (($line = $input->nextLine()) === false) {
1045                 $input->setPos($pos);
1046                 return false;
1047             }
1048             $pi .= "\n$line";
1049         }
1050         $input->advance();
1051
1052         $pi = str_replace(">>", "?>", $pi);
1053
1054         $this->_element = new Cached_PluginInvocation($pi);
1055         return true;
1056     }
1057 }
1058
1059 class Block_table_wikicreole extends Block_pre
1060 {
1061     var $_re = '\s*\|';
1062
1063     function _match (&$input, $m) {
1064         $pos = $input->getPos();
1065         $pi = "|" . $m->postmatch;
1066
1067         $intable = true;
1068         while ($intable) {
1069             if ((($line = $input->nextLine()) === false) && !$intable) {
1070                 $input->setPos($pos);
1071                 return false;
1072             }
1073             if (!$line) {
1074                 $intable = false;
1075                 $trimline = $line;
1076             } else {
1077                 $trimline = trim($line);
1078                 if ($trimline[0] != "|") {
1079                     $intable = false;
1080                 }
1081             }
1082             $pi .= "\n$trimline";
1083         }
1084
1085         $pi = '<'.'?plugin WikicreoleTable ' . $pi . '?'.'>';
1086
1087         $this->_element = new Cached_PluginInvocation($pi);
1088         return true;
1089     }
1090 }
1091
1092 /** ENABLE_MARKUP_MEDIAWIKI_TABLE
1093  *  Table syntax similar to Mediawiki
1094  *  {|
1095  * => <?plugin MediawikiTable
1096  *  |}
1097  * => ?>
1098  */
1099 class Block_table_mediawiki extends Block_pre
1100 {
1101     var $_re = '{\|';
1102
1103     function _match (&$input, $m) {
1104         $pos = $input->getPos();
1105         $pi = $m->postmatch;
1106         while (!preg_match('/(?<!'.ESCAPE_CHAR.')\|}\s*$/', $pi)) {
1107             if (($line = $input->nextLine()) === false) {
1108                 $input->setPos($pos);
1109                 return false;
1110             }
1111             $pi .= "\n$line";
1112         }
1113         $input->advance();
1114
1115         $pi = str_replace("\|}", "", $pi);
1116         $pi = '<'.'?plugin MediawikiTable ' . $pi . '?'.'>';
1117         $this->_element = new Cached_PluginInvocation($pi);
1118         return true;
1119     }
1120 }
1121
1122 class Block_template_plugin extends Block_pre
1123 {
1124     var $_re = '{{';
1125
1126     function _match (&$input, $m) {
1127         $pos = $input->getPos();
1128         $pi = $m->postmatch;
1129         if ($pi[0] == '{') {
1130             return false;
1131         }
1132         while (!preg_match('/(?<!'.ESCAPE_CHAR.')}}\s*$/', $pi)) {
1133             if (($line = $input->nextLine()) === false) {
1134                 $input->setPos($pos);
1135                 return false;
1136             }
1137             $pi .= "\n$line";
1138         }
1139         $input->advance();
1140
1141         $pi = trim($pi);
1142         $pi = trim($pi, "}}");
1143
1144         if (strpos($pi, "|") === false) {
1145             $imagename = $pi;
1146             $alt = "";
1147         } else {
1148             $imagename = substr($pi, 0, strpos($pi, "|"));
1149             $alt = ltrim(strstr($pi, "|"), "|");
1150         }
1151
1152         // It's not a Mediawiki template, it's a Wikicreole image
1153         if (is_image($imagename)) {
1154             $this->_element = LinkImage(getUploadDataPath() . $imagename, $alt);
1155             return true;
1156         }
1157
1158         $pi = str_replace("\n", "", $pi);
1159         $vars = '';
1160
1161         if (preg_match('/^(\S+?)\|(.*)$/', $pi, $_m)) {
1162             $pi = $_m[1];
1163             $vars = '"' . preg_replace('/\|/', '" "', $_m[2]) . '"';
1164             $vars = preg_replace('/"(\S+)=([^"]*)"/', '\\1="\\2"', $vars);
1165         }
1166
1167         // pi may contain a version number
1168         // {{foo?version=5}}
1169         // in that case, output is "page=foo rev=5"
1170         if (strstr($pi, "?")) {
1171             $pi = str_replace("?version=", "\" rev=\"", $page);
1172         }
1173
1174         if ($vars)
1175             $pi = '<'.'?plugin Template page="'.$pi.'" '.$vars . ' ?>';
1176         else
1177             $pi = '<'.'?plugin Template page="' . $pi . '" ?>';
1178         $this->_element = new Cached_PluginInvocation($pi);
1179         return true;
1180     }
1181 }
1182
1183 class Block_email_blockquote extends BlockMarkup
1184 {
1185     var $_attr = array('class' => 'mail-style-quote');
1186     var $_re = '>\ ?';
1187     
1188     function _match (&$input, $m) {
1189         //$indent = str_replace(' ', '\\ ', $m->match) . '|>$';
1190         $indent = $this->_re;
1191         $this->_element = new SubBlock($input, $indent, $m->match,
1192                                        'blockquote', $this->_attr);
1193         return true;
1194     }
1195 }
1196
1197 class Block_hr extends BlockMarkup
1198 {
1199     var $_re = '-{4,}\s*$';
1200
1201     function _match (&$input, $m) {
1202         $input->advance();
1203         $this->_element = new Block_HtmlElement('hr');
1204         return true;
1205     }
1206
1207     function _setTightness($top, $bot) {
1208         // Don't tighten <hr/>s
1209     }
1210 }
1211
1212 class Block_heading extends BlockMarkup
1213 {
1214     var $_re = '!{1,3}';
1215     
1216     function _match (&$input, $m) {
1217         $tag = "h" . (5 - strlen($m->match));
1218         $text = TransformInline(trim($m->postmatch));
1219         $input->advance();
1220
1221         $this->_element = new Block_HtmlElement($tag, false, $text);
1222         
1223         return true;
1224     }
1225
1226     function _setTightness($top, $bot) {
1227         // Don't tighten headers.
1228     }
1229 }
1230
1231 class Block_heading_wikicreole extends BlockMarkup
1232 {
1233     var $_re = '={2,6}';
1234     
1235     function _match (&$input, $m) {
1236         $tag = "h" . strlen($m->match);
1237         // Remove spaces
1238         $header = trim($m->postmatch);
1239         // Remove '='s at the end so that Mediawiki syntax is recognized
1240         $header = trim($header, "=");
1241         $text = TransformInline(trim($header));
1242         $input->advance();
1243
1244         $this->_element = new Block_HtmlElement($tag, false, $text);
1245         
1246         return true;
1247     }
1248
1249     function _setTightness($top, $bot) {
1250         // Don't tighten headers.
1251     }
1252 }
1253
1254 class Block_p extends BlockMarkup
1255 {
1256     var $_tag = 'p';
1257     var $_re = '\S.*';
1258     var $_text = '';
1259
1260     function _match (&$input, $m) {
1261         $this->_text = $m->match;
1262         $input->advance();
1263         return true;
1264     }
1265
1266     function _setTightness ($top, $bot) {
1267         $this->_tight_top = $top;
1268         $this->_tight_bot = $bot;
1269     }
1270
1271     function merge ($nextBlock) {
1272         $class = get_class($nextBlock);
1273         if (strtolower($class) == 'block_p' and $this->_tight_bot) {
1274             $this->_text .= "\n" . $nextBlock->_text;
1275             $this->_tight_bot = $nextBlock->_tight_bot;
1276             return $this;
1277         }
1278         return false;
1279     }
1280
1281     function finish () {
1282         $content = TransformInline(trim($this->_text));
1283         $p = new Block_HtmlElement('p', false, $content);
1284         $p->setTightness($this->_tight_top, $this->_tight_bot);
1285         return $p;
1286     }
1287 }
1288
1289 class Block_divspan extends BlockMarkup
1290 {
1291     var $_re = '<(?im)(?: div|span)(?:[^>]*)?>';
1292
1293     function _match (&$input, $m) {
1294         if (substr($m->match,1,4) == 'span') {
1295             $tag = 'span';
1296         } else {
1297             $tag = 'div';
1298         }
1299         // without last >
1300         $argstr = substr(trim(substr($m->match,strlen($tag)+1)),0,-1); 
1301         $pos = $input->getPos();
1302         $pi  = $content = $m->postmatch;
1303         while (!preg_match('/^(.*)\<\/'.$tag.'\>(.*)$/i', $pi, $me)) {
1304             if ($pi != $content)
1305                 $content .= "\n$pi";
1306             if (($pi = $input->nextLine()) === false) {
1307                 $input->setPos($pos);
1308                 return false;
1309             }
1310         }
1311         if ($pi != $content)
1312             $content .= $me[1]; // prematch
1313         else
1314             $content = $me[1];
1315         $input->advance();
1316         if (strstr($content, "\n"))
1317             $content = TransformText($content);
1318         else    
1319             $content = TransformInline($content);
1320         if (!$argstr) 
1321             $args = false;
1322         else {
1323             $args = array();
1324             while (preg_match("/(\w+)=(.+)/", $argstr, $m)) {
1325                 $k = $m[1]; $v = $m[2];
1326                 if (preg_match("/^\"(.+?)\"(.*)$/", $v, $m)) {
1327                     $v = $m[1];
1328                     $argstr = $m[2];
1329                 } else {
1330                     preg_match("/^(\s+)(.*)$/", $v, $m);
1331                     $v = $m[1];
1332                     $argstr = $m[2];
1333                 }
1334                 if (trim($k) and trim($v)) $args[$k] = $v;
1335             }
1336         }
1337         $this->_element = new Block_HtmlElement($tag, $args, $content);
1338         //$this->_element->setTightness($tag == 'span', $tag == 'span');
1339         return true;
1340     }
1341     function _setTightness($top, $bot) {
1342         // Don't tighten user <div|span>
1343     }
1344 }
1345
1346
1347 ////////////////////////////////////////////////////////////////
1348 //
1349
1350 /**
1351  * Transform the text of a page, and return a parse tree.
1352  */
1353 function TransformTextPre ($text, $markup = 2.0, $basepage=false) {
1354     if (isa($text, 'WikiDB_PageRevision')) {
1355         $rev = $text;
1356         $text = $rev->getPackedContent();
1357         $markup = $rev->get('markup');
1358     }
1359     // NEW: default markup is new, to increase stability
1360     if (!empty($markup) && $markup < 2.0) {
1361         $text = ConvertOldMarkup($text);
1362     }
1363     // WikiCreole
1364     /*if (!empty($markup) && $markup == 3) {
1365         $text = ConvertFromCreole($text);
1366     }*/
1367     // Expand leading tabs.
1368     $text = expand_tabs($text);
1369     //set_time_limit(3);
1370     $output = new WikiText($text);
1371
1372     return $output;
1373 }
1374
1375 /**
1376  * Transform the text of a page, and return an XmlContent,
1377  * suitable for printXml()-ing.
1378  */
1379 function TransformText ($text, $markup = 2.0, $basepage = false) {
1380     $output = TransformTextPre($text, $markup, $basepage);
1381     if ($basepage) {
1382         // This is for immediate consumption.
1383         // We must bind the contents to a base pagename so that
1384         // relative page links can be properly linkified...
1385         return new CacheableMarkup($output->getContent(), $basepage);
1386     }
1387     return new XmlContent($output->getContent());
1388 }
1389
1390 // (c-file-style: "gnu")
1391 // Local Variables:
1392 // mode: php
1393 // tab-width: 8
1394 // c-basic-offset: 4
1395 // c-hanging-comment-ender-p: nil
1396 // indent-tabs-mode: nil
1397 // End:   
1398 ?>