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