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