xref: /dokuwiki/inc/parser/handler.php (revision b857f6cb524f22ed48a5a08553b2a370969dda38)
1<?php
2if(!defined('DOKU_INC')) die('meh.');
3if (!defined('DOKU_PARSER_EOL')) define('DOKU_PARSER_EOL',"\n");   // add this to make handling test cases simpler
4
5class Doku_Handler {
6
7    var $Renderer = null;
8
9    var $CallWriter = null;
10
11    var $calls = array();
12
13    var $status = array(
14        'section' => false,
15        'doublequote' => 0,
16    );
17
18    var $rewriteBlocks = true;
19
20    function Doku_Handler() {
21        $this->CallWriter = new Doku_Handler_CallWriter($this);
22    }
23
24    /**
25     * @param string $handler
26     */
27    function _addCall($handler, $args, $pos) {
28        $call = array($handler,$args, $pos);
29        $this->CallWriter->writeCall($call);
30    }
31
32    function addPluginCall($plugin, $args, $state, $pos, $match) {
33        $call = array('plugin',array($plugin, $args, $state, $match), $pos);
34        $this->CallWriter->writeCall($call);
35    }
36
37    function _finalize(){
38
39        $this->CallWriter->finalise();
40
41        if ( $this->status['section'] ) {
42            $last_call = end($this->calls);
43            array_push($this->calls,array('section_close',array(), $last_call[2]));
44        }
45
46        if ( $this->rewriteBlocks ) {
47            $B = new Doku_Handler_Block();
48            $this->calls = $B->process($this->calls);
49        }
50
51        trigger_event('PARSER_HANDLER_DONE',$this);
52
53        array_unshift($this->calls,array('document_start',array(),0));
54        $last_call = end($this->calls);
55        array_push($this->calls,array('document_end',array(),$last_call[2]));
56    }
57
58    function fetch() {
59        $call = each($this->calls);
60        if ( $call ) {
61            return $call['value'];
62        }
63        return false;
64    }
65
66
67    /**
68     * Special plugin handler
69     *
70     * This handler is called for all modes starting with 'plugin_'.
71     * An additional parameter with the plugin name is passed
72     *
73     * @author Andreas Gohr <andi@splitbrain.org>
74     */
75    function plugin($match, $state, $pos, $pluginname){
76        $data = array($match);
77        /** @var DokuWiki_Syntax_Plugin $plugin */
78        $plugin = plugin_load('syntax',$pluginname);
79        if($plugin != null){
80            $data = $plugin->handle($match, $state, $pos, $this);
81        }
82        if ($data !== false) {
83            $this->addPluginCall($pluginname,$data,$state,$pos,$match);
84        }
85        return true;
86    }
87
88    function base($match, $state, $pos) {
89        switch ( $state ) {
90            case DOKU_LEXER_UNMATCHED:
91                $this->_addCall('cdata',array($match), $pos);
92                return true;
93            break;
94        }
95    }
96
97    function header($match, $state, $pos) {
98        // get level and title
99        $title = trim($match);
100        $level = 7 - strspn($title,'=');
101        if($level < 1) $level = 1;
102        $title = trim($title,'=');
103        $title = trim($title);
104
105        if ($this->status['section']) $this->_addCall('section_close',array(),$pos);
106
107        $this->_addCall('header',array($title,$level,$pos), $pos);
108
109        $this->_addCall('section_open',array($level),$pos);
110        $this->status['section'] = true;
111        return true;
112    }
113
114    function notoc($match, $state, $pos) {
115        $this->_addCall('notoc',array(),$pos);
116        return true;
117    }
118
119    function nocache($match, $state, $pos) {
120        $this->_addCall('nocache',array(),$pos);
121        return true;
122    }
123
124    function linebreak($match, $state, $pos) {
125        $this->_addCall('linebreak',array(),$pos);
126        return true;
127    }
128
129    function eol($match, $state, $pos) {
130        $this->_addCall('eol',array(),$pos);
131        return true;
132    }
133
134    function hr($match, $state, $pos) {
135        $this->_addCall('hr',array(),$pos);
136        return true;
137    }
138
139    /**
140     * @param string $name
141     */
142    function _nestingTag($match, $state, $pos, $name) {
143        switch ( $state ) {
144            case DOKU_LEXER_ENTER:
145                $this->_addCall($name.'_open', array(), $pos);
146            break;
147            case DOKU_LEXER_EXIT:
148                $this->_addCall($name.'_close', array(), $pos);
149            break;
150            case DOKU_LEXER_UNMATCHED:
151                $this->_addCall('cdata',array($match), $pos);
152            break;
153        }
154    }
155
156    function strong($match, $state, $pos) {
157        $this->_nestingTag($match, $state, $pos, 'strong');
158        return true;
159    }
160
161    function emphasis($match, $state, $pos) {
162        $this->_nestingTag($match, $state, $pos, 'emphasis');
163        return true;
164    }
165
166    function underline($match, $state, $pos) {
167        $this->_nestingTag($match, $state, $pos, 'underline');
168        return true;
169    }
170
171    function monospace($match, $state, $pos) {
172        $this->_nestingTag($match, $state, $pos, 'monospace');
173        return true;
174    }
175
176    function subscript($match, $state, $pos) {
177        $this->_nestingTag($match, $state, $pos, 'subscript');
178        return true;
179    }
180
181    function superscript($match, $state, $pos) {
182        $this->_nestingTag($match, $state, $pos, 'superscript');
183        return true;
184    }
185
186    function deleted($match, $state, $pos) {
187        $this->_nestingTag($match, $state, $pos, 'deleted');
188        return true;
189    }
190
191
192    function footnote($match, $state, $pos) {
193//        $this->_nestingTag($match, $state, $pos, 'footnote');
194        if (!isset($this->_footnote)) $this->_footnote = false;
195
196        switch ( $state ) {
197            case DOKU_LEXER_ENTER:
198                // footnotes can not be nested - however due to limitations in lexer it can't be prevented
199                // we will still enter a new footnote mode, we just do nothing
200                if ($this->_footnote) {
201                    $this->_addCall('cdata',array($match), $pos);
202                    break;
203                }
204
205                $this->_footnote = true;
206
207                $ReWriter = new Doku_Handler_Nest($this->CallWriter,'footnote_close');
208                $this->CallWriter = & $ReWriter;
209                $this->_addCall('footnote_open', array(), $pos);
210            break;
211            case DOKU_LEXER_EXIT:
212                // check whether we have already exitted the footnote mode, can happen if the modes were nested
213                if (!$this->_footnote) {
214                    $this->_addCall('cdata',array($match), $pos);
215                    break;
216                }
217
218                $this->_footnote = false;
219
220                $this->_addCall('footnote_close', array(), $pos);
221                $this->CallWriter->process();
222                $ReWriter = & $this->CallWriter;
223                $this->CallWriter = & $ReWriter->CallWriter;
224            break;
225            case DOKU_LEXER_UNMATCHED:
226                $this->_addCall('cdata', array($match), $pos);
227            break;
228        }
229        return true;
230    }
231
232    function listblock($match, $state, $pos) {
233        switch ( $state ) {
234            case DOKU_LEXER_ENTER:
235                $ReWriter = new Doku_Handler_List($this->CallWriter);
236                $this->CallWriter = & $ReWriter;
237                $this->_addCall('list_open', array($match), $pos);
238            break;
239            case DOKU_LEXER_EXIT:
240                $this->_addCall('list_close', array(), $pos);
241                $this->CallWriter->process();
242                $ReWriter = & $this->CallWriter;
243                $this->CallWriter = & $ReWriter->CallWriter;
244            break;
245            case DOKU_LEXER_MATCHED:
246                $this->_addCall('list_item', array($match), $pos);
247            break;
248            case DOKU_LEXER_UNMATCHED:
249                $this->_addCall('cdata', array($match), $pos);
250            break;
251        }
252        return true;
253    }
254
255    function unformatted($match, $state, $pos) {
256        if ( $state == DOKU_LEXER_UNMATCHED ) {
257            $this->_addCall('unformatted',array($match), $pos);
258        }
259        return true;
260    }
261
262    function php($match, $state, $pos) {
263        global $conf;
264        if ( $state == DOKU_LEXER_UNMATCHED ) {
265            $this->_addCall('php',array($match), $pos);
266        }
267        return true;
268    }
269
270    function phpblock($match, $state, $pos) {
271        global $conf;
272        if ( $state == DOKU_LEXER_UNMATCHED ) {
273            $this->_addCall('phpblock',array($match), $pos);
274        }
275        return true;
276    }
277
278    function html($match, $state, $pos) {
279        global $conf;
280        if ( $state == DOKU_LEXER_UNMATCHED ) {
281            $this->_addCall('html',array($match), $pos);
282        }
283        return true;
284    }
285
286    function htmlblock($match, $state, $pos) {
287        global $conf;
288        if ( $state == DOKU_LEXER_UNMATCHED ) {
289            $this->_addCall('htmlblock',array($match), $pos);
290        }
291        return true;
292    }
293
294    function preformatted($match, $state, $pos) {
295        switch ( $state ) {
296            case DOKU_LEXER_ENTER:
297                $ReWriter = new Doku_Handler_Preformatted($this->CallWriter);
298                $this->CallWriter = & $ReWriter;
299                $this->_addCall('preformatted_start',array(), $pos);
300            break;
301            case DOKU_LEXER_EXIT:
302                $this->_addCall('preformatted_end',array(), $pos);
303                $this->CallWriter->process();
304                $ReWriter = & $this->CallWriter;
305                $this->CallWriter = & $ReWriter->CallWriter;
306            break;
307            case DOKU_LEXER_MATCHED:
308                $this->_addCall('preformatted_newline',array(), $pos);
309            break;
310            case DOKU_LEXER_UNMATCHED:
311                $this->_addCall('preformatted_content',array($match), $pos);
312            break;
313        }
314
315        return true;
316    }
317
318    function quote($match, $state, $pos) {
319
320        switch ( $state ) {
321
322            case DOKU_LEXER_ENTER:
323                $ReWriter = new Doku_Handler_Quote($this->CallWriter);
324                $this->CallWriter = & $ReWriter;
325                $this->_addCall('quote_start',array($match), $pos);
326            break;
327
328            case DOKU_LEXER_EXIT:
329                $this->_addCall('quote_end',array(), $pos);
330                $this->CallWriter->process();
331                $ReWriter = & $this->CallWriter;
332                $this->CallWriter = & $ReWriter->CallWriter;
333            break;
334
335            case DOKU_LEXER_MATCHED:
336                $this->_addCall('quote_newline',array($match), $pos);
337            break;
338
339            case DOKU_LEXER_UNMATCHED:
340                $this->_addCall('cdata',array($match), $pos);
341            break;
342
343        }
344
345        return true;
346    }
347
348    function file($match, $state, $pos) {
349        return $this->code($match, $state, $pos, 'file');
350    }
351
352    function code($match, $state, $pos, $type='code') {
353        if ( $state == DOKU_LEXER_UNMATCHED ) {
354            $matches = explode('>',$match,2);
355
356            $param = preg_split('/\s+/', $matches[0], 2, PREG_SPLIT_NO_EMPTY);
357            while(count($param) < 2) array_push($param, null);
358
359            // We shortcut html here.
360            if ($param[0] == 'html') $param[0] = 'html4strict';
361            if ($param[0] == '-') $param[0] = null;
362            array_unshift($param, $matches[1]);
363
364            $this->_addCall($type, $param, $pos);
365        }
366        return true;
367    }
368
369    function acronym($match, $state, $pos) {
370        $this->_addCall('acronym',array($match), $pos);
371        return true;
372    }
373
374    function smiley($match, $state, $pos) {
375        $this->_addCall('smiley',array($match), $pos);
376        return true;
377    }
378
379    function wordblock($match, $state, $pos) {
380        $this->_addCall('wordblock',array($match), $pos);
381        return true;
382    }
383
384    function entity($match, $state, $pos) {
385        $this->_addCall('entity',array($match), $pos);
386        return true;
387    }
388
389    function multiplyentity($match, $state, $pos) {
390        preg_match_all('/\d+/',$match,$matches);
391        $this->_addCall('multiplyentity',array($matches[0][0],$matches[0][1]), $pos);
392        return true;
393    }
394
395    function singlequoteopening($match, $state, $pos) {
396        $this->_addCall('singlequoteopening',array(), $pos);
397        return true;
398    }
399
400    function singlequoteclosing($match, $state, $pos) {
401        $this->_addCall('singlequoteclosing',array(), $pos);
402        return true;
403    }
404
405    function apostrophe($match, $state, $pos) {
406        $this->_addCall('apostrophe',array(), $pos);
407        return true;
408    }
409
410    function doublequoteopening($match, $state, $pos) {
411        $this->_addCall('doublequoteopening',array(), $pos);
412        $this->status['doublequote']++;
413        return true;
414    }
415
416    function doublequoteclosing($match, $state, $pos) {
417        if ($this->status['doublequote'] <= 0) {
418            $this->doublequoteopening($match, $state, $pos);
419        } else {
420            $this->_addCall('doublequoteclosing',array(), $pos);
421            $this->status['doublequote'] = max(0, --$this->status['doublequote']);
422        }
423        return true;
424    }
425
426    function camelcaselink($match, $state, $pos) {
427        $this->_addCall('camelcaselink',array($match), $pos);
428        return true;
429    }
430
431    /*
432    */
433    function internallink($match, $state, $pos) {
434        // Strip the opening and closing markup
435        $link = preg_replace(array('/^\[\[/','/\]\]$/u'),'',$match);
436
437        // Split title from URL
438        $link = explode('|',$link,2);
439        if ( !isset($link[1]) ) {
440            $link[1] = null;
441        } else if ( preg_match('/^\{\{[^\}]+\}\}$/',$link[1]) ) {
442            // If the title is an image, convert it to an array containing the image details
443            $link[1] = Doku_Handler_Parse_Media($link[1]);
444        }
445        $link[0] = trim($link[0]);
446
447        //decide which kind of link it is
448
449        if ( preg_match('/^[a-zA-Z0-9\.]+>{1}.*$/u',$link[0]) ) {
450            // Interwiki
451            $interwiki = explode('>',$link[0],2);
452            $this->_addCall(
453                'interwikilink',
454                array($link[0],$link[1],strtolower($interwiki[0]),$interwiki[1]),
455                $pos
456                );
457        }elseif ( preg_match('/^\\\\\\\\[^\\\\]+?\\\\/u',$link[0]) ) {
458            // Windows Share
459            $this->_addCall(
460                'windowssharelink',
461                array($link[0],$link[1]),
462                $pos
463                );
464        }elseif ( preg_match('#^([a-z0-9\-\.+]+?)://#i',$link[0]) ) {
465            // external link (accepts all protocols)
466            $this->_addCall(
467                    'externallink',
468                    array($link[0],$link[1]),
469                    $pos
470                    );
471        }elseif ( preg_match('<'.PREG_PATTERN_VALID_EMAIL.'>',$link[0]) ) {
472            // E-Mail (pattern above is defined in inc/mail.php)
473            $this->_addCall(
474                'emaillink',
475                array($link[0],$link[1]),
476                $pos
477                );
478        }elseif ( preg_match('!^#.+!',$link[0]) ){
479            // local link
480            $this->_addCall(
481                'locallink',
482                array(substr($link[0],1),$link[1]),
483                $pos
484                );
485        }else{
486            // internal link
487            $this->_addCall(
488                'internallink',
489                array($link[0],$link[1]),
490                $pos
491                );
492        }
493
494        return true;
495    }
496
497    function filelink($match, $state, $pos) {
498        $this->_addCall('filelink',array($match, null), $pos);
499        return true;
500    }
501
502    function windowssharelink($match, $state, $pos) {
503        $this->_addCall('windowssharelink',array($match, null), $pos);
504        return true;
505    }
506
507    function media($match, $state, $pos) {
508        $p = Doku_Handler_Parse_Media($match);
509
510        $this->_addCall(
511              $p['type'],
512              array($p['src'], $p['title'], $p['align'], $p['width'],
513                     $p['height'], $p['cache'], $p['linking']),
514              $pos
515             );
516        return true;
517    }
518
519    function rss($match, $state, $pos) {
520        $link = preg_replace(array('/^\{\{rss>/','/\}\}$/'),'',$match);
521
522        // get params
523        list($link,$params) = explode(' ',$link,2);
524
525        $p = array();
526        if(preg_match('/\b(\d+)\b/',$params,$match)){
527            $p['max'] = $match[1];
528        }else{
529            $p['max'] = 8;
530        }
531        $p['reverse'] = (preg_match('/rev/',$params));
532        $p['author']  = (preg_match('/\b(by|author)/',$params));
533        $p['date']    = (preg_match('/\b(date)/',$params));
534        $p['details'] = (preg_match('/\b(desc|detail)/',$params));
535        $p['nosort']  = (preg_match('/\b(nosort)\b/',$params));
536
537        if (preg_match('/\b(\d+)([dhm])\b/',$params,$match)) {
538            $period = array('d' => 86400, 'h' => 3600, 'm' => 60);
539            $p['refresh'] = max(600,$match[1]*$period[$match[2]]);  // n * period in seconds, minimum 10 minutes
540        } else {
541            $p['refresh'] = 14400;   // default to 4 hours
542        }
543
544        $this->_addCall('rss',array($link,$p),$pos);
545        return true;
546    }
547
548    function externallink($match, $state, $pos) {
549        $url   = $match;
550        $title = null;
551
552        // add protocol on simple short URLs
553        if(substr($url,0,3) == 'ftp' && (substr($url,0,6) != 'ftp://')){
554            $title = $url;
555            $url   = 'ftp://'.$url;
556        }
557        if(substr($url,0,3) == 'www' && (substr($url,0,7) != 'http://')){
558            $title = $url;
559            $url = 'http://'.$url;
560        }
561
562        $this->_addCall('externallink',array($url, $title), $pos);
563        return true;
564    }
565
566    function emaillink($match, $state, $pos) {
567        $email = preg_replace(array('/^</','/>$/'),'',$match);
568        $this->_addCall('emaillink',array($email, null), $pos);
569        return true;
570    }
571
572    function table($match, $state, $pos) {
573        switch ( $state ) {
574
575            case DOKU_LEXER_ENTER:
576
577                $ReWriter = new Doku_Handler_Table($this->CallWriter);
578                $this->CallWriter = & $ReWriter;
579
580                $this->_addCall('table_start', array($pos + 1), $pos);
581                if ( trim($match) == '^' ) {
582                    $this->_addCall('tableheader', array(), $pos);
583                } else {
584                    $this->_addCall('tablecell', array(), $pos);
585                }
586            break;
587
588            case DOKU_LEXER_EXIT:
589                $this->_addCall('table_end', array($pos), $pos);
590                $this->CallWriter->process();
591                $ReWriter = & $this->CallWriter;
592                $this->CallWriter = & $ReWriter->CallWriter;
593            break;
594
595            case DOKU_LEXER_UNMATCHED:
596                if ( trim($match) != '' ) {
597                    $this->_addCall('cdata',array($match), $pos);
598                }
599            break;
600
601            case DOKU_LEXER_MATCHED:
602                if ( $match == ' ' ){
603                    $this->_addCall('cdata', array($match), $pos);
604                } else if ( preg_match('/:::/',$match) ) {
605                    $this->_addCall('rowspan', array($match), $pos);
606                } else if ( preg_match('/\t+/',$match) ) {
607                    $this->_addCall('table_align', array($match), $pos);
608                } else if ( preg_match('/ {2,}/',$match) ) {
609                    $this->_addCall('table_align', array($match), $pos);
610                } else if ( $match == "\n|" ) {
611                    $this->_addCall('table_row', array(), $pos);
612                    $this->_addCall('tablecell', array(), $pos);
613                } else if ( $match == "\n^" ) {
614                    $this->_addCall('table_row', array(), $pos);
615                    $this->_addCall('tableheader', array(), $pos);
616                } else if ( $match == '|' ) {
617                    $this->_addCall('tablecell', array(), $pos);
618                } else if ( $match == '^' ) {
619                    $this->_addCall('tableheader', array(), $pos);
620                }
621            break;
622        }
623        return true;
624    }
625}
626
627//------------------------------------------------------------------------
628function Doku_Handler_Parse_Media($match) {
629
630    // Strip the opening and closing markup
631    $link = preg_replace(array('/^\{\{/','/\}\}$/u'),'',$match);
632
633    // Split title from URL
634    $link = explode('|',$link,2);
635
636    // Check alignment
637    $ralign = (bool)preg_match('/^ /',$link[0]);
638    $lalign = (bool)preg_match('/ $/',$link[0]);
639
640    // Logic = what's that ;)...
641    if ( $lalign & $ralign ) {
642        $align = 'center';
643    } else if ( $ralign ) {
644        $align = 'right';
645    } else if ( $lalign ) {
646        $align = 'left';
647    } else {
648        $align = null;
649    }
650
651    // The title...
652    if ( !isset($link[1]) ) {
653        $link[1] = null;
654    }
655
656    //remove aligning spaces
657    $link[0] = trim($link[0]);
658
659    //split into src and parameters (using the very last questionmark)
660    $pos = strrpos($link[0], '?');
661    if($pos !== false){
662        $src   = substr($link[0],0,$pos);
663        $param = substr($link[0],$pos+1);
664    }else{
665        $src   = $link[0];
666        $param = '';
667    }
668
669    //parse width and height
670    if(preg_match('#(\d+)(x(\d+))?#i',$param,$size)){
671        !empty($size[1]) ? $w = $size[1] : $w = null;
672        !empty($size[3]) ? $h = $size[3] : $h = null;
673    } else {
674        $w = null;
675        $h = null;
676    }
677
678    //get linking command
679    if(preg_match('/nolink/i',$param)){
680        $linking = 'nolink';
681    }else if(preg_match('/direct/i',$param)){
682        $linking = 'direct';
683    }else if(preg_match('/linkonly/i',$param)){
684        $linking = 'linkonly';
685    }else{
686        $linking = 'details';
687    }
688
689    //get caching command
690    if (preg_match('/(nocache|recache)/i',$param,$cachemode)){
691        $cache = $cachemode[1];
692    }else{
693        $cache = 'cache';
694    }
695
696    // Check whether this is a local or remote image
697    if ( media_isexternal($src) ) {
698        $call = 'externalmedia';
699    } else {
700        $call = 'internalmedia';
701    }
702
703    $params = array(
704        'type'=>$call,
705        'src'=>$src,
706        'title'=>$link[1],
707        'align'=>$align,
708        'width'=>$w,
709        'height'=>$h,
710        'cache'=>$cache,
711        'linking'=>$linking,
712    );
713
714    return $params;
715}
716
717//------------------------------------------------------------------------
718class Doku_Handler_CallWriter {
719
720    var $Handler;
721
722    /**
723     * @param Doku_Handler $Handler
724     */
725    function Doku_Handler_CallWriter(& $Handler) {
726        $this->Handler = & $Handler;
727    }
728
729    function writeCall($call) {
730        $this->Handler->calls[] = $call;
731    }
732
733    function writeCalls($calls) {
734        $this->Handler->calls = array_merge($this->Handler->calls, $calls);
735    }
736
737    // function is required, but since this call writer is first/highest in
738    // the chain it is not required to do anything
739    function finalise() {
740        unset($this->Handler);
741    }
742}
743
744//------------------------------------------------------------------------
745/**
746 * Generic call writer class to handle nesting of rendering instructions
747 * within a render instruction. Also see nest() method of renderer base class
748 *
749 * @author    Chris Smith <chris@jalakai.co.uk>
750 */
751class Doku_Handler_Nest {
752
753    var $CallWriter;
754    var $calls = array();
755
756    var $closingInstruction;
757
758    /**
759     * constructor
760     *
761     * @param  Doku_Handler_CallWriter $CallWriter     the renderers current call writer
762     * @param  string     $close          closing instruction name, this is required to properly terminate the
763     *                                    syntax mode if the document ends without a closing pattern
764     */
765    function Doku_Handler_Nest(& $CallWriter, $close="nest_close") {
766        $this->CallWriter = & $CallWriter;
767
768        $this->closingInstruction = $close;
769    }
770
771    function writeCall($call) {
772        $this->calls[] = $call;
773    }
774
775    function writeCalls($calls) {
776        $this->calls = array_merge($this->calls, $calls);
777    }
778
779    function finalise() {
780        $last_call = end($this->calls);
781        $this->writeCall(array($this->closingInstruction,array(), $last_call[2]));
782
783        $this->process();
784        $this->CallWriter->finalise();
785        unset($this->CallWriter);
786    }
787
788    function process() {
789        // merge consecutive cdata
790        $unmerged_calls = $this->calls;
791        $this->calls = array();
792
793        foreach ($unmerged_calls as $call) $this->addCall($call);
794
795        $first_call = reset($this->calls);
796        $this->CallWriter->writeCall(array("nest", array($this->calls), $first_call[2]));
797    }
798
799    function addCall($call) {
800        $key = count($this->calls);
801        if ($key and ($call[0] == 'cdata') and ($this->calls[$key-1][0] == 'cdata')) {
802            $this->calls[$key-1][1][0] .= $call[1][0];
803        } else if ($call[0] == 'eol') {
804            // do nothing (eol shouldn't be allowed, to counter preformatted fix in #1652 & #1699)
805        } else {
806            $this->calls[] = $call;
807        }
808    }
809}
810
811class Doku_Handler_List {
812
813    var $CallWriter;
814
815    var $calls = array();
816    var $listCalls = array();
817    var $listStack = array();
818
819    const NODE = 1;
820
821    function Doku_Handler_List(& $CallWriter) {
822        $this->CallWriter = & $CallWriter;
823    }
824
825    function writeCall($call) {
826        $this->calls[] = $call;
827    }
828
829    // Probably not needed but just in case...
830    function writeCalls($calls) {
831        $this->calls = array_merge($this->calls, $calls);
832#        $this->CallWriter->writeCalls($this->calls);
833    }
834
835    function finalise() {
836        $last_call = end($this->calls);
837        $this->writeCall(array('list_close',array(), $last_call[2]));
838
839        $this->process();
840        $this->CallWriter->finalise();
841        unset($this->CallWriter);
842    }
843
844    //------------------------------------------------------------------------
845    function process() {
846
847        foreach ( $this->calls as $call ) {
848            switch ($call[0]) {
849                case 'list_item':
850                    $this->listOpen($call);
851                break;
852                case 'list_open':
853                    $this->listStart($call);
854                break;
855                case 'list_close':
856                    $this->listEnd($call);
857                break;
858                default:
859                    $this->listContent($call);
860                break;
861            }
862        }
863
864        $this->CallWriter->writeCalls($this->listCalls);
865    }
866
867    //------------------------------------------------------------------------
868    function listStart($call) {
869        $depth = $this->interpretSyntax($call[1][0], $listType);
870
871        $this->initialDepth = $depth;
872        //                   array(list type, current depth, index of current listitem_open)
873        $this->listStack[] = array($listType, $depth, 1);
874
875        $this->listCalls[] = array('list'.$listType.'_open',array(),$call[2]);
876        $this->listCalls[] = array('listitem_open',array(1),$call[2]);
877        $this->listCalls[] = array('listcontent_open',array(),$call[2]);
878    }
879
880    //------------------------------------------------------------------------
881    function listEnd($call) {
882        $closeContent = true;
883
884        while ( $list = array_pop($this->listStack) ) {
885            if ( $closeContent ) {
886                $this->listCalls[] = array('listcontent_close',array(),$call[2]);
887                $closeContent = false;
888            }
889            $this->listCalls[] = array('listitem_close',array(),$call[2]);
890            $this->listCalls[] = array('list'.$list[0].'_close', array(), $call[2]);
891        }
892    }
893
894    //------------------------------------------------------------------------
895    function listOpen($call) {
896        $depth = $this->interpretSyntax($call[1][0], $listType);
897        $end = end($this->listStack);
898        $key = key($this->listStack);
899
900        // Not allowed to be shallower than initialDepth
901        if ( $depth < $this->initialDepth ) {
902            $depth = $this->initialDepth;
903        }
904
905        //------------------------------------------------------------------------
906        if ( $depth == $end[1] ) {
907
908            // Just another item in the list...
909            if ( $listType == $end[0] ) {
910                $this->listCalls[] = array('listcontent_close',array(),$call[2]);
911                $this->listCalls[] = array('listitem_close',array(),$call[2]);
912                $this->listCalls[] = array('listitem_open',array($depth-1),$call[2]);
913                $this->listCalls[] = array('listcontent_open',array(),$call[2]);
914
915                // new list item, update list stack's index into current listitem_open
916                $this->listStack[$key][2] = count($this->listCalls) - 2;
917
918            // Switched list type...
919            } else {
920
921                $this->listCalls[] = array('listcontent_close',array(),$call[2]);
922                $this->listCalls[] = array('listitem_close',array(),$call[2]);
923                $this->listCalls[] = array('list'.$end[0].'_close', array(), $call[2]);
924                $this->listCalls[] = array('list'.$listType.'_open', array(), $call[2]);
925                $this->listCalls[] = array('listitem_open', array($depth-1), $call[2]);
926                $this->listCalls[] = array('listcontent_open',array(),$call[2]);
927
928                array_pop($this->listStack);
929                $this->listStack[] = array($listType, $depth, count($this->listCalls) - 2);
930            }
931
932        //------------------------------------------------------------------------
933        // Getting deeper...
934        } else if ( $depth > $end[1] ) {
935
936            $this->listCalls[] = array('listcontent_close',array(),$call[2]);
937            $this->listCalls[] = array('list'.$listType.'_open', array(), $call[2]);
938            $this->listCalls[] = array('listitem_open', array($depth-1), $call[2]);
939            $this->listCalls[] = array('listcontent_open',array(),$call[2]);
940
941            // set the node/leaf state of this item's parent listitem_open to NODE
942            $this->listCalls[$this->listStack[$key][2]][1][1] = self::NODE;
943
944            $this->listStack[] = array($listType, $depth, count($this->listCalls) - 2);
945
946        //------------------------------------------------------------------------
947        // Getting shallower ( $depth < $end[1] )
948        } else {
949            $this->listCalls[] = array('listcontent_close',array(),$call[2]);
950            $this->listCalls[] = array('listitem_close',array(),$call[2]);
951            $this->listCalls[] = array('list'.$end[0].'_close',array(),$call[2]);
952
953            // Throw away the end - done
954            array_pop($this->listStack);
955
956            while (1) {
957                $end = end($this->listStack);
958                $key = key($this->listStack);
959
960                if ( $end[1] <= $depth ) {
961
962                    // Normalize depths
963                    $depth = $end[1];
964
965                    $this->listCalls[] = array('listitem_close',array(),$call[2]);
966
967                    if ( $end[0] == $listType ) {
968                        $this->listCalls[] = array('listitem_open',array($depth-1),$call[2]);
969                        $this->listCalls[] = array('listcontent_open',array(),$call[2]);
970
971                        // new list item, update list stack's index into current listitem_open
972                        $this->listStack[$key][2] = count($this->listCalls) - 2;
973
974                    } else {
975                        // Switching list type...
976                        $this->listCalls[] = array('list'.$end[0].'_close', array(), $call[2]);
977                        $this->listCalls[] = array('list'.$listType.'_open', array(), $call[2]);
978                        $this->listCalls[] = array('listitem_open', array($depth-1), $call[2]);
979                        $this->listCalls[] = array('listcontent_open',array(),$call[2]);
980
981                        array_pop($this->listStack);
982                        $this->listStack[] = array($listType, $depth, count($this->listCalls) - 2);
983                    }
984
985                    break;
986
987                // Haven't dropped down far enough yet.... ( $end[1] > $depth )
988                } else {
989
990                    $this->listCalls[] = array('listitem_close',array(),$call[2]);
991                    $this->listCalls[] = array('list'.$end[0].'_close',array(),$call[2]);
992
993                    array_pop($this->listStack);
994
995                }
996
997            }
998
999        }
1000    }
1001
1002    //------------------------------------------------------------------------
1003    function listContent($call) {
1004        $this->listCalls[] = $call;
1005    }
1006
1007    //------------------------------------------------------------------------
1008    function interpretSyntax($match, & $type) {
1009        if ( substr($match,-1) == '*' ) {
1010            $type = 'u';
1011        } else {
1012            $type = 'o';
1013        }
1014        // Is the +1 needed? It used to be count(explode(...))
1015        // but I don't think the number is seen outside this handler
1016        return substr_count(str_replace("\t",'  ',$match), '  ') + 1;
1017    }
1018}
1019
1020//------------------------------------------------------------------------
1021class Doku_Handler_Preformatted {
1022
1023    var $CallWriter;
1024
1025    var $calls = array();
1026    var $pos;
1027    var $text ='';
1028
1029
1030
1031    function Doku_Handler_Preformatted(& $CallWriter) {
1032        $this->CallWriter = & $CallWriter;
1033    }
1034
1035    function writeCall($call) {
1036        $this->calls[] = $call;
1037    }
1038
1039    // Probably not needed but just in case...
1040    function writeCalls($calls) {
1041        $this->calls = array_merge($this->calls, $calls);
1042#        $this->CallWriter->writeCalls($this->calls);
1043    }
1044
1045    function finalise() {
1046        $last_call = end($this->calls);
1047        $this->writeCall(array('preformatted_end',array(), $last_call[2]));
1048
1049        $this->process();
1050        $this->CallWriter->finalise();
1051        unset($this->CallWriter);
1052    }
1053
1054    function process() {
1055        foreach ( $this->calls as $call ) {
1056            switch ($call[0]) {
1057                case 'preformatted_start':
1058                    $this->pos = $call[2];
1059                break;
1060                case 'preformatted_newline':
1061                    $this->text .= "\n";
1062                break;
1063                case 'preformatted_content':
1064                    $this->text .= $call[1][0];
1065                break;
1066                case 'preformatted_end':
1067                    if (trim($this->text)) {
1068                        $this->CallWriter->writeCall(array('preformatted',array($this->text),$this->pos));
1069                    }
1070                    // see FS#1699 & FS#1652, add 'eol' instructions to ensure proper triggering of following p_open
1071                    $this->CallWriter->writeCall(array('eol',array(),$this->pos));
1072                    $this->CallWriter->writeCall(array('eol',array(),$this->pos));
1073                break;
1074            }
1075        }
1076    }
1077
1078}
1079
1080//------------------------------------------------------------------------
1081class Doku_Handler_Quote {
1082
1083    var $CallWriter;
1084
1085    var $calls = array();
1086
1087    var $quoteCalls = array();
1088
1089    function Doku_Handler_Quote(& $CallWriter) {
1090        $this->CallWriter = & $CallWriter;
1091    }
1092
1093    function writeCall($call) {
1094        $this->calls[] = $call;
1095    }
1096
1097    // Probably not needed but just in case...
1098    function writeCalls($calls) {
1099        $this->calls = array_merge($this->calls, $calls);
1100    }
1101
1102    function finalise() {
1103        $last_call = end($this->calls);
1104        $this->writeCall(array('quote_end',array(), $last_call[2]));
1105
1106        $this->process();
1107        $this->CallWriter->finalise();
1108        unset($this->CallWriter);
1109    }
1110
1111    function process() {
1112
1113        $quoteDepth = 1;
1114
1115        foreach ( $this->calls as $call ) {
1116            switch ($call[0]) {
1117
1118                case 'quote_start':
1119
1120                    $this->quoteCalls[] = array('quote_open',array(),$call[2]);
1121
1122                case 'quote_newline':
1123
1124                    $quoteLength = $this->getDepth($call[1][0]);
1125
1126                    if ( $quoteLength > $quoteDepth ) {
1127                        $quoteDiff = $quoteLength - $quoteDepth;
1128                        for ( $i = 1; $i <= $quoteDiff; $i++ ) {
1129                            $this->quoteCalls[] = array('quote_open',array(),$call[2]);
1130                        }
1131                    } else if ( $quoteLength < $quoteDepth ) {
1132                        $quoteDiff = $quoteDepth - $quoteLength;
1133                        for ( $i = 1; $i <= $quoteDiff; $i++ ) {
1134                            $this->quoteCalls[] = array('quote_close',array(),$call[2]);
1135                        }
1136                    } else {
1137                        if ($call[0] != 'quote_start') $this->quoteCalls[] = array('linebreak',array(),$call[2]);
1138                    }
1139
1140                    $quoteDepth = $quoteLength;
1141
1142                break;
1143
1144                case 'quote_end':
1145
1146                    if ( $quoteDepth > 1 ) {
1147                        $quoteDiff = $quoteDepth - 1;
1148                        for ( $i = 1; $i <= $quoteDiff; $i++ ) {
1149                            $this->quoteCalls[] = array('quote_close',array(),$call[2]);
1150                        }
1151                    }
1152
1153                    $this->quoteCalls[] = array('quote_close',array(),$call[2]);
1154
1155                    $this->CallWriter->writeCalls($this->quoteCalls);
1156                break;
1157
1158                default:
1159                    $this->quoteCalls[] = $call;
1160                break;
1161            }
1162        }
1163    }
1164
1165    function getDepth($marker) {
1166        preg_match('/>{1,}/', $marker, $matches);
1167        $quoteLength = strlen($matches[0]);
1168        return $quoteLength;
1169    }
1170}
1171
1172//------------------------------------------------------------------------
1173class Doku_Handler_Table {
1174
1175    var $CallWriter;
1176
1177    var $calls = array();
1178    var $tableCalls = array();
1179    var $maxCols = 0;
1180    var $maxRows = 1;
1181    var $currentCols = 0;
1182    var $firstCell = false;
1183    var $lastCellType = 'tablecell';
1184    var $inTableHead = true;
1185    var $currentRow = array('tableheader' => 0, 'tablecell' => 0);
1186    var $countTableHeadRows = 0;
1187
1188    function Doku_Handler_Table(& $CallWriter) {
1189        $this->CallWriter = & $CallWriter;
1190    }
1191
1192    function writeCall($call) {
1193        $this->calls[] = $call;
1194    }
1195
1196    // Probably not needed but just in case...
1197    function writeCalls($calls) {
1198        $this->calls = array_merge($this->calls, $calls);
1199    }
1200
1201    function finalise() {
1202        $last_call = end($this->calls);
1203        $this->writeCall(array('table_end',array(), $last_call[2]));
1204
1205        $this->process();
1206        $this->CallWriter->finalise();
1207        unset($this->CallWriter);
1208    }
1209
1210    //------------------------------------------------------------------------
1211    function process() {
1212        foreach ( $this->calls as $call ) {
1213            switch ( $call[0] ) {
1214                case 'table_start':
1215                    $this->tableStart($call);
1216                break;
1217                case 'table_row':
1218                    $this->tableRowClose($call);
1219                    $this->tableRowOpen(array('tablerow_open',$call[1],$call[2]));
1220                break;
1221                case 'tableheader':
1222                case 'tablecell':
1223                    $this->tableCell($call);
1224                break;
1225                case 'table_end':
1226                    $this->tableRowClose($call);
1227                    $this->tableEnd($call);
1228                break;
1229                default:
1230                    $this->tableDefault($call);
1231                break;
1232            }
1233        }
1234        $this->CallWriter->writeCalls($this->tableCalls);
1235    }
1236
1237    function tableStart($call) {
1238        $this->tableCalls[] = array('table_open',$call[1],$call[2]);
1239        $this->tableCalls[] = array('tablerow_open',array(),$call[2]);
1240        $this->firstCell = true;
1241    }
1242
1243    function tableEnd($call) {
1244        $this->tableCalls[] = array('table_close',$call[1],$call[2]);
1245        $this->finalizeTable();
1246    }
1247
1248    function tableRowOpen($call) {
1249        $this->tableCalls[] = $call;
1250        $this->currentCols = 0;
1251        $this->firstCell = true;
1252        $this->lastCellType = 'tablecell';
1253        $this->maxRows++;
1254        if ($this->inTableHead) {
1255            $this->currentRow = array('tablecell' => 0, 'tableheader' => 0);
1256        }
1257    }
1258
1259    function tableRowClose($call) {
1260        if ($this->inTableHead && ($this->inTableHead = $this->isTableHeadRow())) {
1261            $this->countTableHeadRows++;
1262        }
1263        // Strip off final cell opening and anything after it
1264        while ( $discard = array_pop($this->tableCalls ) ) {
1265
1266            if ( $discard[0] == 'tablecell_open' || $discard[0] == 'tableheader_open') {
1267                break;
1268            }
1269            if (!empty($this->currentRow[$discard[0]])) {
1270                $this->currentRow[$discard[0]]--;
1271            }
1272        }
1273        $this->tableCalls[] = array('tablerow_close', array(), $call[2]);
1274
1275        if ( $this->currentCols > $this->maxCols ) {
1276            $this->maxCols = $this->currentCols;
1277        }
1278    }
1279
1280    function isTableHeadRow() {
1281        $td = $this->currentRow['tablecell'];
1282        $th = $this->currentRow['tableheader'];
1283
1284        if (!$th || $td > 2) return false;
1285        if (2*$td > $th) return false;
1286
1287        return true;
1288    }
1289
1290    function tableCell($call) {
1291        if ($this->inTableHead) {
1292            $this->currentRow[$call[0]]++;
1293        }
1294        if ( !$this->firstCell ) {
1295
1296            // Increase the span
1297            $lastCall = end($this->tableCalls);
1298
1299            // A cell call which follows an open cell means an empty cell so span
1300            if ( $lastCall[0] == 'tablecell_open' || $lastCall[0] == 'tableheader_open' ) {
1301                 $this->tableCalls[] = array('colspan',array(),$call[2]);
1302
1303            }
1304
1305            $this->tableCalls[] = array($this->lastCellType.'_close',array(),$call[2]);
1306            $this->tableCalls[] = array($call[0].'_open',array(1,null,1),$call[2]);
1307            $this->lastCellType = $call[0];
1308
1309        } else {
1310
1311            $this->tableCalls[] = array($call[0].'_open',array(1,null,1),$call[2]);
1312            $this->lastCellType = $call[0];
1313            $this->firstCell = false;
1314
1315        }
1316
1317        $this->currentCols++;
1318    }
1319
1320    function tableDefault($call) {
1321        $this->tableCalls[] = $call;
1322    }
1323
1324    function finalizeTable() {
1325
1326        // Add the max cols and rows to the table opening
1327        if ( $this->tableCalls[0][0] == 'table_open' ) {
1328            // Adjust to num cols not num col delimeters
1329            $this->tableCalls[0][1][] = $this->maxCols - 1;
1330            $this->tableCalls[0][1][] = $this->maxRows;
1331            $this->tableCalls[0][1][] = array_shift($this->tableCalls[0][1]);
1332        } else {
1333            trigger_error('First element in table call list is not table_open');
1334        }
1335
1336        $lastRow = 0;
1337        $lastCell = 0;
1338        $cellKey = array();
1339        $toDelete = array();
1340
1341        // if still in tableheader, then there can be no table header
1342        // as all rows can't be within <THEAD>
1343        if ($this->inTableHead) {
1344            $this->inTableHead = false;
1345            $this->countTableHeadRows = 0;
1346        }
1347
1348        // Look for the colspan elements and increment the colspan on the
1349        // previous non-empty opening cell. Once done, delete all the cells
1350        // that contain colspans
1351        for ($key = 0 ; $key < count($this->tableCalls) ; ++$key) {
1352            $call = $this->tableCalls[$key];
1353
1354            switch ($call[0]) {
1355                case 'table_open' :
1356                    if($this->countTableHeadRows) {
1357                        array_splice($this->tableCalls, $key+1, 0, array(
1358                              array('tablethead_open', array(), $call[2]))
1359                        );
1360                    }
1361                    break;
1362
1363                case 'tablerow_open':
1364
1365                    $lastRow++;
1366                    $lastCell = 0;
1367                    break;
1368
1369                case 'tablecell_open':
1370                case 'tableheader_open':
1371
1372                    $lastCell++;
1373                    $cellKey[$lastRow][$lastCell] = $key;
1374                    break;
1375
1376                case 'table_align':
1377
1378                    $prev = in_array($this->tableCalls[$key-1][0], array('tablecell_open', 'tableheader_open'));
1379                    $next = in_array($this->tableCalls[$key+1][0], array('tablecell_close', 'tableheader_close'));
1380                    // If the cell is empty, align left
1381                    if ($prev && $next) {
1382                        $this->tableCalls[$key-1][1][1] = 'left';
1383
1384                    // If the previous element was a cell open, align right
1385                    } elseif ($prev) {
1386                        $this->tableCalls[$key-1][1][1] = 'right';
1387
1388                    // If the next element is the close of an element, align either center or left
1389                    } elseif ( $next) {
1390                        if ( $this->tableCalls[$cellKey[$lastRow][$lastCell]][1][1] == 'right' ) {
1391                            $this->tableCalls[$cellKey[$lastRow][$lastCell]][1][1] = 'center';
1392                        } else {
1393                            $this->tableCalls[$cellKey[$lastRow][$lastCell]][1][1] = 'left';
1394                        }
1395
1396                    }
1397
1398                    // Now convert the whitespace back to cdata
1399                    $this->tableCalls[$key][0] = 'cdata';
1400                    break;
1401
1402                case 'colspan':
1403
1404                    $this->tableCalls[$key-1][1][0] = false;
1405
1406                    for($i = $key-2; $i >= $cellKey[$lastRow][1]; $i--) {
1407
1408                        if ( $this->tableCalls[$i][0] == 'tablecell_open' || $this->tableCalls[$i][0] == 'tableheader_open' ) {
1409
1410                            if ( false !== $this->tableCalls[$i][1][0] ) {
1411                                $this->tableCalls[$i][1][0]++;
1412                                break;
1413                            }
1414
1415                        }
1416                    }
1417
1418                    $toDelete[] = $key-1;
1419                    $toDelete[] = $key;
1420                    $toDelete[] = $key+1;
1421                    break;
1422
1423                case 'rowspan':
1424
1425                    if ( $this->tableCalls[$key-1][0] == 'cdata' ) {
1426                        // ignore rowspan if previous call was cdata (text mixed with :::) we don't have to check next call as that wont match regex
1427                        $this->tableCalls[$key][0] = 'cdata';
1428
1429                    } else {
1430
1431                        $spanning_cell = null;
1432
1433                        // can't cross thead/tbody boundary
1434                        if (!$this->countTableHeadRows || ($lastRow-1 != $this->countTableHeadRows)) {
1435                            for($i = $lastRow-1; $i > 0; $i--) {
1436
1437                                if ( $this->tableCalls[$cellKey[$i][$lastCell]][0] == 'tablecell_open' || $this->tableCalls[$cellKey[$i][$lastCell]][0] == 'tableheader_open' ) {
1438
1439                                    if ($this->tableCalls[$cellKey[$i][$lastCell]][1][2] >= $lastRow - $i) {
1440                                        $spanning_cell = $i;
1441                                        break;
1442                                    }
1443
1444                                }
1445                            }
1446                        }
1447                        if (is_null($spanning_cell)) {
1448                            // No spanning cell found, so convert this cell to
1449                            // an empty one to avoid broken tables
1450                            $this->tableCalls[$key][0] = 'cdata';
1451                            $this->tableCalls[$key][1][0] = '';
1452                            continue;
1453                        }
1454                        $this->tableCalls[$cellKey[$spanning_cell][$lastCell]][1][2]++;
1455
1456                        $this->tableCalls[$key-1][1][2] = false;
1457
1458                        $toDelete[] = $key-1;
1459                        $toDelete[] = $key;
1460                        $toDelete[] = $key+1;
1461                    }
1462                    break;
1463
1464                case 'tablerow_close':
1465
1466                    // Fix broken tables by adding missing cells
1467                    while (++$lastCell < $this->maxCols) {
1468                        array_splice($this->tableCalls, $key, 0, array(
1469                               array('tablecell_open', array(1, null, 1), $call[2]),
1470                               array('cdata', array(''), $call[2]),
1471                               array('tablecell_close', array(), $call[2])));
1472                        $key += 3;
1473                    }
1474
1475                    if($this->countTableHeadRows == $lastRow) {
1476                        array_splice($this->tableCalls, $key+1, 0, array(
1477                              array('tablethead_close', array(), $call[2])));
1478                    }
1479                    break;
1480
1481            }
1482        }
1483
1484        // condense cdata
1485        $cnt = count($this->tableCalls);
1486        for( $key = 0; $key < $cnt; $key++){
1487            if($this->tableCalls[$key][0] == 'cdata'){
1488                $ckey = $key;
1489                $key++;
1490                while($this->tableCalls[$key][0] == 'cdata'){
1491                    $this->tableCalls[$ckey][1][0] .= $this->tableCalls[$key][1][0];
1492                    $toDelete[] = $key;
1493                    $key++;
1494                }
1495                continue;
1496            }
1497        }
1498
1499        foreach ( $toDelete as $delete ) {
1500            unset($this->tableCalls[$delete]);
1501        }
1502        $this->tableCalls = array_values($this->tableCalls);
1503    }
1504}
1505
1506
1507/**
1508 * Handler for paragraphs
1509 *
1510 * @author Harry Fuecks <hfuecks@gmail.com>
1511 */
1512class Doku_Handler_Block {
1513    var $calls = array();
1514    var $skipEol = false;
1515    var $inParagraph = false;
1516
1517    // Blocks these should not be inside paragraphs
1518    var $blockOpen = array(
1519            'header',
1520            'listu_open','listo_open','listitem_open','listcontent_open',
1521            'table_open','tablerow_open','tablecell_open','tableheader_open','tablethead_open',
1522            'quote_open',
1523            'code','file','hr','preformatted','rss',
1524            'htmlblock','phpblock',
1525            'footnote_open',
1526        );
1527
1528    var $blockClose = array(
1529            'header',
1530            'listu_close','listo_close','listitem_close','listcontent_close',
1531            'table_close','tablerow_close','tablecell_close','tableheader_close','tablethead_close',
1532            'quote_close',
1533            'code','file','hr','preformatted','rss',
1534            'htmlblock','phpblock',
1535            'footnote_close',
1536        );
1537
1538    // Stacks can contain paragraphs
1539    var $stackOpen = array(
1540        'section_open',
1541        );
1542
1543    var $stackClose = array(
1544        'section_close',
1545        );
1546
1547
1548    /**
1549     * Constructor. Adds loaded syntax plugins to the block and stack
1550     * arrays
1551     *
1552     * @author Andreas Gohr <andi@splitbrain.org>
1553     */
1554    function Doku_Handler_Block(){
1555        global $DOKU_PLUGINS;
1556        //check if syntax plugins were loaded
1557        if(empty($DOKU_PLUGINS['syntax'])) return;
1558        foreach($DOKU_PLUGINS['syntax'] as $n => $p){
1559            $ptype = $p->getPType();
1560            if($ptype == 'block'){
1561                $this->blockOpen[]  = 'plugin_'.$n;
1562                $this->blockClose[] = 'plugin_'.$n;
1563            }elseif($ptype == 'stack'){
1564                $this->stackOpen[]  = 'plugin_'.$n;
1565                $this->stackClose[] = 'plugin_'.$n;
1566            }
1567        }
1568    }
1569
1570    function openParagraph($pos){
1571        if ($this->inParagraph) return;
1572        $this->calls[] = array('p_open',array(), $pos);
1573        $this->inParagraph = true;
1574        $this->skipEol = true;
1575    }
1576
1577    /**
1578     * Close a paragraph if needed
1579     *
1580     * This function makes sure there are no empty paragraphs on the stack
1581     *
1582     * @author Andreas Gohr <andi@splitbrain.org>
1583     */
1584    function closeParagraph($pos){
1585        if (!$this->inParagraph) return;
1586        // look back if there was any content - we don't want empty paragraphs
1587        $content = '';
1588        $ccount = count($this->calls);
1589        for($i=$ccount-1; $i>=0; $i--){
1590            if($this->calls[$i][0] == 'p_open'){
1591                break;
1592            }elseif($this->calls[$i][0] == 'cdata'){
1593                $content .= $this->calls[$i][1][0];
1594            }else{
1595                $content = 'found markup';
1596                break;
1597            }
1598        }
1599
1600        if(trim($content)==''){
1601            //remove the whole paragraph
1602            //array_splice($this->calls,$i); // <- this is much slower than the loop below
1603            for($x=$ccount; $x>$i; $x--) array_pop($this->calls);
1604        }else{
1605            // remove ending linebreaks in the paragraph
1606            $i=count($this->calls)-1;
1607            if ($this->calls[$i][0] == 'cdata') $this->calls[$i][1][0] = rtrim($this->calls[$i][1][0],DOKU_PARSER_EOL);
1608            $this->calls[] = array('p_close',array(), $pos);
1609        }
1610
1611        $this->inParagraph = false;
1612        $this->skipEol = true;
1613    }
1614
1615    function addCall($call) {
1616        $key = count($this->calls);
1617        if ($key and ($call[0] == 'cdata') and ($this->calls[$key-1][0] == 'cdata')) {
1618            $this->calls[$key-1][1][0] .= $call[1][0];
1619        } else {
1620            $this->calls[] = $call;
1621        }
1622    }
1623
1624    // simple version of addCall, without checking cdata
1625    function storeCall($call) {
1626        $this->calls[] = $call;
1627    }
1628
1629    /**
1630     * Processes the whole instruction stack to open and close paragraphs
1631     *
1632     * @author Harry Fuecks <hfuecks@gmail.com>
1633     * @author Andreas Gohr <andi@splitbrain.org>
1634     */
1635    function process($calls) {
1636        // open first paragraph
1637        $this->openParagraph(0);
1638        foreach ( $calls as $key => $call ) {
1639            $cname = $call[0];
1640            if ($cname == 'plugin') {
1641                $cname='plugin_'.$call[1][0];
1642                $plugin = true;
1643                $plugin_open = (($call[1][2] == DOKU_LEXER_ENTER) || ($call[1][2] == DOKU_LEXER_SPECIAL));
1644                $plugin_close = (($call[1][2] == DOKU_LEXER_EXIT) || ($call[1][2] == DOKU_LEXER_SPECIAL));
1645            } else {
1646                $plugin = false;
1647            }
1648            /* stack */
1649            if ( in_array($cname,$this->stackClose ) && (!$plugin || $plugin_close)) {
1650                $this->closeParagraph($call[2]);
1651                $this->storeCall($call);
1652                $this->openParagraph($call[2]);
1653                continue;
1654            }
1655            if ( in_array($cname,$this->stackOpen ) && (!$plugin || $plugin_open) ) {
1656                $this->closeParagraph($call[2]);
1657                $this->storeCall($call);
1658                $this->openParagraph($call[2]);
1659                continue;
1660            }
1661            /* block */
1662            // If it's a substition it opens and closes at the same call.
1663            // To make sure next paragraph is correctly started, let close go first.
1664            if ( in_array($cname, $this->blockClose) && (!$plugin || $plugin_close)) {
1665                $this->closeParagraph($call[2]);
1666                $this->storeCall($call);
1667                $this->openParagraph($call[2]);
1668                continue;
1669            }
1670            if ( in_array($cname, $this->blockOpen) && (!$plugin || $plugin_open)) {
1671                $this->closeParagraph($call[2]);
1672                $this->storeCall($call);
1673                continue;
1674            }
1675            /* eol */
1676            if ( $cname == 'eol' ) {
1677                // Check this isn't an eol instruction to skip...
1678                if ( !$this->skipEol ) {
1679                    // Next is EOL => double eol => mark as paragraph
1680                    if ( isset($calls[$key+1]) && $calls[$key+1][0] == 'eol' ) {
1681                        $this->closeParagraph($call[2]);
1682                        $this->openParagraph($call[2]);
1683                    } else {
1684                        //if this is just a single eol make a space from it
1685                        $this->addCall(array('cdata',array(DOKU_PARSER_EOL), $call[2]));
1686                    }
1687                }
1688                continue;
1689            }
1690            /* normal */
1691            $this->addCall($call);
1692            $this->skipEol = false;
1693        }
1694        // close last paragraph
1695        $call = end($this->calls);
1696        $this->closeParagraph($call[2]);
1697        return $this->calls;
1698    }
1699}
1700
1701//Setup VIM: ex: et ts=4 :
1702