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