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