aboutsummaryrefslogtreecommitdiff
path: root/vendors/dokuwiki/inc/parser/handler.php
blob: 9fe5866ad275f120215d2a833486207bf5b759bc (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
<?php
if(!defined('DOKU_INC')) die('meh.');
if (!defined('DOKU_PARSER_EOL')) define('DOKU_PARSER_EOL',"\n");   // add this to make handling test cases simpler

class Doku_Handler {

    var $Renderer = NULL;

    var $CallWriter = NULL;

    var $calls = array();

    var $status = array(
        'section' => false,
        'section_edit_start' => -1,
        'section_edit_level' => 1,
        'section_edit_title' => ''
    );

    var $rewriteBlocks = true;

    function Doku_Handler() {
        $this->CallWriter = & new Doku_Handler_CallWriter($this);
    }

    function _addCall($handler, $args, $pos) {
        $call = array($handler,$args, $pos);
        $this->CallWriter->writeCall($call);
    }

    function addPluginCall($plugin, $args, $state, $pos, $match) {
        $call = array('plugin',array($plugin, $args, $state, $match), $pos);
        $this->CallWriter->writeCall($call);
    }

    function _finalize(){

        $this->CallWriter->finalise();

        if ( $this->status['section'] ) {
           $last_call = end($this->calls);
           array_push($this->calls,array('section_close',array(), $last_call[2]));
           if ($this->status['section_edit_start']>1) {
               // ignore last edit section if there is only one header
               array_push($this->calls,array('section_edit',array($this->status['section_edit_start'], 0, $this->status['section_edit_level'], $this->status['section_edit_title']), $last_call[2]));
           }
        }

        if ( $this->rewriteBlocks ) {
            $B = & new Doku_Handler_Block();
            $this->calls = $B->process($this->calls);
        }

        trigger_event('PARSER_HANDLER_DONE',$this);

        array_unshift($this->calls,array('document_start',array(),0));
        $last_call = end($this->calls);
        array_push($this->calls,array('document_end',array(),$last_call[2]));
    }

    function fetch() {
        $call = each($this->calls);
        if ( $call ) {
            return $call['value'];
        }
        return false;
    }


    /**
     * Special plugin handler
     *
     * This handler is called for all modes starting with 'plugin_'.
     * An additional parameter with the plugin name is passed
     *
     * @author Andreas Gohr <andi@splitbrain.org>
     */
    function plugin($match, $state, $pos, $pluginname){
        $data = array($match);
        $plugin =& plugin_load('syntax',$pluginname);
        if($plugin != null){
            $data = $plugin->handle($match, $state, $pos, $this);
        }
        if ($data !== false) {
          $this->addPluginCall($pluginname,$data,$state,$pos,$match);
        }
        return true;
    }

    function base($match, $state, $pos) {
        switch ( $state ) {
            case DOKU_LEXER_UNMATCHED:
                $this->_addCall('cdata',array($match), $pos);
                return true;
            break;
        }
    }

    function header($match, $state, $pos) {
        global $conf;

        // get level and title
        $title = trim($match);
        $level = 7 - strspn($title,'=');
        if($level < 1) $level = 1;
        $title = trim($title,'=');
        $title = trim($title);

        if ($this->status['section']) $this->_addCall('section_close',array(),$pos);

        if ($level<=$conf['maxseclevel']) {
            $this->_addCall('section_edit',array($this->status['section_edit_start'], $pos-1, $this->status['section_edit_level'], $this->status['section_edit_title']), $pos);
            $this->status['section_edit_start'] = $pos;
            $this->status['section_edit_level'] = $level;
            $this->status['section_edit_title'] = $title;
        }

        $this->_addCall('header',array($title,$level,$pos), $pos);

        $this->_addCall('section_open',array($level),$pos);
        $this->status['section'] = true;
        return true;
    }

    function notoc($match, $state, $pos) {
        $this->_addCall('notoc',array(),$pos);
        return true;
    }

    function nocache($match, $state, $pos) {
        $this->_addCall('nocache',array(),$pos);
        return true;
    }

    function linebreak($match, $state, $pos) {
        $this->_addCall('linebreak',array(),$pos);
        return true;
    }

    function eol($match, $state, $pos) {
        $this->_addCall('eol',array(),$pos);
        return true;
    }

    function hr($match, $state, $pos) {
        $this->_addCall('hr',array(),$pos);
        return true;
    }

    function _nestingTag($match, $state, $pos, $name) {
        switch ( $state ) {
            case DOKU_LEXER_ENTER:
                $this->_addCall($name.'_open', array(), $pos);
            break;
            case DOKU_LEXER_EXIT:
                $this->_addCall($name.'_close', array(), $pos);
            break;
            case DOKU_LEXER_UNMATCHED:
                $this->_addCall('cdata',array($match), $pos);
            break;
        }
    }

    function strong($match, $state, $pos) {
        $this->_nestingTag($match, $state, $pos, 'strong');
        return true;
    }

    function emphasis($match, $state, $pos) {
        $this->_nestingTag($match, $state, $pos, 'emphasis');
        return true;
    }

    function underline($match, $state, $pos) {
        $this->_nestingTag($match, $state, $pos, 'underline');
        return true;
    }

    function monospace($match, $state, $pos) {
        $this->_nestingTag($match, $state, $pos, 'monospace');
        return true;
    }

    function subscript($match, $state, $pos) {
        $this->_nestingTag($match, $state, $pos, 'subscript');
        return true;
    }

    function superscript($match, $state, $pos) {
        $this->_nestingTag($match, $state, $pos, 'superscript');
        return true;
    }

    function deleted($match, $state, $pos) {
        $this->_nestingTag($match, $state, $pos, 'deleted');
        return true;
    }


    function footnote($match, $state, $pos) {
//        $this->_nestingTag($match, $state, $pos, 'footnote');
        if (!isset($this->_footnote)) $this->_footnote = false;

        switch ( $state ) {
            case DOKU_LEXER_ENTER:
                // footnotes can not be nested - however due to limitations in lexer it can't be prevented
                // we will still enter a new footnote mode, we just do nothing
                if ($this->_footnote) {
                  $this->_addCall('cdata',array($match), $pos);
                  break;
                }

                $this->_footnote = true;

                $ReWriter = & new Doku_Handler_Nest($this->CallWriter,'footnote_close');
                $this->CallWriter = & $ReWriter;
                $this->_addCall('footnote_open', array(), $pos);
            break;
            case DOKU_LEXER_EXIT:
                // check whether we have already exitted the footnote mode, can happen if the modes were nested
                if (!$this->_footnote) {
                  $this->_addCall('cdata',array($match), $pos);
                  break;
                }

                $this->_footnote = false;

                $this->_addCall('footnote_close', array(), $pos);
                $this->CallWriter->process();
                $ReWriter = & $this->CallWriter;
                $this->CallWriter = & $ReWriter->CallWriter;
            break;
            case DOKU_LEXER_UNMATCHED:
                $this->_addCall('cdata', array($match), $pos);
            break;
        }
        return true;
    }

    function listblock($match, $state, $pos) {
        switch ( $state ) {
            case DOKU_LEXER_ENTER:
                $ReWriter = & new Doku_Handler_List($this->CallWriter);
                $this->CallWriter = & $ReWriter;
                $this->_addCall('list_open', array($match), $pos);
            break;
            case DOKU_LEXER_EXIT:
                $this->_addCall('list_close', array(), $pos);
                $this->CallWriter->process();
                $ReWriter = & $this->CallWriter;
                $this->CallWriter = & $ReWriter->CallWriter;
            break;
            case DOKU_LEXER_MATCHED:
                $this->_addCall('list_item', array($match), $pos);
            break;
            case DOKU_LEXER_UNMATCHED:
                $this->_addCall('cdata', array($match), $pos);
            break;
        }
        return true;
    }

    function unformatted($match, $state, $pos) {
        if ( $state == DOKU_LEXER_UNMATCHED ) {
            $this->_addCall('unformatted',array($match), $pos);
        }
        return true;
    }

    function php($match, $state, $pos) {
        global $conf;
        if ( $state == DOKU_LEXER_UNMATCHED ) {
            $this->_addCall('php',array($match), $pos);
        }
        return true;
    }

    function phpblock($match, $state, $pos) {
        global $conf;
        if ( $state == DOKU_LEXER_UNMATCHED ) {
            $this->_addCall('phpblock',array($match), $pos);
        }
        return true;
    }

    function html($match, $state, $pos) {
        global $conf;
        if ( $state == DOKU_LEXER_UNMATCHED ) {
            $this->_addCall('html',array($match), $pos);
        }
        return true;
    }

    function htmlblock($match, $state, $pos) {
        global $conf;
        if ( $state == DOKU_LEXER_UNMATCHED ) {
            $this->_addCall('htmlblock',array($match), $pos);
        }
        return true;
    }

    function preformatted($match, $state, $pos) {
        switch ( $state ) {
            case DOKU_LEXER_ENTER:
                $ReWriter = & new Doku_Handler_Preformatted($this->CallWriter);
                $this->CallWriter = & $ReWriter;
                $this->_addCall('preformatted_start',array(), $pos);
            break;
            case DOKU_LEXER_EXIT:
                $this->_addCall('preformatted_end',array(), $pos);
                $this->CallWriter->process();
                $ReWriter = & $this->CallWriter;
                $this->CallWriter = & $ReWriter->CallWriter;
            break;
            case DOKU_LEXER_MATCHED:
                $this->_addCall('preformatted_newline',array(), $pos);
            break;
            case DOKU_LEXER_UNMATCHED:
                $this->_addCall('preformatted_content',array($match), $pos);
            break;
        }

        return true;
    }

    function quote($match, $state, $pos) {

        switch ( $state ) {

            case DOKU_LEXER_ENTER:
                $ReWriter = & new Doku_Handler_Quote($this->CallWriter);
                $this->CallWriter = & $ReWriter;
                $this->_addCall('quote_start',array($match), $pos);
            break;

            case DOKU_LEXER_EXIT:
                $this->_addCall('quote_end',array(), $pos);
                $this->CallWriter->process();
                $ReWriter = & $this->CallWriter;
                $this->CallWriter = & $ReWriter->CallWriter;
            break;

            case DOKU_LEXER_MATCHED:
                $this->_addCall('quote_newline',array($match), $pos);
            break;

            case DOKU_LEXER_UNMATCHED:
                $this->_addCall('cdata',array($match), $pos);
            break;

        }

        return true;
    }

    function file($match, $state, $pos) {
        return $this->code($match, $state, $pos, 'file');
    }

    function code($match, $state, $pos, $type='code') {
        if ( $state == DOKU_LEXER_UNMATCHED ) {
            $matches = explode('>',$match,2);
            $matches[0] = trim($matches[0]);

            list($language,$filename) = explode(' ',$matches[0],2);
            $language = trim($language);
            $filename = trim($filename);
            if ( $language == '' )  $language = null;
            if ( $language == '-' ) $language = null;
            if ( $filename == '' )  $filename = null;
            # We shortcut html here.
            if($language == 'html') $language = 'html4strict';
            $this->_addCall(
                    $type,
                    array($matches[1],$language,$filename),
                    $pos
                );
        }
        return true;
    }

    function acronym($match, $state, $pos) {
        $this->_addCall('acronym',array($match), $pos);
        return true;
    }

    function smiley($match, $state, $pos) {
        $this->_addCall('smiley',array($match), $pos);
        return true;
    }

    function wordblock($match, $state, $pos) {
        $this->_addCall('wordblock',array($match), $pos);
        return true;
    }

    function entity($match, $state, $pos) {
        $this->_addCall('entity',array($match), $pos);
        return true;
    }

    function multiplyentity($match, $state, $pos) {
        preg_match_all('/\d+/',$match,$matches);
        $this->_addCall('multiplyentity',array($matches[0][0],$matches[0][1]), $pos);
        return true;
    }

    function singlequoteopening($match, $state, $pos) {
        $this->_addCall('singlequoteopening',array(), $pos);
        return true;
    }

    function singlequoteclosing($match, $state, $pos) {
        $this->_addCall('singlequoteclosing',array(), $pos);
        return true;
    }

    function apostrophe($match, $state, $pos) {
        $this->_addCall('apostrophe',array(), $pos);
        return true;
    }

    function doublequoteopening($match, $state, $pos) {
        $this->_addCall('doublequoteopening',array(), $pos);
        return true;
    }

    function doublequoteclosing($match, $state, $pos) {
        $this->_addCall('doublequoteclosing',array(), $pos);
        return true;
    }

    function camelcaselink($match, $state, $pos) {
        $this->_addCall('camelcaselink',array($match), $pos);
        return true;
    }

    /*
    */
    function internallink($match, $state, $pos) {
        // Strip the opening and closing markup
        $link = preg_replace(array('/^\[\[/','/\]\]$/u'),'',$match);

        // Split title from URL
        $link = explode('|',$link,2);
        if ( !isset($link[1]) ) {
            $link[1] = NULL;
        } else if ( preg_match('/^\{\{[^\}]+\}\}$/',$link[1]) ) {
            // If the title is an image, convert it to an array containing the image details
            $link[1] = Doku_Handler_Parse_Media($link[1]);
        }
        $link[0] = trim($link[0]);

        //decide which kind of link it is

        if ( preg_match('/^[a-zA-Z0-9\.]+>{1}.*$/u',$link[0]) ) {
        // Interwiki
            $interwiki = explode('>',$link[0],2);
            $this->_addCall(
                'interwikilink',
                array($link[0],$link[1],strtolower($interwiki[0]),$interwiki[1]),
                $pos
                );
        }elseif ( preg_match('/^\\\\\\\\[\w.:?\-;,]+?\\\\/u',$link[0]) ) {
        // Windows Share
            $this->_addCall(
                'windowssharelink',
                array($link[0],$link[1]),
                $pos
                );
        }elseif ( preg_match('#^([a-z0-9\-\.+]+?)://#i',$link[0]) ) {
        // external link (accepts all protocols)
            $this->_addCall(
                    'externallink',
                    array($link[0],$link[1]),
                    $pos
                    );
        }elseif ( preg_match('<'.PREG_PATTERN_VALID_EMAIL.'>',$link[0]) ) {
        // E-Mail (pattern above is defined in inc/mail.php)
            $this->_addCall(
                'emaillink',
                array($link[0],$link[1]),
                $pos
                );
        }elseif ( preg_match('!^#.+!',$link[0]) ){
        // local link
            $this->_addCall(
                'locallink',
                array(substr($link[0],1),$link[1]),
                $pos
                );
        }else{
        // internal link
            $this->_addCall(
                'internallink',
                array($link[0],$link[1]),
                $pos
                );
        }

        return true;
    }

    function filelink($match, $state, $pos) {
        $this->_addCall('filelink',array($match, NULL), $pos);
        return true;
    }

    function windowssharelink($match, $state, $pos) {
        $this->_addCall('windowssharelink',array($match, NULL), $pos);
        return true;
    }

    function media($match, $state, $pos) {
        $p = Doku_Handler_Parse_Media($match);

        $this->_addCall(
              $p['type'],
              array($p['src'], $p['title'], $p['align'], $p['width'],
                     $p['height'], $p['cache'], $p['linking']),
              $pos
             );
        return true;
    }

    function rss($match, $state, $pos) {
        $link = preg_replace(array('/^\{\{rss>/','/\}\}$/'),'',$match);

        // get params
        list($link,$params) = explode(' ',$link,2);

        $p = array();
        if(preg_match('/\b(\d+)\b/',$params,$match)){
            $p['max'] = $match[1];
        }else{
            $p['max'] = 8;
        }
        $p['reverse'] = (preg_match('/rev/',$params));
        $p['author']  = (preg_match('/\b(by|author)/',$params));
        $p['date']    = (preg_match('/\b(date)/',$params));
        $p['details'] = (preg_match('/\b(desc|detail)/',$params));

        if (preg_match('/\b(\d+)([dhm])\b/',$params,$match)) {
          $period = array('d' => 86400, 'h' => 3600, 'm' => 60);
          $p['refresh'] = max(600,$match[1]*$period[$match[2]]);  // n * period in seconds, minimum 10 minutes
        } else {
          $p['refresh'] = 14400;   // default to 4 hours
        }

        $this->_addCall('rss',array($link,$p),$pos);
        return true;
    }

    function externallink($match, $state, $pos) {
        $url   = $match;
        $title = null;

        // add protocol on simple short URLs
        if(substr($url,0,3) == 'ftp' && (substr($url,0,6) != 'ftp://')){
            $title = $url;
            $url   = 'ftp://'.$url;
        }
        if(substr($url,0,3) == 'www' && (substr($url,0,7) != 'http://')){
            $title = $url;
            $url = 'http://'.$url;
        }

        $this->_addCall('externallink',array($url, $title), $pos);
        return true;
    }

    function emaillink($match, $state, $pos) {
        $email = preg_replace(array('/^</','/>$/'),'',$match);
        $this->_addCall('emaillink',array($email, NULL), $pos);
        return true;
    }

    function table($match, $state, $pos) {
        switch ( $state ) {

            case DOKU_LEXER_ENTER:

                $ReWriter = & new Doku_Handler_Table($this->CallWriter);
                $this->CallWriter = & $ReWriter;

                $this->_addCall('table_start', array(), $pos);
                if ( trim($match) == '^' ) {
                    $this->_addCall('tableheader', array(), $pos);
                } else {
                    $this->_addCall('tablecell', array(), $pos);
                }
            break;

            case DOKU_LEXER_EXIT:
                $this->_addCall('table_end', array(), $pos);
                $this->CallWriter->process();
                $ReWriter = & $this->CallWriter;
                $this->CallWriter = & $ReWriter->CallWriter;
            break;

            case DOKU_LEXER_UNMATCHED:
                if ( trim($match) != '' ) {
                    $this->_addCall('cdata',array($match), $pos);
                }
            break;

            case DOKU_LEXER_MATCHED:
                if ( $match == ' ' ){
                    $this->_addCall('cdata', array($match), $pos);
                } else if ( preg_match('/:::/',$match) ) {
                    $this->_addCall('rowspan', array($match), $pos);
                } else if ( preg_match('/\t+/',$match) ) {
                    $this->_addCall('table_align', array($match), $pos);
                } else if ( preg_match('/ {2,}/',$match) ) {
                    $this->_addCall('table_align', array($match), $pos);
                } else if ( $match == "\n|" ) {
                    $this->_addCall('table_row', array(), $pos);
                    $this->_addCall('tablecell', array(), $pos);
                } else if ( $match == "\n^" ) {
                    $this->_addCall('table_row', array(), $pos);
                    $this->_addCall('tableheader', array(), $pos);
                } else if ( $match == '|' ) {
                    $this->_addCall('tablecell', array(), $pos);
                } else if ( $match == '^' ) {
                    $this->_addCall('tableheader', array(), $pos);
                }
            break;
        }
        return true;
    }
}

//------------------------------------------------------------------------
function Doku_Handler_Parse_Media($match) {

    // Strip the opening and closing markup
    $link = preg_replace(array('/^\{\{/','/\}\}$/u'),'',$match);

    // Split title from URL
    $link = explode('|',$link,2);


    // Check alignment
    $ralign = (bool)preg_match('/^ /',$link[0]);
    $lalign = (bool)preg_match('/ $/',$link[0]);

    // Logic = what's that ;)...
    if ( $lalign & $ralign ) {
        $align = 'center';
    } else if ( $ralign ) {
        $align = 'right';
    } else if ( $lalign ) {
        $align = 'left';
    } else {
        $align = NULL;
    }

    // The title...
    if ( !isset($link[1]) ) {
        $link[1] = NULL;
    }

    //remove aligning spaces
    $link[0] = trim($link[0]);

    //split into src and parameters (using the very last questionmark)
    $pos = strrpos($link[0], '?');
    if($pos !== false){
        $src   = substr($link[0],0,$pos);
        $param = substr($link[0],$pos+1);
    }else{
        $src   = $link[0];
        $param = '';
    }

    //parse width and height
    if(preg_match('#(\d+)(x(\d+))?#i',$param,$size)){
        ($size[1]) ? $w = $size[1] : $w = NULL;
        ($size[3]) ? $h = $size[3] : $h = NULL;
    } else {
        $w = NULL;
        $h = NULL;
    }

    //get linking command
    if(preg_match('/nolink/i',$param)){
        $linking = 'nolink';
    }else if(preg_match('/direct/i',$param)){
        $linking = 'direct';
    }else if(preg_match('/linkonly/i',$param)){
        $linking = 'linkonly';
    }else{
        $linking = 'details';
    }

    //get caching command
    if (preg_match('/(nocache|recache)/i',$param,$cachemode)){
        $cache = $cachemode[1];
    }else{
        $cache = 'cache';
    }

    // Check whether this is a local or remote image
    if ( preg_match('#^(https?|ftp)#i',$src) ) {
        $call = 'externalmedia';
    } else {
        $call = 'internalmedia';
    }

    $params = array(
        'type'=>$call,
        'src'=>$src,
        'title'=>$link[1],
        'align'=>$align,
        'width'=>$w,
        'height'=>$h,
        'cache'=>$cache,
        'linking'=>$linking,
    );

    return $params;
}

//------------------------------------------------------------------------
class Doku_Handler_CallWriter {

    var $Handler;

    function Doku_Handler_CallWriter(& $Handler) {
        $this->Handler = & $Handler;
    }

    function writeCall($call) {
        $this->Handler->calls[] = $call;
    }

    function writeCalls($calls) {
        $this->Handler->calls = array_merge($this->Handler->calls, $calls);
    }

    // function is required, but since this call writer is first/highest in
    // the chain it is not required to do anything
    function finalise() {
    }
}

//------------------------------------------------------------------------
/**
 * Generic call writer class to handle nesting of rendering instructions
 * within a render instruction. Also see nest() method of renderer base class
 *
 * @author    Chris Smith <chris@jalakai.co.uk>
 */
class Doku_Handler_Nest {

    var $CallWriter;
    var $calls = array();

    var $closingInstruction;

    /**
     * constructor
     *
     * @param  object     $CallWriter     the renderers current call writer
     * @param  string     $close          closing instruction name, this is required to properly terminate the
     *                                    syntax mode if the document ends without a closing pattern
     */
    function Doku_Handler_Nest(& $CallWriter, $close="nest_close") {
        $this->CallWriter = & $CallWriter;

        $this->closingInstruction = $close;
    }

    function writeCall($call) {
        $this->calls[] = $call;
    }

    function writeCalls($calls) {
        $this->calls = array_merge($this->calls, $calls);
    }

    function finalise() {
        $last_call = end($this->calls);
        $this->writeCall(array($this->closingInstruction,array(), $last_call[2]));

        $this->process();
        $this->CallWriter->finalise();
    }

    function process() {
        // merge consecutive cdata
        $unmerged_calls = $this->calls;
        $this->calls = array();

        foreach ($unmerged_calls as $call) $this->addCall($call);

        $first_call = reset($this->calls);
        $this->CallWriter->writeCall(array("nest", array($this->calls), $first_call[2]));
    }

    function addCall($call) {
        $key = count($this->calls);
        if ($key and ($call[0] == 'cdata') and ($this->calls[$key-1][0] == 'cdata')) {
            $this->calls[$key-1][1][0] .= $call[1][0];
        } else if ($call[0] == 'eol') {
            // do nothing (eol shouldn't be allowed, to counter preformatted fix in #1652 & #1699)
        } else {
            $this->calls[] = $call;
        }
    }
}

class Doku_Handler_List {

    var $CallWriter;

    var $calls = array();
    var $listCalls = array();
    var $listStack = array();

    function Doku_Handler_List(& $CallWriter) {
        $this->CallWriter = & $CallWriter;
    }

    function writeCall($call) {
        $this->calls[] = $call;
    }

    // Probably not needed but just in case...
    function writeCalls($calls) {
        $this->calls = array_merge($this->calls, $calls);
#        $this->CallWriter->writeCalls($this->calls);
    }

    function finalise() {
        $last_call = end($this->calls);
        $this->writeCall(array('list_close',array(), $last_call[2]));

        $this->process();
        $this->CallWriter->finalise();
    }

    //------------------------------------------------------------------------
    function process() {

        foreach ( $this->calls as $call ) {
            switch ($call[0]) {
                case 'list_item':
                    $this->listOpen($call);
                break;
                case 'list_open':
                    $this->listStart($call);
                break;
                case 'list_close':
                    $this->listEnd($call);
                break;
                default:
                    $this->listContent($call);
                break;
            }
        }

        $this->CallWriter->writeCalls($this->listCalls);
    }

    //------------------------------------------------------------------------
    function listStart($call) {
        $depth = $this->interpretSyntax($call[1][0], $listType);

        $this->initialDepth = $depth;
        $this->listStack[] = array($listType, $depth);

        $this->listCalls[] = array('list'.$listType.'_open',array(),$call[2]);
        $this->listCalls[] = array('listitem_open',array(1),$call[2]);
        $this->listCalls[] = array('listcontent_open',array(),$call[2]);
    }

    //------------------------------------------------------------------------
    function listEnd($call) {
        $closeContent = true;

        while ( $list = array_pop($this->listStack) ) {
            if ( $closeContent ) {
                $this->listCalls[] = array('listcontent_close',array(),$call[2]);
                $closeContent = false;
            }
            $this->listCalls[] = array('listitem_close',array(),$call[2]);
            $this->listCalls[] = array('list'.$list[0].'_close', array(), $call[2]);
        }
    }

    //------------------------------------------------------------------------
    function listOpen($call) {
        $depth = $this->interpretSyntax($call[1][0], $listType);
        $end = end($this->listStack);

        // Not allowed to be shallower than initialDepth
        if ( $depth < $this->initialDepth ) {
            $depth = $this->initialDepth;
        }

        //------------------------------------------------------------------------
        if ( $depth == $end[1] ) {

            // Just another item in the list...
            if ( $listType == $end[0] ) {
                $this->listCalls[] = array('listcontent_close',array(),$call[2]);
                $this->listCalls[] = array('listitem_close',array(),$call[2]);
                $this->listCalls[] = array('listitem_open',array($depth-1),$call[2]);
                $this->listCalls[] = array('listcontent_open',array(),$call[2]);

            // Switched list type...
            } else {

                $this->listCalls[] = array('listcontent_close',array(),$call[2]);
                $this->listCalls[] = array('listitem_close',array(),$call[2]);
                $this->listCalls[] = array('list'.$end[0].'_close', array(), $call[2]);
                $this->listCalls[] = array('list'.$listType.'_open', array(), $call[2]);
                $this->listCalls[] = array('listitem_open', array($depth-1), $call[2]);
                $this->listCalls[] = array('listcontent_open',array(),$call[2]);

                array_pop($this->listStack);
                $this->listStack[] = array($listType, $depth);
            }

        //------------------------------------------------------------------------
        // Getting deeper...
        } else if ( $depth > $end[1] ) {

            $this->listCalls[] = array('listcontent_close',array(),$call[2]);
            $this->listCalls[] = array('list'.$listType.'_open', array(), $call[2]);
            $this->listCalls[] = array('listitem_open', array($depth-1), $call[2]);
            $this->listCalls[] = array('listcontent_open',array(),$call[2]);

            $this->listStack[] = array($listType, $depth);

        //------------------------------------------------------------------------
        // Getting shallower ( $depth < $end[1] )
        } else {
            $this->listCalls[] = array('listcontent_close',array(),$call[2]);
            $this->listCalls[] = array('listitem_close',array(),$call[2]);
            $this->listCalls[] = array('list'.$end[0].'_close',array(),$call[2]);

            // Throw away the end - done
            array_pop($this->listStack);

            while (1) {
                $end = end($this->listStack);

                if ( $end[1] <= $depth ) {

                    // Normalize depths
                    $depth = $end[1];

                    $this->listCalls[] = array('listitem_close',array(),$call[2]);

                    if ( $end[0] == $listType ) {
                        $this->listCalls[] = array('listitem_open',array($depth-1),$call[2]);
                        $this->listCalls[] = array('listcontent_open',array(),$call[2]);

                    } else {
                        // Switching list type...
                        $this->listCalls[] = array('list'.$end[0].'_close', array(), $call[2]);
                        $this->listCalls[] = array('list'.$listType.'_open', array(), $call[2]);
                        $this->listCalls[] = array('listitem_open', array($depth-1), $call[2]);
                        $this->listCalls[] = array('listcontent_open',array(),$call[2]);

                        array_pop($this->listStack);
                        $this->listStack[] = array($listType, $depth);
                    }

                    break;

                // Haven't dropped down far enough yet.... ( $end[1] > $depth )
                } else {

                    $this->listCalls[] = array('listitem_close',array(),$call[2]);
                    $this->listCalls[] = array('list'.$end[0].'_close',array(),$call[2]);

                    array_pop($this->listStack);

                }

            }

        }
    }

    //------------------------------------------------------------------------
    function listContent($call) {
        $this->listCalls[] = $call;
    }

    //------------------------------------------------------------------------
    function interpretSyntax($match, & $type) {
        if ( substr($match,-1) == '*' ) {
            $type = 'u';
        } else {
            $type = 'o';
        }
        // Is the +1 needed? It used to be count(explode(...))
        // but I don't think the number is seen outside this handler
        return substr_count(str_replace("\t",'  ',$match), '  ') + 1;
    }
}

//------------------------------------------------------------------------
class Doku_Handler_Preformatted {

    var $CallWriter;

    var $calls = array();
    var $pos;
    var $text ='';



    function Doku_Handler_Preformatted(& $CallWriter) {
        $this->CallWriter = & $CallWriter;
    }

    function writeCall($call) {
        $this->calls[] = $call;
    }

    // Probably not needed but just in case...
    function writeCalls($calls) {
        $this->calls = array_merge($this->calls, $calls);
#        $this->CallWriter->writeCalls($this->calls);
    }

    function finalise() {
        $last_call = end($this->calls);
        $this->writeCall(array('preformatted_end',array(), $last_call[2]));

        $this->process();
        $this->CallWriter->finalise();
    }

    function process() {
        foreach ( $this->calls as $call ) {
            switch ($call[0]) {
                case 'preformatted_start':
                    $this->pos = $call[2];
                break;
                case 'preformatted_newline':
                    $this->text .= "\n";
                break;
                case 'preformatted_content':
                    $this->text .= $call[1][0];
                break;
                case 'preformatted_end':
                    if (trim($this->text)) {
                      $this->CallWriter->writeCall(array('preformatted',array($this->text),$this->pos));
                    }
                    // see FS#1699 & FS#1652, add 'eol' instructions to ensure proper triggering of following p_open
                    $this->CallWriter->writeCall(array('eol',array(),$this->pos));
                    $this->CallWriter->writeCall(array('eol',array(),$this->pos));
                break;
            }
        }
    }

}

//------------------------------------------------------------------------
class Doku_Handler_Quote {

    var $CallWriter;

    var $calls = array();

    var $quoteCalls = array();

    function Doku_Handler_Quote(& $CallWriter) {
        $this->CallWriter = & $CallWriter;
    }

    function writeCall($call) {
        $this->calls[] = $call;
    }

    // Probably not needed but just in case...
    function writeCalls($calls) {
        $this->calls = array_merge($this->calls, $calls);
    }

    function finalise() {
        $last_call = end($this->calls);
        $this->writeCall(array('quote_end',array(), $last_call[2]));

        $this->process();
        $this->CallWriter->finalise();
    }

    function process() {

        $quoteDepth = 1;

        foreach ( $this->calls as $call ) {
            switch ($call[0]) {

                case 'quote_start':

                    $this->quoteCalls[] = array('quote_open',array(),$call[2]);

                case 'quote_newline':

                    $quoteLength = $this->getDepth($call[1][0]);

                    if ( $quoteLength > $quoteDepth ) {
                        $quoteDiff = $quoteLength - $quoteDepth;
                        for ( $i = 1; $i <= $quoteDiff; $i++ ) {
                            $this->quoteCalls[] = array('quote_open',array(),$call[2]);
                        }
                    } else if ( $quoteLength < $quoteDepth ) {
                        $quoteDiff = $quoteDepth - $quoteLength;
                        for ( $i = 1; $i <= $quoteDiff; $i++ ) {
                            $this->quoteCalls[] = array('quote_close',array(),$call[2]);
                        }
                    } else {
                        if ($call[0] != 'quote_start') $this->quoteCalls[] = array('linebreak',array(),$call[2]);
                    }

                    $quoteDepth = $quoteLength;

                break;

                case 'quote_end':

                    if ( $quoteDepth > 1 ) {
                        $quoteDiff = $quoteDepth - 1;
                        for ( $i = 1; $i <= $quoteDiff; $i++ ) {
                            $this->quoteCalls[] = array('quote_close',array(),$call[2]);
                        }
                    }

                    $this->quoteCalls[] = array('quote_close',array(),$call[2]);

                    $this->CallWriter->writeCalls($this->quoteCalls);
                break;

                default:
                    $this->quoteCalls[] = $call;
                break;
            }
        }
    }

    function getDepth($marker) {
        preg_match('/>{1,}/', $marker, $matches);
        $quoteLength = strlen($matches[0]);
        return $quoteLength;
    }
}

//------------------------------------------------------------------------
class Doku_Handler_Table {

    var $CallWriter;

    var $calls = array();
    var $tableCalls = array();
    var $maxCols = 0;
    var $maxRows = 1;
    var $currentCols = 0;
    var $firstCell = false;
    var $lastCellType = 'tablecell';

    function Doku_Handler_Table(& $CallWriter) {
        $this->CallWriter = & $CallWriter;
    }

    function writeCall($call) {
        $this->calls[] = $call;
    }

    // Probably not needed but just in case...
    function writeCalls($calls) {
        $this->calls = array_merge($this->calls, $calls);
    }

    function finalise() {
        $last_call = end($this->calls);
        $this->writeCall(array('table_end',array(), $last_call[2]));

        $this->process();
        $this->CallWriter->finalise();
    }

    //------------------------------------------------------------------------
    function process() {
        foreach ( $this->calls as $call ) {
            switch ( $call[0] ) {
                case 'table_start':
                    $this->tableStart($call);
                break;
                case 'table_row':
                    $this->tableRowClose(array('tablerow_close',$call[1],$call[2]));
                    $this->tableRowOpen(array('tablerow_open',$call[1],$call[2]));
                break;
                case 'tableheader':
                case 'tablecell':
                    $this->tableCell($call);
                break;
                case 'table_end':
                    $this->tableRowClose(array('tablerow_close',$call[1],$call[2]));
                    $this->tableEnd($call);
                break;
                default:
                    $this->tableDefault($call);
                break;
            }
        }
        $this->CallWriter->writeCalls($this->tableCalls);
    }

    function tableStart($call) {
        $this->tableCalls[] = array('table_open',array(),$call[2]);
        $this->tableCalls[] = array('tablerow_open',array(),$call[2]);
        $this->firstCell = true;
    }

    function tableEnd($call) {
        $this->tableCalls[] = array('table_close',array(),$call[2]);
        $this->finalizeTable();
    }

    function tableRowOpen($call) {
        $this->tableCalls[] = $call;
        $this->currentCols = 0;
        $this->firstCell = true;
        $this->lastCellType = 'tablecell';
        $this->maxRows++;
    }

    function tableRowClose($call) {
        // Strip off final cell opening and anything after it
        while ( $discard = array_pop($this->tableCalls ) ) {

            if ( $discard[0] == 'tablecell_open' || $discard[0] == 'tableheader_open') {
                break;
            }
        }
        $this->tableCalls[] = $call;

        if ( $this->currentCols > $this->maxCols ) {
            $this->maxCols = $this->currentCols;
        }
    }

    function tableCell($call) {
        if ( !$this->firstCell ) {

            // Increase the span
            $lastCall = end($this->tableCalls);

            // A cell call which follows an open cell means an empty cell so span
            if ( $lastCall[0] == 'tablecell_open' || $lastCall[0] == 'tableheader_open' ) {
                 $this->tableCalls[] = array('colspan',array(),$call[2]);

            }

            $this->tableCalls[] = array($this->lastCellType.'_close',array(),$call[2]);
            $this->tableCalls[] = array($call[0].'_open',array(1,NULL,1),$call[2]);
            $this->lastCellType = $call[0];

        } else {

            $this->tableCalls[] = array($call[0].'_open',array(1,NULL,1),$call[2]);
            $this->lastCellType = $call[0];
            $this->firstCell = false;

        }

        $this->currentCols++;
    }

    function tableDefault($call) {
        $this->tableCalls[] = $call;
    }

    function finalizeTable() {

        // Add the max cols and rows to the table opening
        if ( $this->tableCalls[0][0] == 'table_open' ) {
            // Adjust to num cols not num col delimeters
            $this->tableCalls[0][1][] = $this->maxCols - 1;
            $this->tableCalls[0][1][] = $this->maxRows;
        } else {
            trigger_error('First element in table call list is not table_open');
        }

        $lastRow = 0;
        $lastCell = 0;
        $cellKey = array();
        $toDelete = array();

        // Look for the colspan elements and increment the colspan on the
        // previous non-empty opening cell. Once done, delete all the cells
        // that contain colspans
        foreach ( $this->tableCalls as $key => $call ) {

            if ( $call[0] == 'tablerow_open' ) {

                $lastRow++;
                $lastCell = 0;

            } else if ( $call[0] == 'tablecell_open' || $call[0] == 'tableheader_open' ) {

                $lastCell++;
                $cellKey[$lastRow][$lastCell] = $key;

            } else if ( $call[0] == 'table_align' ) {

                $prev = in_array($this->tableCalls[$key-1][0], array('tablecell_open', 'tableheader_open'));
                $next = in_array($this->tableCalls[$key+1][0], array('tablecell_close', 'tableheader_close'));
                // If the cell is empty, align left
                if ($prev && $next) {
                    $this->tableCalls[$key-1][1][1] = 'left';

                // If the previous element was a cell open, align right
                } elseif ($prev) {
                    $this->tableCalls[$key-1][1][1] = 'right';

                // If the next element is the close of an element, align either center or left
                } elseif ( $next) {
                    if ( $this->tableCalls[$cellKey[$lastRow][$lastCell]][1][1] == 'right' ) {
                        $this->tableCalls[$cellKey[$lastRow][$lastCell]][1][1] = 'center';
                    } else {
                        $this->tableCalls[$cellKey[$lastRow][$lastCell]][1][1] = 'left';
                    }

                }

                // Now convert the whitespace back to cdata
                $this->tableCalls[$key][0] = 'cdata';

            } else if ( $call[0] == 'colspan' ) {

                $this->tableCalls[$key-1][1][0] = false;

                for($i = $key-2; $i >= $cellKey[$lastRow][1]; $i--) {

                    if ( $this->tableCalls[$i][0] == 'tablecell_open' || $this->tableCalls[$i][0] == 'tableheader_open' ) {

                        if ( false !== $this->tableCalls[$i][1][0] ) {
                            $this->tableCalls[$i][1][0]++;
                            break;
                        }


                    }
                }

                $toDelete[] = $key-1;
                $toDelete[] = $key;
                $toDelete[] = $key+1;

            } else if ( $call[0] == 'rowspan' ) {

                if ( $this->tableCalls[$key-1][0] == 'cdata' ) {
                    // ignore rowspan if previous call was cdata (text mixed with :::) we don't have to check next call as that wont match regex
                    $this->tableCalls[$key][0] = 'cdata';

                } else {

                    $this->tableCalls[$key-1][1][2] = false;

                    for($i = $lastRow-1; $i > 0; $i--) {

                        if ( $this->tableCalls[$cellKey[$i][$lastCell]][0] == 'tablecell_open' || $this->tableCalls[$cellKey[$i][$lastCell]][0] == 'tableheader_open' ) {

                            if ( false !== $this->tableCalls[$cellKey[$i][$lastCell]][1][2] ) {
                                $this->tableCalls[$cellKey[$i][$lastCell]][1][2]++;
                                break;
                            }


                        }
                    }

                    $toDelete[] = $key-1;
                    $toDelete[] = $key;
                    $toDelete[] = $key+1; 
                }
            }
        }


        // condense cdata
        $cnt = count($this->tableCalls);
        for( $key = 0; $key < $cnt; $key++){
            if($this->tableCalls[$key][0] == 'cdata'){
                $ckey = $key;
                $key++;
                while($this->tableCalls[$key][0] == 'cdata'){
                    $this->tableCalls[$ckey][1][0] .= $this->tableCalls[$key][1][0];
                    $toDelete[] = $key;
                    $key++;
                }
                continue;
            }
        }

        foreach ( $toDelete as $delete ) {
            unset($this->tableCalls[$delete]);
        }
        $this->tableCalls = array_values($this->tableCalls);
    }
}


/**
 * Handler for paragraphs
 *
 * @author Harry Fuecks <hfuecks@gmail.com>
 */
class Doku_Handler_Block {

    var $calls = array();

    var $blockStack = array();

    var $inParagraph = false;
    var $atStart = true;
    var $skipEolKey = -1;

    // Blocks these should not be inside paragraphs
    var $blockOpen = array(
            'header',
            'listu_open','listo_open','listitem_open','listcontent_open',
            'table_open','tablerow_open','tablecell_open','tableheader_open',
            'quote_open',
            'section_open', // Needed to prevent p_open between header and section_open
            'code','file','hr','preformatted','rss',
            'htmlblock','phpblock',
        );

    var $blockClose = array(
            'header',
            'listu_close','listo_close','listitem_close','listcontent_close',
            'table_close','tablerow_close','tablecell_close','tableheader_close',
            'quote_close',
            'section_close', // Needed to prevent p_close after section_close
            'code','file','hr','preformatted','rss',
            'htmlblock','phpblock',
        );

    // Stacks can contain paragraphs
    var $stackOpen = array(
        'footnote_open','section_open',
        );

    var $stackClose = array(
        'footnote_close','section_close',
        );


    /**
     * Constructor. Adds loaded syntax plugins to the block and stack
     * arrays
     *
     * @author Andreas Gohr <andi@splitbrain.org>
     */
    function Doku_Handler_Block(){
        global $DOKU_PLUGINS;
        //check if syntax plugins were loaded
        if(empty($DOKU_PLUGINS['syntax'])) return;
        foreach($DOKU_PLUGINS['syntax'] as $n => $p){
            $ptype = $p->getPType();
            if($ptype == 'block'){
                $this->blockOpen[]  = 'plugin_'.$n;
                $this->blockClose[] = 'plugin_'.$n;
            }elseif($ptype == 'stack'){
                $this->stackOpen[]  = 'plugin_'.$n;
                $this->stackClose[] = 'plugin_'.$n;
            }
        }
    }

    /**
     * Close a paragraph if needed
     *
     * This function makes sure there are no empty paragraphs on the stack
     *
     * @author Andreas Gohr <andi@splitbrain.org>
     */
    function closeParagraph($pos){
        // look back if there was any content - we don't want empty paragraphs
        $content = '';
        for($i=count($this->calls)-1; $i>=0; $i--){
            if($this->calls[$i][0] == 'p_open'){
                break;
            }elseif($this->calls[$i][0] == 'cdata'){
                $content .= $this->calls[$i][1][0];
            }else{
                $content = 'found markup';
                break;
            }
        }

        if(trim($content)==''){
            //remove the whole paragraph
            array_splice($this->calls,$i);
        }else{
            if ($this->calls[count($this->calls)-1][0] == 'section_edit') {
                $tmp = array_pop($this->calls);
                $this->calls[] = array('p_close',array(), $pos);
                $this->calls[] = $tmp;
            } else {
                $this->calls[] = array('p_close',array(), $pos);
            }
        }

        $this->inParagraph = false;
    }

    /**
     * Processes the whole instruction stack to open and close paragraphs
     *
     * @author Harry Fuecks <hfuecks@gmail.com>
     * @author Andreas Gohr <andi@splitbrain.org>
     * @todo   This thing is really messy and should be rewritten
     */
    function process($calls) {
        foreach ( $calls as $key => $call ) {
            $cname = $call[0];
            if($cname == 'plugin') {
                $cname='plugin_'.$call[1][0];

                $plugin = true;
                $plugin_open = (($call[1][2] == DOKU_LEXER_ENTER) || ($call[1][2] == DOKU_LEXER_SPECIAL));
                $plugin_close = (($call[1][2] == DOKU_LEXER_EXIT) || ($call[1][2] == DOKU_LEXER_SPECIAL));
            } else {
                $plugin = false;
            }

            // Process blocks which are stack like... (contain linefeeds)
            if ( in_array($cname,$this->stackOpen ) && (!$plugin || $plugin_open) ) {

                $this->calls[] = $call;

                // Hack - footnotes shouldn't immediately contain a p_open
                if ( $cname != 'footnote_open' ) {
                    $this->addToStack();
                } else {
                    $this->addToStack(false);
                }
                continue;
            }

            if ( in_array($cname,$this->stackClose ) && (!$plugin || $plugin_close)) {

                if ( $this->inParagraph ) {
                    $this->closeParagraph($call[2]);
                }
                $this->calls[] = $call;
                $this->removeFromStack();
                continue;
            }

            if ( !$this->atStart ) {

                if ( $cname == 'eol' ) {

                    // Check this isn't an eol instruction to skip...
                    if ( $this->skipEolKey != $key ) {
                        // Look to see if the next instruction is an EOL
                        if ( isset($calls[$key+1]) && $calls[$key+1][0] == 'eol' ) {

                            if ( $this->inParagraph ) {
                                //$this->calls[] = array('p_close',array(), $call[2]);
                                $this->closeParagraph($call[2]);
                            }

                            $this->calls[] = array('p_open',array(), $call[2]);
                            $this->inParagraph = true;


                            // Mark the next instruction for skipping
                            $this->skipEolKey = $key+1;

                        }else{
                            //if this is just a single eol make a space from it
                            $this->addCall(array('cdata',array(DOKU_PARSER_EOL), $call[2]));
                        }
                    }


                } else {

                    $storeCall = true;
                    if ( $this->inParagraph && (in_array($cname, $this->blockOpen) && (!$plugin || $plugin_open))) {
                        $this->closeParagraph($call[2]);
                        $this->calls[] = $call;
                        $storeCall = false;
                    }

                    if ( in_array($cname, $this->blockClose) && (!$plugin || $plugin_close)) {
                        if ( $this->inParagraph ) {
                            $this->closeParagraph($call[2]);
                        }
                        if ( $storeCall ) {
                            $this->calls[] = $call;
                            $storeCall = false;
                        }

                        // This really sucks and suggests this whole class sucks but...
                        if ( isset($calls[$key+1])) {
                            $cname_plusone = $calls[$key+1][0];
                            if ($cname_plusone == 'plugin') {
                                $cname_plusone = 'plugin'.$calls[$key+1][1][0];

                                // plugin test, true if plugin has a state which precludes it requiring blockOpen or blockClose
                                $plugin_plusone = true;
                                $plugin_test = ($call[$key+1][1][2] == DOKU_LEXER_MATCHED) || ($call[$key+1][1][2] == DOKU_LEXER_MATCHED);
                            } else {
                                $plugin_plusone = false;
                            }
                            if ((!in_array($cname_plusone, $this->blockOpen) && !in_array($cname_plusone, $this->blockClose)) ||
                                ($plugin_plusone && $plugin_test)
                                ) {

                                $this->calls[] = array('p_open',array(), $call[2]);
                                $this->inParagraph = true;
                            }
                        }
                    }

                    if ( $storeCall ) {
                        $this->addCall($call);
                    }

                }


            } else {

                // Unless there's already a block at the start, start a paragraph
                if ( !in_array($cname,$this->blockOpen) ) {
                    $this->calls[] = array('p_open',array(), $call[2]);
                    if ( $call[0] != 'eol' ) {
                        $this->calls[] = $call;
                    }
                    $this->atStart = false;
                    $this->inParagraph = true;
                } else {
                    $this->addCall($call);
                    $this->atStart = false;
                }

            }

        }

        if ( $this->inParagraph ) {
            if ( $cname == 'p_open' ) {
                // Ditch the last call
                array_pop($this->calls);
            } else if ( !in_array($cname, $this->blockClose) ) {
                //$this->calls[] = array('p_close',array(), $call[2]);
                $this->closeParagraph($call[2]);
            } else {
                $last_call = array_pop($this->calls);
                //$this->calls[] = array('p_close',array(), $call[2]);
                $this->closeParagraph($call[2]);
                $this->calls[] = $last_call;
            }
        }

        return $this->calls;
    }

    function addToStack($newStart = true) {
        $this->blockStack[] = array($this->atStart, $this->inParagraph);
        $this->atStart = $newStart;
        $this->inParagraph = false;
    }

    function removeFromStack() {
        $state = array_pop($this->blockStack);
        $this->atStart = $state[0];
        $this->inParagraph = $state[1];
    }

    function addCall($call) {
        $key = count($this->calls);
        if ($key and ($call[0] == 'cdata') and ($this->calls[$key-1][0] == 'cdata')) {
            $this->calls[$key-1][1][0] .= $call[1][0];
        } else {
            $this->calls[] = $call;
        }
    }
}

//Setup VIM: ex: et ts=4 enc=utf-8 :