]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/BlockParser.php
fix Regex Syntax Error
[SourceForge/phpwiki.git] / lib / BlockParser.php
1 <?php rcs_id('$Id: BlockParser.php,v 1.58 2006-11-19 13:57:14 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             $Block_types = array
376                     ('oldlists', 'list', 'dl', 'table_dl',
377                      'blockquote', 'heading', 'hr', 'pre', 'email_blockquote',
378                      'plugin', 'p');
379             if (ENABLE_MARKUP_DIVSPAN)
380                 $Block_types[] = 'divspan';
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                 assert($elem->getAttr('class') == 'tightenable top bottom');
466                 $this->setContent($elem->getContent());
467             }
468         }
469     }
470 }
471
472 class BlockMarkup {
473     var $_re;
474
475     function _match (&$input, $match) {
476         trigger_error('pure virtual', E_USER_ERROR);
477     }
478
479     function _setTightness ($top, $bot) {
480         $this->_element->setTightness($top, $bot);
481     }
482
483     function merge ($followingBlock) {
484         return false;
485     }
486
487     function finish () {
488         return $this->_element;
489     }
490 }
491
492 class Block_blockquote extends BlockMarkup
493 {
494     var $_depth;
495     var $_re = '\ +(?=\S)';
496
497     function _match (&$input, $m) {
498         $this->_depth = strlen($m->match);
499         $indent = sprintf("\\ {%d}", $this->_depth);
500         $this->_element = new SubBlock($input, $indent, $m->match,
501                                        'blockquote');
502         return true;
503     }
504     
505     function merge ($nextBlock) {
506         if (get_class($nextBlock) == get_class($this)) {
507             assert ($nextBlock->_depth < $this->_depth);
508             $nextBlock->_element->unshiftContent($this->_element);
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         $first = &$this->firstTR();
654         $last  = &$this->lastTR();
655         $first->setInClass('top', $tight_top);
656         if (!empty($last)) {
657             $last->setInClass('bottom', $tight_bot);
658         } else {
659             trigger_error(sprintf("no lastTR: %s",AsXML($this->_content[0])), E_USER_WARNING);
660         }
661     }
662     
663     function _addToRow ($item) {
664         if (empty($this->_accum)) {
665             $this->_accum = HTML::td();
666             if ($this->_ncols > 2)
667                 $this->_accum->setAttr('colspan', $this->_ncols - 1);
668         }
669         $this->_accum->pushContent($item);
670     }
671
672     function _flushRow ($tight_bottom=false) {
673         if (!empty($this->_accum)) {
674             $row = new Block_HtmlElement('tr', false, $this->_accum);
675
676             $row->setTightness($this->_next_tight_top, $tight_bottom);
677             $this->_next_tight_top = $tight_bottom;
678             
679             $this->pushContent($row);
680             $this->_accum = false;
681             $this->_nrows++;
682         }
683     }
684
685     function _addSubtable ($table) {
686         if (!($table_rows = $table->getContent()))
687             return;
688
689         $this->_flushRow($table_rows[0]->_tight_top);
690             
691         foreach ($table_rows as $subdef) {
692             $this->pushContent($subdef);
693             $this->_nrows += $subdef->nrows();
694             $this->_next_tight_top = $subdef->_tight_bot;
695         }
696     }
697
698     function _setTerm ($th) {
699         $first_row = &$this->_content[0];
700         if (isa($first_row, 'Block_table_dl_defn'))
701             $first_row->_setTerm($th);
702         else
703             $first_row->unshiftContent($th);
704     }
705     
706     function _ComputeNcols ($defn) {
707         $ncols = 2;
708         foreach ($defn as $item) {
709             if ($this->_IsASubtable($item)) {
710                 $row = $this->_FirstDefn($item);
711                 $ncols = max($ncols, $row->ncols() + 1);
712             }
713         }
714         return $ncols;
715     }
716
717     function _IsASubtable ($item) {
718         return isa($item, 'HtmlElement')
719             && $item->getTag() == 'table'
720             && $item->getAttr('class') == 'wiki-dl-table';
721     }
722
723     function _FirstDefn ($subtable) {
724         $defs = $subtable->getContent();
725         return $defs[0];
726     }
727
728     function ncols () {
729         return $this->_ncols;
730     }
731
732     function nrows () {
733         return $this->_nrows;
734     }
735
736     function & firstTR() {
737         $first = &$this->_content[0];
738         if (isa($first, 'Block_table_dl_defn'))
739             return $first->firstTR();
740         return $first;
741     }
742
743     function & lastTR() {
744         $last = &$this->_content[$this->_nrows - 1];
745         if (isa($last, 'Block_table_dl_defn'))
746             return $last->lastTR();
747         return $last;
748     }
749
750     function setWidth ($ncols) {
751         assert($ncols >= $this->_ncols);
752         if ($ncols <= $this->_ncols)
753             return;
754         $rows = &$this->_content;
755         for ($i = 0; $i < count($rows); $i++) {
756             $row = &$rows[$i];
757             if (isa($row, 'Block_table_dl_defn'))
758                 $row->setWidth($ncols - 1);
759             else {
760                 $n = count($row->_content);
761                 $lastcol = &$row->_content[$n - 1];
762                 if (!empty($lastcol))
763                   $lastcol->setAttr('colspan', $ncols - 1);
764             }
765         }
766     }
767 }
768
769 class Block_table_dl extends Block_dl
770 {
771     var $_tag = 'dl-table';     // phony.
772
773     function Block_table_dl() {
774         $this->_re = '\ {0,4} (?:\S.*)? (?<!'.ESCAPE_CHAR.') \| \s* $';
775     }
776
777     function _match (&$input, $m) {
778         if (!($p = $this->_do_match($input, $m)))
779             return false;
780         list ($term, $defn, $loose) = $p;
781
782         $this->_content[] = new Block_table_dl_defn($term, $defn);
783         return true;
784     }
785
786     function _setTightness($top, $bot) {
787         $this->_content[0]->setTightness($top, $bot);
788     }
789     
790     function finish () {
791
792         $defs = &$this->_content;
793
794         $ncols = 0;
795         foreach ($defs as $defn)
796             $ncols = max($ncols, $defn->ncols());
797         
798         foreach ($defs as $key => $defn)
799             $defs[$key]->setWidth($ncols);
800
801         return HTML::table(array('class' => 'wiki-dl-table',
802                                  'border' => 1,
803                                  'cellspacing' => 0,
804                                  'cellpadding' => 6),
805                            $defs);
806     }
807 }
808
809 class Block_oldlists extends Block_list
810 {
811     //var $_tag = 'ol', 'ul', or 'dl';
812     var $_re = '(?: [*] (?!(?=\S)[^*]*(?<=\S)[*](?:\\s|[-)}>"\'\\/:.,;!?_*=]))
813                   | [#] (?! \[ .*? \] )
814                   | ; .*? :
815                 ) .*? (?=\S)';
816
817     function _match (&$input, $m) {
818         // FIXME:
819         if (!preg_match('/[*#;]*$/A', $input->getPrefix())) {
820             return false;
821         }
822         
823
824         $prefix = $m->match;
825         $oldindent = '[*#;](?=[#*]|;.*:.*\S)';
826         $newindent = sprintf('\\ {%d}', strlen($prefix));
827         $indent = "(?:$oldindent|$newindent)";
828
829         $bullet = $prefix[0];
830         if ($bullet == '*') {
831             $this->_tag = 'ul';
832             $itemtag = 'li';
833         }
834         elseif ($bullet == '#') {
835             $this->_tag = 'ol';
836             $itemtag = 'li';
837         }
838         else {
839             $this->_tag = 'dl';
840             list ($term,) = explode(':', substr($prefix, 1), 2);
841             $term = trim($term);
842             if ($term)
843                 $this->_content[] = new Block_HtmlElement('dt', false,
844                                                           TransformInline($term));
845             $itemtag = 'dd';
846         }
847
848         $this->_content[] = new TightSubBlock($input, $indent, $m->match, $itemtag);
849         return true;
850     }
851
852     function _setTightness($top, $bot) {
853         if (count($this->_content) == 1) {
854             $li = &$this->_content[0];
855             $li->setTightness($top, $bot);
856         }
857         else {
858             // This is where php5 usually brakes.
859             // wrong duplicated <li> contents
860             if (DEBUG and DEBUG & _DEBUG_PARSER and check_php_version(5)) {
861                 if (count($this->_content) != 2) {
862                     echo "<pre>";
863                     /*
864                     $class = new Reflection_Class('XmlElement');
865                     // Print out basic information
866                     printf(
867                            "===> The %s%s%s %s '%s' [extends %s]\n".
868                            "     declared in %s\n".
869                            "     lines %d to %d\n".
870                            "     having the modifiers %d [%s]\n",
871                            $class->isInternal() ? 'internal' : 'user-defined',
872                            $class->isAbstract() ? ' abstract' : '',
873                            $class->isFinal() ? ' final' : '',
874                            $class->isInterface() ? 'interface' : 'class',
875                            $class->getName(),
876                            var_export($class->getParentClass(), 1),
877                            $class->getFileName(),
878                            $class->getStartLine(),
879                            $class->getEndline(),
880                            $class->getModifiers(),
881                            implode(' ', Reflection::getModifierNames($class->getModifiers()))
882                            );
883                     // Print class properties
884                     printf("---> Properties: %s\n", var_export($class->getProperties(), 1));
885                     */
886                     echo 'count($this->_content): ', count($this->_content),"\n";
887                     echo "\$this->_content[0]: "; var_dump ($this->_content[0]);
888                     
889                     for ($i=1; $i < min(5, count($this->_content)); $i++) {
890                         $c =& $this->_content[$i];
891                         echo '$this->_content[',$i,"]: \n";
892                         echo "_tag: "; var_dump ($c->_tag);
893                         echo "_content: "; var_dump ($c->_content);
894                         echo "_properties: "; var_dump ($c->_properties);
895                     }
896                     debug_print_backtrace();
897                     if (DEBUG & _DEBUG_APD) {
898                         if (function_exists("xdebug_get_function_stack")) {
899                             var_dump (xdebug_get_function_stack());
900                         }
901                     }
902                     echo "</pre>";
903                 }
904             }
905             if (!check_php_version(5))
906                 assert(count($this->_content) == 2);
907             $dt = &$this->_content[0];
908             $dd = &$this->_content[1];
909             $dt->setTightness($top, false);
910             $dd->setTightness(false, $bot);
911         }
912     }
913 }
914
915 class Block_pre extends BlockMarkup
916 {
917     var $_re = '<(?:pre|verbatim|nowiki)>';
918
919     function _match (&$input, $m) {
920         $endtag = '</' . substr($m->match, 1);
921         $text = array();
922         $pos = $input->getPos();
923
924         $line = $m->postmatch;
925         while (ltrim($line) != $endtag) {
926             $text[] = $line;
927             if (($line = $input->nextLine()) === false) {
928                 $input->setPos($pos);
929                 return false;
930             }
931         }
932         $input->advance();
933         
934         if ($m->match == '<nowiki>')
935             $text = join("<br>\n", $text);
936         else
937             $text = join("\n", $text);
938         
939         // FIXME: no <img>, <big>, <small>, <sup>, or <sub>'s allowed
940         // in a <pre>.
941         if ($m->match == '<pre>')
942             $text = TransformInline($text);
943         if ($m->match == '<nowiki>') {
944             $text = TransformInlineNowiki($text);
945             $this->_element = new Block_HtmlElement('p', false, $text);
946         } else {
947             $this->_element = new Block_HtmlElement('pre', false, $text);
948         }
949         return true;
950     }
951 }
952
953 class Block_plugin extends Block_pre
954 {
955     var $_re = '<\?plugin(?:-form)?(?!\S)';
956
957     // FIXME:
958     /* <?plugin Backlinks
959      *       page=ThisPage ?>
960     /* <?plugin ListPages pages=<!plugin-list Backlinks!>
961      *                    exclude=<!plugin-list TitleSearch s=T*!> ?>
962      *
963      * should all work.
964      */
965     function _match (&$input, $m) {
966         $pos = $input->getPos();
967         $pi = $m->match . $m->postmatch;
968         while (!preg_match('/(?<!'.ESCAPE_CHAR.')\?>\s*$/', $pi)) {
969             if (($line = $input->nextLine()) === false) {
970                 $input->setPos($pos);
971                 return false;
972             }
973             $pi .= "\n$line";
974         }
975         $input->advance();
976
977         $this->_element = new Cached_PluginInvocation($pi);
978         return true;
979     }
980 }
981
982 class Block_email_blockquote extends BlockMarkup
983 {
984     var $_attr = array('class' => 'mail-style-quote');
985     var $_re = '>\ ?';
986     
987     function _match (&$input, $m) {
988         //$indent = str_replace(' ', '\\ ', $m->match) . '|>$';
989         $indent = $this->_re;
990         $this->_element = new SubBlock($input, $indent, $m->match,
991                                        'blockquote', $this->_attr);
992         return true;
993     }
994 }
995
996 class Block_hr extends BlockMarkup
997 {
998     var $_re = '-{4,}\s*$';
999
1000     function _match (&$input, $m) {
1001         $input->advance();
1002         $this->_element = new Block_HtmlElement('hr');
1003         return true;
1004     }
1005
1006     function _setTightness($top, $bot) {
1007         // Don't tighten <hr/>s
1008     }
1009 }
1010
1011 class Block_heading extends BlockMarkup
1012 {
1013     var $_re = '!{1,3}';
1014     
1015     function _match (&$input, $m) {
1016         $tag = "h" . (5 - strlen($m->match));
1017         $text = TransformInline(trim($m->postmatch));
1018         $input->advance();
1019
1020         $this->_element = new Block_HtmlElement($tag, false, $text);
1021         
1022         return true;
1023     }
1024
1025     function _setTightness($top, $bot) {
1026         // Don't tighten headers.
1027     }
1028 }
1029
1030 class Block_p extends BlockMarkup
1031 {
1032     var $_tag = 'p';
1033     var $_re = '\S.*';
1034     var $_text = '';
1035
1036     function _match (&$input, $m) {
1037         $this->_text = $m->match;
1038         $input->advance();
1039         return true;
1040     }
1041
1042     function _setTightness ($top, $bot) {
1043         $this->_tight_top = $top;
1044         $this->_tight_bot = $bot;
1045     }
1046
1047     function merge ($nextBlock) {
1048         $class = get_class($nextBlock);
1049         if (strtolower($class) == 'block_p' and $this->_tight_bot) {
1050             $this->_text .= "\n" . $nextBlock->_text;
1051             $this->_tight_bot = $nextBlock->_tight_bot;
1052             return $this;
1053         }
1054         return false;
1055     }
1056             
1057     function finish () {
1058         $content = TransformInline(trim($this->_text));
1059         $p = new Block_HtmlElement('p', false, $content);
1060         $p->setTightness($this->_tight_top, $this->_tight_bot);
1061         return $p;
1062     }
1063 }
1064
1065 class Block_divspan extends BlockMarkup
1066 {
1067     var $_re = '<(?: div|span)(?:[^>]*)?>';
1068
1069     function _match (&$input, $m) {
1070         if (substr($m->match,1,4) == 'span') {
1071             $tag = 'span';
1072         } else {
1073             $tag = 'div';
1074         }
1075         // without last >
1076         $args = substr(trim(substr($m->match,strlen($tag))),-1,1); 
1077         $pos = $input->getPos();
1078         $pi  = $m->postmatch;
1079         while (!preg_match('/(?:</'.$tag.'>)/', $pi)) {
1080             if (($line = $input->nextLine()) === false) {
1081                 $input->setPos($pos);
1082                 return false;
1083             }
1084             $pi .= "\n$line";
1085         }
1086         $input->advance();
1087         $content = TransformInline(trim($pi));
1088         $this->_element = new Block_HtmlElement($tag, $args, $content);
1089         $this->_element->setTightness($this->_tight_top, $this->_tight_bot);
1090         return true;
1091     }
1092 }
1093
1094
1095 ////////////////////////////////////////////////////////////////
1096 //
1097
1098 /**
1099  * Transform the text of a page, and return a parse tree.
1100  */
1101 function TransformTextPre ($text, $markup = 2.0, $basepage=false) {
1102     if (isa($text, 'WikiDB_PageRevision')) {
1103         $rev = $text;
1104         $text = $rev->getPackedContent();
1105         $markup = $rev->get('markup');
1106     }
1107     // NEW: default markup is new, to increase stability
1108     if (!empty($markup) && $markup < 2.0) {
1109         $text = ConvertOldMarkup($text);
1110     }
1111     
1112     // Expand leading tabs.
1113     $text = expand_tabs($text);
1114     //set_time_limit(3);
1115     $output = new WikiText($text);
1116
1117     return $output;
1118 }
1119
1120 /**
1121  * Transform the text of a page, and return an XmlContent,
1122  * suitable for printXml()-ing.
1123  */
1124 function TransformText ($text, $markup = 2.0, $basepage=false) {
1125     $output = TransformTextPre($text, $markup, $basepage);
1126     if ($basepage) {
1127         // This is for immediate consumption.
1128         // We must bind the contents to a base pagename so that
1129         // relative page links can be properly linkified...
1130         return new CacheableMarkup($output->getContent(), $basepage);
1131     }
1132     return new XmlContent($output->getContent());
1133 }
1134
1135 // $Log: not supported by cvs2svn $
1136 // Revision 1.57  2006/10/12 06:32:30  rurban
1137 // Optionally support new tags <div>, <span> with ENABLE_MARKUP_DIVSPAN (in work)
1138 //
1139 // Revision 1.56  2006/07/23 14:03:18  rurban
1140 // add new feature: DISABLE_MARKUP_WIKIWORD
1141 //
1142 // Revision 1.55  2005/01/29 21:08:41  rurban
1143 // update (C)
1144 //
1145 // Revision 1.54  2005/01/29 21:00:54  rurban
1146 // do not warn on empty nextBlock
1147 //
1148 // Revision 1.53  2005/01/29 20:36:44  rurban
1149 // very important php5 fix! clone objects
1150 //
1151 // Revision 1.52  2004/10/21 19:52:10  rurban
1152 // Patch #994487: Allow callers to get the parse tree for a page (danfr)
1153 //
1154 // Revision 1.51  2004/09/14 09:54:04  rurban
1155 // cache ParsedBlock::_initBlockTypes
1156 //
1157 // Revision 1.50  2004/09/08 13:38:00  rurban
1158 // improve loadfile stability by using markup=2 as default for undefined markup-style.
1159 // use more refs for huge objects.
1160 // fix debug=static issue in WikiPluginCached
1161 //
1162 // Revision 1.49  2004/07/02 09:55:58  rurban
1163 // more stability fixes: new DISABLE_GETIMAGESIZE if your php crashes when loading LinkIcons: failing getimagesize in old phps; blockparser stabilized
1164 //
1165 // Revision 1.48  2004/06/21 06:30:16  rurban
1166 // revert to prev references
1167 //
1168 // Revision 1.47  2004/06/20 15:30:04  rurban
1169 // get_class case-sensitivity issues
1170 //
1171 // Revision 1.46  2004/06/20 14:42:53  rurban
1172 // various php5 fixes (still broken at blockparser)
1173 //
1174
1175 // (c-file-style: "gnu")
1176 // Local Variables:
1177 // mode: php
1178 // tab-width: 8
1179 // c-basic-offset: 4
1180 // c-hanging-comment-ender-p: nil
1181 // indent-tabs-mode: nil
1182 // End:   
1183 ?>