xref: /dokuwiki/inc/parser/handler.php (revision cded11250d495f6039a20f1036c64ea7b230ceb2)
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    function Doku_Handler_CallWriter(& $Handler) {
716        $this->Handler = & $Handler;
717    }
718
719    function writeCall($call) {
720        $this->Handler->calls[] = $call;
721    }
722
723    function writeCalls($calls) {
724        $this->Handler->calls = array_merge($this->Handler->calls, $calls);
725    }
726
727    // function is required, but since this call writer is first/highest in
728    // the chain it is not required to do anything
729    function finalise() {
730        unset($this->Handler);
731    }
732}
733
734//------------------------------------------------------------------------
735/**
736 * Generic call writer class to handle nesting of rendering instructions
737 * within a render instruction. Also see nest() method of renderer base class
738 *
739 * @author    Chris Smith <chris@jalakai.co.uk>
740 */
741class Doku_Handler_Nest {
742
743    var $CallWriter;
744    var $calls = array();
745
746    var $closingInstruction;
747
748    /**
749     * constructor
750     *
751     * @param  object     $CallWriter     the renderers current call writer
752     * @param  string     $close          closing instruction name, this is required to properly terminate the
753     *                                    syntax mode if the document ends without a closing pattern
754     */
755    function Doku_Handler_Nest(& $CallWriter, $close="nest_close") {
756        $this->CallWriter = & $CallWriter;
757
758        $this->closingInstruction = $close;
759    }
760
761    function writeCall($call) {
762        $this->calls[] = $call;
763    }
764
765    function writeCalls($calls) {
766        $this->calls = array_merge($this->calls, $calls);
767    }
768
769    function finalise() {
770        $last_call = end($this->calls);
771        $this->writeCall(array($this->closingInstruction,array(), $last_call[2]));
772
773        $this->process();
774        $this->CallWriter->finalise();
775        unset($this->CallWriter);
776    }
777
778    function process() {
779        // merge consecutive cdata
780        $unmerged_calls = $this->calls;
781        $this->calls = array();
782
783        foreach ($unmerged_calls as $call) $this->addCall($call);
784
785        $first_call = reset($this->calls);
786        $this->CallWriter->writeCall(array("nest", array($this->calls), $first_call[2]));
787    }
788
789    function addCall($call) {
790        $key = count($this->calls);
791        if ($key and ($call[0] == 'cdata') and ($this->calls[$key-1][0] == 'cdata')) {
792            $this->calls[$key-1][1][0] .= $call[1][0];
793        } else if ($call[0] == 'eol') {
794            // do nothing (eol shouldn't be allowed, to counter preformatted fix in #1652 & #1699)
795        } else {
796            $this->calls[] = $call;
797        }
798    }
799}
800
801class Doku_Handler_List {
802
803    var $CallWriter;
804
805    var $calls = array();
806    var $listCalls = array();
807    var $listStack = array();
808
809    function Doku_Handler_List(& $CallWriter) {
810        $this->CallWriter = & $CallWriter;
811    }
812
813    function writeCall($call) {
814        $this->calls[] = $call;
815    }
816
817    // Probably not needed but just in case...
818    function writeCalls($calls) {
819        $this->calls = array_merge($this->calls, $calls);
820#        $this->CallWriter->writeCalls($this->calls);
821    }
822
823    function finalise() {
824        $last_call = end($this->calls);
825        $this->writeCall(array('list_close',array(), $last_call[2]));
826
827        $this->process();
828        $this->CallWriter->finalise();
829        unset($this->CallWriter);
830    }
831
832    //------------------------------------------------------------------------
833    function process() {
834
835        foreach ( $this->calls as $call ) {
836            switch ($call[0]) {
837                case 'list_item':
838                    $this->listOpen($call);
839                break;
840                case 'list_open':
841                    $this->listStart($call);
842                break;
843                case 'list_close':
844                    $this->listEnd($call);
845                break;
846                default:
847                    $this->listContent($call);
848                break;
849            }
850        }
851
852        $this->CallWriter->writeCalls($this->listCalls);
853    }
854
855    //------------------------------------------------------------------------
856    function listStart($call) {
857        $depth = $this->interpretSyntax($call[1][0], $listType);
858
859        $this->initialDepth = $depth;
860        $this->listStack[] = array($listType, $depth);
861
862        $this->listCalls[] = array('list'.$listType.'_open',array(),$call[2]);
863        $this->listCalls[] = array('listitem_open',array(1),$call[2]);
864        $this->listCalls[] = array('listcontent_open',array(),$call[2]);
865    }
866
867    //------------------------------------------------------------------------
868    function listEnd($call) {
869        $closeContent = true;
870
871        while ( $list = array_pop($this->listStack) ) {
872            if ( $closeContent ) {
873                $this->listCalls[] = array('listcontent_close',array(),$call[2]);
874                $closeContent = false;
875            }
876            $this->listCalls[] = array('listitem_close',array(),$call[2]);
877            $this->listCalls[] = array('list'.$list[0].'_close', array(), $call[2]);
878        }
879    }
880
881    //------------------------------------------------------------------------
882    function listOpen($call) {
883        $depth = $this->interpretSyntax($call[1][0], $listType);
884        $end = end($this->listStack);
885
886        // Not allowed to be shallower than initialDepth
887        if ( $depth < $this->initialDepth ) {
888            $depth = $this->initialDepth;
889        }
890
891        //------------------------------------------------------------------------
892        if ( $depth == $end[1] ) {
893
894            // Just another item in the list...
895            if ( $listType == $end[0] ) {
896                $this->listCalls[] = array('listcontent_close',array(),$call[2]);
897                $this->listCalls[] = array('listitem_close',array(),$call[2]);
898                $this->listCalls[] = array('listitem_open',array($depth-1),$call[2]);
899                $this->listCalls[] = array('listcontent_open',array(),$call[2]);
900
901            // Switched list type...
902            } else {
903
904                $this->listCalls[] = array('listcontent_close',array(),$call[2]);
905                $this->listCalls[] = array('listitem_close',array(),$call[2]);
906                $this->listCalls[] = array('list'.$end[0].'_close', array(), $call[2]);
907                $this->listCalls[] = array('list'.$listType.'_open', array(), $call[2]);
908                $this->listCalls[] = array('listitem_open', array($depth-1), $call[2]);
909                $this->listCalls[] = array('listcontent_open',array(),$call[2]);
910
911                array_pop($this->listStack);
912                $this->listStack[] = array($listType, $depth);
913            }
914
915        //------------------------------------------------------------------------
916        // Getting deeper...
917        } else if ( $depth > $end[1] ) {
918
919            $this->listCalls[] = array('listcontent_close',array(),$call[2]);
920            $this->listCalls[] = array('list'.$listType.'_open', array(), $call[2]);
921            $this->listCalls[] = array('listitem_open', array($depth-1), $call[2]);
922            $this->listCalls[] = array('listcontent_open',array(),$call[2]);
923
924            $this->listStack[] = array($listType, $depth);
925
926        //------------------------------------------------------------------------
927        // Getting shallower ( $depth < $end[1] )
928        } else {
929            $this->listCalls[] = array('listcontent_close',array(),$call[2]);
930            $this->listCalls[] = array('listitem_close',array(),$call[2]);
931            $this->listCalls[] = array('list'.$end[0].'_close',array(),$call[2]);
932
933            // Throw away the end - done
934            array_pop($this->listStack);
935
936            while (1) {
937                $end = end($this->listStack);
938
939                if ( $end[1] <= $depth ) {
940
941                    // Normalize depths
942                    $depth = $end[1];
943
944                    $this->listCalls[] = array('listitem_close',array(),$call[2]);
945
946                    if ( $end[0] == $listType ) {
947                        $this->listCalls[] = array('listitem_open',array($depth-1),$call[2]);
948                        $this->listCalls[] = array('listcontent_open',array(),$call[2]);
949
950                    } else {
951                        // Switching list type...
952                        $this->listCalls[] = array('list'.$end[0].'_close', array(), $call[2]);
953                        $this->listCalls[] = array('list'.$listType.'_open', array(), $call[2]);
954                        $this->listCalls[] = array('listitem_open', array($depth-1), $call[2]);
955                        $this->listCalls[] = array('listcontent_open',array(),$call[2]);
956
957                        array_pop($this->listStack);
958                        $this->listStack[] = array($listType, $depth);
959                    }
960
961                    break;
962
963                // Haven't dropped down far enough yet.... ( $end[1] > $depth )
964                } else {
965
966                    $this->listCalls[] = array('listitem_close',array(),$call[2]);
967                    $this->listCalls[] = array('list'.$end[0].'_close',array(),$call[2]);
968
969                    array_pop($this->listStack);
970
971                }
972
973            }
974
975        }
976    }
977
978    //------------------------------------------------------------------------
979    function listContent($call) {
980        $this->listCalls[] = $call;
981    }
982
983    //------------------------------------------------------------------------
984    function interpretSyntax($match, & $type) {
985        if ( substr($match,-1) == '*' ) {
986            $type = 'u';
987        } else {
988            $type = 'o';
989        }
990        // Is the +1 needed? It used to be count(explode(...))
991        // but I don't think the number is seen outside this handler
992        return substr_count(str_replace("\t",'  ',$match), '  ') + 1;
993    }
994}
995
996//------------------------------------------------------------------------
997class Doku_Handler_Preformatted {
998
999    var $CallWriter;
1000
1001    var $calls = array();
1002    var $pos;
1003    var $text ='';
1004
1005
1006
1007    function Doku_Handler_Preformatted(& $CallWriter) {
1008        $this->CallWriter = & $CallWriter;
1009    }
1010
1011    function writeCall($call) {
1012        $this->calls[] = $call;
1013    }
1014
1015    // Probably not needed but just in case...
1016    function writeCalls($calls) {
1017        $this->calls = array_merge($this->calls, $calls);
1018#        $this->CallWriter->writeCalls($this->calls);
1019    }
1020
1021    function finalise() {
1022        $last_call = end($this->calls);
1023        $this->writeCall(array('preformatted_end',array(), $last_call[2]));
1024
1025        $this->process();
1026        $this->CallWriter->finalise();
1027        unset($this->CallWriter);
1028    }
1029
1030    function process() {
1031        foreach ( $this->calls as $call ) {
1032            switch ($call[0]) {
1033                case 'preformatted_start':
1034                    $this->pos = $call[2];
1035                break;
1036                case 'preformatted_newline':
1037                    $this->text .= "\n";
1038                break;
1039                case 'preformatted_content':
1040                    $this->text .= $call[1][0];
1041                break;
1042                case 'preformatted_end':
1043                    if (trim($this->text)) {
1044                        $this->CallWriter->writeCall(array('preformatted',array($this->text),$this->pos));
1045                    }
1046                    // see FS#1699 & FS#1652, add 'eol' instructions to ensure proper triggering of following p_open
1047                    $this->CallWriter->writeCall(array('eol',array(),$this->pos));
1048                    $this->CallWriter->writeCall(array('eol',array(),$this->pos));
1049                break;
1050            }
1051        }
1052    }
1053
1054}
1055
1056//------------------------------------------------------------------------
1057class Doku_Handler_Quote {
1058
1059    var $CallWriter;
1060
1061    var $calls = array();
1062
1063    var $quoteCalls = array();
1064
1065    function Doku_Handler_Quote(& $CallWriter) {
1066        $this->CallWriter = & $CallWriter;
1067    }
1068
1069    function writeCall($call) {
1070        $this->calls[] = $call;
1071    }
1072
1073    // Probably not needed but just in case...
1074    function writeCalls($calls) {
1075        $this->calls = array_merge($this->calls, $calls);
1076    }
1077
1078    function finalise() {
1079        $last_call = end($this->calls);
1080        $this->writeCall(array('quote_end',array(), $last_call[2]));
1081
1082        $this->process();
1083        $this->CallWriter->finalise();
1084        unset($this->CallWriter);
1085    }
1086
1087    function process() {
1088
1089        $quoteDepth = 1;
1090
1091        foreach ( $this->calls as $call ) {
1092            switch ($call[0]) {
1093
1094                case 'quote_start':
1095
1096                    $this->quoteCalls[] = array('quote_open',array(),$call[2]);
1097
1098                case 'quote_newline':
1099
1100                    $quoteLength = $this->getDepth($call[1][0]);
1101
1102                    if ( $quoteLength > $quoteDepth ) {
1103                        $quoteDiff = $quoteLength - $quoteDepth;
1104                        for ( $i = 1; $i <= $quoteDiff; $i++ ) {
1105                            $this->quoteCalls[] = array('quote_open',array(),$call[2]);
1106                        }
1107                    } else if ( $quoteLength < $quoteDepth ) {
1108                        $quoteDiff = $quoteDepth - $quoteLength;
1109                        for ( $i = 1; $i <= $quoteDiff; $i++ ) {
1110                            $this->quoteCalls[] = array('quote_close',array(),$call[2]);
1111                        }
1112                    } else {
1113                        if ($call[0] != 'quote_start') $this->quoteCalls[] = array('linebreak',array(),$call[2]);
1114                    }
1115
1116                    $quoteDepth = $quoteLength;
1117
1118                break;
1119
1120                case 'quote_end':
1121
1122                    if ( $quoteDepth > 1 ) {
1123                        $quoteDiff = $quoteDepth - 1;
1124                        for ( $i = 1; $i <= $quoteDiff; $i++ ) {
1125                            $this->quoteCalls[] = array('quote_close',array(),$call[2]);
1126                        }
1127                    }
1128
1129                    $this->quoteCalls[] = array('quote_close',array(),$call[2]);
1130
1131                    $this->CallWriter->writeCalls($this->quoteCalls);
1132                break;
1133
1134                default:
1135                    $this->quoteCalls[] = $call;
1136                break;
1137            }
1138        }
1139    }
1140
1141    function getDepth($marker) {
1142        preg_match('/>{1,}/', $marker, $matches);
1143        $quoteLength = strlen($matches[0]);
1144        return $quoteLength;
1145    }
1146}
1147
1148//------------------------------------------------------------------------
1149class Doku_Handler_Table {
1150
1151    var $CallWriter;
1152
1153    var $calls = array();
1154    var $tableCalls = array();
1155    var $maxCols = 0;
1156    var $maxRows = 1;
1157    var $currentCols = 0;
1158    var $firstCell = false;
1159    var $lastCellType = 'tablecell';
1160    var $inTableHead = true;
1161    var $currentRow = array('tableheader' => 0, 'tablecell' => 0);
1162    var $countTableHeadRows = 0;
1163
1164    function Doku_Handler_Table(& $CallWriter) {
1165        $this->CallWriter = & $CallWriter;
1166    }
1167
1168    function writeCall($call) {
1169        $this->calls[] = $call;
1170    }
1171
1172    // Probably not needed but just in case...
1173    function writeCalls($calls) {
1174        $this->calls = array_merge($this->calls, $calls);
1175    }
1176
1177    function finalise() {
1178        $last_call = end($this->calls);
1179        $this->writeCall(array('table_end',array(), $last_call[2]));
1180
1181        $this->process();
1182        $this->CallWriter->finalise();
1183        unset($this->CallWriter);
1184    }
1185
1186    //------------------------------------------------------------------------
1187    function process() {
1188        foreach ( $this->calls as $call ) {
1189            switch ( $call[0] ) {
1190                case 'table_start':
1191                    $this->tableStart($call);
1192                break;
1193                case 'table_row':
1194                    $this->tableRowClose($call);
1195                    $this->tableRowOpen(array('tablerow_open',$call[1],$call[2]));
1196                break;
1197                case 'tableheader':
1198                case 'tablecell':
1199                    $this->tableCell($call);
1200                break;
1201                case 'table_end':
1202                    $this->tableRowClose($call);
1203                    $this->tableEnd($call);
1204                break;
1205                default:
1206                    $this->tableDefault($call);
1207                break;
1208            }
1209        }
1210        $this->CallWriter->writeCalls($this->tableCalls);
1211    }
1212
1213    function tableStart($call) {
1214        $this->tableCalls[] = array('table_open',$call[1],$call[2]);
1215        $this->tableCalls[] = array('tablerow_open',array(),$call[2]);
1216        $this->firstCell = true;
1217    }
1218
1219    function tableEnd($call) {
1220        $this->tableCalls[] = array('table_close',$call[1],$call[2]);
1221        $this->finalizeTable();
1222    }
1223
1224    function tableRowOpen($call) {
1225        $this->tableCalls[] = $call;
1226        $this->currentCols = 0;
1227        $this->firstCell = true;
1228        $this->lastCellType = 'tablecell';
1229        $this->maxRows++;
1230        if ($this->inTableHead) {
1231            $this->currentRow = array('tablecell' => 0, 'tableheader' => 0);
1232        }
1233    }
1234
1235    function tableRowClose($call) {
1236        if ($this->inTableHead && ($this->inTableHead = $this->isTableHeadRow())) {
1237            $this->countTableHeadRows++;
1238        }
1239        // Strip off final cell opening and anything after it
1240        while ( $discard = array_pop($this->tableCalls ) ) {
1241
1242            if ( $discard[0] == 'tablecell_open' || $discard[0] == 'tableheader_open') {
1243                break;
1244            }
1245            if (!empty($this->currentRow[$discard[0]])) {
1246                $this->currentRow[$discard[0]]--;
1247            }
1248        }
1249        $this->tableCalls[] = array('tablerow_close', array(), $call[2]);
1250
1251        if ( $this->currentCols > $this->maxCols ) {
1252            $this->maxCols = $this->currentCols;
1253        }
1254    }
1255
1256    function isTableHeadRow() {
1257        $td = $this->currentRow['tablecell'];
1258        $th = $this->currentRow['tableheader'];
1259
1260        if (!$th || $td > 2) return false;
1261        if (2*$td > $th) return false;
1262
1263        return true;
1264    }
1265
1266    function tableCell($call) {
1267        if ($this->inTableHead) {
1268            $this->currentRow[$call[0]]++;
1269        }
1270        if ( !$this->firstCell ) {
1271
1272            // Increase the span
1273            $lastCall = end($this->tableCalls);
1274
1275            // A cell call which follows an open cell means an empty cell so span
1276            if ( $lastCall[0] == 'tablecell_open' || $lastCall[0] == 'tableheader_open' ) {
1277                 $this->tableCalls[] = array('colspan',array(),$call[2]);
1278
1279            }
1280
1281            $this->tableCalls[] = array($this->lastCellType.'_close',array(),$call[2]);
1282            $this->tableCalls[] = array($call[0].'_open',array(1,null,1),$call[2]);
1283            $this->lastCellType = $call[0];
1284
1285        } else {
1286
1287            $this->tableCalls[] = array($call[0].'_open',array(1,null,1),$call[2]);
1288            $this->lastCellType = $call[0];
1289            $this->firstCell = false;
1290
1291        }
1292
1293        $this->currentCols++;
1294    }
1295
1296    function tableDefault($call) {
1297        $this->tableCalls[] = $call;
1298    }
1299
1300    function finalizeTable() {
1301
1302        // Add the max cols and rows to the table opening
1303        if ( $this->tableCalls[0][0] == 'table_open' ) {
1304            // Adjust to num cols not num col delimeters
1305            $this->tableCalls[0][1][] = $this->maxCols - 1;
1306            $this->tableCalls[0][1][] = $this->maxRows;
1307            $this->tableCalls[0][1][] = array_shift($this->tableCalls[0][1]);
1308        } else {
1309            trigger_error('First element in table call list is not table_open');
1310        }
1311
1312        $lastRow = 0;
1313        $lastCell = 0;
1314        $cellKey = array();
1315        $toDelete = array();
1316
1317        // if still in tableheader, then there can be no table header
1318        // as all rows can't be within <THEAD>
1319        if ($this->inTableHead) {
1320            $this->inTableHead = false;
1321            $this->countTableHeadRows = 0;
1322        }
1323
1324        // Look for the colspan elements and increment the colspan on the
1325        // previous non-empty opening cell. Once done, delete all the cells
1326        // that contain colspans
1327        for ($key = 0 ; $key < count($this->tableCalls) ; ++$key) {
1328            $call = $this->tableCalls[$key];
1329
1330            switch ($call[0]) {
1331                case 'table_open' :
1332                    if($this->countTableHeadRows) {
1333                        array_splice($this->tableCalls, $key+1, 0, array(
1334                              array('tablethead_open', array(), $call[2]))
1335                        );
1336                    }
1337                    break;
1338
1339                case 'tablerow_open':
1340
1341                    $lastRow++;
1342                    $lastCell = 0;
1343                    break;
1344
1345                case 'tablecell_open':
1346                case 'tableheader_open':
1347
1348                    $lastCell++;
1349                    $cellKey[$lastRow][$lastCell] = $key;
1350                    break;
1351
1352                case 'table_align':
1353
1354                    $prev = in_array($this->tableCalls[$key-1][0], array('tablecell_open', 'tableheader_open'));
1355                    $next = in_array($this->tableCalls[$key+1][0], array('tablecell_close', 'tableheader_close'));
1356                    // If the cell is empty, align left
1357                    if ($prev && $next) {
1358                        $this->tableCalls[$key-1][1][1] = 'left';
1359
1360                    // If the previous element was a cell open, align right
1361                    } elseif ($prev) {
1362                        $this->tableCalls[$key-1][1][1] = 'right';
1363
1364                    // If the next element is the close of an element, align either center or left
1365                    } elseif ( $next) {
1366                        if ( $this->tableCalls[$cellKey[$lastRow][$lastCell]][1][1] == 'right' ) {
1367                            $this->tableCalls[$cellKey[$lastRow][$lastCell]][1][1] = 'center';
1368                        } else {
1369                            $this->tableCalls[$cellKey[$lastRow][$lastCell]][1][1] = 'left';
1370                        }
1371
1372                    }
1373
1374                    // Now convert the whitespace back to cdata
1375                    $this->tableCalls[$key][0] = 'cdata';
1376                    break;
1377
1378                case 'colspan':
1379
1380                    $this->tableCalls[$key-1][1][0] = false;
1381
1382                    for($i = $key-2; $i >= $cellKey[$lastRow][1]; $i--) {
1383
1384                        if ( $this->tableCalls[$i][0] == 'tablecell_open' || $this->tableCalls[$i][0] == 'tableheader_open' ) {
1385
1386                            if ( false !== $this->tableCalls[$i][1][0] ) {
1387                                $this->tableCalls[$i][1][0]++;
1388                                break;
1389                            }
1390
1391                        }
1392                    }
1393
1394                    $toDelete[] = $key-1;
1395                    $toDelete[] = $key;
1396                    $toDelete[] = $key+1;
1397                    break;
1398
1399                case 'rowspan':
1400
1401                    if ( $this->tableCalls[$key-1][0] == 'cdata' ) {
1402                        // ignore rowspan if previous call was cdata (text mixed with :::) we don't have to check next call as that wont match regex
1403                        $this->tableCalls[$key][0] = 'cdata';
1404
1405                    } else {
1406
1407                        $spanning_cell = null;
1408
1409                        // can't cross thead/tbody boundary
1410                        if (!$this->countTableHeadRows || ($lastRow-1 != $this->countTableHeadRows)) {
1411                            for($i = $lastRow-1; $i > 0; $i--) {
1412
1413                                if ( $this->tableCalls[$cellKey[$i][$lastCell]][0] == 'tablecell_open' || $this->tableCalls[$cellKey[$i][$lastCell]][0] == 'tableheader_open' ) {
1414
1415                                    if ($this->tableCalls[$cellKey[$i][$lastCell]][1][2] >= $lastRow - $i) {
1416                                        $spanning_cell = $i;
1417                                        break;
1418                                    }
1419
1420                                }
1421                            }
1422                        }
1423                        if (is_null($spanning_cell)) {
1424                            // No spanning cell found, so convert this cell to
1425                            // an empty one to avoid broken tables
1426                            $this->tableCalls[$key][0] = 'cdata';
1427                            $this->tableCalls[$key][1][0] = '';
1428                            continue;
1429                        }
1430                        $this->tableCalls[$cellKey[$spanning_cell][$lastCell]][1][2]++;
1431
1432                        $this->tableCalls[$key-1][1][2] = false;
1433
1434                        $toDelete[] = $key-1;
1435                        $toDelete[] = $key;
1436                        $toDelete[] = $key+1;
1437                    }
1438                    break;
1439
1440                case 'tablerow_close':
1441
1442                    // Fix broken tables by adding missing cells
1443                    while (++$lastCell < $this->maxCols) {
1444                        array_splice($this->tableCalls, $key, 0, array(
1445                               array('tablecell_open', array(1, null, 1), $call[2]),
1446                               array('cdata', array(''), $call[2]),
1447                               array('tablecell_close', array(), $call[2])));
1448                        $key += 3;
1449                    }
1450
1451                    if($this->countTableHeadRows == $lastRow) {
1452                        array_splice($this->tableCalls, $key+1, 0, array(
1453                              array('tablethead_close', array(), $call[2])));
1454                    }
1455                    break;
1456
1457            }
1458        }
1459
1460        // condense cdata
1461        $cnt = count($this->tableCalls);
1462        for( $key = 0; $key < $cnt; $key++){
1463            if($this->tableCalls[$key][0] == 'cdata'){
1464                $ckey = $key;
1465                $key++;
1466                while($this->tableCalls[$key][0] == 'cdata'){
1467                    $this->tableCalls[$ckey][1][0] .= $this->tableCalls[$key][1][0];
1468                    $toDelete[] = $key;
1469                    $key++;
1470                }
1471                continue;
1472            }
1473        }
1474
1475        foreach ( $toDelete as $delete ) {
1476            unset($this->tableCalls[$delete]);
1477        }
1478        $this->tableCalls = array_values($this->tableCalls);
1479    }
1480}
1481
1482
1483/**
1484 * Handler for paragraphs
1485 *
1486 * @author Harry Fuecks <hfuecks@gmail.com>
1487 */
1488class Doku_Handler_Block {
1489    var $calls = array();
1490    var $skipEol = false;
1491    var $inParagraph = false;
1492
1493    // Blocks these should not be inside paragraphs
1494    var $blockOpen = array(
1495            'header',
1496            'listu_open','listo_open','listitem_open','listcontent_open',
1497            'table_open','tablerow_open','tablecell_open','tableheader_open','tablethead_open',
1498            'quote_open',
1499            'code','file','hr','preformatted','rss',
1500            'htmlblock','phpblock',
1501            'footnote_open',
1502        );
1503
1504    var $blockClose = array(
1505            'header',
1506            'listu_close','listo_close','listitem_close','listcontent_close',
1507            'table_close','tablerow_close','tablecell_close','tableheader_close','tablethead_close',
1508            'quote_close',
1509            'code','file','hr','preformatted','rss',
1510            'htmlblock','phpblock',
1511            'footnote_close',
1512        );
1513
1514    // Stacks can contain paragraphs
1515    var $stackOpen = array(
1516        'section_open',
1517        );
1518
1519    var $stackClose = array(
1520        'section_close',
1521        );
1522
1523
1524    /**
1525     * Constructor. Adds loaded syntax plugins to the block and stack
1526     * arrays
1527     *
1528     * @author Andreas Gohr <andi@splitbrain.org>
1529     */
1530    function Doku_Handler_Block(){
1531        global $DOKU_PLUGINS;
1532        //check if syntax plugins were loaded
1533        if(empty($DOKU_PLUGINS['syntax'])) return;
1534        foreach($DOKU_PLUGINS['syntax'] as $n => $p){
1535            $ptype = $p->getPType();
1536            if($ptype == 'block'){
1537                $this->blockOpen[]  = 'plugin_'.$n;
1538                $this->blockClose[] = 'plugin_'.$n;
1539            }elseif($ptype == 'stack'){
1540                $this->stackOpen[]  = 'plugin_'.$n;
1541                $this->stackClose[] = 'plugin_'.$n;
1542            }
1543        }
1544    }
1545
1546    function openParagraph($pos){
1547        if ($this->inParagraph) return;
1548        $this->calls[] = array('p_open',array(), $pos);
1549        $this->inParagraph = true;
1550        $this->skipEol = true;
1551    }
1552
1553    /**
1554     * Close a paragraph if needed
1555     *
1556     * This function makes sure there are no empty paragraphs on the stack
1557     *
1558     * @author Andreas Gohr <andi@splitbrain.org>
1559     */
1560    function closeParagraph($pos){
1561        if (!$this->inParagraph) return;
1562        // look back if there was any content - we don't want empty paragraphs
1563        $content = '';
1564        $ccount = count($this->calls);
1565        for($i=$ccount-1; $i>=0; $i--){
1566            if($this->calls[$i][0] == 'p_open'){
1567                break;
1568            }elseif($this->calls[$i][0] == 'cdata'){
1569                $content .= $this->calls[$i][1][0];
1570            }else{
1571                $content = 'found markup';
1572                break;
1573            }
1574        }
1575
1576        if(trim($content)==''){
1577            //remove the whole paragraph
1578            //array_splice($this->calls,$i); // <- this is much slower than the loop below
1579            for($x=$ccount; $x>$i; $x--) array_pop($this->calls);
1580        }else{
1581            // remove ending linebreaks in the paragraph
1582            $i=count($this->calls)-1;
1583            if ($this->calls[$i][0] == 'cdata') $this->calls[$i][1][0] = rtrim($this->calls[$i][1][0],DOKU_PARSER_EOL);
1584            $this->calls[] = array('p_close',array(), $pos);
1585        }
1586
1587        $this->inParagraph = false;
1588        $this->skipEol = true;
1589    }
1590
1591    function addCall($call) {
1592        $key = count($this->calls);
1593        if ($key and ($call[0] == 'cdata') and ($this->calls[$key-1][0] == 'cdata')) {
1594            $this->calls[$key-1][1][0] .= $call[1][0];
1595        } else {
1596            $this->calls[] = $call;
1597        }
1598    }
1599
1600    // simple version of addCall, without checking cdata
1601    function storeCall($call) {
1602        $this->calls[] = $call;
1603    }
1604
1605    /**
1606     * Processes the whole instruction stack to open and close paragraphs
1607     *
1608     * @author Harry Fuecks <hfuecks@gmail.com>
1609     * @author Andreas Gohr <andi@splitbrain.org>
1610     */
1611    function process($calls) {
1612        // open first paragraph
1613        $this->openParagraph(0);
1614        foreach ( $calls as $key => $call ) {
1615            $cname = $call[0];
1616            if ($cname == 'plugin') {
1617                $cname='plugin_'.$call[1][0];
1618                $plugin = true;
1619                $plugin_open = (($call[1][2] == DOKU_LEXER_ENTER) || ($call[1][2] == DOKU_LEXER_SPECIAL));
1620                $plugin_close = (($call[1][2] == DOKU_LEXER_EXIT) || ($call[1][2] == DOKU_LEXER_SPECIAL));
1621            } else {
1622                $plugin = false;
1623            }
1624            /* stack */
1625            if ( in_array($cname,$this->stackClose ) && (!$plugin || $plugin_close)) {
1626                $this->closeParagraph($call[2]);
1627                $this->storeCall($call);
1628                $this->openParagraph($call[2]);
1629                continue;
1630            }
1631            if ( in_array($cname,$this->stackOpen ) && (!$plugin || $plugin_open) ) {
1632                $this->closeParagraph($call[2]);
1633                $this->storeCall($call);
1634                $this->openParagraph($call[2]);
1635                continue;
1636            }
1637            /* block */
1638            // If it's a substition it opens and closes at the same call.
1639            // To make sure next paragraph is correctly started, let close go first.
1640            if ( in_array($cname, $this->blockClose) && (!$plugin || $plugin_close)) {
1641                $this->closeParagraph($call[2]);
1642                $this->storeCall($call);
1643                $this->openParagraph($call[2]);
1644                continue;
1645            }
1646            if ( in_array($cname, $this->blockOpen) && (!$plugin || $plugin_open)) {
1647                $this->closeParagraph($call[2]);
1648                $this->storeCall($call);
1649                continue;
1650            }
1651            /* eol */
1652            if ( $cname == 'eol' ) {
1653                // Check this isn't an eol instruction to skip...
1654                if ( !$this->skipEol ) {
1655                    // Next is EOL => double eol => mark as paragraph
1656                    if ( isset($calls[$key+1]) && $calls[$key+1][0] == 'eol' ) {
1657                        $this->closeParagraph($call[2]);
1658                        $this->openParagraph($call[2]);
1659                    } else {
1660                        //if this is just a single eol make a space from it
1661                        $this->addCall(array('cdata',array(DOKU_PARSER_EOL), $call[2]));
1662                    }
1663                }
1664                continue;
1665            }
1666            /* normal */
1667            $this->addCall($call);
1668            $this->skipEol = false;
1669        }
1670        // close last paragraph
1671        $call = end($this->calls);
1672        $this->closeParagraph($call[2]);
1673        return $this->calls;
1674    }
1675}
1676
1677//Setup VIM: ex: et ts=4 :
1678