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
|
{-# OPTIONS_CYMAKE -Wno-incomplete-patterns #-}
module HTML(HtmlExp(..),HtmlPage(..),PageParam(..),
HtmlForm(..),FormParam(..),CookieParam(..),
CgiRef(..),idOfCgiRef,CgiEnv,HtmlHandler,
defaultEncoding,
form,standardForm,answerText,answerEncText,
cookieForm,getCookies,
page,standardPage,
pageEnc,pageCSS,pageMetaInfo,pageLinkInfo,pageBodyAttr,addPageParam,
formEnc,formCSS,formMetaInfo,formBodyAttr,addFormParam,
htxt,htxts,hempty,nbsp,h1,h2,h3,h4,h5,
par,section,header,footer,emphasize,strong,bold,italic,nav,code,
center,blink,teletype,pre,verbatim,address,href,anchor,
ulist,olist,litem,dlist,table,headedTable,addHeadings,
hrule,breakline,image,
styleSheet,style,textstyle,blockstyle,inline,block,
redirect,expires,
button,resetbutton,imageButton,coordinates,
textfield,password,textarea,checkbox,checkedbox,
radio_main,radio_main_off,radio_other,
selection,selectionInitial,multipleSelection,
hiddenfield,htmlQuote,htmlIsoUmlauts,addAttr,addAttrs,addClass,
showHtmlExps,showHtmlExp,showHtmlPage,
runFormServerWithKey,runFormServerWithKeyAndFormParams,
intForm,intFormMain,
getUrlParameter,urlencoded2string,string2urlencoded,
showLatexExps,showLatexExp,showLatexDoc,showLatexDocs,
showLatexDocsWithPackages,showLatexDocWithPackages,
germanLatexDoc,htmlSpecialChars2tex,
addSound,addCookies) where
import Char
import Directory (getHomeDirectory)
import Distribution (installDir)
import HtmlCgi
import IO
import NamedSocket
import List
import Profile
import Random (getRandomSeed, nextInt)
import ReadNumeric (readNat, readHex)
import ReadShowTerm (showQTerm, readsQTerm)
import System
import Time
import Json
infixl 0 `addAttr`
infixl 0 `addAttrs`
infixl 0 `addClass`
infixl 0 `addPageParam`
infixl 0 `addFormParam`
defaultEncoding :: String
defaultEncoding = "utf-8"
data CgiRef = CgiRef String
idOfCgiRef :: CgiRef -> String
idOfCgiRef (CgiRef i) = i
type CgiEnv = CgiRef -> String
type HtmlHandler = CgiEnv -> IO HtmlForm
data HtmlExp =
HtmlText String
| HtmlStruct String [(String,String)] [HtmlExp]
| HtmlCRef HtmlExp CgiRef
| HtmlEvent HtmlExp HtmlHandler
| AjaxEvent String HtmlHandler
| AjaxEvent2 HtmlExp HtmlHandler String String
textOf :: [HtmlExp] -> String
textOf = unwords . filter (not . null) . map textOfHtmlExp
where
textOfHtmlExp (HtmlText s) = s
textOfHtmlExp (HtmlStruct _ _ hs) = textOf hs
textOfHtmlExp (HtmlCRef hexp _) = textOf [hexp]
textOfHtmlExp (HtmlEvent hexp _) = textOf [hexp]
textOfHtmlExp (AjaxEvent _ _) = ""
textOfHtmlExp (AjaxEvent2 hexp _ _ _) = textOf [hexp]
data HtmlForm =
HtmlForm String [FormParam] [HtmlExp]
| HtmlAnswer String String
| AjaxAnswer Json [([(String,String)],[HtmlExp])]
data FormParam = FormCookie String String [CookieParam]
| FormCSS String
| FormJScript String
| FormOnSubmit String
| FormTarget String
| FormEnc String
| FormMeta [(String,String)]
| HeadInclude HtmlExp
| MultipleHandlers
| BodyAttr (String,String)
formEnc :: String -> FormParam
formEnc enc = FormEnc enc
formCSS :: String -> FormParam
formCSS css = FormCSS css
formMetaInfo :: [(String,String)] -> FormParam
formMetaInfo attrs = FormMeta attrs
formBodyAttr :: (String,String) -> FormParam
formBodyAttr attr = BodyAttr attr
formCookie :: (String,String) -> FormParam
formCookie (n,v) = FormCookie n v []
data CookieParam = CookieExpire ClockTime
| CookieDomain String
| CookiePath String
| CookieSecure
form :: String -> [HtmlExp] -> HtmlForm
form title hexps = HtmlForm title [] hexps
standardForm :: String -> [HtmlExp] -> HtmlForm
standardForm title hexps = form title (h1 [htxt title] : hexps)
cookieForm :: String -> [(String,String)] -> [HtmlExp] -> HtmlForm
cookieForm t cs he = HtmlForm t (map (\(n,v)->FormCookie n v []) cs) he
addCookies :: [(String,String)] -> HtmlForm -> HtmlForm
addCookies cs (HtmlForm t fas hs) =
HtmlForm t (map (\ (n,v) -> FormCookie n v []) cs ++ fas) hs
addCookies _ (HtmlAnswer _ _) =
error "addCookies: cannot add cookie to Html answer"
formatCookie :: (String,String,[CookieParam]) -> String
formatCookie (name,value,params) =
"Set-Cookie: " ++ name ++ "=" ++ string2urlencoded value ++
concatMap (\p->"; "++formatCookieParam p) params
formatCookieParam :: CookieParam -> String
formatCookieParam (CookieExpire e) = "expires=" ++ toCookieDateString e
formatCookieParam (CookieDomain d) = "domain=" ++ d
formatCookieParam (CookiePath p) = "path=" ++ p
formatCookieParam CookieSecure = "secure"
toCookieDateString :: ClockTime -> String
toCookieDateString time =
let (CalendarTime y mo d h mi s tz) = toUTCTime time
in (show d ++ "-" ++ shortMonths!!(mo-1) ++ "-" ++ show y ++ " " ++
toTimeString (CalendarTime y mo d h mi s tz) ++ " UTC")
where shortMonths = ["Jan","Feb","Mar","Apr","May","Jun",
"Jul","Aug","Sep","Oct","Nov","Dec"]
answerText :: String -> HtmlForm
answerText = HtmlAnswer "text/plain"
answerEncText :: String -> String -> HtmlForm
answerEncText enc = HtmlAnswer ("text/plain; charset="++enc)
addFormParam :: HtmlForm -> FormParam -> HtmlForm
addFormParam (HtmlForm title params hexps) param =
HtmlForm title (param:params) hexps
addFormParam hexp@(HtmlAnswer _ _) _ = hexp
addFormParams :: HtmlForm -> [FormParam] -> HtmlForm
addFormParams hform [] = hform
addFormParams hform (fp:fps) = addFormParams (hform `addFormParam` fp) fps
redirect :: Int -> String -> HtmlForm -> HtmlForm
redirect secs url hform =
hform `addFormParam`
HeadInclude (HtmlStruct "meta" [("http-equiv","refresh"),
("content",show secs++"; URL="++url)] [])
expires :: Int -> HtmlForm -> HtmlForm
expires secs hform =
hform `addFormParam`
HeadInclude (HtmlStruct "meta" [("http-equiv","expires"),
("content",show secs)] [])
addSound :: String -> Bool -> HtmlForm -> HtmlForm
addSound soundfile loop (HtmlForm title params conts) =
HtmlForm title
(HeadInclude
(HtmlStruct "bgsound"
[("src",soundfile),
("loop",if loop then "infinite" else "1")] []):params)
(HtmlStruct "embed"
((if loop then [("loop","true")] else []) ++
[("src",soundfile),("autostart","true"), ("hidden","true"),
("height","0"), ("width","0")]) []:
conts)
addSound _ _ (HtmlAnswer _ _)
= error "HTML.addSound: unable to add sound to general HTML Answer"
data HtmlPage = HtmlPage String [PageParam] [HtmlExp]
data PageParam = PageEnc String
| PageCSS String
| PageJScript String
| PageMeta [(String,String)]
| PageLink [(String,String)]
| PageBodyAttr (String,String)
pageEnc :: String -> PageParam
pageEnc enc = PageEnc enc
pageCSS :: String -> PageParam
pageCSS css = PageCSS css
pageMetaInfo :: [(String,String)] -> PageParam
pageMetaInfo attrs = PageMeta attrs
pageLinkInfo :: [(String,String)] -> PageParam
pageLinkInfo attrs = PageLink attrs
pageBodyAttr :: (String,String) -> PageParam
pageBodyAttr attr = PageBodyAttr attr
page :: String -> [HtmlExp] -> HtmlPage
page title hexps = HtmlPage title [PageEnc defaultEncoding] hexps
standardPage :: String -> [HtmlExp] -> HtmlPage
standardPage title hexps = page title (h1 [htxt title] : hexps)
addPageParam :: HtmlPage -> PageParam -> HtmlPage
addPageParam (HtmlPage title params hexps) param =
HtmlPage title (param:params) hexps
htxt :: String -> HtmlExp
htxt s = HtmlText (htmlQuote s)
htxts :: [String] -> [HtmlExp]
htxts = map htxt
hempty :: HtmlExp
hempty = HtmlText ""
nbsp :: HtmlExp
nbsp = HtmlText " "
h1 :: [HtmlExp] -> HtmlExp
h1 hexps = HtmlStruct "h1" [] hexps
h2 :: [HtmlExp] -> HtmlExp
h2 hexps = HtmlStruct "h2" [] hexps
h3 :: [HtmlExp] -> HtmlExp
h3 hexps = HtmlStruct "h3" [] hexps
h4 :: [HtmlExp] -> HtmlExp
h4 hexps = HtmlStruct "h4" [] hexps
h5 :: [HtmlExp] -> HtmlExp
h5 hexps = HtmlStruct "h5" [] hexps
par :: [HtmlExp] -> HtmlExp
par hexps = HtmlStruct "p" [] hexps
section :: [HtmlExp] -> HtmlExp
section hexps = HtmlStruct "section" [] hexps
header :: [HtmlExp] -> HtmlExp
hexps = HtmlStruct "header" [] hexps
footer :: [HtmlExp] -> HtmlExp
hexps = HtmlStruct "footer" [] hexps
emphasize :: [HtmlExp] -> HtmlExp
emphasize hexps = HtmlStruct "em" [] hexps
strong :: [HtmlExp] -> HtmlExp
strong hexps = HtmlStruct "strong" [] hexps
bold :: [HtmlExp] -> HtmlExp
bold hexps = HtmlStruct "b" [] hexps
italic :: [HtmlExp] -> HtmlExp
italic hexps = HtmlStruct "i" [] hexps
nav :: [HtmlExp] -> HtmlExp
nav doc = HtmlStruct "nav" [] doc
code :: [HtmlExp] -> HtmlExp
code hexps = HtmlStruct "code" [] hexps
center :: [HtmlExp] -> HtmlExp
center hexps = HtmlStruct "center" [] hexps
blink :: [HtmlExp] -> HtmlExp
blink hexps = HtmlStruct "blink" [] hexps
teletype :: [HtmlExp] -> HtmlExp
teletype hexps = HtmlStruct "tt" [] hexps
pre :: [HtmlExp] -> HtmlExp
pre hexps = HtmlStruct "pre" [] hexps
verbatim :: String -> HtmlExp
verbatim s = HtmlStruct "pre" [] [HtmlText (htmlQuote s)]
address :: [HtmlExp] -> HtmlExp
address hexps = HtmlStruct "address" [] hexps
href :: String -> [HtmlExp] -> HtmlExp
href ref hexps = HtmlStruct "a" [("href",ref)] hexps
anchor :: String -> [HtmlExp] -> HtmlExp
anchor anc hexps = HtmlStruct "span" [("id",anc)] hexps
ulist :: [[HtmlExp]] -> HtmlExp
ulist items = HtmlStruct "ul" [] (map litem items)
olist :: [[HtmlExp]] -> HtmlExp
olist items = HtmlStruct "ol" [] (map litem items)
litem :: [HtmlExp] -> HtmlExp
litem hexps = HtmlStruct "li" [] hexps
dlist :: [([HtmlExp],[HtmlExp])] -> HtmlExp
dlist items = HtmlStruct "dl" [] (concatMap ditem items)
where
ditem (hexps1,hexps2) = [HtmlStruct "dt" [] hexps1,
HtmlStruct "dd" [] hexps2]
table :: [[[HtmlExp]]] -> HtmlExp
table items = HtmlStruct "table" []
(map (\row->HtmlStruct "tr" []
(map (\item -> HtmlStruct "td" [] item) row)) items)
headedTable :: [[[HtmlExp]]] -> HtmlExp
headedTable = withinTable . table
where
withinTable (HtmlStruct "table" attrs (HtmlStruct "tr" rowAttrs row:rows)) =
HtmlStruct "table" attrs
(HtmlStruct "tr" rowAttrs (map addTh row):rows)
addTh x = case x of
(HtmlStruct "td" attrs conts) -> HtmlStruct "th" attrs conts
other -> other
addHeadings :: HtmlExp -> [[HtmlExp]] -> HtmlExp
addHeadings htable headings = case htable of
HtmlStruct "table" attrs rows ->
HtmlStruct "table" attrs
(HtmlStruct "tr" [] (map (\item->HtmlStruct "th" [] item) headings):rows)
_ -> htable
hrule :: HtmlExp
hrule = HtmlStruct "hr" [] []
breakline :: HtmlExp
breakline = HtmlStruct "br" [] []
image :: String -> String -> HtmlExp
image src alt = HtmlStruct "img" [("src",src),("alt",htmlQuote alt)] []
styleSheet :: String -> HtmlExp
styleSheet css = HtmlStruct "style" [("type","text/css")] [HtmlText css]
style :: String -> [HtmlExp] -> HtmlExp
style st hexps = HtmlStruct "span" [("class",st)] hexps
textstyle :: String -> String -> HtmlExp
textstyle st txt = HtmlStruct "span" [("class",st)] [htxt txt]
blockstyle :: String -> [HtmlExp] -> HtmlExp
blockstyle st hexps = HtmlStruct "div" [("class",st)] hexps
inline :: [HtmlExp] -> HtmlExp
inline hexps = HtmlStruct "span" [] hexps
block :: [HtmlExp] -> HtmlExp
block hexps = HtmlStruct "div" [] hexps
button :: String -> HtmlHandler -> HtmlExp
button label handler =
HtmlEvent
(HtmlStruct "input" [("type","submit"),("name","EVENT"),
("value",htmlQuote label)] [])
handler
resetbutton :: String -> HtmlExp
resetbutton label =
HtmlStruct "input" [("type","reset"),("value",htmlQuote label)] []
imageButton :: String -> HtmlHandler -> HtmlExp
imageButton src handler
= HtmlEvent
(HtmlStruct "input" [("type","image"),("name","EVENT"),("src",src)] [])
handler
textfield :: CgiRef -> String -> HtmlExp
textfield cref contents
| cref =:= CgiRef ref
= HtmlCRef
(HtmlStruct "input" [("type","text"),("name",ref),
("value",htmlQuote contents)] [])
cref
where ref free
password :: CgiRef -> HtmlExp
password cref
| cref =:= CgiRef ref
= HtmlCRef
(HtmlStruct "input" [("type","password"),("name",ref)] [])
cref
where
ref free
textarea :: CgiRef -> (Int,Int) -> String -> HtmlExp
textarea cref (height,width) contents
| cref =:= CgiRef ref
= HtmlCRef
(HtmlStruct "textarea" [("name",ref),
("rows",show height),("cols",show width)]
[htxt contents])
cref
where
ref free
checkbox :: CgiRef -> String -> HtmlExp
checkbox cref value
| cref =:= CgiRef ref
= HtmlCRef
(HtmlStruct "input" [("type","checkbox"),("name",ref),
("value",htmlQuote value)] [])
cref
where
ref free
checkedbox :: CgiRef -> String -> HtmlExp
checkedbox cref value
| cref =:= CgiRef ref
= HtmlCRef
(HtmlStruct "input" [("type","checkbox"),("name",ref),
("value",htmlQuote value),("checked","checked")] [])
cref
where
ref free
radio_main :: CgiRef -> String -> HtmlExp
radio_main cref value
| cref =:= CgiRef ref
= HtmlCRef
(HtmlStruct "input" [("type","radio"),("name",ref),
("value",htmlQuote value),("checked","yes")] [])
cref
where
ref free
radio_main_off :: CgiRef -> String -> HtmlExp
radio_main_off cref value
| cref =:= CgiRef ref
= HtmlCRef
(HtmlStruct "input" [("type","radio"),("name",ref),
("value",htmlQuote value)] [])
cref
where
ref free
radio_other :: CgiRef -> String -> HtmlExp
radio_other cref value
| cref =:= CgiRef ref
= HtmlStruct "input"
[("type","radio"),("name",ref),("value",htmlQuote value)] []
where
ref free
selection :: CgiRef -> [(String,String)] -> HtmlExp
selection cref menue
| cref =:= CgiRef ref
= HtmlCRef
(HtmlStruct "select" [("name",ref)]
((concat . map (\(n,v)->[HtmlStruct "option" [("value",v)] [htxt n]]))
menue))
cref
where
ref free
selectionInitial :: CgiRef -> [(String,String)] -> Int -> HtmlExp
selectionInitial cref sellist sel
| cref =:= CgiRef ref
= HtmlCRef (HtmlStruct "select" [("name",ref)] (selOption sellist sel))
cref
where
ref free
selOption [] _ = []
selOption ((n,v):nvs) i =
HtmlStruct "option"
([("value",v)] ++ if i==0 then [("selected","selected")] else [])
[htxt n] : selOption nvs (i-1)
multipleSelection :: CgiRef -> [(String,String,Bool)] -> HtmlExp
multipleSelection cref sellist
| cref =:= CgiRef ref
= HtmlCRef (HtmlStruct "select" [("name",ref),("multiple","multiple")]
(map selOption sellist))
cref
where
ref free
selOption (n,v,flag) =
HtmlStruct "option"
([("value",v)] ++ if flag then [("selected","selected")] else [])
[htxt n]
hiddenfield :: String -> String -> HtmlExp
hiddenfield name value =
HtmlStruct "input" [("type","hidden"),("name",name),("value",value)] []
htmlQuote :: String -> String
htmlQuote [] = []
htmlQuote (c:cs) | c=='<' = "<" ++ htmlQuote cs
| c=='>' = ">" ++ htmlQuote cs
| c=='&' = "&" ++ htmlQuote cs
| c=='"' = """ ++ htmlQuote cs
| otherwise = htmlIsoUmlauts [c] ++ htmlQuote cs
htmlIsoUmlauts :: String -> String
htmlIsoUmlauts [] = []
htmlIsoUmlauts (c:cs) | oc==228 = "ä" ++ htmlIsoUmlauts cs
| oc==246 = "ö" ++ htmlIsoUmlauts cs
| oc==252 = "ü" ++ htmlIsoUmlauts cs
| oc==196 = "Ä" ++ htmlIsoUmlauts cs
| oc==214 = "Ö" ++ htmlIsoUmlauts cs
| oc==220 = "Ü" ++ htmlIsoUmlauts cs
| oc==223 = "ß" ++ htmlIsoUmlauts cs
| oc==197 = "Å" ++ htmlIsoUmlauts cs
| oc==250 = "ú"++ htmlIsoUmlauts cs
| oc==237 = "í"++ htmlIsoUmlauts cs
| oc==225 = "á"++ htmlIsoUmlauts cs
| otherwise = c : htmlIsoUmlauts cs
where oc = ord c
addAttr :: HtmlExp -> (String,String) -> HtmlExp
addAttr hexp attr = addAttrs hexp [attr]
addAttrs :: HtmlExp -> [(String,String)] -> HtmlExp
addAttrs (HtmlText s) _ = HtmlText s
addAttrs (HtmlStruct tag attrs hexps) newattrs =
HtmlStruct tag (attrs++newattrs) hexps
addAttrs (HtmlEvent hexp handler) attrs =
HtmlEvent (addAttrs hexp attrs) handler
addAttrs (HtmlCRef hexp cref) attrs =
HtmlCRef (addAttrs hexp attrs) cref
addAttrs (AjaxEvent id handler) _ = AjaxEvent id handler
addAttrs (AjaxEvent2 hexp handler str1 str2) attrs =
AjaxEvent2 (addAttrs hexp attrs) handler str1 str2
addClass :: HtmlExp -> String -> HtmlExp
addClass hexp cls = addAttr hexp ("class",cls)
type ShowS = String -> String
showString :: String -> String -> String
showString s = (s++)
showChar :: Char -> String -> String
showChar c = (c:)
nl :: String -> String
nl = showChar '\n'
concatS :: [a -> a] -> a -> a
concatS [] = id
concatS xs@(_:_) = foldr1 (\ f g -> f . g) xs
showHtmlExps :: [HtmlExp] -> String
showHtmlExps hexps = showsHtmlExps 0 hexps ""
getText :: HtmlExp -> String
getText (HtmlText s) = s
getText (HtmlStruct _ _ _) = ""
getText (HtmlEvent he _) = getText he
getText (HtmlCRef he _) = getText he
getText (AjaxEvent _ _) = ""
getText (AjaxEvent2 _ _ _ _) = ""
getTag :: HtmlExp -> String
getTag (HtmlText _) = ""
getTag (HtmlStruct tag _ _) = tag
getTag (HtmlEvent he _) = getTag he
getTag (HtmlCRef he _) = getTag he
getTag (AjaxEvent _ _) = ""
getTag (AjaxEvent2 _ _ _ _) = ""
tagWithLn :: String -> Bool
tagWithLn t = t/="" &&
t `elem` ["br","p","li","ul","ol","dl","dt","dd","hr",
"h1","h2","h3","h4","h5","h6","div",
"html","title","head","body","link","meta","script",
"form","table","tr","td"]
showHtmlExp :: HtmlExp -> String
showHtmlExp hexp = showsHtmlExp 0 hexp ""
noEndTags :: [String]
noEndTags = ["img","input","link","meta"]
showsHtmlExp :: Int -> HtmlExp -> ShowS
showsHtmlExp _ (HtmlText s) = showString s
showsHtmlExp i (HtmlStruct tag attrs hexps) =
let maybeLn j = if tagWithLn tag then nl . showTab j else id
in maybeLn i .
(if null hexps && (null attrs || tag `elem` noEndTags)
then showsHtmlOpenTag tag attrs "/>"
else showsHtmlOpenTag tag attrs ">" . maybeLn (i+2) . showExps hexps .
maybeLn i . showString "</" . showString tag . showChar '>'
) . maybeLn i
where
showExps = if tag=="pre"
then concatS . map (showsHtmlExp 0) else showsHtmlExps (i+2)
showsHtmlExp i (HtmlEvent hexp _) = showsHtmlExp i hexp
showsHtmlExp i (HtmlCRef hexp _) = showsHtmlExp i hexp
showsHtmlExp _ (AjaxEvent _ _) = showString ""
showsHtmlExp _ (AjaxEvent2 _ _ _ _) = showString ""
showsHtmlExps :: Int -> [HtmlExp] -> ShowS
showsHtmlExps _ [] = id
showsHtmlExps i (he:hes) = showsWithLnPrefix he . showsHtmlExps i hes
where
showsWithLnPrefix hexp = let s = getText hexp
in if s/="" && isSpace (head s)
then nl . showTab i . showString (tail s)
else showsHtmlExp i hexp
showTab :: Int -> String -> String
showTab n = showString (take n (repeat ' '))
showsHtmlOpenTag :: String -> [(String,String)] -> String -> ShowS
showsHtmlOpenTag tag attrs close =
showChar '<' . showString tag .
concatS (map attr2string attrs) . showString close
where
attr2string (attr,value) = showChar ' ' . showString attr .
showString "=\"" . encodeQuotes value . showChar '"'
encodeQuotes [] = id
encodeQuotes (c:cs) | c=='"' = showString """ . encodeQuotes cs
| otherwise = showChar c . encodeQuotes cs
showHtmlPage :: HtmlPage -> String
showHtmlPage (HtmlPage title params html) =
htmlPrelude ++
showHtmlExp (HtmlStruct "html" htmlTagAttrs
[HtmlStruct "head" []
([HtmlStruct "title" [] [HtmlText (htmlQuote title)]] ++
concatMap param2html params),
HtmlStruct "body" bodyattrs html])
where
param2html (PageEnc enc) =
[HtmlStruct "meta" [("http-equiv","Content-Type"),
("content","text/html; charset="++enc)] []]
param2html (PageCSS css) =
[HtmlStruct "link" [("rel","stylesheet"),("type","text/css"),("href",css)]
[]]
param2html (PageJScript js) =
[HtmlStruct "script" [("type","text/javascript"),("src",js)] []]
param2html (PageMeta attrs) = [HtmlStruct "meta" attrs []]
param2html (PageLink attrs) = [HtmlStruct "link" attrs []]
param2html (PageBodyAttr _) = []
bodyattrs = [attr | (PageBodyAttr attr) <- params]
htmlPrelude :: String
htmlPrelude = "<!DOCTYPE html>\n"
htmlTagAttrs :: [(String,String)]
htmlTagAttrs = [("lang","en")]
getUrlParameter :: IO String
getUrlParameter = getEnviron "QUERY_STRING"
urlencoded2string :: String -> String
urlencoded2string [] = []
urlencoded2string (c:cs)
| c == '+' = ' ' : urlencoded2string cs
| c == '%' = chr (maybe 0 fst (readHex (take 2 cs)))
: urlencoded2string (drop 2 cs)
| otherwise = c : urlencoded2string cs
string2urlencoded :: String -> String
string2urlencoded [] = []
string2urlencoded (c:cs)
| isAlphaNum c = c : string2urlencoded cs
| c == ' ' = '+' : string2urlencoded cs
| otherwise = let oc = ord c
in '%' : int2hex(oc `div` 16) : int2hex(oc `mod` 16) : string2urlencoded cs
where
int2hex i = if i<10 then chr (ord '0' + i)
else chr (ord 'A' + i - 10)
getCookies :: IO [(String,String)]
getCookies =
do cookiestring <- getEnviron "HTTP_COOKIE"
return $ parseCookies cookiestring
parseCookies :: String -> [(String,String)]
parseCookies str = if str=="" then [] else
let (c1,cs) = break (==';') str
in parseCookie c1 :
parseCookies (dropWhile (==' ') (if cs=="" then "" else tail cs))
where
parseCookie s = let (name,evalue) = break (=='=') s in
(name,if evalue=="" then "" else urlencoded2string (tail evalue))
coordinates :: CgiEnv -> Maybe (Int,Int)
coordinates env = let x = env (CgiRef "x")
y = env (CgiRef "y")
in if x/="" && y/=""
then Just (tryReadNat 0 x, tryReadNat 0 y)
else Nothing
runFormServerWithKey :: String -> String -> IO HtmlForm -> IO ()
runFormServerWithKey url cgikey hformact =
runFormServerWithKeyAndFormParams url cgikey [] hformact
runFormServerWithKeyAndFormParams :: String -> String -> [FormParam]
-> IO HtmlForm -> IO ()
runFormServerWithKeyAndFormParams url cgikey formparams hformact = do
args <- getArgs
let (timeout,rargs) = stripTimeoutArg args
case rargs of
["-port",port,"-scriptkey",skey] -> startCgiServer timeout port skey
_ -> putErrLn $ "ERROR: cgi server called with illegal arguments"
where
stripTimeoutArg args = case args of
("-servertimeout":tos:rargs) ->
(tryReadNat defaultCgiServerTimeout tos, rargs)
_ -> (defaultCgiServerTimeout,args)
startCgiServer timeout port scriptkey = do
time <- getClockTime
ltime <- toCalendarTime time
(state,htmlstring) <- computeFormInStateAndEnv url cgikey formparams
(initialServerState time) scriptkey hformact []
putStr htmlstring
hClose stdout
if isServerStateWithoutHandlers state
then done
else
do let portname = port++scriptkey
socket <- listenOn portname
putErrLn $ calendarTimeToString ltime ++
": server started on port " ++ portname
registerCgiServer url portname
serveCgiMessagesForForm timeout url cgikey portname formparams
hformact socket state
defaultCgiServerTimeout :: Int
defaultCgiServerTimeout = 7200000
serveCgiMessagesForForm :: Int -> String -> String -> String -> [FormParam]
-> IO HtmlForm -> Socket -> ServerState -> IO ()
serveCgiMessagesForForm servertimeout url cgikey portname
fparams initform socket = serveCgiMessages
where
serveCgiMessages state =
if isServerStateWithoutHandlers state
then do
ltime <- getLocalTime
putErrLn $ calendarTimeToString ltime ++
": terminated due to empty handler list"
unregisterCgiServer portname
sClose socket
else waitForSocketAccept socket servertimeout >>=
maybe (do
ltime <- getLocalTime
putErrLn $ calendarTimeToString ltime ++
": terminated due to timeout"
unregisterCgiServer portname
sClose socket )
(\ (rhost,hdl) -> do
hostname <- getHostname
if rhost `elem` ["localhost","localhost.localdomain",hostname]
|| take 8 rhost == "127.0.0."
then readCgiServerMsg hdl >>=
maybe (hClose hdl >> serveCgiMessages state)
(serveCgiMessage state hdl)
else putErrLn ("Ignored message from: "++rhost) >>
hClose hdl >> serveCgiMessages state )
serveCgiMessage _ hdl StopCgiServer = do
hClose hdl
ltime <- getLocalTime
putErrLn $ calendarTimeToString ltime ++
": server terminated by stop message"
unregisterCgiServer portname
sClose socket
serveCgiMessage state hdl CleanServer = do
hClose hdl
nstate <- cleanOldEventHandlers state
serveCgiMessages nstate
serveCgiMessage oldstate hdl GetLoad = do
state <- cleanOldEventHandlers oldstate
serverload <- getServerLoad state
hPutStrLn hdl serverload
hClose hdl
serveCgiMessages state
serveCgiMessage oldstate hdl SketchStatus = do
state <- cleanOldEventHandlers oldstate
serverstatus <- getServerStatus state
hPutStrLn hdl serverstatus
hClose hdl
serveCgiMessages state
serveCgiMessage state hdl SketchHandlers =
reportStatus state hdl sketchEventHandler
where
sketchEventHandler (key,time,_,_,gkey) = do
ltime <- toCalendarTime time
return $ "No. " ++ show key ++ " (" ++ showGroupKey gkey ++
"), expires at: " ++
calendarTimeToString ltime ++ "\n"
serveCgiMessage state hdl ShowStatus =
reportStatus state hdl showEventHandler
where
showEventHandler (key,time,_,(_,_),gkey) = do
ltime <- toCalendarTime time
return $ "No. " ++ show key ++ " (" ++ showGroupKey gkey ++
"), expires at " ++
calendarTimeToString ltime ++ ": " ++
"<sorry, can't show handler>\n"
serveCgiMessage state hdl (CgiSubmit scriptenv formenv) = do
let scriptkey = maybe "" id (lookup "SCRIPTKEY" scriptenv)
mapIO_ (\(var,val) -> if var=="SCRIPTKEY" then done
else setEnviron var val)
scriptenv
if null formenv
then serveFormInEnv state scriptkey initform []
else do
(rstate,mfe) <- getNextFormAndCgiEnv state cgikey formenv
maybe (do urlparam <- getUrlParameter
hPutStrLn hdl (noHandlerPage url urlparam)
hClose hdl
serveCgiMessages rstate)
(\ (ioform,env) -> serveFormInEnv rstate scriptkey ioform env )
mfe
where
serveFormInEnv rstate scriptkey hformact cenv = do
(nstate,htmlstring) <- computeFormInStateAndEnv url cgikey fparams
rstate scriptkey hformact cenv
hPutStrLn hdl htmlstring
hClose hdl
serveCgiMessages nstate
reportStatus state@(stime,maxkey,ctime,ehs) hdl eh2string = do
lstime <- toCalendarTime stime
lctime <- toCalendarTime ctime
ehsstrings <- mapIO eh2string ehs
hPutStrLn hdl $ "Started at: " ++ calendarTimeToString lstime ++ "\n" ++
"Next cleanup: " ++ calendarTimeToString lctime ++
" (maxkey: " ++ show maxkey ++")\n"++
"Current event handlers:\n" ++ concat ehsstrings
hClose hdl
serveCgiMessages state
computeFormInStateAndEnv
:: String -> String -> [FormParam] -> ServerState -> String
-> IO HtmlForm -> [(String,String)] -> IO (ServerState,String)
computeFormInStateAndEnv url cgikey fparams state scriptkey hformact cenv =
catch tryComputeForm
(\e -> do uparam <- getUrlParameter
return (state,errorAsHtml e uparam))
where
errorAsHtml e urlparam = addHtmlContentType $ showHtmlPage $
page "Server Error"
[h1 [htxt "Error: Failure during computation"],
par [htxt "Your request cannot be processed due to a run-time error:"],
pre [htxt (showError e)],
par [htxt "You can try to ",
href (url ++ if null urlparam then "" else '?':urlparam)
[htxt "click here"],
htxt " to try again loading the web page or inform the web ",
htxt "administrator about this problem."]]
tryComputeForm = do
cform <- hformact
let (cookiestring,hform) = extractCookies cform
(htmlstring,evhs) <- showAnswerFormInEnv url scriptkey
(addFormParams hform fparams)
(getMaxFieldNr cenv + 1)
nstate <- storeEnvHandlers state
(formWithMultipleHandlers hform)
(encodeKey cgikey)
(filter (\ (t,_) -> t/="DEFAULT" && take 6 t /= "EVENT_") cenv)
evhs
seq (isList htmlstring) done
return (nstate, cookiestring++htmlstring)
isList [] = True
isList (_:xs) = isList xs
formWithMultipleHandlers :: HtmlForm -> Bool
formWithMultipleHandlers (HtmlAnswer _ _) = False
formWithMultipleHandlers (HtmlForm _ params _) = any isMultipleHandlers params
where
isMultipleHandlers formparam =
case formparam of MultipleHandlers -> True
_ -> False
formWithMultipleHandlers (AjaxAnswer _ _) = True
encodeKey :: String -> String
encodeKey = map mapchr . reverse . filter (not . isSpace)
where
mapchr c | oc<33 || oc>126 = c
| oc<114 = chr (oc+13)
| otherwise = chr (oc-81)
where oc = ord c
putErrLn :: String -> IO ()
putErrLn s = hPutStrLn stderr s >> hFlush stderr
getNextFormAndCgiEnv :: ServerState -> String -> [(String,String)]
-> IO (ServerState, Maybe (IO HtmlForm,[(String,String)]))
getNextFormAndCgiEnv state cgikey newcenv = do
(nstate,mbh) <- retrieveEnvHandlers state (encodeKey cgikey)
(urlencoded2string (getFormEvent "" newcenv))
return $ maybe (nstate,Nothing)
(\ (oldcenv,handler) -> let cenv = newcenv++oldcenv in
(nstate, Just (handler (cgiGetValue cenv), cenv)))
mbh
showAnswerFormInEnv :: String -> String -> HtmlForm -> Int
-> IO (String,[(HtmlHandler,String)])
showAnswerFormInEnv url key hform@(HtmlForm _ _ _) crefnr = do
(htmlstring,evhs) <- showHtmlFormInEnv url key hform crefnr
return (addHtmlContentType htmlstring, evhs)
showAnswerFormInEnv _ _ (HtmlAnswer ctype cont) _ = do
return ("Content-Length: " ++ show (length cont) ++
"\nContent-Type: "++ctype++"\n\n"++cont, [])
showAnswerFormInEnv _ _ (AjaxAnswer cont nvsAndhexps) crefnr = do
(pairs,evhs) <- converttohtml ([],[]) nvsAndhexps crefnr
let jsonpairs = map (\ (nvs,html) ->
Object ((map (\ (n,v) -> (n,String v)) nvs) ++
[("html",String html)]) ) pairs
return ("Content-Type: text/json\n\n" ++
(showJson $ Object [("content",cont),("popups",Array jsonpairs)]),evhs)
converttohtml :: ([(a,String)],[(HtmlHandler,String)])
-> [(a, [HtmlExp])] -> Int
-> IO ([(a, String)], [(HtmlHandler,String)])
converttohtml (xs,evhs) [] _ = return (xs,evhs)
converttohtml (xs,evhs) ((nvs,hexp):ys) crefnr = do
(htmlstring,newevhs,newrefnr) <- htmlForm2html_ hexp crefnr
converttohtml ((nvs,(showHtmlExps htmlstring)):xs,evhs++newevhs) ys newrefnr
htmlForm2html_ :: [HtmlExp] -> Int
-> IO ([HtmlExp],[(HtmlHandler,String)],Int)
htmlForm2html_ html crefnr = do
let (htmlwithoutcrefs,newrefnr) = numberCgiRefs html crefnr
seq newrefnr done
let (transhtml, evhs, _) = translateHandlers htmlwithoutcrefs
return (transhtml, evhs, newrefnr)
addHtmlContentType :: String -> String
addHtmlContentType htmlstring =
"Content-Length: " ++ show (length htmlstring) ++ "\n" ++
"Content-Type: text/html\n\n" ++ htmlstring
showHtmlFormInEnv :: String -> String -> HtmlForm -> Int
-> IO (String,[(HtmlHandler,String)])
showHtmlFormInEnv url key (HtmlForm ftitle fparams fhexp) crefnr = do
qstr <- getEnviron "QUERY_STRING"
(title,params,hexps,firsthandler,evhs) <-
htmlForm2html (HtmlForm ftitle fparams fhexp) crefnr
return (showForm (if null evhs
then []
else [("SCRIPTKEY",key),("DEFAULT","EVENT_"++firsthandler)])
(if qstr=="" then url else url++"?"++qstr)
(HtmlForm title params hexps),
evhs)
extractCookies :: HtmlForm -> (String,HtmlForm)
(HtmlAnswer ctype cont) = ("",HtmlAnswer ctype cont)
extractCookies (HtmlForm title params hexp) =
let cookiestring = if null cookies
then ""
else "Cache-control: no-cache=\"set-cookie\"\n" ++
concatMap ((++"\n") . formatCookie) cookies
in (cookiestring, HtmlForm title otherparams hexp)
where
(cookies,otherparams) = splitFormParams params
splitFormParams [] = ([],[])
splitFormParams (fparam:fps) =
let (cs,ops) = splitFormParams fps
in case fparam of
FormCookie n v ps -> ((n,v,ps):cs,ops)
_ -> (cs,fparam:ops)
extractCookies (AjaxAnswer x y) = ("",AjaxAnswer x y)
getFormEvent :: String -> [(String,String)] -> String
getFormEvent deflt [] = deflt
getFormEvent deflt ((tag,val):tvs) =
if tag == "DEFAULT" then getFormEvent (drop 6 val) tvs else
if take 6 tag == "EVENT_" then urlencoded2string (drop 6 tag)
else getFormEvent deflt tvs
getMaxFieldNr :: [(String,String)] -> Int
getMaxFieldNr [] = 0
getMaxFieldNr ((name,_):env) =
if take 6 name == "FIELD_"
then max (tryReadNat 0 (drop 6 name)) (getMaxFieldNr env)
else getMaxFieldNr env
tryReadNat :: Int -> String -> Int
tryReadNat d s = maybe d (\(i,rs)->if null rs then i else d) (readNat s)
cgiGetValue :: [(String,String)] -> CgiRef -> String
cgiGetValue cenv (CgiRef ref) =
concat (intersperse "\n" (map snd (filter ((ref==) . fst) cenv)))
htmlForm2html :: HtmlForm -> Int
-> IO (String,[FormParam],[HtmlExp],String,[(HtmlHandler,String)])
htmlForm2html (HtmlForm title params html) crefnr = do
let (htmlwithoutcrefs,newrefnr) = numberCgiRefs html crefnr
seq newrefnr done
let (transhtml, evhs, fh) = translateHandlers htmlwithoutcrefs
return (title, params, transhtml, fh, evhs)
numberCgiRefs :: [HtmlExp] -> Int -> ([HtmlExp],Int)
numberCgiRefs [] i = ([],i)
numberCgiRefs (HtmlText s : hexps) i =
case numberCgiRefs hexps i of
(nhexps,j) -> (HtmlText s : nhexps, j)
numberCgiRefs (HtmlStruct tag attrs hexps1 : hexps2) i =
case numberCgiRefs hexps1 i of
(nhexps1,j) -> case numberCgiRefs hexps2 j of
(nhexps2,k) -> (HtmlStruct tag attrs nhexps1 : nhexps2, k)
numberCgiRefs (HtmlEvent (HtmlStruct tag attrs hes) handler : hexps) i =
case numberCgiRefs hexps i of
(nhexps,j) -> (HtmlEvent (HtmlStruct tag attrs hes) handler : nhexps, j)
numberCgiRefs (HtmlCRef hexp (CgiRef ref) : hexps) i
| ref =:= ("FIELD_"++show i)
= case numberCgiRefs [hexp] (i+1) of
([nhexp],j) -> case numberCgiRefs hexps j of
(nhexps,k) -> (nhexp : nhexps, k)
numberCgiRefs (AjaxEvent id handler: hexps) i =
let (nhexps,j) = numberCgiRefs hexps i
in (AjaxEvent id handler : nhexps, j)
numberCgiRefs (AjaxEvent2 hexp handler str1 str2 : hexps) i =
let (nhexps1,j) = numberCgiRefs [hexp] i
(nhexps2,k) = numberCgiRefs hexps j
in (AjaxEvent2 (head nhexps1) handler str1 str2 : nhexps2, k)
translateHandlers :: [HtmlExp] -> ([HtmlExp],[(HtmlHandler,String)],String)
translateHandlers [] = ([],[],"")
translateHandlers (HtmlText s : hexps) =
let (nhexps,evhs,fh) = translateHandlers hexps
in (HtmlText s : nhexps, evhs, fh)
translateHandlers (HtmlStruct tag attrs hexps1 : hexps2) =
let (nhexps1,evhs1,fh1) = translateHandlers hexps1
(nhexps2,evhs2,fh2) = translateHandlers hexps2
in (HtmlStruct tag attrs nhexps1 : nhexps2, evhs1++evhs2,
if fh1=="" then fh2 else fh1)
translateHandlers (HtmlEvent (HtmlStruct tag attrs hes) handler : hexps) =
let (nhexps,evhs,_) = translateHandlers hexps
fh = string2urlencoded key
in (HtmlStruct tag (changeAssoc attrs "name" ("EVENT_" ++ fh)) hes : nhexps,
(handler,key):evhs, fh)
where key free
translateHandlers (AjaxEvent key handler : hexps) =
let (nhexps,evhs,_) = translateHandlers hexps
fh = string2urlencoded key
in (nhexps, (handler,key):evhs, fh)
translateHandlers (AjaxEvent2 hexp handler str1 str2 : hexps) =
let (nhexps1,evhs1,_) = translateHandlers [hexp]
(nhexps2,evhs2,_) = translateHandlers hexps
fh = string2urlencoded key
changeAttr (HtmlStruct tag attrs hes) =
if null str2
then HtmlStruct tag (changeAssoc attrs str1 ("EVENT_" ++ fh)) hes
else HtmlStruct tag
(changeAssoc attrs str1
(str2 ++ "(event,window,'EVENT_" ++ fh ++ "');")) hes
changeAttr (AjaxEvent2 he hdlr s1 s2) =
AjaxEvent2 (changeAttr he) hdlr s1 s2
changeAttr (HtmlEvent he hdlr) = HtmlEvent (changeAttr he) hdlr
in (changeAttr (head nhexps1) : nhexps2,(handler,key):evhs1++evhs2, fh)
where key free
showForm :: [(String,String)] -> String -> HtmlForm -> String
showForm cenv url (HtmlForm title params html) =
htmlPrelude ++
showHtmlExp
(HtmlStruct "html" htmlTagAttrs
[HtmlStruct "head" []
([HtmlStruct "title" [] [HtmlText (htmlQuote title)]] ++
concatMap param2html paramsWithEncoding),
HtmlStruct "body" bodyattrs
((if null url || null cenv then id
else \he->[HtmlStruct "form"
([("method","post"),("action",url)]
++ onsubmitattr ++ targetattr)
he])
(
cenv2hidden cenv ++
html))])
where
paramsWithEncoding = if null [e | (FormEnc e) <- params]
then FormEnc defaultEncoding : params
else params
param2html (FormEnc enc) =
[HtmlStruct "meta" [("http-equiv","Content-Type"),
("content","text/html; charset="++enc)] []]
param2html (FormCSS css) =
[HtmlStruct "link" [("rel","stylesheet"),("type","text/css"),("href",css)]
[]]
param2html (FormMeta attrs) = [HtmlStruct "meta" attrs []]
param2html (FormJScript js) =
[HtmlStruct "script" [("type","text/javascript"),("src",js)] []]
param2html (FormOnSubmit _) = []
param2html (FormTarget _) = []
param2html (HeadInclude hexp) = [hexp]
param2html MultipleHandlers = []
param2html (BodyAttr _) = []
bodyattrs = [ps | (BodyAttr ps) <- params]
onsubmit = [s | (FormOnSubmit s) <- params]
onsubmitattr = if null onsubmit then [] else [("onsubmit",head onsubmit)]
target = [s | (FormTarget s) <- params]
targetattr = if null target then [] else [("target",head target)]
env2html :: [(String,String)] -> [HtmlExp]
env2html env = concat (map (\(n,v)->[htxt (n++": "++v),breakline]) env)
cenv2hidden :: [(String,String)] -> [HtmlExp]
cenv2hidden env = concat (map pair2hidden env)
where
pair2hidden (n,v)
| take 6 n == "EVENT_" = []
| take 6 n == "FIELD_" = [hiddenfield ('U':n) (string2urlencoded v)]
| otherwise = [hiddenfield n v]
changeAssoc :: [(tt,tv)] -> tt -> tv -> [(tt,tv)]
changeAssoc [] tag val = [(tag,val)]
changeAssoc ((tag1,val1):tvs) tag val =
if tag1 == tag then (tag,val) : tvs
else (tag1,val1) : changeAssoc tvs tag val
showLatexExps :: [HtmlExp] -> String
showLatexExps hexps = concat (map showLatexExp hexps)
showLatexExp :: HtmlExp -> String
showLatexExp (HtmlText s) = "{" ++ specialchars2tex s ++ "}"
showLatexExp (HtmlStruct tag attrs htmlexp)
| tag=="html" = showLatexExps htmlexp
| tag=="head" = ""
| tag=="body" = showLatexExps htmlexp
| tag=="form" = showLatexExps htmlexp
| tag=="h1" = "\\section*{" ++ showLatexExps htmlexp ++ "}\n"
| tag=="h2" = "\\subsection*{" ++ showLatexExps htmlexp ++ "}\n"
| tag=="h3" = "\\subsubsection*{" ++ showLatexExps htmlexp ++ "}\n"
| tag=="h4" = "\\paragraph*{" ++ showLatexExps htmlexp ++ "}\n"
| tag=="h5" = "\\subparagraph*{" ++ showLatexExps htmlexp ++ "}\n"
| tag=="p" = showLatexExps htmlexp ++ "\\par\n"
| tag=="b" = "{\\bf " ++ showLatexExps htmlexp ++ "}"
| tag=="em" = "\\emph{" ++ showLatexExps htmlexp ++ "}"
| tag=="i" = "{\\it " ++ showLatexExps htmlexp ++ "}"
| tag=="tt" = "{\\tt " ++ showLatexExps htmlexp ++ "}"
| tag=="code" = "{\\tt " ++ showLatexExps htmlexp ++ "}"
| tag=="center" = latexEnvironment "center" (showLatexExps htmlexp)
| tag=="pre" = latexEnvironment "verbatim" (textOf htmlexp)
| tag=="font" = showLatexExps htmlexp
| tag=="address" = showLatexExps htmlexp
| tag=="blink" = showLatexExps htmlexp
| tag=="sub" = "$_{\\mbox{" ++ showLatexExps htmlexp ++ "}}$"
| tag=="sup" = "$^{\\mbox{" ++ showLatexExps htmlexp ++ "}}$"
| tag=="a" = showLatexExps htmlexp ++
maybe ""
(\url->"\\footnote{\\tt "++specialchars2tex url++"}\n")
(findHtmlAttr "href" attrs)
| tag=="ul" = latexEnvironment "itemize" (showLatexExps htmlexp)
| tag=="ol" = latexEnvironment "enumerate" (showLatexExps htmlexp)
| tag=="li" = "\\item\n" ++ showLatexExps htmlexp ++ "\n"
| tag=="dl" = latexEnvironment "description" (showLatexExps htmlexp)
| tag=="dt" = "\\item[" ++ showLatexExps htmlexp ++ "]~\\\\\n"
| tag=="dd" = showLatexExps htmlexp
| tag=="table" = attrLatexEnv "longtable" (latexTabFormat htmlexp)
(showLatexTableContents htmlexp)
| tag=="tr" = let cells = map showLatexExp htmlexp
in concat (intersperse " & " cells) ++ "\\\\\n"
| tag=="td" = showLatexExps htmlexp
| tag=="br" = "\\par\n"
| tag=="hr" = "\\vspace{2ex}\\hrule\n"
| tag=="img" = "{" ++ maybe "{\\tt<IMAGE>}" specialchars2tex
(findHtmlAttr "alt" attrs)
++ "}"
| tag=="input" && maybe "" id (findHtmlAttr "type" attrs) == "hidden" = ""
| otherwise = "{\\tt<"++tag++">}" ++ showLatexExps htmlexp ++
"{\\tt</"++tag++">}"
latexEnvironment :: String -> String -> String
latexEnvironment env content = attrLatexEnv env "" content
attrLatexEnv :: String -> String -> String -> String
attrLatexEnv env attr content
= "\\begin{"++env++"}"++attr++"\n"
++content
++"\n\\end{"++env++"}\n"
latexTabFormat :: [HtmlExp] -> String
latexTabFormat rows = "{" ++ replicate breadth 'l' ++ "}"
++ "\\setcounter{LTchunksize}{"++show (length rows+5)++"}%"
where
breadth = foldl max 0 (map getBreadth rows)
getBreadth :: HtmlExp -> Int
getBreadth row = case row of
HtmlStruct "tr" _ tds -> length tds
_ -> error "getBreadth: no row given"
showLatexTableContents :: [HtmlExp] -> String
showLatexTableContents hexps = concatMap showLatexTableContent hexps
showLatexTableContent :: HtmlExp -> String
showLatexTableContent (HtmlText s) = "{" ++ specialchars2tex s ++ "}"
showLatexTableContent (HtmlStruct tag attrs htmlexp)
| tag=="html" = showLatexTableContents htmlexp
| tag=="head" = ""
| tag=="body" = showLatexTableContents htmlexp
| tag=="form" = showLatexTableContents htmlexp
| tag=="p" = showLatexTableContents htmlexp ++ "\\par\n"
| tag=="b" = "{\\bf " ++ showLatexTableContents htmlexp ++ "}"
| tag=="em" = "\\emph{" ++ showLatexTableContents htmlexp ++ "}"
| tag=="i" = "{\\it " ++ showLatexTableContents htmlexp ++ "}"
| tag=="tt" = "{\\tt " ++ showLatexTableContents htmlexp ++ "}"
| tag=="font" = showLatexTableContents htmlexp
| tag=="address" = showLatexTableContents htmlexp
| tag=="blink" = showLatexTableContents htmlexp
| tag=="a" = showLatexTableContents htmlexp ++
maybe ""
(\url->"\\footnote{\\tt "++specialchars2tex url++"}\n")
(findHtmlAttr "href" attrs)
| tag=="tr" = let cells = map showLatexTableContent htmlexp
in concat (intersperse " & " cells) ++ "\\\\\n"
| tag=="td" = showLatexTableContents htmlexp
| tag=="br" = "\\par\n"
| tag=="hr" = "\\vspace{2ex}\\hrule\n"
| tag=="img" = "{" ++ maybe "{\\tt<IMAGE>}" specialchars2tex
(findHtmlAttr "alt" attrs)
++ "}"
| tag=="input" && maybe "" id (findHtmlAttr "type" attrs) == "hidden" = ""
| otherwise = "{\\tt<"++tag++">}" ++ showLatexTableContents htmlexp ++
"{\\tt</"++tag++">}"
findHtmlAttr :: String -> [(String,String)] -> Maybe String
findHtmlAttr _ [] = Nothing
findHtmlAttr atag ((t,f):attrs) =
if atag==t then Just f
else findHtmlAttr atag attrs
specialchars2tex :: String -> String
specialchars2tex = htmlSpecialChars2tex . escapeLaTeXSpecials
escapeLaTeXSpecials :: String -> String
escapeLaTeXSpecials [] = []
escapeLaTeXSpecials (c:cs)
| c=='^' = "{\\tt\\char94}" ++ escapeLaTeXSpecials cs
| c=='~' = "{\\tt\\char126}" ++ escapeLaTeXSpecials cs
| c=='\\' = "{\\textbackslash}" ++ escapeLaTeXSpecials cs
| c=='<' = "{\\tt\\char60}" ++ escapeLaTeXSpecials cs
| c=='>' = "{\\tt\\char62}" ++ escapeLaTeXSpecials cs
| c=='_' = "\\_" ++ escapeLaTeXSpecials cs
| c=='#' = "\\#" ++ escapeLaTeXSpecials cs
| c=='$' = "\\$" ++ escapeLaTeXSpecials cs
| c=='%' = "\\%" ++ escapeLaTeXSpecials cs
| c=='{' = "\\{" ++ escapeLaTeXSpecials cs
| c=='}' = "\\}" ++ escapeLaTeXSpecials cs
| otherwise = c : escapeLaTeXSpecials cs
htmlSpecialChars2tex :: String -> String
htmlSpecialChars2tex [] = []
htmlSpecialChars2tex (c:cs)
| c==chr 228 = "{\\\"a}" ++ htmlSpecialChars2tex cs
| c==chr 246 = "{\\\"o}" ++ htmlSpecialChars2tex cs
| c==chr 252 = "{\\\"u}" ++ htmlSpecialChars2tex cs
| c==chr 196 = "{\\\"A}" ++ htmlSpecialChars2tex cs
| c==chr 214 = "{\\\"O}" ++ htmlSpecialChars2tex cs
| c==chr 220 = "{\\\"U}" ++ htmlSpecialChars2tex cs
| c==chr 223 = "{\\ss}" ++ htmlSpecialChars2tex cs
| c=='&' = let (special,rest) = break (==';') cs
in if null rest
then "\\&" ++ htmlSpecialChars2tex special
else htmlspecial2tex special ++
htmlSpecialChars2tex (tail rest)
| otherwise = c : htmlSpecialChars2tex cs
htmlspecial2tex :: String -> String
htmlspecial2tex special
| special=="Auml" = "{\\\"A}"
| special=="Euml" = "{\\\"E}"
| special=="Iuml" = "{\\\"I}"
| special=="Ouml" = "{\\\"O}"
| special=="Uuml" = "{\\\"U}"
| special=="auml" = "{\\\"a}"
| special=="euml" = "{\\\"e}"
| special=="iuml" = "{\\\"\\i}"
| special=="ouml" = "{\\\"o}"
| special=="uuml" = "{\\\"u}"
| special=="szlig" = "{\\ss}"
| special=="Aacute" = "{\\'A}"
| special=="Eacute" = "{\\'E}"
| special=="Iacute" = "{\\'I}"
| special=="Oacute" = "{\\'O}"
| special=="Uacute" = "{\\'U}"
| special=="aacute" = "{\\'a}"
| special=="eacute" = "{\\'e}"
| special=="iacute" = "{\\'\\i}"
| special=="oacute" = "{\\'o}"
| special=="uacute" = "{\\'u}"
| special=="Agrave" = "{\\`A}"
| special=="Egrave" = "{\\`E}"
| special=="Igrave" = "{\\`I}"
| special=="Ograve" = "{\\`O}"
| special=="Ugrave" = "{\\`U}"
| special=="agrave" = "{\\`a}"
| special=="egrave" = "{\\`e}"
| special=="igrave" = "{\\`\\i}"
| special=="ograve" = "{\\`o}"
| special=="ugrave" = "{\\`u}"
| special=="Acirc" = "{\\^A}"
| special=="Ecirc" = "{\\^E}"
| special=="Icirc" = "{\\^I}"
| special=="Ocirc" = "{\\^O}"
| special=="Ucirc" = "{\\^U}"
| special=="acirc" = "{\\^a}"
| special=="ecirc" = "{\\^e}"
| special=="icirc" = "{\\^\\i}"
| special=="ocirc" = "{\\^o}"
| special=="ucirc" = "{\\^u}"
| special=="Oslash" = "{\\O}"
| special=="oslash" = "{\\o}"
| special=="amp" = "{\\&}"
| special=="ntilde" = "{\\~n}"
| special=="otilde" = "{\\~o}"
| special=="ccedil" = "{\\c{c}}"
| special=="nbsp" = "~"
| special=="quot" = "\""
| special=="lt" = "{$<$}"
| special=="gt" = "{$>$}"
| otherwise = "\\&"++special++";"
showLatexDoc :: [HtmlExp] -> String
showLatexDoc htmlexps = showLatexDocs [htmlexps]
showLatexDocWithPackages :: [HtmlExp] -> [String] -> String
showLatexDocWithPackages hexps packages
= showLatexDocsWithPackages [hexps] packages
showLatexDocs :: [[HtmlExp]] -> String
showLatexDocs htmlexps_list = showLatexDocsWithPackages htmlexps_list []
showLatexDocsWithPackages :: [[HtmlExp]] -> [String] -> String
showLatexDocsWithPackages htmlexps_list packages =
"\\documentclass[12pt]{article}\n"++
concatMap (\p->"\\usepackage{"++p++"}\n") packages++
"\\usepackage{longtable}"++
"\\nonstopmode\n"++
"\\setlength{\\topmargin}{ -1.5cm}\n"++
"\\setlength{\\oddsidemargin}{0.0cm}\n"++
"\\setlength{\\evensidemargin}{0.0cm}\n"++
"\\setlength{\\marginparwidth}{0.0cm}\n"++
"\\setlength{\\marginparsep}{0.0cm}\n"++
"\\setlength{\\textwidth}{16.5cm}\n"++
"\\setlength{\\textheight}{24.0cm}\n"++
"\\pagestyle{empty}\n"++
"\\begin{document}\n\\sloppy\n"++
"\\addtolength{\\baselineskip}{0.0ex}\n"++
"\\setlength{\\parindent}{0.0ex}\n"++
"\\addtolength{\\parskip}{0.5ex}\n"++
concat (intersperse "\\newpage\n" (map showLatexExps htmlexps_list))++
"\\end{document}\n"
germanLatexDoc :: [HtmlExp] -> String
germanLatexDoc hexps = showLatexDocWithPackages hexps ["ngerman"]
intForm :: IO HtmlForm -> IO ()
intForm = intFormMain "" "" "" "" False ""
intFormMain :: String -> String -> String -> String ->
Bool -> String -> IO HtmlForm -> IO ()
intFormMain baseurl basecgi reldir cginame forever urlparam hformact = do
pid <- getPID
user <- getEnviron "USER"
home <- getHomeDirectory
let portname = "intcgi_" ++ show pid
socket <- listenOn portname
let cgiprogname = if null cginame then "cgitest_"++show pid++".cgi"
else cginame
url = (if null baseurl then "http://localhost/~"++user else baseurl)
++ "/" ++ reldir ++ "/" ++ cgiprogname
cgifile = (if null basecgi then home++"/public_html/" else basecgi++"/")++
(if null reldir then "" else reldir ++"/") ++ cgiprogname
cgikey = url++" 42"
installShowCgiEnvScript portname cgifile
setEnviron "QUERY_STRING" urlparam
time <- getClockTime
intFormInEnv url cgikey hformact hformact [] (initialServerState time)
forever socket
system ("rm "++cgifile) >> done
intFormInEnv :: String -> String -> IO HtmlForm -> IO HtmlForm
-> [(String,String)] -> ServerState -> Bool -> Socket -> IO ()
intFormInEnv url cgikey initform hformact cenv state forever socket = do
if null cenv then putStrLn ">>> Start initial web form..." else done
cform <- hformact
let (cookiestring,hform) = extractCookies cform
(htmlstring,evhs) <- showHtmlFormInEnv url "" (extendForm hform)
(getMaxFieldNr cenv + 1)
nstate <- storeEnvHandlers state
(formWithMultipleHandlers hform)
(encodeKey cgikey)
(filter (\ (t,_) -> t/="DEFAULT" && take 6 t /= "EVENT_") cenv)
evhs
showHtmlStringInBrowser (cookiestring++htmlstring)
if forever || formWithHandlers hform
then do putStrLn ">>> Waiting for web page submission..."
(_,hdl) <- socketAccept socket
mbmsg <- readCgiServerMsg hdl
maybe (intFormInEnv url cgikey initform hformact
cenv state forever socket)
(intFormProceed nstate hdl)
mbmsg
else putStrLn ">>> Final web page reached"
where
intFormProceed nstate hdl (CgiSubmit scriptenv newcenv) = do
hPutStrLn hdl answerTxt
hClose hdl
mapIO_ (\ (var,val) -> setEnviron var val) scriptenv
if null newcenv
then intFormInEnv url cgikey initform initform [] nstate forever socket
else do
(rstate,mfe) <- getNextFormAndCgiEnv nstate cgikey newcenv
maybe (putStrLn "ERROR: no submission handler")
(\ (ioform,env) -> intFormInEnv url cgikey initform ioform
env rstate forever socket)
mfe
answerTxt = "Content-Type: text/html\n\n" ++
showHtmlExp (italic [htxt "Waiting for next web form..."])
extendForm orgform =
orgform `addFormParam` HeadInclude (HtmlStruct "base" [("href",url)] [])
formWithHandlers :: HtmlForm -> Bool
formWithHandlers (HtmlForm _ _ hexps) = hasHandlers hexps
where
hasHandlers :: [HtmlExp] -> Bool
hasHandlers [] = False
hasHandlers (HtmlText _ : hes) = hasHandlers hes
hasHandlers (HtmlStruct _ _ hes1 : hes2) =
hasHandlers hes1 || hasHandlers hes2
hasHandlers (HtmlCRef he _ : hes) = hasHandlers [he] || hasHandlers hes
hasHandlers (HtmlEvent _ _ : _) = True
hasHandlers (AjaxEvent _ _ : _) = True
hasHandlers (AjaxEvent2 _ _ _ _ : _) = True
showHtmlStringInBrowser :: String -> IO ()
showHtmlStringInBrowser htmlstring = do
pid <- getPID
let htmlfilename = "tmpcgiform_" ++ show pid ++ ".html"
writeFile htmlfilename htmlstring
system ("remote-netscape file:`pwd`/"++htmlfilename)
done
installShowCgiEnvScript :: String -> String -> IO ()
installShowCgiEnvScript portname cgifile = do
putStrLn ">>> Installing web script..."
putStrLn $ "for port name: "++portname
writeFile cgifile $ "#!/bin/sh\n"++
installDir++"/www/submitform \""++portname++"\"\n"
system ("chmod 755 "++cgifile)
done
type ServerState =
(ClockTime, Int, ClockTime,
[(Int,ClockTime,String,([(String,String)],HtmlHandler),Maybe Int)])
initialServerState :: ClockTime -> ServerState
initialServerState ctime = (ctime, 0, nextCleanup ctime, [])
isServerStateWithoutHandlers :: ServerState -> Bool
isServerStateWithoutHandlers (_,_,_,evhandlers) = null evhandlers
getServerLoad :: ServerState -> IO String
getServerLoad (stime,maxkey,_,evs) = do
ctime <- getClockTime
let busy = maxkey>500
|| (compareClockTime ctime (addMinutes 30 stime) == GT)
|| null evs
return (if busy then "busy" else "ready")
getServerStatus :: ServerState -> IO String
getServerStatus state@(stime,maxkey,_,evs) = do
busy <- getServerLoad state
lstime <- toCalendarTime stime
pinfos <- getProcessInfos
return $ "Status: " ++ busy ++ ", Maxkey: "++show maxkey ++ ", #Handlers: " ++
show (length evs) ++ ", Start time: " ++
calendarTimeToString lstime ++ "\n" ++
showMemInfo pinfos
showGroupKey :: Maybe Int -> String
showGroupKey Nothing = "multiple use"
showGroupKey (Just gk) = "group " ++ show gk
storeEnvHandlers :: ServerState -> Bool -> String -> [(String,String)]
-> [(HtmlHandler,String)] -> IO ServerState
storeEnvHandlers ostate multipleuse cgikey env handlerkeys = do
time <- getClockTime
cstate <- cleanOldEventHandlers ostate
rannums <- getRandomSeed >>= return . drop 3 . nextInt
let nstate = generateEventServerMessages
rannums
(if multipleuse then Nothing else Just (keyOfState cstate))
(eventHandlerExpiration time)
cstate
handlerkeys
seq nstate done
return nstate
where
generateEventServerMessages _ _ _ state [] = state
generateEventServerMessages (rannum:rannums) groupkey expiredate state
((handler,hkey) : evhs)
| hkey =:= show (keyOfState state) ++ ' ':showQTerm (toUTCTime expiredate)
++ '_' : show rannum
= generateEventServerMessages
rannums
groupkey
expiredate
(storeNewEnvEventWithCgiKey groupkey expiredate state env handler)
evhs
keyOfState (_,key,_,_) = key
storeNewEnvEventWithCgiKey groupkey date (stime,maxkey,cleandate,ehs)
cenv info =
(stime,
if maxkey>30000 then 0 else maxkey+1,
cleandate,
(maxkey,date,cgikey,(cenv,info),groupkey):ehs)
cleanOldEventHandlers :: ServerState -> IO ServerState
cleanOldEventHandlers state@(_,_,_,[]) = return state
cleanOldEventHandlers state@(stime,maxkey,cleandate,ehs@(_:_)) = do
ctime <- getClockTime
if compareClockTime ctime cleandate == LT
then return state
else do
let currentehs = filter (isNotExpired ctime) ehs
noehs = length ehs
nocurrentehs = length currentehs
if nocurrentehs < noehs
then do
ltime <- toCalendarTime ctime
putErrLn $ calendarTimeToString ltime ++ ": cleanup " ++
"(number of handlers: old = "++ show noehs ++ " / " ++
"current = "++ show nocurrentehs ++ ")"
else done
return (stime,maxkey, nextCleanup ctime, currentehs)
where
isNotExpired time (_,etime,_,_,_) = compareClockTime time etime == LT
retrieveEnvHandlers :: ServerState -> String -> String
-> IO (ServerState,Maybe ([(String,String)],HtmlHandler))
retrieveEnvHandlers state cgikey skey =
let (numstring,datestring) = break (==' ') skey
dateps = readsQTerm datestring
num = tryReadNat (-1) numstring
in if null datestring || null dateps || num < 0
then return (state,Nothing)
else let (newstate,info) =
getEnvEventWithCgiKey state num (fst (head dateps))
in seq newstate (return (newstate, info))
where
getEnvEventWithCgiKey oldstate@(stime,maxkey,cleandate,ehs) key date =
maybe (oldstate,Nothing)
(\ (evhdlr,groupkey) ->
maybe (oldstate, Just evhdlr)
(\gk -> let newehs = deleteEv gk ehs
in seq newehs ((stime,maxkey,cleandate,newehs),
Just evhdlr))
groupkey )
(searchEv ehs)
where
searchEv [] = Nothing
searchEv ((n,t,c,i,gk):es) =
if key==n && date == toUTCTime t
then if c==cgikey then Just (i,gk) else Nothing
else searchEv es
deleteEv _ [] = []
deleteEv groupkey (ev@(_,_,_,_,Nothing):es) =
let des = deleteEv groupkey es in seq des (ev : des)
deleteEv groupkey (ev@(_,_,_,_,Just gk):es) =
if groupkey==gk
then deleteEvInGroup groupkey es
else let des = deleteEv groupkey es in seq des (ev : des)
deleteEvInGroup _ [] = []
deleteEvInGroup _ (ev@(_,_,_,_,Nothing):es) = ev : es
deleteEvInGroup groupkey (ev@(_,_,_,_,Just gk):es) =
if groupkey==gk
then deleteEvInGroup groupkey es
else ev : es
eventHandlerExpiration :: ClockTime -> ClockTime
eventHandlerExpiration = addHours 1
nextCleanup :: ClockTime -> ClockTime
nextCleanup = addMinutes 5
|