summaryrefslogtreecommitdiff
path: root/inc/html.php
blob: 0914a1762de1ba12bc0bff21d0c424f20b3c60da (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
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
<?php
/**
 * HTML output functions
 *
 * @license    GPL 2 (http://www.gnu.org/licenses/gpl.html)
 * @author     Andreas Gohr <andi@splitbrain.org>
 */

if(!defined('DOKU_INC')) die('meh.');
if(!defined('NL')) define('NL',"\n");

/**
 * Convenience function to quickly build a wikilink
 *
 * @author Andreas Gohr <andi@splitbrain.org>
 * @param string  $id      id of the target page
 * @param string  $name    the name of the link, i.e. the text that is displayed
 * @param string|array  $search  search string(s) that shall be highlighted in the target page
 * @return string the HTML code of the link
 */
function html_wikilink($id,$name=null,$search=''){
    /** @var Doku_Renderer_xhtml $xhtml_renderer */
    static $xhtml_renderer = null;
    if(is_null($xhtml_renderer)){
        $xhtml_renderer = p_get_renderer('xhtml');
    }

    return $xhtml_renderer->internallink($id,$name,$search,true,'navigation');
}

/**
 * The loginform
 *
 * @author   Andreas Gohr <andi@splitbrain.org>
 */
function html_login(){
    global $lang;
    global $conf;
    global $ID;
    global $INPUT;

    print p_locale_xhtml('login');
    print '<div class="centeralign">'.NL;
    $form = new Doku_Form(array('id' => 'dw__login'));
    $form->startFieldset($lang['btn_login']);
    $form->addHidden('id', $ID);
    $form->addHidden('do', 'login');
    $form->addElement(form_makeTextField('u', ((!$INPUT->bool('http_credentials')) ? $INPUT->str('u') : ''), $lang['user'], 'focus__this', 'block'));
    $form->addElement(form_makePasswordField('p', $lang['pass'], '', 'block'));
    if($conf['rememberme']) {
        $form->addElement(form_makeCheckboxField('r', '1', $lang['remember'], 'remember__me', 'simple'));
    }
    $form->addElement(form_makeButton('submit', '', $lang['btn_login']));
    $form->endFieldset();

    if(actionOK('register')){
        $form->addElement('<p>'.$lang['reghere'].': '.tpl_actionlink('register','','','',true).'</p>');
    }

    if (actionOK('resendpwd')) {
        $form->addElement('<p>'.$lang['pwdforget'].': '.tpl_actionlink('resendpwd','','','',true).'</p>');
    }

    html_form('login', $form);
    print '</div>'.NL;
}


/**
 * Denied page content
 *
 * @return string html
 */
function html_denied() {
    print p_locale_xhtml('denied');

    if(!$_SERVER['REMOTE_USER']){
        html_login();
    }
}

/**
 * inserts section edit buttons if wanted or removes the markers
 *
 * @author Andreas Gohr <andi@splitbrain.org>
 *
 * @param string $text
 * @param bool   $show show section edit buttons?
 * @return string
 */
function html_secedit($text,$show=true){
    global $INFO;

    $regexp = '#<!-- EDIT(\d+) ([A-Z_]+) (?:"([^"]*)" )?\[(\d+-\d*)\] -->#';

    if(!$INFO['writable'] || !$show || $INFO['rev']){
        return preg_replace($regexp,'',$text);
    }

    return preg_replace_callback($regexp,
                'html_secedit_button', $text);
}

/**
 * prepares section edit button data for event triggering
 * used as a callback in html_secedit
 *
 * @author Andreas Gohr <andi@splitbrain.org>
 *
 * @param array $matches matches with regexp
 * @return string
 * @triggers HTML_SECEDIT_BUTTON
 */
function html_secedit_button($matches){
    $data = array('secid'  => $matches[1],
                  'target' => strtolower($matches[2]),
                  'range'  => $matches[count($matches) - 1]);
    if (count($matches) === 5) {
        $data['name'] = $matches[3];
    }

    return trigger_event('HTML_SECEDIT_BUTTON', $data,
                         'html_secedit_get_button');
}

/**
 * prints a section editing button
 * used as default action form HTML_SECEDIT_BUTTON
 *
 * @author Adrian Lang <lang@cosmocode.de>
 *
 * @param array $data name, section id and target
 * @return string html
 */
function html_secedit_get_button($data) {
    global $ID;
    global $INFO;

    if (!isset($data['name']) || $data['name'] === '') return '';

    $name = $data['name'];
    unset($data['name']);

    $secid = $data['secid'];
    unset($data['secid']);

    return "<div class='secedit editbutton_" . $data['target'] .
                       " editbutton_" . $secid . "'>" .
           html_btn('secedit', $ID, '',
                    array_merge(array('do'  => 'edit',
                                      'rev' => $INFO['lastmod'],
                                      'summary' => '['.$name.'] '), $data),
                    'post', $name) . '</div>';
}

/**
 * Just the back to top button (in its own form)
 *
 * @author Andreas Gohr <andi@splitbrain.org>
 *
 * @return string html
 */
function html_topbtn(){
    global $lang;

    $ret  = '<a class="nolink" href="#dokuwiki__top"><input type="button" class="button" value="'.$lang['btn_top'].'" onclick="window.scrollTo(0, 0)" title="'.$lang['btn_top'].'" /></a>';

    return $ret;
}

/**
 * Displays a button (using its own form)
 * If tooltip exists, the access key tooltip is replaced.
 *
 * @author Andreas Gohr <andi@splitbrain.org>
 *
 * @param string         $name
 * @param string         $id
 * @param string         $akey   access key
 * @param string[] $params key-value pairs added as hidden inputs
 * @param string         $method
 * @param string         $tooltip
 * @param bool|string    $label  label text, false: lookup btn_$name in localization
 * @return string
 */
function html_btn($name, $id, $akey, $params, $method='get', $tooltip='', $label=false){
    global $conf;
    global $lang;

    if (!$label)
        $label = $lang['btn_'.$name];

    $ret = '';

    //filter id (without urlencoding)
    $id = idfilter($id,false);

    //make nice URLs even for buttons
    if($conf['userewrite'] == 2){
        $script = DOKU_BASE.DOKU_SCRIPT.'/'.$id;
    }elseif($conf['userewrite']){
        $script = DOKU_BASE.$id;
    }else{
        $script = DOKU_BASE.DOKU_SCRIPT;
        $params['id'] = $id;
    }

    $ret .= '<form class="button btn_'.$name.'" method="'.$method.'" action="'.$script.'"><div class="no">';

    if(is_array($params)){
        reset($params);
        while (list($key, $val) = each($params)) {
            $ret .= '<input type="hidden" name="'.$key.'" ';
            $ret .= 'value="'.htmlspecialchars($val).'" />';
        }
    }

    if ($tooltip!='') {
        $tip = htmlspecialchars($tooltip);
    }else{
        $tip = htmlspecialchars($label);
    }

    $ret .= '<button type="submit" ';
    if($akey){
        $tip .= ' ['.strtoupper($akey).']';
        $ret .= 'accesskey="'.$akey.'" ';
    }
    $ret .= 'title="'.$tip.'" ';
    $ret .= '/>';
    $ret .= hsc($label);
    $ret .= '</button>';
    $ret .= '</div></form>';

    return $ret;
}
/**
 * show a revision warning
 *
 * @author Szymon Olewniczak <dokuwiki@imz.re>
 */
function html_showrev() {
    print p_locale_xhtml('showrev');
}

/**
 * Show a wiki page
 *
 * @author Andreas Gohr <andi@splitbrain.org>
 *
 * @param null|string $txt wiki text or null for showing $ID
 */
function html_show($txt=null){
    global $ID;
    global $REV;
    global $HIGH;
    global $INFO;
    global $DATE_AT;
    //disable section editing for old revisions or in preview
    if($txt || $REV){
        $secedit = false;
    }else{
        $secedit = true;
    }

    if (!is_null($txt)){
        //PreviewHeader
        echo '<br id="scroll__here" />';
        echo p_locale_xhtml('preview');
        echo '<div class="preview"><div class="pad">';
        $html = html_secedit(p_render('xhtml',p_get_instructions($txt),$info),$secedit);
        if($INFO['prependTOC']) $html = tpl_toc(true).$html;
        echo $html;
        echo '<div class="clearer"></div>';
        echo '</div></div>';

    }else{
        if ($REV||$DATE_AT){
            $data = array('rev' => &$REV, 'date_at' => &$DATE_AT);
            trigger_event('HTML_SHOWREV_OUTPUT', $data, 'html_showrev');
        }
        $html = p_wiki_xhtml($ID,$REV,true,$DATE_AT);
        $html = html_secedit($html,$secedit);
        if($INFO['prependTOC']) $html = tpl_toc(true).$html;
        $html = html_hilight($html,$HIGH);
        echo $html;
    }
}

/**
 * ask the user about how to handle an exisiting draft
 *
 * @author Andreas Gohr <andi@splitbrain.org>
 */
function html_draft(){
    global $INFO;
    global $ID;
    global $lang;
    $draft = unserialize(io_readFile($INFO['draft'],false));
    $text  = cleanText(con($draft['prefix'],$draft['text'],$draft['suffix'],true));

    print p_locale_xhtml('draft');
    $form = new Doku_Form(array('id' => 'dw__editform'));
    $form->addHidden('id', $ID);
    $form->addHidden('date', $draft['date']);
    $form->addElement(form_makeWikiText($text, array('readonly'=>'readonly')));
    $form->addElement(form_makeOpenTag('div', array('id'=>'draft__status')));
    $form->addElement($lang['draftdate'].' '. dformat(filemtime($INFO['draft'])));
    $form->addElement(form_makeCloseTag('div'));
    $form->addElement(form_makeButton('submit', 'recover', $lang['btn_recover'], array('tabindex'=>'1')));
    $form->addElement(form_makeButton('submit', 'draftdel', $lang['btn_draftdel'], array('tabindex'=>'2')));
    $form->addElement(form_makeButton('submit', 'show', $lang['btn_cancel'], array('tabindex'=>'3')));
    html_form('draft', $form);
}

/**
 * Highlights searchqueries in HTML code
 *
 * @author Andreas Gohr <andi@splitbrain.org>
 * @author Harry Fuecks <hfuecks@gmail.com>
 *
 * @param string $html
 * @param array|string $phrases
 * @return string html
 */
function html_hilight($html,$phrases){
    $phrases = (array) $phrases;
    $phrases = array_map('preg_quote_cb', $phrases);
    $phrases = array_map('ft_snippet_re_preprocess', $phrases);
    $phrases = array_filter($phrases);
    $regex = join('|',$phrases);

    if ($regex === '') return $html;
    if (!utf8_check($regex)) return $html;
    $html = @preg_replace_callback("/((<[^>]*)|$regex)/ui",'html_hilight_callback',$html);
    return $html;
}

/**
 * Callback used by html_hilight()
 *
 * @author Harry Fuecks <hfuecks@gmail.com>
 *
 * @param array $m matches
 * @return string html
 */
function html_hilight_callback($m) {
    $hlight = unslash($m[0]);
    if ( !isset($m[2])) {
        $hlight = '<span class="search_hit">'.$hlight.'</span>';
    }
    return $hlight;
}

/**
 * Run a search and display the result
 *
 * @author Andreas Gohr <andi@splitbrain.org>
 */
function html_search(){
    global $QUERY, $ID;
    global $lang;

    $intro = p_locale_xhtml('searchpage');
    // allow use of placeholder in search intro
    $pagecreateinfo = (auth_quickaclcheck($ID) >= AUTH_CREATE) ? $lang['searchcreatepage'] : '';
    $intro = str_replace(
        array('@QUERY@', '@SEARCH@', '@CREATEPAGEINFO@'),
        array(hsc(rawurlencode($QUERY)), hsc($QUERY), $pagecreateinfo),
        $intro
    );
    echo $intro;
    flush();

    //show progressbar
    print '<div id="dw__loading">'.NL;
    print '<script type="text/javascript">/*<![CDATA[*/'.NL;
    print 'showLoadBar();'.NL;
    print '/*!]]>*/</script>'.NL;
    print '</div>'.NL;
    flush();

    //do quick pagesearch
    $data = ft_pageLookup($QUERY,true,useHeading('navigation'));
    if(count($data)){
        print '<div class="search_quickresult">';
        print '<h3>'.$lang['quickhits'].':</h3>';
        print '<ul class="search_quickhits">';
        foreach($data as $id => $title){
            print '<li> ';
            if (useHeading('navigation')) {
                $name = $title;
            }else{
                $ns = getNS($id);
                if($ns){
                    $name = shorten(noNS($id), ' ('.$ns.')',30);
                }else{
                    $name = $id;
                }
            }
            print html_wikilink(':'.$id,$name);
            print '</li> ';
        }
        print '</ul> ';
        //clear float (see http://www.complexspiral.com/publications/containing-floats/)
        print '<div class="clearer"></div>';
        print '</div>';
    }
    flush();

    //do fulltext search
    $data = ft_pageSearch($QUERY,$regex);
    if(count($data)){
        print '<dl class="search_results">';
        $num = 1;
        foreach($data as $id => $cnt){
            print '<dt>';
            print html_wikilink(':'.$id,useHeading('navigation')?null:$id,$regex);
            if($cnt !== 0){
                print ': '.$cnt.' '.$lang['hits'].'';
            }
            print '</dt>';
            if($cnt !== 0){
                if($num < FT_SNIPPET_NUMBER){ // create snippets for the first number of matches only
                    print '<dd>'.ft_snippet($id,$regex).'</dd>';
                }
                $num++;
            }
            flush();
        }
        print '</dl>';
    }else{
        print '<div class="nothing">'.$lang['nothingfound'].'</div>';
    }

    //hide progressbar
    print '<script type="text/javascript">/*<![CDATA[*/'.NL;
    print 'hideLoadBar("dw__loading");'.NL;
    print '/*!]]>*/</script>'.NL;
    flush();
}

/**
 * Display error on locked pages
 *
 * @author Andreas Gohr <andi@splitbrain.org>
 */
function html_locked(){
    global $ID;
    global $conf;
    global $lang;
    global $INFO;

    $locktime = filemtime(wikiLockFN($ID));
    $expire = dformat($locktime + $conf['locktime']);
    $min    = round(($conf['locktime'] - (time() - $locktime) )/60);

    print p_locale_xhtml('locked');
    print '<ul>';
    print '<li><div class="li"><strong>'.$lang['lockedby'].'</strong> '.editorinfo($INFO['locked']).'</div></li>';
    print '<li><div class="li"><strong>'.$lang['lockexpire'].'</strong> '.$expire.' ('.$min.' min)</div></li>';
    print '</ul>';
}

/**
 * list old revisions
 *
 * @author Andreas Gohr <andi@splitbrain.org>
 * @author Ben Coburn <btcoburn@silicodon.net>
 * @author Kate Arzamastseva <pshns@ukr.net>
 *
 * @param int $first skip the first n changelog lines
 * @param bool|string $media_id id of media, or false for current page
 */
function html_revisions($first=0, $media_id = false){
    global $ID;
    global $INFO;
    global $conf;
    global $lang;
    $id = $ID;
    if ($media_id) {
        $id = $media_id;
        $changelog = new MediaChangeLog($id);
    } else {
        $changelog = new PageChangeLog($id);
    }

    /* we need to get one additional log entry to be able to
     * decide if this is the last page or is there another one.
     * see html_recent()
     */

    $revisions = $changelog->getRevisions($first, $conf['recent']+1);

    if(count($revisions)==0 && $first!=0){
        $first=0;
        $revisions = $changelog->getRevisions($first, $conf['recent']+1);
    }
    $hasNext = false;
    if (count($revisions)>$conf['recent']) {
        $hasNext = true;
        array_pop($revisions); // remove extra log entry
    }

    if (!$media_id) $date = dformat($INFO['lastmod']);
    else $date = dformat(@filemtime(mediaFN($id)));

    if (!$media_id) print p_locale_xhtml('revisions');

    $params = array('id' => 'page__revisions', 'class' => 'changes');
    if ($media_id) $params['action'] = media_managerURL(array('image' => $media_id), '&');

    $form = new Doku_Form($params);
    $form->addElement(form_makeOpenTag('ul'));

    if (!$media_id) $exists = $INFO['exists'];
    else $exists = file_exists(mediaFN($id));

    $display_name = (!$media_id && useHeading('navigation')) ? hsc(p_get_first_heading($id)) : $id;
    if (!$display_name) $display_name = $id;

    if($exists && $first==0){
        if (!$media_id && isset($INFO['meta']) && isset($INFO['meta']['last_change']) && $INFO['meta']['last_change']['type']===DOKU_CHANGE_TYPE_MINOR_EDIT)
            $form->addElement(form_makeOpenTag('li', array('class' => 'minor')));
        else
            $form->addElement(form_makeOpenTag('li'));
        $form->addElement(form_makeOpenTag('div', array('class' => 'li')));
        $form->addElement(form_makeTag('input', array(
                        'type' => 'checkbox',
                        'name' => 'rev2[]',
                        'value' => 'current')));

        $form->addElement(form_makeOpenTag('span', array('class' => 'date')));
        $form->addElement($date);
        $form->addElement(form_makeCloseTag('span'));

        $form->addElement('<img src="'.DOKU_BASE.'lib/images/blank.gif" width="15" height="11" alt="" />');

        if (!$media_id) $href = wl($id);
        else $href = media_managerURL(array('image' => $id, 'tab_details' => 'view'), '&');
        $form->addElement(form_makeOpenTag('a', array(
                        'class' => 'wikilink1',
                        'href'  => $href)));
        $form->addElement($display_name);
        $form->addElement(form_makeCloseTag('a'));

        if ($media_id) $form->addElement(form_makeOpenTag('div'));

        if (!$media_id) {
            $form->addElement(form_makeOpenTag('span', array('class' => 'sum')));
            $form->addElement(' – ');
            $form->addElement(htmlspecialchars($INFO['sum']));
            $form->addElement(form_makeCloseTag('span'));
        }

        $changelog->setChunkSize(1024);

        $form->addElement(form_makeOpenTag('span', array('class' => 'user')));
        if($media_id) {
            $revinfo = $changelog->getRevisionInfo(@filemtime(fullpath(mediaFN($id))));
            if($revinfo['user']) {
                $editor = $revinfo['user'];
            } else {
                $editor = $revinfo['ip'];
            }
        } else {
            $editor = $INFO['editor'];
        }
        $form->addElement((empty($editor))?('('.$lang['external_edit'].')'):editorinfo($editor));
        $form->addElement(form_makeCloseTag('span'));

        $form->addElement('('.$lang['current'].')');

        if ($media_id) $form->addElement(form_makeCloseTag('div'));

        $form->addElement(form_makeCloseTag('div'));
        $form->addElement(form_makeCloseTag('li'));
    }

    foreach($revisions as $rev){
        $date = dformat($rev);
        $info = $changelog->getRevisionInfo($rev);
        if($media_id) {
            $exists = file_exists(mediaFN($id, $rev));
        } else {
            $exists = page_exists($id, $rev);
        }

        if ($info['type']===DOKU_CHANGE_TYPE_MINOR_EDIT)
            $form->addElement(form_makeOpenTag('li', array('class' => 'minor')));
        else
            $form->addElement(form_makeOpenTag('li'));
        $form->addElement(form_makeOpenTag('div', array('class' => 'li')));
        if($exists){
            $form->addElement(form_makeTag('input', array(
                            'type' => 'checkbox',
                            'name' => 'rev2[]',
                            'value' => $rev)));
        }else{
            $form->addElement('<img src="'.DOKU_BASE.'lib/images/blank.gif" width="15" height="11" alt="" />');
        }

        $form->addElement(form_makeOpenTag('span', array('class' => 'date')));
        $form->addElement($date);
        $form->addElement(form_makeCloseTag('span'));

        if($exists){
            if (!$media_id) $href = wl($id,"rev=$rev,do=diff", false, '&');
            else $href = media_managerURL(array('image' => $id, 'rev' => $rev, 'mediado' => 'diff'), '&');
            $form->addElement(form_makeOpenTag('a', array('href' => $href, 'class' => 'diff_link')));
            $form->addElement(form_makeTag('img', array(
                            'src'    => DOKU_BASE.'lib/images/diff.png',
                            'width'  => 15,
                            'height' => 11,
                            'title'  => $lang['diff'],
                            'alt'    => $lang['diff'])));
            $form->addElement(form_makeCloseTag('a'));
            if (!$media_id) $href = wl($id,"rev=$rev",false,'&');
            else $href = media_managerURL(array('image' => $id, 'tab_details' => 'view', 'rev' => $rev), '&');
            $form->addElement(form_makeOpenTag('a', array('href' => $href, 'class' => 'wikilink1')));
            $form->addElement($display_name);
            $form->addElement(form_makeCloseTag('a'));
        }else{
            $form->addElement('<img src="'.DOKU_BASE.'lib/images/blank.gif" width="15" height="11" alt="" />');
            $form->addElement($display_name);
        }

        if ($media_id) $form->addElement(form_makeOpenTag('div'));

        if ($info['sum']) {
            $form->addElement(form_makeOpenTag('span', array('class' => 'sum')));
            if (!$media_id) $form->addElement(' – ');
            $form->addElement('<bdi>'.htmlspecialchars($info['sum']).'</bdi>');
            $form->addElement(form_makeCloseTag('span'));
        }

        $form->addElement(form_makeOpenTag('span', array('class' => 'user')));
        if($info['user']){
            $form->addElement('<bdi>'.editorinfo($info['user']).'</bdi>');
            if(auth_ismanager()){
                $form->addElement(' <bdo dir="ltr">('.$info['ip'].')</bdo>');
            }
        }else{
            $form->addElement('<bdo dir="ltr">'.$info['ip'].'</bdo>');
        }
        $form->addElement(form_makeCloseTag('span'));

        if ($media_id) $form->addElement(form_makeCloseTag('div'));

        $form->addElement(form_makeCloseTag('div'));
        $form->addElement(form_makeCloseTag('li'));
    }
    $form->addElement(form_makeCloseTag('ul'));
    if (!$media_id) {
        $form->addElement(form_makeButton('submit', 'diff', $lang['diff2']));
    } else {
        $form->addHidden('mediado', 'diff');
        $form->addElement(form_makeButton('submit', '', $lang['diff2']));
    }
    html_form('revisions', $form);

    print '<div class="pagenav">';
    $last = $first + $conf['recent'];
    if ($first > 0) {
        $first -= $conf['recent'];
        if ($first < 0) $first = 0;
        print '<div class="pagenav-prev">';
        if ($media_id) {
            print html_btn('newer',$media_id,"p",media_managerURL(array('first' => $first), '&amp;', false, true));
        } else {
            print html_btn('newer',$id,"p",array('do' => 'revisions', 'first' => $first));
        }
        print '</div>';
    }
    if ($hasNext) {
        print '<div class="pagenav-next">';
        if ($media_id) {
            print html_btn('older',$media_id,"n",media_managerURL(array('first' => $last), '&amp;', false, true));
        } else {
            print html_btn('older',$id,"n",array('do' => 'revisions', 'first' => $last));
        }
        print '</div>';
    }
    print '</div>';

}

/**
 * display recent changes
 *
 * @author Andreas Gohr <andi@splitbrain.org>
 * @author Matthias Grimm <matthiasgrimm@users.sourceforge.net>
 * @author Ben Coburn <btcoburn@silicodon.net>
 * @author Kate Arzamastseva <pshns@ukr.net>
 *
 * @param int $first
 * @param string $show_changes
 */
function html_recent($first=0, $show_changes='both'){
    global $conf;
    global $lang;
    global $ID;
    /* we need to get one additionally log entry to be able to
     * decide if this is the last page or is there another one.
     * This is the cheapest solution to get this information.
     */
    $flags = 0;
    if ($show_changes == 'mediafiles' && $conf['mediarevisions']) {
        $flags = RECENTS_MEDIA_CHANGES;
    } elseif ($show_changes == 'pages') {
        $flags = 0;
    } elseif ($conf['mediarevisions']) {
        $show_changes = 'both';
        $flags = RECENTS_MEDIA_PAGES_MIXED;
    }

    $recents = getRecents($first,$conf['recent'] + 1,getNS($ID),$flags);
    if(count($recents) == 0 && $first != 0){
        $first=0;
        $recents = getRecents($first,$conf['recent'] + 1,getNS($ID),$flags);
    }
    $hasNext = false;
    if (count($recents)>$conf['recent']) {
        $hasNext = true;
        array_pop($recents); // remove extra log entry
    }

    print p_locale_xhtml('recent');

    if (getNS($ID) != '')
        print '<div class="level1"><p>' . sprintf($lang['recent_global'], getNS($ID), wl('', 'do=recent')) . '</p></div>';

    $form = new Doku_Form(array('id' => 'dw__recent', 'method' => 'GET', 'class' => 'changes'));
    $form->addHidden('sectok', null);
    $form->addHidden('do', 'recent');
    $form->addHidden('id', $ID);

    if ($conf['mediarevisions']) {
        $form->addElement('<div class="changeType">');
        $form->addElement(form_makeListboxField(
                    'show_changes',
                    array(
                        'pages'      => $lang['pages_changes'],
                        'mediafiles' => $lang['media_changes'],
                        'both'       => $lang['both_changes']),
                    $show_changes,
                    $lang['changes_type'],
                    '','',
                    array('class'=>'quickselect')));

        $form->addElement(form_makeButton('submit', 'recent', $lang['btn_apply']));
        $form->addElement('</div>');
    }

    $form->addElement(form_makeOpenTag('ul'));

    foreach($recents as $recent){
        $date = dformat($recent['date']);
        if ($recent['type']===DOKU_CHANGE_TYPE_MINOR_EDIT)
            $form->addElement(form_makeOpenTag('li', array('class' => 'minor')));
        else
            $form->addElement(form_makeOpenTag('li'));

        $form->addElement(form_makeOpenTag('div', array('class' => 'li')));

        if (!empty($recent['media'])) {
            $form->addElement(media_printicon($recent['id']));
        } else {
            $icon = DOKU_BASE.'lib/images/fileicons/file.png';
            $form->addElement('<img src="'.$icon.'" alt="'.$recent['id'].'" class="icon" />');
        }

        $form->addElement(form_makeOpenTag('span', array('class' => 'date')));
        $form->addElement($date);
        $form->addElement(form_makeCloseTag('span'));

        $diff = false;
        $href = '';

        if (!empty($recent['media'])) {
            $changelog = new MediaChangeLog($recent['id']);
            $revs = $changelog->getRevisions(0, 1);
            $diff = (count($revs) && file_exists(mediaFN($recent['id'])));
            if ($diff) {
                $href = media_managerURL(array(
                                             'tab_details' => 'history',
                                             'mediado' => 'diff',
                                             'image' => $recent['id'],
                                             'ns' => getNS($recent['id'])
                                         ), '&');
            }
        } else {
            $href = wl($recent['id'],"do=diff", false, '&');
        }

        if (!empty($recent['media']) && !$diff) {
            $form->addElement('<img src="'.DOKU_BASE.'lib/images/blank.gif" width="15" height="11" alt="" />');
        } else {
            $form->addElement(form_makeOpenTag('a', array('class' => 'diff_link', 'href' => $href)));
            $form->addElement(form_makeTag('img', array(
                            'src'   => DOKU_BASE.'lib/images/diff.png',
                            'width' => 15,
                            'height'=> 11,
                            'title' => $lang['diff'],
                            'alt'   => $lang['diff']
                            )));
            $form->addElement(form_makeCloseTag('a'));
        }

        if (!empty($recent['media'])) {
            $href = media_managerURL(array('tab_details' => 'history',
                'image' => $recent['id'], 'ns' => getNS($recent['id'])), '&');
        } else {
            $href = wl($recent['id'],"do=revisions",false,'&');
        }
        $form->addElement(form_makeOpenTag('a', array('class' => 'revisions_link', 'href' => $href)));
        $form->addElement(form_makeTag('img', array(
                        'src'   => DOKU_BASE.'lib/images/history.png',
                        'width' => 12,
                        'height'=> 14,
                        'title' => $lang['btn_revs'],
                        'alt'   => $lang['btn_revs']
                        )));
        $form->addElement(form_makeCloseTag('a'));

        if (!empty($recent['media'])) {
            $href = media_managerURL(array('tab_details' => 'view', 'image' => $recent['id'], 'ns' => getNS($recent['id'])), '&');
            $class = (file_exists(mediaFN($recent['id']))) ? 'wikilink1' : $class = 'wikilink2';
            $form->addElement(form_makeOpenTag('a', array('class' => $class, 'href' => $href)));
            $form->addElement($recent['id']);
            $form->addElement(form_makeCloseTag('a'));
        } else {
            $form->addElement(html_wikilink(':'.$recent['id'],useHeading('navigation')?null:$recent['id']));
        }
        $form->addElement(form_makeOpenTag('span', array('class' => 'sum')));
        $form->addElement(' – '.htmlspecialchars($recent['sum']));
        $form->addElement(form_makeCloseTag('span'));

        $form->addElement(form_makeOpenTag('span', array('class' => 'user')));
        if($recent['user']){
            $form->addElement('<bdi>'.editorinfo($recent['user']).'</bdi>');
            if(auth_ismanager()){
                $form->addElement(' <bdo dir="ltr">('.$recent['ip'].')</bdo>');
            }
        }else{
            $form->addElement('<bdo dir="ltr">'.$recent['ip'].'</bdo>');
        }
        $form->addElement(form_makeCloseTag('span'));

        $form->addElement(form_makeCloseTag('div'));
        $form->addElement(form_makeCloseTag('li'));
    }
    $form->addElement(form_makeCloseTag('ul'));

    $form->addElement(form_makeOpenTag('div', array('class' => 'pagenav')));
    $last = $first + $conf['recent'];
    if ($first > 0) {
        $first -= $conf['recent'];
        if ($first < 0) $first = 0;
        $form->addElement(form_makeOpenTag('div', array('class' => 'pagenav-prev')));
        $form->addElement(form_makeOpenTag('button', array(
                    'type'  => 'submit',
                    'name'  => 'first['.$first.']',
                    'accesskey' => 'n',
                    'title' => $lang['btn_newer'].' [N]',
                    'class' => 'button show'
                    )));
        $form->addElement($lang['btn_newer']);
        $form->addElement(form_makeCloseTag('button'));
        $form->addElement(form_makeCloseTag('div'));
    }
    if ($hasNext) {
        $form->addElement(form_makeOpenTag('div', array('class' => 'pagenav-next')));
        $form->addElement(form_makeOpenTag('button', array(
                        'type'  => 'submit',
                        'name'  => 'first['.$last.']',
                        'accesskey' => 'p',
                        'title' => $lang['btn_older'].' [P]',
                        'class' => 'button show'
                        )));
        $form->addElement($lang['btn_older']);
        $form->addElement(form_makeCloseTag('button'));
        $form->addElement(form_makeCloseTag('div'));
    }
    $form->addElement(form_makeCloseTag('div'));
    html_form('recent', $form);
}

/**
 * Display page index
 *
 * @author Andreas Gohr <andi@splitbrain.org>
 *
 * @param string $ns
 */
function html_index($ns){
    global $conf;
    global $ID;
    $ns  = cleanID($ns);
    #fixme use appropriate function
    if(empty($ns)){
        $ns = dirname(str_replace(':','/',$ID));
        if($ns == '.') $ns ='';
    }
    $ns  = utf8_encodeFN(str_replace(':','/',$ns));

    echo p_locale_xhtml('index');
    echo '<div id="index__tree">';

    $data = array();
    search($data,$conf['datadir'],'search_index',array('ns' => $ns));
    echo html_buildlist($data,'idx','html_list_index','html_li_index');

    echo '</div>';
}

/**
 * Index item formatter
 *
 * User function for html_buildlist()
 *
 * @author Andreas Gohr <andi@splitbrain.org>
 *
 * @param array $item
 * @return string
 */
function html_list_index($item){
    global $ID, $conf;

    // prevent searchbots needlessly following links
    $nofollow = ($ID != $conf['start'] || $conf['sitemap']) ? ' rel="nofollow"' : '';

    $ret = '';
    $base = ':'.$item['id'];
    $base = substr($base,strrpos($base,':')+1);
    if($item['type']=='d'){
        // FS#2766, no need for search bots to follow namespace links in the index
        $ret .= '<a href="'.wl($ID,'idx='.rawurlencode($item['id'])).'" title="' . $item['id'] . '" class="idx_dir"' . $nofollow . '><strong>';
        $ret .= $base;
        $ret .= '</strong></a>';
    }else{
        // default is noNSorNS($id), but we want noNS($id) when useheading is off FS#2605
        $ret .= html_wikilink(':'.$item['id'], useHeading('navigation') ? null : noNS($item['id']));
    }
    return $ret;
}

/**
 * Index List item
 *
 * This user function is used in html_buildlist to build the
 * <li> tags for namespaces when displaying the page index
 * it gives different classes to opened or closed "folders"
 *
 * @author Andreas Gohr <andi@splitbrain.org>
 *
 * @param array $item
 * @return string html
 */
function html_li_index($item){
    global $INFO;

    $class = '';
    $id = '';

    if($item['type'] == "f"){
        // scroll to the current item
        if($item['id'] == $INFO['id']) {
            $id = ' id="scroll__here"';
            $class = ' bounce';
        }
        return '<li class="level'.$item['level'].$class.'" '.$id.'>';
    }elseif($item['open']){
        return '<li class="open">';
    }else{
        return '<li class="closed">';
    }
}

/**
 * Default List item
 *
 * @author Andreas Gohr <andi@splitbrain.org>
 *
 * @param array $item
 * @return string html
 */
function html_li_default($item){
    return '<li class="level'.$item['level'].'">';
}

/**
 * Build an unordered list
 *
 * Build an unordered list from the given $data array
 * Each item in the array has to have a 'level' property
 * the item itself gets printed by the given $func user
 * function. The second and optional function is used to
 * print the <li> tag. Both user function need to accept
 * a single item.
 *
 * Both user functions can be given as array to point to
 * a member of an object.
 *
 * @author Andreas Gohr <andi@splitbrain.org>
 *
 * @param array    $data  array with item arrays
 * @param string   $class class of ul wrapper
 * @param callable $func  callback to print an list item
 * @param callable $lifunc callback to the opening li tag
 * @param bool     $forcewrapper Trigger building a wrapper ul if the first level is
 *                               0 (we have a root object) or 1 (just the root content)
 * @return string html of an unordered list
 */
function html_buildlist($data,$class,$func,$lifunc='html_li_default',$forcewrapper=false){
    if (count($data) === 0) {
        return '';
    }

    $start_level = $data[0]['level'];
    $level = $start_level;
    $ret   = '';
    $open  = 0;

    foreach ($data as $item){

        if( $item['level'] > $level ){
            //open new list
            for($i=0; $i<($item['level'] - $level); $i++){
                if ($i) $ret .= "<li class=\"clear\">";
                $ret .= "\n<ul class=\"$class\">\n";
                $open++;
            }
            $level = $item['level'];

        }elseif( $item['level'] < $level ){
            //close last item
            $ret .= "</li>\n";
            while( $level > $item['level'] && $open > 0 ){
                //close higher lists
                $ret .= "</ul>\n</li>\n";
                $level--;
                $open--;
            }
        } elseif ($ret !== '') {
            //close previous item
            $ret .= "</li>\n";
        }

        //print item
        $ret .= call_user_func($lifunc,$item);
        $ret .= '<div class="li">';

        $ret .= call_user_func($func,$item);
        $ret .= '</div>';
    }

    //close remaining items and lists
    $ret .= "</li>\n";
    while($open-- > 0) {
        $ret .= "</ul></li>\n";
    }

    if ($forcewrapper || $start_level < 2) {
        // Trigger building a wrapper ul if the first level is
        // 0 (we have a root object) or 1 (just the root content)
        $ret = "\n<ul class=\"$class\">\n".$ret."</ul>\n";
    }

    return $ret;
}

/**
 * display backlinks
 *
 * @author Andreas Gohr <andi@splitbrain.org>
 * @author Michael Klier <chi@chimeric.de>
 */
function html_backlinks(){
    global $ID;
    global $lang;

    print p_locale_xhtml('backlinks');

    $data = ft_backlinks($ID);

    if(!empty($data)) {
        print '<ul class="idx">';
        foreach($data as $blink){
            print '<li><div class="li">';
            print html_wikilink(':'.$blink,useHeading('navigation')?null:$blink);
            print '</div></li>';
        }
        print '</ul>';
    } else {
        print '<div class="level1"><p>' . $lang['nothingfound'] . '</p></div>';
    }
}

/**
 * Get header of diff HTML
 *
 * @param string $l_rev   Left revisions
 * @param string $r_rev   Right revision
 * @param string $id      Page id, if null $ID is used
 * @param bool   $media   If it is for media files
 * @param bool   $inline  Return the header on a single line
 * @return string[] HTML snippets for diff header
 */
function html_diff_head($l_rev, $r_rev, $id = null, $media = false, $inline = false) {
    global $lang;
    if ($id === null) {
        global $ID;
        $id = $ID;
    }
    $head_separator = $inline ? ' ' : '<br />';
    $media_or_wikiFN = $media ? 'mediaFN' : 'wikiFN';
    $ml_or_wl = $media ? 'ml' : 'wl';
    $l_minor = $r_minor = '';

    if($media) {
        $changelog = new MediaChangeLog($id);
    } else {
        $changelog = new PageChangeLog($id);
    }
    if(!$l_rev){
        $l_head = '&mdash;';
    }else{
        $l_info   = $changelog->getRevisionInfo($l_rev);
        if($l_info['user']){
            $l_user = '<bdi>'.editorinfo($l_info['user']).'</bdi>';
            if(auth_ismanager()) $l_user .= ' <bdo dir="ltr">('.$l_info['ip'].')</bdo>';
        } else {
            $l_user = '<bdo dir="ltr">'.$l_info['ip'].'</bdo>';
        }
        $l_user  = '<span class="user">'.$l_user.'</span>';
        $l_sum   = ($l_info['sum']) ? '<span class="sum"><bdi>'.hsc($l_info['sum']).'</bdi></span>' : '';
        if ($l_info['type']===DOKU_CHANGE_TYPE_MINOR_EDIT) $l_minor = 'class="minor"';

        $l_head_title = ($media) ? dformat($l_rev) : $id.' ['.dformat($l_rev).']';
        $l_head = '<bdi><a class="wikilink1" href="'.$ml_or_wl($id,"rev=$l_rev").'">'.
        $l_head_title.'</a></bdi>'.
        $head_separator.$l_user.' '.$l_sum;
    }

    if($r_rev){
        $r_info   = $changelog->getRevisionInfo($r_rev);
        if($r_info['user']){
            $r_user = '<bdi>'.editorinfo($r_info['user']).'</bdi>';
            if(auth_ismanager()) $r_user .= ' <bdo dir="ltr">('.$r_info['ip'].')</bdo>';
        } else {
            $r_user = '<bdo dir="ltr">'.$r_info['ip'].'</bdo>';
        }
        $r_user = '<span class="user">'.$r_user.'</span>';
        $r_sum  = ($r_info['sum']) ? '<span class="sum"><bdi>'.hsc($r_info['sum']).'</bdi></span>' : '';
        if ($r_info['type']===DOKU_CHANGE_TYPE_MINOR_EDIT) $r_minor = 'class="minor"';

        $r_head_title = ($media) ? dformat($r_rev) : $id.' ['.dformat($r_rev).']';
        $r_head = '<bdi><a class="wikilink1" href="'.$ml_or_wl($id,"rev=$r_rev").'">'.
        $r_head_title.'</a></bdi>'.
        $head_separator.$r_user.' '.$r_sum;
    }elseif($_rev = @filemtime($media_or_wikiFN($id))){
        $_info   = $changelog->getRevisionInfo($_rev);
        if($_info['user']){
            $_user = '<bdi>'.editorinfo($_info['user']).'</bdi>';
            if(auth_ismanager()) $_user .= ' <bdo dir="ltr">('.$_info['ip'].')</bdo>';
        } else {
            $_user = '<bdo dir="ltr">'.$_info['ip'].'</bdo>';
        }
        $_user = '<span class="user">'.$_user.'</span>';
        $_sum  = ($_info['sum']) ? '<span class="sum"><bdi>'.hsc($_info['sum']).'</span></bdi>' : '';
        if ($_info['type']===DOKU_CHANGE_TYPE_MINOR_EDIT) $r_minor = 'class="minor"';

        $r_head_title = ($media) ? dformat($_rev) : $id.' ['.dformat($_rev).']';
        $r_head  = '<bdi><a class="wikilink1" href="'.$ml_or_wl($id).'">'.
        $r_head_title.'</a></bdi> '.
        '('.$lang['current'].')'.
        $head_separator.$_user.' '.$_sum;
    }else{
        $r_head = '&mdash; ('.$lang['current'].')';
    }

    return array($l_head, $r_head, $l_minor, $r_minor);
}

/**
 * Show diff
 * between current page version and provided $text
 * or between the revisions provided via GET or POST
 *
 * @author Andreas Gohr <andi@splitbrain.org>
 * @param  string $text  when non-empty: compare with this text with most current version
 * @param  bool   $intro display the intro text
 * @param  string $type  type of the diff (inline or sidebyside)
 */
function html_diff($text = '', $intro = true, $type = null) {
    global $ID;
    global $REV;
    global $lang;
    global $INPUT;
    global $INFO;
    $pagelog = new PageChangeLog($ID);

    /*
     * Determine diff type
     */
    if(!$type) {
        $type = $INPUT->str('difftype');
        if(empty($type)) {
            $type = get_doku_pref('difftype', $type);
            if(empty($type) && $INFO['ismobile']) {
                $type = 'inline';
            }
        }
    }
    if($type != 'inline') $type = 'sidebyside';

    /*
     * Determine requested revision(s)
     */
    // we're trying to be clever here, revisions to compare can be either
    // given as rev and rev2 parameters, with rev2 being optional. Or in an
    // array in rev2.
    $rev1 = $REV;

    $rev2 = $INPUT->ref('rev2');
    if(is_array($rev2)) {
        $rev1 = (int) $rev2[0];
        $rev2 = (int) $rev2[1];

        if(!$rev1) {
            $rev1 = $rev2;
            unset($rev2);
        }
    } else {
        $rev2 = $INPUT->int('rev2');
    }

    /*
     * Determine left and right revision, its texts and the header
     */
    $r_minor = '';
    $l_minor = '';

    if($text) { // compare text to the most current revision
        $l_rev = '';
        $l_text = rawWiki($ID, '');
        $l_head = '<a class="wikilink1" href="' . wl($ID) . '">' .
            $ID . ' ' . dformat((int) @filemtime(wikiFN($ID))) . '</a> ' .
            $lang['current'];

        $r_rev = '';
        $r_text = cleanText($text);
        $r_head = $lang['yours'];
    } else {
        if($rev1 && isset($rev2) && $rev2) { // two specific revisions wanted
            // make sure order is correct (older on the left)
            if($rev1 < $rev2) {
                $l_rev = $rev1;
                $r_rev = $rev2;
            } else {
                $l_rev = $rev2;
                $r_rev = $rev1;
            }
        } elseif($rev1) { // single revision given, compare to current
            $r_rev = '';
            $l_rev = $rev1;
        } else { // no revision was given, compare previous to current
            $r_rev = '';
            $revs = $pagelog->getRevisions(0, 1);
            $l_rev = $revs[0];
            $REV = $l_rev; // store revision back in $REV
        }

        // when both revisions are empty then the page was created just now
        if(!$l_rev && !$r_rev) {
            $l_text = '';
        } else {
            $l_text = rawWiki($ID, $l_rev);
        }
        $r_text = rawWiki($ID, $r_rev);

        list($l_head, $r_head, $l_minor, $r_minor) = html_diff_head($l_rev, $r_rev, null, false, $type == 'inline');
    }

    /*
     * Build navigation
     */
    $l_nav = '';
    $r_nav = '';
    if(!$text) {
        list($l_nav, $r_nav) = html_diff_navigation($pagelog, $type, $l_rev, $r_rev);
    }
    /*
     * Create diff object and the formatter
     */
    $diff = new Diff(explode("\n", $l_text), explode("\n", $r_text));

    if($type == 'inline') {
        $diffformatter = new InlineDiffFormatter();
    } else {
        $diffformatter = new TableDiffFormatter();
    }
    /*
     * Display intro
     */
    if($intro) print p_locale_xhtml('diff');

    /*
     * Display type and exact reference
     */
    if(!$text) {
        ptln('<div class="diffoptions group">');


        $form = new Doku_Form(array('action' => wl()));
        $form->addHidden('id', $ID);
        $form->addHidden('rev2[0]', $l_rev);
        $form->addHidden('rev2[1]', $r_rev);
        $form->addHidden('do', 'diff');
        $form->addElement(
             form_makeListboxField(
                 'difftype',
                 array(
                     'sidebyside' => $lang['diff_side'],
                     'inline' => $lang['diff_inline']
                 ),
                 $type,
                 $lang['diff_type'],
                 '', '',
                 array('class' => 'quickselect')
             )
        );
        $form->addElement(form_makeButton('submit', 'diff', 'Go'));
        $form->printForm();

        ptln('<p>');
        // link to exactly this view FS#2835
        echo html_diff_navigationlink($type, 'difflink', $l_rev, $r_rev ? $r_rev : $INFO['currentrev']);
        ptln('</p>');

        ptln('</div>'); // .diffoptions
    }

    /*
     * Display diff view table
     */
    ?>
    <div class="table">
    <table class="diff diff_<?php echo $type ?>">

        <?php
        //navigation and header
        if($type == 'inline') {
            if(!$text) { ?>
                <tr>
                    <td class="diff-lineheader">-</td>
                    <td class="diffnav"><?php echo $l_nav ?></td>
                </tr>
                <tr>
                    <th class="diff-lineheader">-</th>
                    <th <?php echo $l_minor ?>>
                        <?php echo $l_head ?>
                    </th>
                </tr>
            <?php } ?>
            <tr>
                <td class="diff-lineheader">+</td>
                <td class="diffnav"><?php echo $r_nav ?></td>
            </tr>
            <tr>
                <th class="diff-lineheader">+</th>
                <th <?php echo $r_minor ?>>
                    <?php echo $r_head ?>
                </th>
            </tr>
        <?php } else {
            if(!$text) { ?>
                <tr>
                    <td colspan="2" class="diffnav"><?php echo $l_nav ?></td>
                    <td colspan="2" class="diffnav"><?php echo $r_nav ?></td>
                </tr>
            <?php } ?>
            <tr>
                <th colspan="2" <?php echo $l_minor ?>>
                    <?php echo $l_head ?>
                </th>
                <th colspan="2" <?php echo $r_minor ?>>
                    <?php echo $r_head ?>
                </th>
            </tr>
        <?php }

        //diff view
        echo html_insert_softbreaks($diffformatter->format($diff)); ?>

    </table>
    </div>
<?php
}

/**
 * Create html for revision navigation
 *
 * @param PageChangeLog $pagelog changelog object of current page
 * @param string        $type    inline vs sidebyside
 * @param int           $l_rev   left revision timestamp
 * @param int           $r_rev   right revision timestamp
 * @return string[] html of left and right navigation elements
 */
function html_diff_navigation($pagelog, $type, $l_rev, $r_rev) {
    global $INFO, $ID;

    // last timestamp is not in changelog, retrieve timestamp from metadata
    // note: when page is removed, the metadata timestamp is zero
    if(!$r_rev) {
        if(isset($INFO['meta']['last_change']['date'])) {
            $r_rev = $INFO['meta']['last_change']['date'];
        } else {
            $r_rev = 0;
        }
    }

    //retrieve revisions with additional info
    list($l_revs, $r_revs) = $pagelog->getRevisionsAround($l_rev, $r_rev);
    $l_revisions = array();
    if(!$l_rev) {
        $l_revisions[0] = array(0, "", false); //no left revision given, add dummy
    }
    foreach($l_revs as $rev) {
        $info = $pagelog->getRevisionInfo($rev);
        $l_revisions[$rev] = array(
            $rev,
            dformat($info['date']) . ' ' . editorinfo($info['user'], true) . ' ' . $info['sum'],
            $r_rev ? $rev >= $r_rev : false //disable?
        );
    }
    $r_revisions = array();
    if(!$r_rev) {
        $r_revisions[0] = array(0, "", false); //no right revision given, add dummy
    }
    foreach($r_revs as $rev) {
        $info = $pagelog->getRevisionInfo($rev);
        $r_revisions[$rev] = array(
            $rev,
            dformat($info['date']) . ' ' . editorinfo($info['user'], true) . ' ' . $info['sum'],
            $rev <= $l_rev //disable?
        );
    }

    //determine previous/next revisions
    $l_index = array_search($l_rev, $l_revs);
    $l_prev = $l_revs[$l_index + 1];
    $l_next = $l_revs[$l_index - 1];
    if($r_rev) {
        $r_index = array_search($r_rev, $r_revs);
        $r_prev = $r_revs[$r_index + 1];
        $r_next = $r_revs[$r_index - 1];
    } else {
        //removed page
        if($l_next) {
            $r_prev = $r_revs[0];
        } else {
            $r_prev = null;
        }
        $r_next = null;
    }

    /*
     * Left side:
     */
    $l_nav = '';
    //move back
    if($l_prev) {
        $l_nav .= html_diff_navigationlink($type, 'diffbothprevrev', $l_prev, $r_prev);
        $l_nav .= html_diff_navigationlink($type, 'diffprevrev', $l_prev, $r_rev);
    }
    //dropdown
    $form = new Doku_Form(array('action' => wl()));
    $form->addHidden('id', $ID);
    $form->addHidden('difftype', $type);
    $form->addHidden('rev2[1]', $r_rev);
    $form->addHidden('do', 'diff');
    $form->addElement(
         form_makeListboxField(
             'rev2[0]',
             $l_revisions,
             $l_rev,
             '', '', '',
             array('class' => 'quickselect')
         )
    );
    $form->addElement(form_makeButton('submit', 'diff', 'Go'));
    $l_nav .= $form->getForm();
    //move forward
    if($l_next && ($l_next < $r_rev || !$r_rev)) {
        $l_nav .= html_diff_navigationlink($type, 'diffnextrev', $l_next, $r_rev);
    }

    /*
     * Right side:
     */
    $r_nav = '';
    //move back
    if($l_rev < $r_prev) {
        $r_nav .= html_diff_navigationlink($type, 'diffprevrev', $l_rev, $r_prev);
    }
    //dropdown
    $form = new Doku_Form(array('action' => wl()));
    $form->addHidden('id', $ID);
    $form->addHidden('rev2[0]', $l_rev);
    $form->addHidden('difftype', $type);
    $form->addHidden('do', 'diff');
    $form->addElement(
         form_makeListboxField(
             'rev2[1]',
             $r_revisions,
             $r_rev,
             '', '', '',
             array('class' => 'quickselect')
         )
    );
    $form->addElement(form_makeButton('submit', 'diff', 'Go'));
    $r_nav .= $form->getForm();
    //move forward
    if($r_next) {
        if($pagelog->isCurrentRevision($r_next)) {
            $r_nav .= html_diff_navigationlink($type, 'difflastrev', $l_rev); //last revision is diff with current page
        } else {
            $r_nav .= html_diff_navigationlink($type, 'diffnextrev', $l_rev, $r_next);
        }
        $r_nav .= html_diff_navigationlink($type, 'diffbothnextrev', $l_next, $r_next);
    }
    return array($l_nav, $r_nav);
}

/**
 * Create html link to a diff defined by two revisions
 *
 * @param string $difftype display type
 * @param string $linktype
 * @param int $lrev oldest revision
 * @param int $rrev newest revision or null for diff with current revision
 * @return string html of link to a diff
 */
function html_diff_navigationlink($difftype, $linktype, $lrev, $rrev = null) {
    global $ID, $lang;
    if(!$rrev) {
        $urlparam = array(
            'do' => 'diff',
            'rev' => $lrev,
            'difftype' => $difftype,
        );
    } else {
        $urlparam = array(
            'do' => 'diff',
            'rev2[0]' => $lrev,
            'rev2[1]' => $rrev,
            'difftype' => $difftype,
        );
    }
    return  '<a class="' . $linktype . '" href="' . wl($ID, $urlparam) . '" title="' . $lang[$linktype] . '">' .
                '<span>' . $lang[$linktype] . '</span>' .
            '</a>' . "\n";
}

/**
 * Insert soft breaks in diff html
 *
 * @param string $diffhtml
 * @return string
 */
function html_insert_softbreaks($diffhtml) {
    // search the diff html string for both:
    // - html tags, so these can be ignored
    // - long strings of characters without breaking characters
    return preg_replace_callback('/<[^>]*>|[^<> ]{12,}/','html_softbreak_callback',$diffhtml);
}

/**
 * callback which adds softbreaks
 *
 * @param array $match array with first the complete match
 * @return string the replacement
 */
function html_softbreak_callback($match){
    // if match is an html tag, return it intact
    if ($match[0]{0} == '<') return $match[0];

    // its a long string without a breaking character,
    // make certain characters into breaking characters by inserting a
    // breaking character (zero length space, U+200B / #8203) in front them.
    $regex = <<< REGEX
(?(?=                                 # start a conditional expression with a positive look ahead ...
&\#?\\w{1,6};)                        # ... for html entities - we don't want to split them (ok to catch some invalid combinations)
&\#?\\w{1,6};                         # yes pattern - a quicker match for the html entity, since we know we have one
|
[?/,&\#;:]                            # no pattern - any other group of 'special' characters to insert a breaking character after
)+                                    # end conditional expression
REGEX;

    return preg_replace('<'.$regex.'>xu','\0&#8203;',$match[0]);
}

/**
 * show warning on conflict detection
 *
 * @author Andreas Gohr <andi@splitbrain.org>
 *
 * @param string $text
 * @param string $summary
 */
function html_conflict($text,$summary){
    global $ID;
    global $lang;

    print p_locale_xhtml('conflict');
    $form = new Doku_Form(array('id' => 'dw__editform'));
    $form->addHidden('id', $ID);
    $form->addHidden('wikitext', $text);
    $form->addHidden('summary', $summary);
    $form->addElement(form_makeButton('submit', 'save', $lang['btn_save'], array('accesskey'=>'s')));
    $form->addElement(form_makeButton('submit', 'cancel', $lang['btn_cancel']));
    html_form('conflict', $form);
    print '<br /><br /><br /><br />'.NL;
}

/**
 * Prints the global message array
 *
 * @author Andreas Gohr <andi@splitbrain.org>
 */
function html_msgarea(){
    global $MSG, $MSG_shown;
    /** @var array $MSG */
    // store if the global $MSG has already been shown and thus HTML output has been started
    $MSG_shown = true;

    if(!isset($MSG)) return;

    $shown = array();
    foreach($MSG as $msg){
        $hash = md5($msg['msg']);
        if(isset($shown[$hash])) continue; // skip double messages
        if(info_msg_allowed($msg)){
            print '<div class="'.$msg['lvl'].'">';
            print $msg['msg'];
            print '</div>';
        }
        $shown[$hash] = 1;
    }

    unset($GLOBALS['MSG']);
}

/**
 * Prints the registration form
 *
 * @author Andreas Gohr <andi@splitbrain.org>
 */
function html_register(){
    global $lang;
    global $conf;
    global $INPUT;

    $base_attrs = array('size'=>50,'required'=>'required');
    $email_attrs = $base_attrs + array('type'=>'email','class'=>'edit');

    print p_locale_xhtml('register');
    print '<div class="centeralign">'.NL;
    $form = new Doku_Form(array('id' => 'dw__register'));
    $form->startFieldset($lang['btn_register']);
    $form->addHidden('do', 'register');
    $form->addHidden('save', '1');
    $form->addElement(form_makeTextField('login', $INPUT->post->str('login'), $lang['user'], '', 'block', $base_attrs));
    if (!$conf['autopasswd']) {
        $form->addElement(form_makePasswordField('pass', $lang['pass'], '', 'block', $base_attrs));
        $form->addElement(form_makePasswordField('passchk', $lang['passchk'], '', 'block', $base_attrs));
    }
    $form->addElement(form_makeTextField('fullname', $INPUT->post->str('fullname'), $lang['fullname'], '', 'block', $base_attrs));
    $form->addElement(form_makeField('email','email', $INPUT->post->str('email'), $lang['email'], '', 'block', $email_attrs));
    $form->addElement(form_makeButton('submit', '', $lang['btn_register']));
    $form->endFieldset();
    html_form('register', $form);

    print '</div>'.NL;
}

/**
 * Print the update profile form
 *
 * @author Christopher Smith <chris@jalakai.co.uk>
 * @author Andreas Gohr <andi@splitbrain.org>
 */
function html_updateprofile(){
    global $lang;
    global $conf;
    global $INPUT;
    global $INFO;
    /** @var DokuWiki_Auth_Plugin $auth */
    global $auth;

    print p_locale_xhtml('updateprofile');
    print '<div class="centeralign">'.NL;

    $fullname = $INPUT->post->str('fullname', $INFO['userinfo']['name'], true);
    $email = $INPUT->post->str('email', $INFO['userinfo']['mail'], true);
    $form = new Doku_Form(array('id' => 'dw__register'));
    $form->startFieldset($lang['profile']);
    $form->addHidden('do', 'profile');
    $form->addHidden('save', '1');
    $form->addElement(form_makeTextField('login', $_SERVER['REMOTE_USER'], $lang['user'], '', 'block', array('size'=>'50', 'disabled'=>'disabled')));
    $attr = array('size'=>'50');
    if (!$auth->canDo('modName')) $attr['disabled'] = 'disabled';
    $form->addElement(form_makeTextField('fullname', $fullname, $lang['fullname'], '', 'block', $attr));
    $attr = array('size'=>'50', 'class'=>'edit');
    if (!$auth->canDo('modMail')) $attr['disabled'] = 'disabled';
    $form->addElement(form_makeField('email','email', $email, $lang['email'], '', 'block', $attr));
    $form->addElement(form_makeTag('br'));
    if ($auth->canDo('modPass')) {
        $form->addElement(form_makePasswordField('newpass', $lang['newpass'], '', 'block', array('size'=>'50')));
        $form->addElement(form_makePasswordField('passchk', $lang['passchk'], '', 'block', array('size'=>'50')));
    }
    if ($conf['profileconfirm']) {
        $form->addElement(form_makeTag('br'));
        $form->addElement(form_makePasswordField('oldpass', $lang['oldpass'], '', 'block', array('size'=>'50', 'required' => 'required')));
    }
    $form->addElement(form_makeButton('submit', '', $lang['btn_save']));
    $form->addElement(form_makeButton('reset', '', $lang['btn_reset']));

    $form->endFieldset();
    html_form('updateprofile', $form);

    if ($auth->canDo('delUser') && actionOK('profile_delete')) {
        $form_profiledelete = new Doku_Form(array('id' => 'dw__profiledelete'));
        $form_profiledelete->startFieldset($lang['profdeleteuser']);
        $form_profiledelete->addHidden('do', 'profile_delete');
        $form_profiledelete->addHidden('delete', '1');
        $form_profiledelete->addElement(form_makeCheckboxField('confirm_delete', '1', $lang['profconfdelete'],'dw__confirmdelete','', array('required' => 'required')));
        if ($conf['profileconfirm']) {
            $form_profiledelete->addElement(form_makeTag('br'));
            $form_profiledelete->addElement(form_makePasswordField('oldpass', $lang['oldpass'], '', 'block', array('size'=>'50', 'required' => 'required')));
        }
        $form_profiledelete->addElement(form_makeButton('submit', '', $lang['btn_deleteuser']));
        $form_profiledelete->endFieldset();

        html_form('profiledelete', $form_profiledelete);
    }

    print '</div>'.NL;
}

/**
 * Preprocess edit form data
 *
 * @author   Andreas Gohr <andi@splitbrain.org>
 *
 * @triggers HTML_EDITFORM_OUTPUT
 */
function html_edit(){
    global $INPUT;
    global $ID;
    global $REV;
    global $DATE;
    global $PRE;
    global $SUF;
    global $INFO;
    global $SUM;
    global $lang;
    global $conf;
    global $TEXT;

    if ($INPUT->has('changecheck')) {
        $check = $INPUT->str('changecheck');
    } elseif(!$INFO['exists']){
        // $TEXT has been loaded from page template
        $check = md5('');
    } else {
        $check = md5($TEXT);
    }
    $mod = md5($TEXT) !== $check;

    $wr = $INFO['writable'] && !$INFO['locked'];
    $include = 'edit';
    if($wr){
        if ($REV) $include = 'editrev';
    }else{
        // check pseudo action 'source'
        if(!actionOK('source')){
            msg('Command disabled: source',-1);
            return;
        }
        $include = 'read';
    }

    global $license;

    $form = new Doku_Form(array('id' => 'dw__editform'));
    $form->addHidden('id', $ID);
    $form->addHidden('rev', $REV);
    $form->addHidden('date', $DATE);
    $form->addHidden('prefix', $PRE . '.');
    $form->addHidden('suffix', $SUF);
    $form->addHidden('changecheck', $check);

    $data = array('form' => $form,
                  'wr'   => $wr,
                  'media_manager' => true,
                  'target' => ($INPUT->has('target') && $wr) ? $INPUT->str('target') : 'section',
                  'intro_locale' => $include);

    if ($data['target'] !== 'section') {
        // Only emit event if page is writable, section edit data is valid and
        // edit target is not section.
        trigger_event('HTML_EDIT_FORMSELECTION', $data, 'html_edit_form', true);
    } else {
        html_edit_form($data);
    }
    if (isset($data['intro_locale'])) {
        echo p_locale_xhtml($data['intro_locale']);
    }

    $form->addHidden('target', $data['target']);
    $form->addElement(form_makeOpenTag('div', array('id'=>'wiki__editbar', 'class'=>'editBar')));
    $form->addElement(form_makeOpenTag('div', array('id'=>'size__ctl')));
    $form->addElement(form_makeCloseTag('div'));
    if ($wr) {
        $form->addElement(form_makeOpenTag('div', array('class'=>'editButtons')));
        $form->addElement(form_makeButton('submit', 'save', $lang['btn_save'], array('id'=>'edbtn__save', 'accesskey'=>'s', 'tabindex'=>'4')));
        $form->addElement(form_makeButton('submit', 'preview', $lang['btn_preview'], array('id'=>'edbtn__preview', 'accesskey'=>'p', 'tabindex'=>'5')));
        $form->addElement(form_makeButton('submit', 'draftdel', $lang['btn_cancel'], array('tabindex'=>'6')));
        $form->addElement(form_makeCloseTag('div'));
        $form->addElement(form_makeOpenTag('div', array('class'=>'summary')));
        $form->addElement(form_makeTextField('summary', $SUM, $lang['summary'], 'edit__summary', 'nowrap', array('size'=>'50', 'tabindex'=>'2')));
        $elem = html_minoredit();
        if ($elem) $form->addElement($elem);
        $form->addElement(form_makeCloseTag('div'));
    }
    $form->addElement(form_makeCloseTag('div'));
    if($wr && $conf['license']){
        $form->addElement(form_makeOpenTag('div', array('class'=>'license')));
        $out  = $lang['licenseok'];
        $out .= ' <a href="'.$license[$conf['license']]['url'].'" rel="license" class="urlextern"';
        if($conf['target']['extern']) $out .= ' target="'.$conf['target']['extern'].'"';
        $out .= '>'.$license[$conf['license']]['name'].'</a>';
        $form->addElement($out);
        $form->addElement(form_makeCloseTag('div'));
    }

    if ($wr) {
        // sets changed to true when previewed
        echo '<script type="text/javascript">/*<![CDATA[*/'. NL;
        echo 'textChanged = ' . ($mod ? 'true' : 'false');
        echo '/*!]]>*/</script>' . NL;
    } ?>
    <div class="editBox" role="application">

    <div class="toolbar group">
        <div id="draft__status"><?php if(!empty($INFO['draft'])) echo $lang['draftdate'].' '.dformat();?></div>
        <div id="tool__bar"><?php if ($wr && $data['media_manager']){?><a href="<?php echo DOKU_BASE?>lib/exe/mediamanager.php?ns=<?php echo $INFO['namespace']?>"
            target="_blank"><?php echo $lang['mediaselect'] ?></a><?php }?></div>
    </div>
    <?php

    html_form('edit', $form);
    print '</div>'.NL;
}

/**
 * Display the default edit form
 *
 * Is the default action for HTML_EDIT_FORMSELECTION.
 *
 * @param mixed[] $param
 */
function html_edit_form($param) {
    global $TEXT;

    if ($param['target'] !== 'section') {
        msg('No editor for edit target ' . hsc($param['target']) . ' found.', -1);
    }

    $attr = array('tabindex'=>'1');
    if (!$param['wr']) $attr['readonly'] = 'readonly';

    $param['form']->addElement(form_makeWikiText($TEXT, $attr));
}

/**
 * Adds a checkbox for minor edits for logged in users
 *
 * @author Andreas Gohr <andi@splitbrain.org>
 *
 * @return array|bool
 */
function html_minoredit(){
    global $conf;
    global $lang;
    global $INPUT;
    // minor edits are for logged in users only
    if(!$conf['useacl'] || !$_SERVER['REMOTE_USER']){
        return false;
    }

    $p = array();
    $p['tabindex'] = 3;
    if($INPUT->bool('minor')) $p['checked']='checked';
    return form_makeCheckboxField('minor', '1', $lang['minoredit'], 'minoredit', 'nowrap', $p);
}

/**
 * prints some debug info
 *
 * @author Andreas Gohr <andi@splitbrain.org>
 */
function html_debug(){
    global $conf;
    global $lang;
    /** @var DokuWiki_Auth_Plugin $auth */
    global $auth;
    global $INFO;

    //remove sensitive data
    $cnf = $conf;
    debug_guard($cnf);
    $nfo = $INFO;
    debug_guard($nfo);
    $ses = $_SESSION;
    debug_guard($ses);

    print '<html><body>';

    print '<p>When reporting bugs please send all the following ';
    print 'output as a mail to andi@splitbrain.org ';
    print 'The best way to do this is to save this page in your browser</p>';

    print '<b>$INFO:</b><pre>';
    print_r($nfo);
    print '</pre>';

    print '<b>$_SERVER:</b><pre>';
    print_r($_SERVER);
    print '</pre>';

    print '<b>$conf:</b><pre>';
    print_r($cnf);
    print '</pre>';

    print '<b>DOKU_BASE:</b><pre>';
    print DOKU_BASE;
    print '</pre>';

    print '<b>abs DOKU_BASE:</b><pre>';
    print DOKU_URL;
    print '</pre>';

    print '<b>rel DOKU_BASE:</b><pre>';
    print dirname($_SERVER['PHP_SELF']).'/';
    print '</pre>';

    print '<b>PHP Version:</b><pre>';
    print phpversion();
    print '</pre>';

    print '<b>locale:</b><pre>';
    print setlocale(LC_ALL,0);
    print '</pre>';

    print '<b>encoding:</b><pre>';
    print $lang['encoding'];
    print '</pre>';

    if($auth){
        print '<b>Auth backend capabilities:</b><pre>';
        foreach ($auth->getCapabilities() as $cando){
            print '   '.str_pad($cando,16) . ' => ' . (int)$auth->canDo($cando) . NL;
        }
        print '</pre>';
    }

    print '<b>$_SESSION:</b><pre>';
    print_r($ses);
    print '</pre>';

    print '<b>Environment:</b><pre>';
    print_r($_ENV);
    print '</pre>';

    print '<b>PHP settings:</b><pre>';
    $inis = ini_get_all();
    print_r($inis);
    print '</pre>';

    if (function_exists('apache_get_version')) {
        $apache = array();
        $apache['version'] = apache_get_version();

        if (function_exists('apache_get_modules')) {
            $apache['modules'] = apache_get_modules();
        }
        print '<b>Apache</b><pre>';
        print_r($apache);
        print '</pre>';
    }

    print '</body></html>';
}

/**
 * List available Administration Tasks
 *
 * @author Andreas Gohr <andi@splitbrain.org>
 * @author Håkan Sandell <hakan.sandell@home.se>
 */
function html_admin(){
    global $ID;
    global $INFO;
    global $conf;
    /** @var DokuWiki_Auth_Plugin $auth */
    global $auth;

    // build menu of admin functions from the plugins that handle them
    $pluginlist = plugin_list('admin');
    $menu = array();
    foreach ($pluginlist as $p) {
        /** @var DokuWiki_Admin_Plugin $obj */
        if(($obj = plugin_load('admin',$p)) === null) continue;

        // check permissions
        if($obj->forAdminOnly() && !$INFO['isadmin']) continue;

        $menu[$p] = array('plugin' => $p,
                'prompt' => $obj->getMenuText($conf['lang']),
                'sort' => $obj->getMenuSort()
                );
    }

    // data security check
    // simple check if the 'savedir' is relative and accessible when appended to DOKU_URL
    // it verifies either:
    //   'savedir' has been moved elsewhere, or
    //   has protection to prevent the webserver serving files from it
    if (substr($conf['savedir'],0,2) == './'){
        echo '<a style="border:none; float:right;"
                href="http://www.dokuwiki.org/security#web_access_security">
                <img src="'.DOKU_URL.$conf['savedir'].'/security.png" alt="Your data directory seems to be protected properly."
                onerror="this.parentNode.style.display=\'none\'" /></a>';
    }

    print p_locale_xhtml('admin');

    // Admin Tasks
    if($INFO['isadmin']){
        ptln('<ul class="admin_tasks">');

        if($menu['usermanager'] && $auth && $auth->canDo('getUsers')){
            ptln('  <li class="admin_usermanager"><div class="li">'.
                    '<a href="'.wl($ID, array('do' => 'admin','page' => 'usermanager')).'">'.
                    $menu['usermanager']['prompt'].'</a></div></li>');
        }
        unset($menu['usermanager']);

        if($menu['acl']){
            ptln('  <li class="admin_acl"><div class="li">'.
                    '<a href="'.wl($ID, array('do' => 'admin','page' => 'acl')).'">'.
                    $menu['acl']['prompt'].'</a></div></li>');
        }
        unset($menu['acl']);

        if($menu['extension']){
            ptln('  <li class="admin_plugin"><div class="li">'.
                    '<a href="'.wl($ID, array('do' => 'admin','page' => 'extension')).'">'.
                    $menu['extension']['prompt'].'</a></div></li>');
        }
        unset($menu['extension']);

        if($menu['config']){
            ptln('  <li class="admin_config"><div class="li">'.
                    '<a href="'.wl($ID, array('do' => 'admin','page' => 'config')).'">'.
                    $menu['config']['prompt'].'</a></div></li>');
        }
        unset($menu['config']);

        if($menu['styling']){
            ptln('  <li class="admin_styling"><div class="li">'.
                '<a href="'.wl($ID, array('do' => 'admin','page' => 'styling')).'">'.
                $menu['styling']['prompt'].'</a></div></li>');
        }
        unset($menu['styling']);
    }
    ptln('</ul>');

    // Manager Tasks
    ptln('<ul class="admin_tasks">');

    if($menu['revert']){
        ptln('  <li class="admin_revert"><div class="li">'.
                '<a href="'.wl($ID, array('do' => 'admin','page' => 'revert')).'">'.
                $menu['revert']['prompt'].'</a></div></li>');
    }
    unset($menu['revert']);

    if($menu['popularity']){
        ptln('  <li class="admin_popularity"><div class="li">'.
                '<a href="'.wl($ID, array('do' => 'admin','page' => 'popularity')).'">'.
                $menu['popularity']['prompt'].'</a></div></li>');
    }
    unset($menu['popularity']);

    // print DokuWiki version:
    ptln('</ul>');
    echo '<div id="admin__version">';
    echo getVersion();
    echo '</div>';

    // print the rest as sorted list
    if(count($menu)){
        usort($menu, 'p_sort_modes');
        // output the menu
        ptln('<div class="clearer"></div>');
        print p_locale_xhtml('adminplugins');
        ptln('<ul>');
        foreach ($menu as $item) {
            if (!$item['prompt']) continue;
            ptln('  <li><div class="li"><a href="'.wl($ID, 'do=admin&amp;page='.$item['plugin']).'">'.$item['prompt'].'</a></div></li>');
        }
        ptln('</ul>');
    }
}

/**
 * Form to request a new password for an existing account
 *
 * @author Benoit Chesneau <benoit@bchesneau.info>
 * @author Andreas Gohr <gohr@cosmocode.de>
 */
function html_resendpwd() {
    global $lang;
    global $conf;
    global $INPUT;

    $token = preg_replace('/[^a-f0-9]+/','',$INPUT->str('pwauth'));

    if(!$conf['autopasswd'] && $token){
        print p_locale_xhtml('resetpwd');
        print '<div class="centeralign">'.NL;
        $form = new Doku_Form(array('id' => 'dw__resendpwd'));
        $form->startFieldset($lang['btn_resendpwd']);
        $form->addHidden('token', $token);
        $form->addHidden('do', 'resendpwd');

        $form->addElement(form_makePasswordField('pass', $lang['pass'], '', 'block', array('size'=>'50')));
        $form->addElement(form_makePasswordField('passchk', $lang['passchk'], '', 'block', array('size'=>'50')));

        $form->addElement(form_makeButton('submit', '', $lang['btn_resendpwd']));
        $form->endFieldset();
        html_form('resendpwd', $form);
        print '</div>'.NL;
    }else{
        print p_locale_xhtml('resendpwd');
        print '<div class="centeralign">'.NL;
        $form = new Doku_Form(array('id' => 'dw__resendpwd'));
        $form->startFieldset($lang['resendpwd']);
        $form->addHidden('do', 'resendpwd');
        $form->addHidden('save', '1');
        $form->addElement(form_makeTag('br'));
        $form->addElement(form_makeTextField('login', $INPUT->post->str('login'), $lang['user'], '', 'block'));
        $form->addElement(form_makeTag('br'));
        $form->addElement(form_makeTag('br'));
        $form->addElement(form_makeButton('submit', '', $lang['btn_resendpwd']));
        $form->endFieldset();
        html_form('resendpwd', $form);
        print '</div>'.NL;
    }
}

/**
 * Return the TOC rendered to XHTML
 *
 * @author Andreas Gohr <andi@splitbrain.org>
 *
 * @param array $toc
 * @return string html
 */
function html_TOC($toc){
    if(!count($toc)) return '';
    global $lang;
    $out  = '<!-- TOC START -->'.DOKU_LF;
    $out .= '<div id="dw__toc">'.DOKU_LF;
    $out .= '<h3 class="toggle">';
    $out .= $lang['toc'];
    $out .= '</h3>'.DOKU_LF;
    $out .= '<div>'.DOKU_LF;
    $out .= html_buildlist($toc,'toc','html_list_toc','html_li_default',true);
    $out .= '</div>'.DOKU_LF.'</div>'.DOKU_LF;
    $out .= '<!-- TOC END -->'.DOKU_LF;
    return $out;
}

/**
 * Callback for html_buildlist
 *
 * @param array $item
 * @return string html
 */
function html_list_toc($item){
    if(isset($item['hid'])){
        $link = '#'.$item['hid'];
    }else{
        $link = $item['link'];
    }

    return '<a href="'.$link.'">'.hsc($item['title']).'</a>';
}

/**
 * Helper function to build TOC items
 *
 * Returns an array ready to be added to a TOC array
 *
 * @param string $link  - where to link (if $hash set to '#' it's a local anchor)
 * @param string $text  - what to display in the TOC
 * @param int    $level - nesting level
 * @param string $hash  - is prepended to the given $link, set blank if you want full links
 * @return array the toc item
 */
function html_mktocitem($link, $text, $level, $hash='#'){
    return  array( 'link'  => $hash.$link,
            'title' => $text,
            'type'  => 'ul',
            'level' => $level);
}

/**
 * Output a Doku_Form object.
 * Triggers an event with the form name: HTML_{$name}FORM_OUTPUT
 *
 * @author Tom N Harris <tnharris@whoopdedo.org>
 *
 * @param string     $name The name of the form
 * @param Doku_Form  $form The form
 */
function html_form($name, &$form) {
    // Safety check in case the caller forgets.
    $form->endFieldset();
    trigger_event('HTML_'.strtoupper($name).'FORM_OUTPUT', $form, 'html_form_output', false);
}

/**
 * Form print function.
 * Just calls printForm() on the data object.
 *
 * @param Doku_Form $data The form
 */
function html_form_output($data) {
    $data->printForm();
}

/**
 * Embed a flash object in HTML
 *
 * This will create the needed HTML to embed a flash movie in a cross browser
 * compatble way using valid XHTML
 *
 * The parameters $params, $flashvars and $atts need to be associative arrays.
 * No escaping needs to be done for them. The alternative content *has* to be
 * escaped because it is used as is. If no alternative content is given
 * $lang['noflash'] is used.
 *
 * @author Andreas Gohr <andi@splitbrain.org>
 * @link   http://latrine.dgx.cz/how-to-correctly-insert-a-flash-into-xhtml
 *
 * @param string $swf      - the SWF movie to embed
 * @param int $width       - width of the flash movie in pixels
 * @param int $height      - height of the flash movie in pixels
 * @param array $params    - additional parameters (<param>)
 * @param array $flashvars - parameters to be passed in the flashvar parameter
 * @param array $atts      - additional attributes for the <object> tag
 * @param string $alt      - alternative content (is NOT automatically escaped!)
 * @return string         - the XHTML markup
 */
function html_flashobject($swf,$width,$height,$params=null,$flashvars=null,$atts=null,$alt=''){
    global $lang;

    $out = '';

    // prepare the object attributes
    if(is_null($atts)) $atts = array();
    $atts['width']  = (int) $width;
    $atts['height'] = (int) $height;
    if(!$atts['width'])  $atts['width']  = 425;
    if(!$atts['height']) $atts['height'] = 350;

    // add object attributes for standard compliant browsers
    $std = $atts;
    $std['type'] = 'application/x-shockwave-flash';
    $std['data'] = $swf;

    // add object attributes for IE
    $ie  = $atts;
    $ie['classid'] = 'clsid:D27CDB6E-AE6D-11cf-96B8-444553540000';

    // open object (with conditional comments)
    $out .= '<!--[if !IE]> -->'.NL;
    $out .= '<object '.buildAttributes($std).'>'.NL;
    $out .= '<!-- <![endif]-->'.NL;
    $out .= '<!--[if IE]>'.NL;
    $out .= '<object '.buildAttributes($ie).'>'.NL;
    $out .= '    <param name="movie" value="'.hsc($swf).'" />'.NL;
    $out .= '<!--><!-- -->'.NL;

    // print params
    if(is_array($params)) foreach($params as $key => $val){
        $out .= '  <param name="'.hsc($key).'" value="'.hsc($val).'" />'.NL;
    }

    // add flashvars
    if(is_array($flashvars)){
        $out .= '  <param name="FlashVars" value="'.buildURLparams($flashvars).'" />'.NL;
    }

    // alternative content
    if($alt){
        $out .= $alt.NL;
    }else{
        $out .= $lang['noflash'].NL;
    }

    // finish
    $out .= '</object>'.NL;
    $out .= '<!-- <![endif]-->'.NL;

    return $out;
}

/**
 * Prints HTML code for the given tab structure
 *
 * @param array  $tabs        tab structure
 * @param string $current_tab the current tab id
 */
function html_tabs($tabs, $current_tab = null) {
    echo '<ul class="tabs">'.NL;

    foreach($tabs as $id => $tab) {
        html_tab($tab['href'], $tab['caption'], $id === $current_tab);
    }

    echo '</ul>'.NL;
}
/**
 * Prints a single tab
 *
 * @author Kate Arzamastseva <pshns@ukr.net>
 * @author Adrian Lang <mail@adrianlang.de>
 *
 * @param string $href - tab href
 * @param string $caption - tab caption
 * @param boolean $selected - is tab selected
 */

function html_tab($href, $caption, $selected=false) {
    $tab = '<li>';
    if ($selected) {
        $tab .= '<strong>';
    } else {
        $tab .= '<a href="' . hsc($href) . '">';
    }
    $tab .= hsc($caption)
         .  '</' . ($selected ? 'strong' : 'a') . '>'
         .  '</li>'.NL;
    echo $tab;
}