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