summaryrefslogtreecommitdiffstats
path: root/mollom.module
blob: ff84e340494a77d36e6052e2b57ab84764c1982e (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
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
<?php

/**
 * @file
 * Main Mollom integration module functions.
 */

/**
 * Mollom API version; used for XML-RPC communication with Mollom servers.
 */
define('MOLLOM_API_VERSION', '1.0');

/**
 * Text analysis result flag: No result.
 */
define('MOLLOM_ANALYSIS_UNKNOWN', 0);

/**
 * Text analysis result flag: Content is no spam.
 */
define('MOLLOM_ANALYSIS_HAM', 1);

/**
 * Text analysis result flag: Content is spam.
 */
define('MOLLOM_ANALYSIS_SPAM', 2);

/**
 * Text analysis result flag: Ambiguous result.
 */
define('MOLLOM_ANALYSIS_UNSURE', 3);

/**
 * Form protection mode: No protection.
 */
define('MOLLOM_MODE_DISABLED', 0);

/**
 * Form protection mode: CAPTCHA-only protection.
 */
define('MOLLOM_MODE_CAPTCHA', 1);

/**
 * Form protection mode: Text analysis with fallback to CAPTCHA.
 */
define('MOLLOM_MODE_ANALYSIS', 2);

/**
 * XML-RPC communication failure fallback mode: Block all submissions of protected forms.
 */
define('MOLLOM_FALLBACK_BLOCK', 0);

/**
 * XML-RPC communication failure fallback mode: Accept all submissions of protected forms.
 */
define('MOLLOM_FALLBACK_ACCEPT', 1);

/**
 * XML-RPC communication failure: No servers could be reached.
 *
 * @todo Prefix with MOLLOM_.
 */
define('NETWORK_ERROR', 900);

/**
 * XML-RPC communication failure: Error on Mollom server.
 *
 * @todo Prefix with SERVER_.
 */
define('MOLLOM_ERROR', 1000);

/**
 * XML-RPC communication failure: Mollom server requests client to update its server list.
 *
 * @todo Prefix with SERVER_.
 */
define('MOLLOM_REFRESH', 1100);

/**
 * XML-RPC communication failure: Mollom server defers communication to next server in server list.
 *
 * @todo Prefix with SERVER_.
 */
define('MOLLOM_REDIRECT', 1200);

/**
 * Implements hook_help().
 */
function mollom_help($path, $arg) {
  $output = '';

  if ($path == 'admin/settings/mollom') {
    $output .= '<p>';
    $output .= t('All listed forms below are protected by Mollom, unless users are able to <a href="@permissions-url">bypass Mollom\'s protection</a>.', array(
      '@permissions-url' => url('admin/user/permissions', array('fragment' => 'module-mollom')),
    ));
    $output .= '</p>';
    $output .= '<p>';
    $output .= t('You can <a href="@add-form-url">add a form</a> to protect, configure already protected forms, or remove the protection.', array(
      '@add-form-url' => url('admin/settings/mollom/add'),
    ));
    $output .= '</p>';
    return $output;
  }

  if ($path == 'admin/settings/mollom/blacklist') {
    return t('Mollom automatically blocks unwanted content and learns from all participating sites to improve its filters. On top of automatic filtering, you can define a custom blacklist.');
  }

  if ($path == 'admin/help#mollom') {
    $output = '<p>';
    $output .= t("Allowing users to react, participate and contribute while still keeping your site's content under control can be a huge challenge. Mollom is a web service that helps you identify content quality and, more importantly, helps you stop spam. When content moderation becomes easier, you have more time and energy to interact with your web community. More information about Mollom is available on the <a href=\"@mollom-website\">Mollom website</a> or in the <a href=\"@mollom-faq\">Mollom FAQ</a>.",
      array(
        '@mollom-website' => 'http://mollom.com',
        '@mollom-faq' => 'http://mollom.com/faq',
      )
    );
    $output .= '</p><p>';
    $output .= t("Mollom can be used to block all types of spam received on your website's protected forms. Each form can be set to one of the following options:");
    $output .= '</p><ul><li>';
    $output .= t("<strong>Text analysis and CAPTCHA backup</strong>: Mollom analyzes the data submitted on the form and presents a CAPTCHA challenge if necessary. This option is strongly recommended, as it takes full advantage of the Mollom anti-spam service to categorize your posts into ham (not spam) and spam.");
    $output .= '</li><li>';
    $output .= t("<strong>CAPTCHA only</strong>: the form's data is not sent to Mollom for analysis, and a remotely-hosted CAPTCHA challenge is always presented. This option is useful when you wish to always display a CAPTCHA or want to send less data to the Mollom network. Note, however, that forms displayed with a CAPTCHA are never cached, so always displaying a CAPTCHA challenge may reduce performance.");
    $output .= '</li></ul><p>';
    $output .= t("Data is processed and stored as explained in our <a href=\"@mollom-privacy\">Web Service Privacy Policy</a>. It is your responsibility to provide any necessary notices and obtain the appropriate consent regarding Mollom's use of your data. For more information, see <a href=\"@mollom-works\">How Mollom Works</a> and the <a href=\"@mollom-faq\">Mollom FAQ</a>.", array(
      '@mollom-privacy' => 'http://mollom.com/service-agreement-free-subscriptions',
      '@mollom-works' => 'http://mollom.com/how-mollom-works',
      '@mollom-faq' => 'http://mollom.com/faq')
    );
    $output .= '</p>';
    $output .= '<h3>' . t('Mollom blacklist') . '</h3>';
    $output .= '<p>';
    $output .= t("Mollom's filters are shared and trained globally over all participating sites. Due to this, unwanted content might still be accepted on your site, even after sending feedback to Mollom. By using the site-specific blacklist, the filters can be customized to your specific needs. Each entry specifies a reason for why it has been blacklisted, which further helps in improving Mollom's automated filtering.");
    $output .= '</p>';
    $output .= '<p>';
    $output .= t("All blacklist entries are applied to a context: the entire submitted post, or only links in the post. When limiting the context to links, both the link URL and the link text is taken into account.");
    $output .= '</p>';
    $output .= '<p>';
    $output .= t("If a blacklist entry contains multiple words, various combinations will be matched. For example, when adding \"<code>replica&nbsp;watches</code>\" limited to links, the following links will be blocked:");
    $output .= '</p>';
    $output .= '<ul>
<li><code>http://replica-watches.com</code></li>
<li><code>http://replica-watches.com/some/path</code></li>
<li><code>http://replicawatches.net</code></li>
<li><code>http://example.com/replica/watches</code></li>
<li><code>&lt;a href="http://example.com"&gt;replica watches&lt;/a&gt;</code></li>
</ul>';
    $output .= '<p>';
    $output .= t("The blacklist is optional. There is no whitelist, i.e., if a blacklist entry is matched in a post, it overrides any other filter result and the post will not be accepted. Blacklisting potentially ambiguous words should be avoided.");
    $output .= '</p>';
    return $output;
  }
}

/**
 * Implements hook_init().
 */
function mollom_init() {
  // On all Mollom administration pages, check the module configuration and
  // display the corresponding requirements error, if invalid.
  if (empty($_POST) && strpos($_GET['q'], 'admin/settings/mollom') === 0 && user_access('administer mollom')) {
    // Re-check the status on the settings form only.
    $status = _mollom_status($_GET['q'] == 'admin/settings/mollom/settings');
    if ($status !== TRUE) {
      // Fetch and display requirements error message, without re-checking.
      module_load_install('mollom');
      $requirements = mollom_requirements('runtime', FALSE);
      if (isset($requirements['mollom']['description'])) {
        drupal_set_message($requirements['mollom']['description'], 'error');
      }
    }
  }
  $path = drupal_get_path('module', 'mollom');
  drupal_add_js($path . '/mollom.js');
  drupal_add_css($path . '/mollom.css');
}

/**
 * Implements hook_link().
 */
function mollom_link($type, $object, $teaser = FALSE) {
  $links = array();

  // Only show the links if the module is configured.
  if (_mollom_status() === TRUE) {
    if ($type == 'comment' && user_access('administer comments') && mollom_get_mode('comment_form')) {
      $links['mollom_report'] = array(
        'title' => t('report to Mollom'),
        'href' => 'mollom/report/comment/' . $object->cid,
        'query' => drupal_get_destination(),
      );
    }
    elseif ($type == 'node' && user_access('administer nodes') && mollom_get_mode($object->type . '_node_form')) {
      $links['mollom_report'] = array(
        'title' => t('report to Mollom'),
        'href' => 'mollom/report/node/' . $object->nid,
        'query' => drupal_get_destination(),
      );
    }
  }

  return $links;
}

/**
 * Implements hook_menu().
 */
function mollom_menu() {
  $items['mollom/report/%/%'] = array(
    'title' => 'Report to Mollom',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('mollom_report_form', 2, 3),
    'access callback' => 'mollom_report_access',
    'access arguments' => array(2, 3),
    'file' => 'mollom.pages.inc',
    'type' => MENU_CALLBACK,
  );

  $items['admin/settings/mollom'] = array(
    'title' => 'Mollom content moderation',
    'description' => 'Configure how the Mollom service moderates user-submitted content such as spam and profanity.',
    'page callback' => 'mollom_admin_form_list',
    'access arguments' => array('administer mollom'),
    'file' => 'mollom.admin.inc',
  );
  $items['admin/settings/mollom/forms'] = array(
    'title' => 'Forms',
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'weight' => -10,
  );
  $items['admin/settings/mollom/add'] = array(
    'title' => 'Add form',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('mollom_admin_configure_form'),
    'access arguments' => array('administer mollom'),
    'type' => MENU_LOCAL_TASK,
    'file' => 'mollom.admin.inc',
  );
  $items['admin/settings/mollom/manage/%mollom_form'] = array(
    'title' => 'Configure',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('mollom_admin_configure_form', 4),
    'access arguments' => array('administer mollom'),
    'file' => 'mollom.admin.inc',
  );
  $items['admin/settings/mollom/unprotect/%mollom_form'] = array(
    'title' => 'Unprotect form',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('mollom_admin_unprotect_form', 4),
    'access arguments' => array('administer mollom'),
    'type' => MENU_CALLBACK,
    'file' => 'mollom.admin.inc',
  );
  $items['admin/settings/mollom/blacklist'] = array(
    'title' => 'Blacklists',
    'description' => 'Configure blacklists.',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('mollom_admin_blacklist_form'),
    'access arguments' => array('administer mollom'),
    'type' => MENU_LOCAL_TASK,
    'file' => 'mollom.admin.inc',
  );
  $items['admin/settings/mollom/blacklist/spam'] = array(
    'title' => 'Spam',
    'description' => 'Configure spam blacklist entries.',
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'weight' => -10,
  );
  $items['admin/settings/mollom/blacklist/profanity'] = array(
    'title' => 'Profanity',
    'description' => 'Configure profanity blacklist entries.',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('mollom_admin_blacklist_form', 4),
    'access arguments' => array('administer mollom'),
    'type' => MENU_LOCAL_TASK,
    'file' => 'mollom.admin.inc',
  );
  $items['admin/settings/mollom/blacklist/unwanted'] = array(
    'title' => 'Unwanted',
    'description' => 'Configure unwanted blacklist entries.',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('mollom_admin_blacklist_form', 4),
    'access arguments' => array('administer mollom'),
    'type' => MENU_LOCAL_TASK,
    'file' => 'mollom.admin.inc',
  );
  $items['admin/settings/mollom/blacklist/delete'] = array(
    'title' => 'Delete',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('mollom_admin_blacklist_delete'),
    'access arguments' => array('administer mollom'),
    'type' => MENU_CALLBACK,
    'file' => 'mollom.admin.inc',
  );
  $items['admin/settings/mollom/settings'] = array(
    'title' => 'Settings',
    'description' => 'Configure Mollom keys and global settings.',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('mollom_admin_settings'),
    'access arguments' => array('administer mollom'),
    'type' => MENU_LOCAL_TASK,
    'file' => 'mollom.admin.inc',
  );

  $items['admin/reports/mollom'] = array(
    'title' => 'Mollom statistics',
    'description' => 'Reports and usage statistics for the Mollom module.',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('mollom_reports_page'),
    'access callback' => '_mollom_access',
    'access arguments' => array('administer mollom'),
    'file' => 'mollom.admin.inc',
  );

  // AJAX callback to request new CAPTCHA.
  $items['mollom/captcha/%/%'] = array(
    'page callback' => 'mollom_captcha_js',
    'page arguments' => array(2, 3),
    'access callback' => '_mollom_access',
    'file' => 'mollom.pages.inc',
    'type' => MENU_CALLBACK,
  );

  return $items;
}

/**
 * Access callback; check if the module is configured.
 *
 * This function does not actually check whether Mollom keys are valid for the
 * site, but just if the keys have been entered.
 *
 * @param $permission
 *   An optional permission string to check with user_access().
 *
 * @return
 *   TRUE if the module has been configured and user_access() has been checked,
 *   FALSE otherwise.
 */
function _mollom_access($permission = FALSE) {
  return variable_get('mollom_public_key', '') && variable_get('mollom_private_key', '') && (!$permission || user_access($permission));
}

/**
 * Menu access callback; Determine access to report to Mollom.
 *
 * The special $entity type "session" may be used for mails and messages, which
 * originate from form submissions protected by Mollom, and can be reported by
 * anyone; $id is expected to be a Mollom session id instead of an entity id
 * then.
 *
 * @param $entity
 *   The entity type of the data to report.
 * @param $id
 *   The entity id of the data to report.
 *
 * @todo Revamp this based on new {mollom}.form_id info.
 */
function mollom_report_access($entity, $id) {
  // The special entity 'session' means that $id is a Mollom session_id, which
  // can always be reported by everyone.
  if ($entity == 'session') {
    return !empty($id) ? TRUE : FALSE;
  }
  // Retrieve information about all protectable forms. We use the first valid
  // definition, because we assume that multiple form definitions just denote
  // variations of the same entity (e.g. node content types).
  foreach (mollom_form_list() as $form_id => $info) {
    if (!isset($info['entity']) || $info['entity'] != $entity) {
      continue;
    }
    // If there is a 'report access callback', invoke it.
    if (isset($info['report access callback']) && function_exists($info['report access callback'])) {
      $function = $info['report access callback'];
      return $function($entity, $id);
    }
    // Otherwise, if there is a 'report access' list of permissions, iterate
    // over them.
    if (isset($info['report access'])) {
      foreach ($info['report access'] as $permission) {
        if (user_access($permission)) {
          return TRUE;
        }
      }
    }
  }
  // If we end up here, then the current user is not permitted to report this
  // content.
  return FALSE;
}

/**
 * Implements hook_perm().
 */
function mollom_perm() {
  return array(
    'administer mollom',
    'bypass mollom protection',
  );
}

/**
 * Implements hook_flush_caches().
 */
function mollom_flush_caches() {
  return array('cache_mollom');
}

/**
 * Implements hook_cron().
 */
function mollom_cron() {
  // Mollom session data auto-expires after 6 months.
  $expired = time() - 86400 * 30 * 6;
  db_query("DELETE FROM {mollom} WHERE changed < %d", array($expired));
}

/**
 * Load a Mollom data record from the database.
 *
 * @param $entity
 *   The entity type to retrieve data for.
 * @param $id
 *   The entity id to retrieve data for.
 */
function mollom_data_load($entity, $id) {
  return db_fetch_object(db_query_range("SELECT * FROM {mollom} WHERE entity = '%s' AND id = '%s'", array($entity, $id), 0, 1));
}

/**
 * Save Mollom validation data to the database.
 *
 * Based on the specified entity type and id, this function stores the
 * validation results returned by Mollom in the database.
 *
 * The special $entity type "session" may be used for mails and messages, which
 * originate from form submissions protected by Mollom, and can be reported by
 * anyone; $id is expected to be a Mollom session id instead of an entity id
 * then.
 *
 * @param $data
 *   An object containing Mollom session data for the entity, containing at
 *   least the following properties:
 *   - entity: The entity type of the data to save.
 *   - id: The entity ID the data belongs to.
 *   - form_id: The form ID the session data belongs to.
 *   - session_id: The session ID returned by Mollom.
 *   And optionally:
 *   - spam: A spam check result integer returned by Mollom, which can be
 *     MOLLOM_ANALYSIS_SPAM, MOLLOM_ANALYSIS_UNSURE, or MOLLOM_ANALYSIS_HAM.
 *   - quality: A rating of the content's quality, in the range of 0 and 1.0.
 *   - profanity: A profanity check rating returned by Mollom, in the range of
 *     0 and 1.0.
 *   - languages: An array containing language codes the content might be
 *     written in.
 */
function mollom_data_save($data) {
  $data->changed = time();
  // Convert languages array into a string.
  // @todo This conversion and data handling is not correct; needs work.
  if (isset($data->languages) && is_array($data->languages)) {
    $data->languages = implode(' ', $data->languages);
  }

  $update = db_result(db_query_range("SELECT 'id' FROM {mollom} WHERE entity = '%s' AND id = '%s'", $data->entity, $data->id, 0, 1));
  drupal_write_record('mollom', $data, $update ? array('entity', $update) : array());

  if (!$update) {
    module_invoke_all('mollom_data_insert', $data);
  }
  else {
    module_invoke_all('mollom_data_update', $data);
  }

  return $data;
}

/**
 * Deletes a Mollom session data record from the database.
 *
 * @param $entity
 *   The entity type to delete data for.
 * @param $id
 *   The entity id to delete data for.
 */
function mollom_data_delete($entity, $id) {
  return mollom_data_delete_multiple($entity, array($id));
}

/**
 * Deletes multiple Mollom session data records from the database.
 *
 * @param $entity
 *   The entity type to delete data for.
 * @param $ids
 *   An array of entity ids to delete data for.
 */
function mollom_data_delete_multiple($entity, $ids) {
  foreach ($ids as $id) {
    $data = mollom_data_load($entity, $id);
    module_invoke_all('mollom_data_delete', $data);
  }
  $placeholders = db_placeholders($ids, 'varchar');
  return db_query("DELETE FROM {mollom} WHERE entity = '%s' AND id IN ($placeholders)", array_merge(array($entity), $ids));
}

/**
 * Helper function to add Mollom feedback options to confirmation forms.
 */
function mollom_data_delete_form_alter(&$form, &$form_state) {
  if (!isset($form['actions']['#weight'])) {
    $form['actions']['#weight'] = 100;
  }
  if (!isset($form['description']['#weight'])) {
    $form['description']['#weight'] = 90;
  }
  $form['mollom'] = array(
    '#tree' => TRUE,
    '#weight' => 80,
  );
  $form['mollom']['feedback'] = array(
    '#type' => 'radios',
    '#title' => t('Report as inappropriate'),
    '#options' => array(
      0 => t('Do not report'),
      'spam' => t('Spam, unsolicited advertising'),
      'profanity' => t('Obscene, violent, profane'),
      'low-quality' => t('Low-quality'),
      'unwanted' => t('Unwanted, taunting, off-topic'),
    ),
    '#default_value' => 0,
    '#description' => t('Sending feedback to <a href="@mollom-url">Mollom</a> improves the automated moderation of new submissions.', array('@mollom-url' => 'http://mollom.com')),
  );
}

/**
 * Send feedback to Mollom and delete Mollom data.
 *
 * @see mollom_form_alter()
 */
function mollom_data_delete_form_submit($form, &$form_state) {
  $forms = mollom_form_cache();
  $mollom_form = mollom_form_load($forms['delete'][$form_state['values']['form_id']]);
  $data = mollom_form_get_values($form_state, $mollom_form['enabled_fields'], $mollom_form['mapping']);

  $entity = $mollom_form['entity'];
  $id = $data['post_id'];

  if (!empty($form_state['values']['mollom']['feedback'])) {
    if (mollom_data_report($entity, $id, $form_state['values']['mollom']['feedback'])) {
      drupal_set_message(t('The content was successfully reported as inappropriate.'));
    }
  }

  // Remove Mollom session data.
  mollom_data_delete($entity, $id);
}

/**
 * Sends feedback for a Mollom session data record.
 *
 * @param $entity
 *   The entity type to send feedback for.
 * @param $id
 *   The entity id to send feedback for.
 */
function mollom_data_report($entity, $id, $feedback) {
  return mollom_data_report_multiple($entity, array($id), $feedback);
}

/**
 * Sends feedback for multiple Mollom session data records.
 *
 * @param $entity
 *   The entity type to send feedback for.
 * @param $ids
 *   An array of entity ids to send feedback for.
 */
function mollom_data_report_multiple($entity, $ids, $feedback) {
  $return = TRUE;
  foreach ($ids as $id) {
    // Load the Mollom session data.
    $data = mollom_data_load($entity, $id);
    // Send feedback, if we have session data.
    if (!empty($data->session_id)) {
      $result = _mollom_send_feedback($data->session_id, $feedback);
      $return = $return && $result;
    }
  }
  return $return;
}

/**
 * Implements hook_form_alter().
 *
 * This function intercepts all forms in Drupal and Mollom-enables them if
 * necessary.
 */
function mollom_form_alter(&$form, &$form_state, $form_id) {
  // Skip installation and update forms.
  if (defined('MAINTENANCE_MODE')) {
    return;
  }
  // Verify global Mollom configuration status.
  $status = _mollom_status();
  if ($status !== TRUE) {
    return;
  }

  // Retrieve a list of all protected forms once.
  $forms = mollom_form_cache();

  // Remind of enabled testing mode on all protected forms.
  if (isset($forms['protected'][$form_id]) || strpos($_GET['q'], 'admin/settings/mollom') === 0) {
    _mollom_testing_mode_warning();
  }

  // Site administrators don't have their content checked with Mollom.
  if (!user_access('bypass mollom protection')) {
    // Retrieve configuration for this form.
    if (isset($forms['protected'][$form_id]) && ($mollom_form = mollom_form_load($form_id))) {
      // Determine whether to bypass validation for the current user.
      foreach ($mollom_form['bypass access'] as $permission) {
        if (user_access($permission)) {
          return;
        }
      }
      // Compute the weight of the CAPTCHA so we can position it in the form.
      // #type 'actions' is new in D7, but contributed modules use the concept
      // in D6 already. We therefore expect the key without #type.
      if (isset($form['actions']) && !isset($form['actions']['#type'])) {
        // D6 code should set a #weight. If none is set, we ensure a default of
        // 100, like #type 'actions' in D7.
        if (!isset($form['actions']['#weight'])) {
          $form['actions']['#weight'] = 100;
        }
        $weight = $form['actions']['#weight'] - 1;
      }
      // Some forms use 'buttons' as key.
      elseif (isset($form['buttons']) && !isset($form['buttons']['#type'])) {
        // D6 code should set a #weight. If none is set, we ensure a default of
        // 100, like #type 'actions' in D7.
        if (!isset($form['buttons']['#weight'])) {
          $form['buttons']['#weight'] = 100;
        }
        $weight = $form['buttons']['#weight'] - 1;
      }
      else {
        $weight = 99999;
        foreach (element_children($form) as $key) {
          // Scan the top-level form elements for buttons.
          if (isset($form[$key]['#type']) && in_array($form[$key]['#type'], array('submit', 'button', 'image_button'))) {
            // For each button, slightly increase the weight to allocate room for
            // the CAPTCHA.
            if (isset($form[$key]['#weight'])) {
              $form[$key]['#weight'] += 0.0002;
            }
            else {
              $form[$key]['#weight'] = 1.0002;
            }
            // We want to position the CAPTCHA just before the first button, so
            // we make the CAPTCHA's weight slightly lighter than the lightest
            // button's weight.
            $weight = min($weight, $form[$key]['#weight'] - 0.0001);
          }
        }
      }
      // Add Mollom form widget.
      $form['mollom'] = array(
        '#type' => 'mollom',
        '#mollom_form' => $mollom_form,
        '#weight' => $weight,
        '#tree' => TRUE,
      );
      // Add Mollom form validation handlers.
      $form['#validate'][] = 'mollom_validate_analysis';
      $form['#validate'][] = 'mollom_validate_captcha';
      $form['#validate'][] = 'mollom_validate_post';
      // Add an #after_build callback on the $form to collect all buttons.
      // @see mollom_form_get_values()
      // @see _mollom_form_state_values_clean()
      $form['#after_build'][] = 'mollom_form_buttons_after_build';

      // Prepend a submit handler to clean up internal Mollom values from
      // $form_state['values'].
      $form += array('#submit' => array());
      array_unshift($form['#submit'], 'mollom_form_pre_submit');
      // Append a submit handler to store Mollom session data. Requires that
      // the primary submit handler has run already, so a potential 'post_id'
      // mapping can be retrieved from $form_state['values'].
      // @todo Core: node_form_submit() uses a button-level submit handler,
      //   which invokes form-level submit handlers before the node/entity is
      //   saved, so $form_state does not contain the new node ID yet. There is
      //   no #post_submit property or form processing phase, we could rely on.
      //   Potentially applies to other contrib entities, too.
      // @see http://drupal.org/node/1150756
      // In D6, node_form() is probably the only function that sets both
      // $form['#node'] and $form_state['node']. Compared to that, the
      // $form['#id'] of 'node-form' is less reliable, since any module can
      // (rightfully) alter it.
      if (isset($form['#node']) && isset($form_state['node'])) {
        $form_submit_key = &$form['buttons']['submit'];
      }
      else {
        $form_submit_key = &$form;
      }
      $form_submit_key['#submit'][] = 'mollom_form_submit';

      // Add link to privacy policy on forms protected via textual analysis,
      // if enabled.
      if ($mollom_form['mode'] == MOLLOM_MODE_ANALYSIS && variable_get('mollom_privacy_link', 1)) {
        $form['mollom']['privacy'] = array(
          '#prefix' => '<div class="description mollom-privacy">',
          '#suffix' => '</div>',
          '#value' => t('By submitting this form, you accept the <a href="@privacy-policy-url">Mollom privacy policy</a>.', array(
            '@privacy-policy-url' => 'http://mollom.com/web-service-privacy-policy',
          )),
          '#weight' => 10,
        );
      }
    }
  }
  // Integrate with delete confirmation forms to send feedback to Mollom.
  if (isset($forms['delete'][$form_id])) {
    // Check whether the user is allowed to report to Mollom. Limiting report
    // access is optional for forms integrating via 'delete form' and allowed by
    // default, since we assume that users being able to delete entities are
    // sufficiently trusted to also report to Mollom.
    $access = TRUE;
    // Retrieve information about the protected form; the form cache maps delete
    // confirmation forms to protected form_ids, and protected form_ids to their
    // originating modules.
    $mollom_form_id = $forms['delete'][$form_id];
    $module = $forms['protected'][$mollom_form_id];
    $form_info = mollom_form_info($mollom_form_id, $module);
    // Check access, if there is a 'report access' permission list.
    if (isset($form_info['report access'])) {
      $access = FALSE;
      foreach ($form_info['report access'] as $permission) {
        if (user_access($permission)) {
          $access = TRUE;
          break;
        }
      }
    }
    if ($access) {
      mollom_data_delete_form_alter($form, $form_state);
      // Report before deleting. This needs to be handled here, since
      // mollom_data_delete_form_alter() is re-used for mass-operation forms.
      array_unshift($form['#submit'], 'mollom_data_delete_form_submit');
    }
  }
}

/**
 * Returns a cached mapping of protected and delete confirmation form ids.
 *
 * @param $reset
 *   (optional) Boolean whether to reset the static cache, flush the database
 *   cache, and return nothing (TRUE). Defaults to FALSE.
 *
 * @return
 *   An associative array containing:
 *   - protected: An associative array whose keys are protected form IDs and
 *     whose values are the corresponding module names the form belongs to.
 *   - delete: An associative array whose keys are 'delete form' ids and whose
 *     values are protected form ids; e.g.
 *     @code
 *     array(
 *       'node_delete_confirm' => 'article_node_form',
 *     )
 *     @endcode
 *     A single delete confirmation form id can map to multiple registered
 *     $form_ids, but only the first is taken into account. As in above example,
 *     we assume that all 'TYPE_node_form' definitions belong to the same entity
 *     and therefore have an identical 'post_id' mapping.
 */
function mollom_form_cache($reset = FALSE) {
  static $forms;

  if ($reset) {
    // This catches both 'mollom_form_cache' as well as mollom_form_load()'s
    // 'mollom:form:*' entries.
    cache_clear_all('mollom', 'cache', TRUE);
    unset($forms);
    return;
  }

  if (isset($forms)) {
    return $forms;
  }

  if ($cache = cache_get('mollom_form_cache')) {
    $forms = $cache->data;
    return $forms;
  }

  $result = db_query("SELECT form_id, module FROM {mollom_form}");
  $forms['protected'] = array();
  while ($row = db_fetch_array($result)) {
    $forms['protected'][$row['form_id']] = $row['module'];
  }

  // Build a list of delete confirmation forms of entities integrating with
  // Mollom, so we are able to alter the delete confirmation form to display
  // our feedback options.
  $forms['delete'] = array();
  foreach (mollom_form_list() as $form_id => $info) {
    if (!isset($info['delete form']) || !isset($info['entity'])) {
      continue;
    }
    // We expect that the same delete confirmation form uses the same form
    // element mapping, so multiple 'delete form' definitions are only processed
    // once. Additionally, we only care for protected forms.
    if (!isset($forms['delete'][$info['delete form']]) && isset($forms['protected'][$form_id])) {
      // A delete confirmation form integration requires a 'post_id' mapping.
      $form_info = mollom_form_info($form_id, $info['module']);
      if (isset($form_info['mapping']['post_id'])) {
        $forms['delete'][$info['delete form']] = $form_id;
      }
    }
  }
  cache_set('mollom_form_cache', $forms);

  return $forms;
}

/**
 * Return the protection mode for a given form id.
 *
 * @return
 *   The protection mode for the given form id, one of:
 *   - MOLLOM_MODE_DISABLED: None.
 *   - MOLLOM_MODE_CAPTCHA: CAPTCHA only.
 *   - MOLLOM_MODE_ANALYSIS: Text analysis with CAPTCHA fallback.
 */
function mollom_get_mode($form_id) {
  static $modes;

  if (!isset($modes[$form_id])) {
    $mollom_form = mollom_form_load($form_id);
    $modes[$form_id] = isset($mollom_form['mode']) ? $mollom_form['mode'] : MOLLOM_MODE_DISABLED;
  }

  return $modes[$form_id];
}

/**
 * Returns a list of protectable forms registered via hook_mollom_form_info().
 */
function mollom_form_list() {
  $form_list = array();
  foreach (module_implements('mollom_form_list') as $module) {
    $function = $module . '_mollom_form_list';
    $module_forms = $function();
    foreach ($module_forms as $form_id => $info) {
      $form_list[$form_id] = $info;
      $form_list[$form_id] += array(
        'form_id' => $form_id,
        'module' => $module,
      );
    }
  }
  return $form_list;
}

/**
 * Returns information about a form registered via hook_mollom_form_info().
 *
 * @param $form_id
 *   The form id to return information for.
 * @param $module
 *   The module name $form_id belongs to.
 */
function mollom_form_info($form_id, $module) {
  $form_info = module_invoke($module, 'mollom_form_info', $form_id);
  if (empty($form_info)) {
    $form_info = array();
  }

  // Ensure default properties.
  $form_info += array(
    'form_id' => $form_id,
    'title' => $form_id,
    'module' => $module,
    'entity' => NULL,
    'mode' => NULL,
    'discard' => TRUE,
    'bypass access' => array(),
    'elements' => array(),
    'mapping' => array(),
    'mail ids' => array(),
  );

  // Allow modules to alter the default form information.
  drupal_alter('mollom_form_info', $form_info, $form_id);

  return $form_info;
}

/**
 * Creates a bare Mollom form configuration.
 *
 * @param $form_id
 *   (optional) The form id to create the Mollom form configuration for.
 */
function mollom_form_new($form_id = NULL) {
  $mollom_form = array();
  if (isset($form_id)) {
    $form_list = mollom_form_list();
    if (isset($form_list[$form_id])) {
      $mollom_form += $form_list[$form_id];
    }
    $mollom_form += mollom_form_info($form_id, $form_list[$form_id]['module']);
  }
  // Ensure default properties.
  $mollom_form += array(
    'form_id' => $form_id,
    'title' => $form_id,
    'mode' => NULL,
    'checks' => array(),
    'elements' => array(),
    'enabled_fields' => array(),
    'strictness' => 'normal',
  );
  // Enable all fields for textual analysis by default.
  if (!empty($mollom_form['elements'])) {
    $mollom_form['checks'] = array('spam');
    $mollom_form['enabled_fields'] = array_keys($mollom_form['elements']);
  }

  return $mollom_form;
}

/**
 * Menu argument loader; Loads Mollom configuration and form information for a given form id.
 */
function mollom_form_load($form_id) {
  $cid = 'mollom:form:' . $form_id;
  if ($cache = cache_get($cid)) {
    return $cache->data;
  }
  else {
    $mollom_form = db_fetch_array(db_query("SELECT * FROM {mollom_form} WHERE form_id = '%s'", $form_id));
    if ($mollom_form) {
      $mollom_form['checks'] = unserialize($mollom_form['checks']);
      $mollom_form['enabled_fields'] = unserialize($mollom_form['enabled_fields']);

      // Attach form registry information.
      $form_list = module_invoke($mollom_form['module'], 'mollom_form_list');
      if (isset($form_list[$form_id])) {
        $mollom_form += $form_list[$form_id];
      }
      $mollom_form += mollom_form_info($form_id, $mollom_form['module']);

      cache_set($cid, $mollom_form);
    }
  }
  return $mollom_form;
}

/**
 * Saves a Mollom form configuration.
 */
function mollom_form_save(&$mollom_form) {
  $exists = db_result(db_query_range("SELECT 1 FROM {mollom_form} WHERE form_id = '%s'", $mollom_form['form_id'], 0, 1));
  $status = drupal_write_record('mollom_form', $mollom_form, ($exists ? 'form_id' : array()));

  // Allow modules to react on saved form configurations.
  if ($status === SAVED_NEW) {
    module_invoke_all('mollom_form_insert', $mollom_form);
  }
  else {
    module_invoke_all('mollom_form_update', $mollom_form);
  }

  // Flush cached Mollom forms and the Mollom form mapping cache.
  mollom_form_cache(TRUE);

  return $status;
}

/**
 * Deletes a Mollom form configuration.
 */
function mollom_form_delete($form_id) {
  $mollom_form = mollom_form_load($form_id);

  db_query("DELETE FROM {mollom_form} WHERE form_id = '%s'", $form_id);

  // Allow modules to react on saved form configurations.
  module_invoke_all('mollom_form_delete', $mollom_form);

  // Flush cached Mollom forms and the Mollom form mapping cache.
  mollom_form_cache(TRUE);
}

/**
 * Given an array of values and an array of fields, extract data for use.
 *
 * This function generates the data to send for validation to Mollom by walking
 * through the submitted form values and
 * - copying element values as specified via 'mapping' in hook_mollom_form_info()
 *   into the dedicated data properties
 * - collecting and concatenating all fields that have been selected for textual
 *   analysis into the 'post_body' property
 *
 * The processing accounts for the following possibilities:
 * - A field was selected for textual analysis, but there is no submitted form
 *   value. The value should have been appended to the 'post_body' property, but
 *   will be skipped.
 * - A field is contained in the 'mapping' and there is a submitted form value.
 *   The value will not be appended to the 'post_body', but instead be assigned
 *   to the specified data property.
 * - All fields specified in 'mapping', for which there is a submitted value,
 *   but which were NOT selected for textual analysis, are assigned to the
 *   specified data property. This is usually the case for form elements that
 *   hold system user information.
 *
 * @param $form_state
 *   An associative array containing
 *   - values: The submitted form values.
 *   - buttons: A list of button form elements. See form_state_values_clean().
 *   Not passed by reference.
 * @param $fields
 *   A list of strings representing form elements to extract. Nested fields are
 *   in the form of 'parent][child'.
 * @param $mapping
 *   An associative array of form elements to map to Mollom's dedicated data
 *   properties. See hook_mollom_form_info() for details.
 *
 * @see hook_mollom_form_info()
 */
function mollom_form_get_values($form_state, $fields, $mapping) {
  global $user;

  // Remove all button values from $form_state['values'].
  _mollom_form_state_values_clean($form_state);
  $form_values = $form_state['values'];

  // All elements specified in $mapping must be excluded from $fields, as they
  // are used for dedicated $data properties instead. To reduce the parsing code
  // size, we are turning a given $mapping of f.e.
  //   array('post_title' => 'title_form_element')
  // into
  //   array('title_form_element' => 'post_title')
  // and we reset $mapping afterwards.
  // When iterating over the $fields, this allows us to quickly test whether the
  // current field should be excluded, and if it should, we directly get the
  // mapped property name to rebuild $mapping with the field values.
  $exclude_fields = array();
  if (!empty($mapping)) {
    $exclude_fields = array_flip($mapping);
  }
  $mapping = array();

  // Process all fields that have been selected for text analysis.
  $post_body = array();
  foreach ($fields as $field) {
    // Nested elements use a key of 'parent][child', so we need to recurse.
    $parents = explode('][', $field);
    $value = $form_values;
    foreach ($parents as $key) {
      $value = isset($value[$key]) ? $value[$key] : NULL;
    }
    // If this field was contained in $mapping and should be excluded, add it to
    // $mapping with the actual form element value, and continue to the next
    // field. Also unset this field from $exclude_fields, so we can process the
    // remaining mappings below.
    if (isset($exclude_fields[$field])) {
      $mapping[$exclude_fields[$field]] = $value;
      unset($exclude_fields[$field]);
      continue;
    }
    // Only add form element values that are not empty.
    if (isset($value)) {
      // UTF-8 validation happens later.
      if (is_string($value) && strlen($value)) {
        $post_body[$field] = $value;
      }
      // Recurse into nested values (e.g. multiple value fields).
      elseif (is_array($value) && !empty($value)) {
        // Ensure we have a flat, indexed array to implode(); form values of
        // field_attach_form() use several subkeys.
        $value = _mollom_flatten_form_values($value);
        $post_body = array_merge($post_body, $value);
      }
    }
  }
  // XML-RPC parser of Mollom backend removes linefeeds, so use a combination of
  // space and linefeed to ensure proper separation of concatenated fields on
  // the backend but also have linefeeds in our logs.
  $post_body = implode(" \n", $post_body);

  // Try to assign any further form values by processing the remaining mappings,
  // which have been turned into $exclude_fields above. All fields that were
  // already used for 'post_body' no longer exist in $exclude_fields.
  foreach ($exclude_fields as $field => $property) {
    // Nested elements use a key of 'parent][child', so we need to recurse.
    $parents = explode('][', $field);
    $value = $form_values;
    foreach ($parents as $key) {
      $value = isset($value[$key]) ? $value[$key] : NULL;
    }
    if (isset($value)) {
      $mapping[$property] = $value;
    }
  }

  // Mollom's XML-RPC methods only accept data properties that are defined. We
  // also do not want to send more than we have to, so we need to build an
  // exact data structure.
  $data = array();
  // Post id; not sent to Mollom.
  // @see mollom_form_submit()
  if (!empty($mapping['post_id'])) {
    $data['post_id'] = $mapping['post_id'];
  }
  // Post title.
  if (!empty($mapping['post_title'])) {
    $data['post_title'] = $mapping['post_title'];
  }
  // Post body.
  if (!empty($post_body)) {
    $data['post_body'] = $post_body;
  }

  // User name.
  if (!empty($mapping['author_name'])) {
    $data['author_name'] = $mapping['author_name'];
    // Try to inherit user from author name.
    $account = user_load(array('name' => $data['author_name']));
  }
  elseif (!empty($user->name)) {
    $data['author_name'] = $user->name;
  }

  // User e-mail.
  if (!empty($mapping['author_mail'])) {
    $data['author_mail'] = $mapping['author_mail'];
  }
  elseif (!empty($data['author_name'])) {
    if (!empty($account->mail)) {
      $data['author_mail'] = $account->mail;
    }
  }
  elseif (!empty($user->mail)) {
    $data['author_mail'] = $user->mail;
  }

  // User homepage.
  if (!empty($mapping['author_url'])) {
    $data['author_url'] = $mapping['author_url'];
  }

  // User ID.
  if (!empty($mapping['author_id'])) {
    $data['author_id'] = $mapping['author_id'];
  }
  elseif (!empty($data['author_name'])) {
    if (!empty($account->uid)) {
      $data['author_id'] = $account->uid;
    }
  }
  elseif (!empty($user->uid)) {
    $data['author_id'] = $user->uid;
  }

  // User OpenID.
  if (!empty($mapping['author_openid'])) {
    $data['author_openid'] = $mapping['author_openid'];
  }
  elseif (!empty($data['author_id'])) {
    if (!empty($account->uid) && ($openid = _mollom_get_openid($account))) {
      $data['author_openid'] = $openid;
    }
  }
  elseif (!empty($user->uid) && ($openid = _mollom_get_openid($user))) {
    $data['author_openid'] = $openid;
  }

  // User IP.
  $data['author_ip'] = ip_address();

  // Honeypot.
  // For the Mollom backend, it only matters whether 'honeypot' is non-empty.
  // The submitted value is only taken over to allow site administrators to
  // see the actual honeypot value in watchdog log entries.
  if (isset($form_values['mollom']['homepage']) && $form_values['mollom']['homepage'] !== '') {
    $data['honeypot'] = $form_values['mollom']['homepage'];
  }

  // Ensure that all $data values contain valid UTF-8. Invalid UTF-8 would be
  // sanitized into an empty string, so the Mollom backend would not receive
  // any value.
  $invalid_utf8 = FALSE;
  $invalid_xml = FALSE;
  foreach ($data as $key => $value) {
    // Check for invalid UTF-8 byte sequences first.
    if (!drupal_validate_utf8($value)) {
      $invalid_utf8 = TRUE;
      // Replace the bogus string, since $data will be logged as
      // check_plain(var_export($data)), and check_plain() would empty the
      // entire exported variable string otherwise.
      $data[$key] = '- Invalid UTF-8 -';
    }
    // Since values are transmitted over XML-RPC and not merely output as
    // (X)HTML, they have to be valid XML characters.
    // @see http://www.w3.org/TR/2000/REC-xml-20001006#charsets
    // @see http://drupal.org/node/882298
    elseif (preg_match('@[^\x9\xA\xD\x20-\x{D7FF}\x{E000}-\x{FFFD}\x{10000}-\x{10FFFF}]@u', $value)) {
      $invalid_xml = TRUE;
    }
  }
  if ($invalid_utf8 || $invalid_xml) {
    form_set_error('', t('Your submission contains invalid characters and will not be accepted.'));
    _mollom_watchdog(array(
      'Invalid !type in form values' => array('!type' => $invalid_utf8 ? 'UTF-8' : 'XML characters'),
      'Data:<pre>@data</pre>' => array('@data' => $data),
    ));
    $data = FALSE;
  }

  return $data;
}

/**
 * #after_build callback to collect all buttons in the form.
 *
 * D7 provides this natively in $form_state['buttons'] and retains the info for
 * other modules, but D6 deletes $form_state['buttons'] right after any button
 * in the form has been built.
 *
 * @see form_builder()
 * @see _mollom_form_state_values_clean()
 */
function mollom_form_buttons_after_build(&$element, &$form_state) {
  // Only collect buttons upon a form submission.
  if (!empty($form_state['submitted'])) {
    foreach (element_children($element) as $key) {
      // If the element is a button, add it to the stack.
      if (isset($element[$key]['#type']) && ($element[$key]['#type'] == 'submit' || $element[$key]['#type'] == 'button')) {
        // Collect buttons in a separate key, since $form_state['mollom'] is
        // cached. Otherwise, repetitive form submissions would duplicate the
        // existing buttons stack.
        $form_state['mollom_buttons'][] = $element[$key];
      }
      // Otherwise, if the element has children, recurse into them.
      elseif (element_children($element[$key])) {
        mollom_form_buttons_after_build($element[$key], $form_state);
      }
    }
  }
  // #after_build callbacks are supposed to return the processed element. This
  // callback does not change the $form element. By taking it by reference, we
  // return the identical element that was passed in.
  return $element;
}

/**
 * Removes internal Form API elements and buttons from submitted form values.
 *
 * Backported from Drupal 7.
 *
 * This function can be used when a module wants to store all submitted form
 * values, for example, by serializing them into a single database column. In
 * such cases, all internal Form API values and all form button elements should
 * not be contained, and this function allows to remove them before the module
 * proceeds to storage. Next to button elements, the following internal values
 * are removed:
 * - form_id
 * - form_token
 * - form_build_id
 * - op
 *
 * @param $form_state
 *   A keyed array containing the current state of the form, including
 *   submitted form values; altered by reference.
 */
function _mollom_form_state_values_clean(&$form_state) {
  // Remove internal Form API values.
  unset($form_state['values']['form_id'], $form_state['values']['form_token'], $form_state['values']['form_build_id'], $form_state['values']['op']);

  // Remove button values.
  // form_builder() collects all button elements in a form. We remove the button
  // value separately for each button element.
  $buttons = !empty($form_state['mollom_buttons']) ? $form_state['mollom_buttons'] : array();
  foreach ($buttons as $button) {
    // Remove this button's value from the submitted form values by finding
    // the value corresponding to this button.
    // We iterate over the #parents of this button and move a reference to
    // each parent in $form_state['values']. For example, if #parents is:
    //   array('foo', 'bar', 'baz')
    // then the corresponding $form_state['values'] part will look like this:
    // array(
    //   'foo' => array(
    //     'bar' => array(
    //       'baz' => 'button_value',
    //     ),
    //   ),
    // )
    // We start by (re)moving 'baz' to $last_parent, so we are able unset it
    // at the end of the iteration. Initially, $values will contain a
    // reference to $form_state['values'], but in the iteration we move the
    // reference to $form_state['values']['foo'], and finally to
    // $form_state['values']['foo']['bar'], which is the level where we can
    // unset 'baz' (that is stored in $last_parent).
    $parents = $button['#parents'];
    $values = &$form_state['values'];
    $last_parent = array_pop($parents);
    foreach ($parents as $parent) {
      $values = &$values[$parent];
    }
    unset($values[$last_parent]);
  }
}

/**
 * Recursive helper function to flatten nested form values.
 *
 * Takes a potentially nested array and returns all non-empty string values in
 * nested keys as new indexed array.
 */
function _mollom_flatten_form_values($values) {
  $flat_values = array();
  foreach ($values as $value) {
    if (is_array($value) && !empty($value)) {
      $flat_values = array_merge($flat_values, _mollom_flatten_form_values($value));
    }
    // UTF-8 validation happens elsewhere later.
    elseif (is_string($value) && strlen($value)) {
      $flat_values[] = $value;
    }
  }
  return $flat_values;
}

/**
 * Helper function to return OpenID identifiers associated with a given user account.
 */
function _mollom_get_openid($account) {
  if (isset($account->uid)) {
    $result = db_query("SELECT * FROM {authmap} WHERE module = 'openid' AND uid = %d", $account->uid);

    $ids = array();
    while ($identity = db_fetch_object($result)) {
      $ids[] = $identity->authname;
    }

    if (!empty($ids)) {
      return implode($ids, ' ');
    }
  }
}

/**
 * Returns the (last known) status of the configured Mollom API keys.
 *
 * @param $reset
 *   (optional) Boolean whether to reset the stored state and re-check.
 *   Defaults to FALSE.
 *
 * @return
 *   TRUE if the module is considered operable, or an associative array
 *   describing the current status of the module:
 *   - keys: Boolean whether Mollom API keys have been configured.
 *   - keys valid: TRUE if Mollom API keys are valid, or the error code as
 *     returned by Mollom servers.
 *   - servers: Boolean whether there is a non-empty list of Mollom servers.
 *
 * @see mollom_init()
 * @see mollom_admin_settings()
 * @see mollom_requirements()
 */
function _mollom_status($reset = FALSE) {
  // Load stored status.
  $status = variable_get('mollom_status', array(
    'keys' => FALSE,
    'keys valid' => FALSE,
  ));

  // Both API keys are required.
  $public_key = variable_get('mollom_public_key', '');
  $private_key = variable_get('mollom_private_key', '');
  $status['keys'] = (!empty($public_key) && !empty($private_key));

  // If we have keys and are asked to reset, check whether keys are valid.
  if ($status['keys'] && $reset) {
    $status['keys valid'] = mollom('mollom.verifyKey', _mollom_get_version());
  }
  // Otherwise, if there are no keys, they cannot be valid.
  elseif (!$status['keys']) {
    $status['keys valid'] = FALSE;
  }

  // In case of an error, indicate whether we have a non-empty server list.
  if ($status['keys valid'] !== TRUE) {
    $servers = variable_get('mollom_servers', array());
    $status['servers'] = !empty($servers);
  }

  // Update stored status upon reset.
  if ($reset) {
    variable_set('mollom_status', $status);
  }

  return ($status['keys valid'] === TRUE ? TRUE : $status);
}

/**
 * Outputs a warning message about enabled testing mode (once).
 */
function _mollom_testing_mode_warning() {
  static $warned;
  if (isset($warned)) {
    return;
  }
  $warned = TRUE;

  if (variable_get('mollom_testing_mode', 0) && empty($_POST)) {
    $admin_message = '';
    if (user_access('administer mollom') && $_GET['q'] != 'admin/settings/mollom/settings') {
      $admin_message = t('Visit the <a href="@settings-url">Mollom settings page</a> to disable it.', array(
        '@settings-url' => url('admin/settings/mollom/settings'),
      ));
    }
    $message = t('Mollom testing mode is still enabled. !admin-message', array(
      '!admin-message' => $admin_message,
    ));
    drupal_set_message($message, 'warning');
  }
}

/**
 * Helper function to log and optionally output an error message when Mollom servers are unavailable.
 */
function _mollom_fallback() {
  $fallback = variable_get('mollom_fallback', MOLLOM_FALLBACK_BLOCK);
  // @todo Prevents mollom_admin_settings() from implementing a proper form
  //   validation. Add !empty($_POST) to this condition + manually invoke from
  //   mollom_process_form() on GET requests? Or don't call it from mollom()?
  //   Anything, but just don't mix FAPI logic into XML-RPC logic.
  if ($fallback == MOLLOM_FALLBACK_BLOCK) {
    form_set_error('mollom', t("The spam filter installed on this site is currently unavailable. Per site policy, we are unable to accept new submissions until that problem is resolved. Please try resubmitting the form in a couple of minutes."));
  }

  $servers = variable_get('mollom_servers', array());
  _mollom_watchdog(array(
    'All servers unavailable: %servers' => array('%servers' => $servers ? implode(', ', $servers) : '--'),
    'Last error: @code %message' => array('@code' => xmlrpc_errno(), '%message' => xmlrpc_error_msg()),
  ), WATCHDOG_ERROR);
}

/**
 * @defgroup mollom_form_api Mollom Form API workarounds
 * @{
 * Various helper functions to work around bugs in Form API.
 *
 * Normally, Mollom's integration with Form API would be quite simple:
 * - If a form is protected by Mollom, we setup initial information
 *   about the session and the form in $form_state['storage'], bound to the
 *   'form_build_id'.
 * - We enable form caching via $form_state['cache'], so our information in the
 *   form storage is cached. Form API then automatically ensures a proper
 *   'form_build_id' for every form and every user.
 * - We mainly work in and after form validation. Textual analysis validates all
 *   values in the form as a form validation handler. If this validation fails,
 *   we alter the form (during validation) to add a CAPTCHA. If the CAPTCHA
 *   response is invalid, we still alter the form during validation to display a
 *   new CAPTCHA, but without the previously entered value.
 * - In short, roughly:
 *   - Form construction: Nothing.
 *   - Form processing: Nothing.
 *   - Form validation: Perform validation and alterations based on validation.
 *
 * This, however, is not possible due to various bugs in Drupal core.
 * - Form caching cannot be enabled for certain forms, because they contain
 *   processing and validation logic.
 *   http://drupal.org/node/644222
 * - $form_state['storage'] is not updated after form processing and validation.
 *   http://drupal.org/node/644150
 * - Form validation handlers cannot alter the form structure.
 *   http://drupal.org/node/642702
 *
 * Hence, something that could be done in one simple function becomes quite a
 * nightmare:
 * - We need our own {cache_mollom} table as replacement for native form
 *   caching, as well as our own logic to validate a submitted 'session_id'
 *   ('form_build_id') against forms and users.
 * - We need to perform form alterations during form rendering, where
 *   $form_state is no longer available. To make this possible, we leverage the
 *   fact that an element property that is a reference to a key in $form_state
 *   (which in itself is passed by reference) persists on to the rendering
 *   layer. The essential part is:
 *   @code
 *     $element['#mollom'] = &$form_state['mollom'];
 *   @endcode
 * - Since we cannot alter elements in the form structure during form
 *   validation, this reference already needs to be set up during form
 *   processing (in a #process callback), while everything else lives in form
 *   validation handlers (unless it needs to add or alter the form structure).
 *
 * @see mollom_form_alter()
 */

/**
 * Implements hook_elements().
 */
function mollom_elements() {
  return array(
    'mollom' => array(
      '#input' => TRUE,
      '#process' => array(
        // Try to fetch a Mollom session from cache during form processing/validation.
        'mollom_process_mollom_session_id',
        // Setup a new Mollom session.
        'mollom_process_mollom',
      ),
      '#pre_render' => array('mollom_pre_render_mollom'),
    ),
  );
}

/**
 * Implements hook_theme().
 */
function mollom_theme() {
  return array(
    'mollom' => array(
      'arguments' => array('element' => NULL),
    ),
    'mollom_admin_blacklist_form' => array(
      'arguments' => array('form' => NULL),
      'file' => 'mollom.admin.inc',
    ),
  );
}

/**
 * Format the Mollom form element.
 *
 * This works like #type 'markup' and is only required, because D6 only supports
 * #process callbacks on elements with #input = TRUE.
 *
 * @see form_builder()
 * @see _form_builder_handle_input_element()
 */
function theme_mollom($element) {
  return isset($element['#children']) ? $element['#children'] : '';
}

/**
 * Form element #process callback for the 'mollom' element.
 *
 * The 'mollom' form element is stateful. The Mollom session ID that is exchanged
 * between Drupal, the Mollom back-end, and the user allows us to keep track of
 * the form validation state.
 *
 * The session ID is valid for a given $form_id only. We expire it as soon as
 * the form is submitted, to avoid it being replayed.
 */
function mollom_process_mollom($element, $input, &$form_state, $complete_form) {
  // Setup initial Mollom session and form information.
  $form_state += array('mollom' => array());
  $form_state['mollom'] += array(
    'require_analysis' => $element['#mollom_form']['mode'] == MOLLOM_MODE_ANALYSIS,
    'require_captcha' => $element['#mollom_form']['mode'] == MOLLOM_MODE_CAPTCHA,
    'passed_captcha' => FALSE,
    'require_moderation' => FALSE,
    'response' => array(
      'session_id' => '',
    ),
  );
  $form_state['mollom'] += $element['#mollom_form'];

  // By default, bad form submissions are discarded, unless the form was
  // configured to moderate bad posts. 'discard' may only be FALSE, if there is
  // a valid 'moderation callback'. Otherwise, it must be TRUE.
  if (empty($form_state['mollom']['moderation callback']) || !function_exists($form_state['mollom']['moderation callback'])) {
    $form_state['mollom']['discard'] = TRUE;
  }

  // Add the Mollom session element.
  $element['session_id'] = array(
    '#type' => 'hidden',
    '#default_value' => isset($form_state['mollom']['response']['session_id']) ? $form_state['mollom']['response']['session_id'] : '',
    '#attributes' => array('class' => 'mollom-session-id'),
  );

  // Add the CAPTCHA element.
  $element['captcha'] = array(
    '#type' => 'textfield',
    '#title' => t('Word verification'),
    '#size' => 10,
    '#default_value' => '',
    '#description' => t("Type the characters you see in the picture above; if you can't read them, submit the form and a new image will be generated. Not case sensitive."),
  );
  // Disable browser autocompletion, unless testing mode is enabled, in which
  // case autocompletion for 'correct' and 'incorrect' is handy.
  if (!variable_get('mollom_testing_mode', 0)) {
    $element['captcha']['#attributes']['autocomplete'] = 'off';
  }

  // Add a spambot trap. Purposively use 'homepage' as field name.
  // @todo Use a random field name (from the usual names of 'name', 'email',
  //   'url', etc.) to make it harder to identify this trap.
  $element['homepage'] = array(
    '#type' => 'textfield',
    // Wrap the entire honeypot form element markup into a hidden container, so
    // robots cannot simply check for a style attribute, but instead have to
    // implement advanced DOM processing to figure out whether they are dealing
    // with a honeypot field.
    '#prefix' => '<div style="display: none;">',
    '#suffix' => '</div>',
    // Although this input is hidden and not visible to screen readers,
    // accessibility validators (such as WAVE) would still complain about a form
    // field without any kind of legend/label. t() is needless here.
    '#attributes' => array(
      'title' => 'Homepage',
      // Disable browser autocompletion.
      'autocomplete' => 'off',
    ),
  );

  // Make Mollom form and session information available to #pre_render callback.
  // This must be assigned by reference. It is the essential "communication
  // layer" between form API and the rendering system. Any modifications to
  // $form_state['mollom'] will be carried over to the element for rendering.
  $element['#mollom'] = &$form_state['mollom'];

  // Make Mollom form and session information available to entirely different
  // functions.
  $GLOBALS['mollom'] = &$form_state['mollom'];

  return $element;
}

/**
 * Form element #process callback for Mollom's form storage handling.
 *
 * Albeit this *should* be an #element_validate handler that is only executed
 * during form validation, we must use a #process callback, because
 * mollom_process_mollom() needs to copy over $form_state['mollom'] into
 * $element['#mollom'], and as of now, Form API does not allow form validation
 * handlers to alter any elements in the form structure by reference.
 * @see http://drupal.org/node/642702
 */
function mollom_process_mollom_session_id($element, $input, &$form_state) {
  // The current state can come either from the $form_state, if the form
  // was just rebuilt in the same request, or from data posted by the user. In
  // the latter case the state is fetched from the temporary data store. It is
  // verified that the session was created for the current form and that it has
  // not expired or already been used.
  if (empty($form_state['mollom']) && !empty($input['session_id'])) {
    @list($timestamp, $mollom_session_id) = explode('-', $input['session_id'], 2);

    if (empty($mollom_session_id)) {
      watchdog('mollom', 'Bogus session id %session.', array('%session' => $form_state['input']['mollom']['session_id']), WATCHDOG_WARNING);
    }
    elseif (!$cache = cache_get($mollom_session_id, 'cache_mollom')) {
      if (time() - $timestamp > 30 * 60) {
        watchdog('mollom', 'Expired session id %session.', array('%session' => $mollom_session_id));
      }
      else {
        watchdog('mollom', 'Unknown session id %session. This is not a bug in Mollom. If this happens too often, check your site for attacks.', array('%session' => $mollom_session_id), WATCHDOG_WARNING);
      }
    }
    elseif ($cache->data['form_id'] !== $form_state['values']['form_id']) {
      watchdog('mollom', 'Invalid form id %form_id for session id %session (generated for %form_id_session).  This is not a bug in Mollom. If this happens too often, check your site for attacks.', array('%session' => $mollom_session_id, '%form_id_session' => $cache->data['form_id'], '%form_id' => $form_state['values']['form_id']), WATCHDOG_WARNING);
    }
    else {
      $form_state['mollom'] = $cache->data;
    }
  }
  return $element;
}

/**
 * Form validation handler to perform textual analysis of submitted form values.
 *
 * Validation needs to re-run in case of a form validation error (elsewhere in
 * the form). In case Mollom's textual analysis returns no definite result, we
 * must trigger a CAPTCHA, but text analysis is always performed, even if the
 * CAPTCHA was solved correctly.
 */
function mollom_validate_analysis(&$form, &$form_state) {
  // Text analysis may only ever be skipped, if we do not require it in the
  // first place. With regard to that, $form_state['mollom']['require_analysis']
  // is only set once during initialization of $form_state['mollom'] in
  // mollom_process_form() and must not be updated elsewhere.
  if (!$form_state['mollom']['require_analysis']) {
    return;
  }

  // Perform textual analysis.
  $all_data = mollom_form_get_values($form_state, $form_state['mollom']['enabled_fields'], $form_state['mollom']['mapping']);
  // Cancel processing upon invalid UTF-8 data.
  if ($all_data === FALSE) {
    return;
  }
  $data = $all_data;
  // Remove 'post_id' property; only used by mollom_form_submit().
  if (isset($data['post_id'])) {
    unset($data['post_id']);
  }
  $data['session_id'] = $form_state['mollom']['response']['session_id'];
  $data['checks'] = implode(',', $form_state['mollom']['checks']);
  $data['strictness'] = $form_state['mollom']['strictness'];
  $result = mollom('mollom.checkContent', $data);

  // Use all available data properties for log messages below.
  $data += $all_data;

  // Trigger global fallback behavior if there is no result.
  if (!isset($result['session_id'])) {
    return _mollom_fallback();
  }

  // If a new session ID was generated by Mollom, flush the old session from the
  // database cache.
  if (!empty($form_state['mollom']['response']['session_id']) && $result['session_id'] != $form_state['mollom']['response']['session_id']) {
    cache_clear_all($form_state['mollom']['response']['session_id'], 'cache_mollom');
  }
  // Store the response returned by Mollom.
  $form_state['mollom']['response'] = $result;

  // Prepare watchdog message teaser text.
  $teaser = '--';
  if (isset($data['post_title'])) {
    $teaser = truncate_utf8(strip_tags($data['post_title']), 40);
  }
  elseif (isset($data['post_body'])) {
    $teaser = truncate_utf8(strip_tags($data['post_body']), 40);
  }

  // Handle the profanity check result.
  if (isset($result['profanity']) && $result['profanity'] >= 0.5) {
    if ($form_state['mollom']['discard']) {
      form_set_error('mollom', t('Your submission has triggered the profanity filter and will not be accepted until the inappropriate language is removed.'));
    }
    else {
      $form_state['mollom']['require_moderation'] = TRUE;
    }
    _mollom_watchdog(array(
      'Profanity: %teaser' => array('%teaser' => $teaser),
      'Data:<pre>@data</pre>' => array('@data' => $data),
      'Result:<pre>@result</pre>' => array('@result' => $result),
    ));
  }

  // Handle the spam check result.
  // The Mollom backend is remembering results of previous mollom.checkContent
  // invocations for a single user/post session. When content is re-checked
  // during form validation, the result may change according to the values that
  // have been submitted (which e.g. can change during previews). Only in case
  // the spam check led to a MOLLOM_ANALYSIS_UNSURE result, and the user solved
  // the CAPTCHA correctly, subsequent spam check results will likely be
  // MOLLOM_ANALYSIS_HAM (though not guaranteed).
  if (isset($result['spam'])) {
    switch ($result['spam']) {
      case MOLLOM_ANALYSIS_HAM:
        $form_state['mollom']['require_captcha'] = FALSE;
        _mollom_watchdog(array(
          'Ham: %teaser' => array('%teaser' => $teaser),
          'Data:<pre>@data</pre>' => array('@data' => $data),
          'Result:<pre>@result</pre>' => array('@result' => $result),
        ), WATCHDOG_INFO);
        break;

      case MOLLOM_ANALYSIS_SPAM:
        $form_state['mollom']['require_captcha'] = FALSE;
        if ($form_state['mollom']['discard']) {
          form_set_error('mollom', t('Your submission has triggered the spam filter and will not be accepted.'));
        }
        else {
          $form_state['mollom']['require_moderation'] = TRUE;
        }
        _mollom_watchdog(array(
          'Spam: %teaser' => array('%teaser' => $teaser),
          'Data:<pre>@data</pre>' => array('@data' => $data),
          'Result:<pre>@result</pre>' => array('@result' => $result),
        ));
        break;

      case MOLLOM_ANALYSIS_UNSURE:
        _mollom_watchdog(array(
          'Unsure: %teaser' => array('%teaser' => $teaser),
          'Data:<pre>@data</pre>' => array('@data' => $data),
          'Result:<pre>@result</pre>' => array('@result' => $result),
        ), WATCHDOG_INFO);

        // Only throw a validation error and retrieve a CAPTCHA, if we check
        // this post for the first time. Otherwise, mollom_validate_captcha()
        // issued the CAPTCHA and needs to validate it prior to throwing any
        // errors.
        if (!$form_state['mollom']['require_captcha']) {
          $form_state['mollom']['require_captcha'] = TRUE;
          form_set_error('mollom][captcha', t('To complete this form, please complete the word verification below.'));
        }
        break;

      case MOLLOM_ANALYSIS_UNKNOWN:
      default:
        // If we end up here, Mollom responded with an unknown 'spam' value.
        // Normally, this should not happen, but if it does, log it. As there
        // could be multiple reasons for this, it is not safe to trigger the
        // fallback mode.
        _mollom_watchdog(array(
          'Unknown: %teaser' => array('%teaser' => $teaser),
          'Data:<pre>@data</pre>' => array('@data' => $data),
          'Result:<pre>@result</pre>' => array('@result' => $result),
        ));
        break;
    }
  }
}

/**
 * Form validation handler for Mollom's CAPTCHA form element.
 *
 * Validates whether a CAPTCHA was solved correctly. A form may contain a
 * CAPTCHA, if it was configured to be protected by a CAPTCHA only, or when the
 * text analysis result is "unsure".
 */
function mollom_validate_captcha(&$form, &$form_state) {
  // CAPTCHA validation may only be skipped, if we do not require it in the
  // first place, or if the user already solved a CAPTCHA correctly. We need to
  // validate, if $form_state['mollom']['require_captcha'] is TRUE, which is
  // either set during initialization of $form_state['mollom'] in
  // mollom_process_form(), or after performing text analysis. The second
  // return condition, $form_state['mollom']['passed_captcha'], may only ever be
  // set by this validation handler and must not be changed elsewhere.
 if (!$form_state['mollom']['require_captcha'] || $form_state['mollom']['passed_captcha']) {
    return;
  }

  // Nothing to validate if there is no value.
  // @todo The field is #required, so Form API should already handle this. Add a
  //   test to be sure and remove this code.
  if (empty($form_state['values']['mollom']['captcha'])) {
    form_set_error('mollom][captcha', t('The word verification field is required.'));
    return;
  }

  // Check the CAPTCHA result.
  // Next to the Mollom session id and captcha result, the Mollom back-end also
  // takes into account the author's IP and local user id (if registered). Any
  // other values are ignored.
  $all_data = mollom_form_get_values($form_state, $form_state['mollom']['enabled_fields'], $form_state['mollom']['mapping']);
  // Cancel processing upon invalid UTF-8 data.
  if ($all_data === FALSE) {
    return;
  }
  $data = array(
    'session_id' => $form_state['mollom']['response']['session_id'],
    'captcha_result' => $form_state['values']['mollom']['captcha'],
    'author_ip' => $all_data['author_ip'],
  );
  if (isset($all_data['author_id'])) {
    $data['author_id'] = $all_data['author_id'];
  }
  if (isset($all_data['honeypot'])) {
    $data['honeypot'] = $all_data['honeypot'];
  }
  $result = mollom('mollom.checkCaptcha', $data);
  // Use all available data properties for log messages below.
  $data += $all_data;

  // Invoke fallback behavior upon a server error; communication errors are
  // handled by mollom() already. A server error may happen in case of an
  // expired or invalid session_id.
  if ($result === MOLLOM_ERROR) {
    return _mollom_fallback();
  }

  // Store the response for #submit handlers.
  $form_state['mollom']['response']['captcha'] = $result;

  if ($result === TRUE) {
    $form_state['mollom']['passed_captcha'] = TRUE;

    _mollom_watchdog(array(
      'Correct CAPTCHA' => array(),
      'Data:<pre>@data</pre>' => array('@data' => $data),
      'Result:<pre>@result</pre>' => array('@result' => $result),
    ), WATCHDOG_INFO);
  }
  else {
    form_set_error('mollom][captcha', t('The word verification was not completed correctly. Please complete this new word verification and try again.'));
    _mollom_watchdog(array(
      'Incorrect CAPTCHA' => array(),
      'Data:<pre>@data</pre>' => array('@data' => $data),
      'Result:<pre>@result</pre>' => array('@result' => $result),
    ), WATCHDOG_INFO);
  }
}

/**
 * Form element #pre_render callback for CAPTCHA element.
 *
 * Conditionally alters the #type of the CAPTCHA form element into a 'hidden'
 * element if the response was correct. If it was not, then we empty the value
 * of the textfield to allow the user to re-enter a new one.
 *
 * This #pre_render trick is required, because form API validation does not
 * allow form validation handlers to alter the actual form structure. Both the
 * form constructor function and the #process callback for the 'mollom' element
 * are therefore executed too early (before form validation), so the CAPTCHA
 * element still contains not yet validated (default) values.
 * We also cannot invoke a form validation handler during form construction or
 * processing, because mollom_form_get_values() would be invoked too early
 * and therefore $form_state['values'] would not contain any additions from
 * form validation functions like mollom_comment_form_validate().
 * @see http://drupal.org/node/642702
 */
function mollom_pre_render_mollom($element) {
  $form_state['mollom'] = &$element['#mollom'];
  // Request and inject a CAPTCHA when required; but also in case validation
  // through textual analysis failed.
  if ($form_state['mollom']['require_captcha'] && !$form_state['mollom']['passed_captcha']) {
    $element['captcha']['#required'] = TRUE;
    // Empty the CAPTCHA field value, since the user has to re-enter a new one.
    $element['captcha']['#value'] = '';

    // Prevent the page cache from storing a form containing a CAPTCHA element.
    $GLOBALS['conf']['cache'] = CACHE_DISABLED;
    // Pressflow in CACHE_EXTERNAL caching mode additionally requires to mark
    // this request as non-cacheable to bypass external caches (e.g., Varnish).
    if (function_exists('drupal_page_is_cacheable')) {
      drupal_set_header('Cache-Control', 'no-cache, must-revalidate, post-check=0, pre-check=0', FALSE);
    }

    $data = array();
    if (!empty($form_state['mollom']['response']['session_id'])) {
      $data['session_id'] = $form_state['mollom']['response']['session_id'];
    }
    $captcha = mollom_get_captcha('image', $data);

    // If we get a response, add the image CAPTCHA to the form element.
    if (isset($captcha['response']['session_id']) && !empty($captcha['markup'])) {
      $element['captcha']['#field_prefix'] = $captcha['markup'];

      // If a new session ID was generated by Mollom, flush the old session from
      // the database cache.
      if (!empty($form_state['mollom']['response']['session_id']) && $captcha['response']['session_id'] != $form_state['mollom']['response']['session_id']) {
        cache_clear_all($form_state['mollom']['response']['session_id'], 'cache_mollom');
      }
      // Assign the session ID returned by Mollom.
      $form_state['mollom']['response']['session_id'] = $captcha['response']['session_id'];
    }
    // Otherwise, we have a communication or configuration error.
    // @todo Short-cut form processing entirely in this case; see also
    //   mollom_validate_captcha().
    else {
      $form_state['mollom']['require_analysis'] = FALSE;
      $form_state['mollom']['require_captcha'] = FALSE;
      return array();
    }
  }
  // If no CAPTCHA is required or the response was correct, hide the CAPTCHA.
  elseif (!$form_state['mollom']['require_captcha'] || $form_state['mollom']['passed_captcha']) {
    $element['captcha']['#access'] = FALSE;
  }

  // If we received a Mollom session id via textual analysis or a CAPTCHA
  // request, inject it to the form.
  $timestamp = time();
  if (!empty($form_state['mollom']['response']['session_id'])) {
    $element['session_id']['#value'] = $timestamp . '-' . $form_state['mollom']['response']['session_id'];
    cache_set($form_state['mollom']['response']['session_id'], $form_state['mollom'], 'cache_mollom', $timestamp + 21600);
  }

  return $element;
}

/**
 * Form validation handler to perform post-validation tasks.
 */
function mollom_validate_post(&$form, &$form_state) {
  // Retain a post instead of discarding it. If 'discard' is FALSE, then the
  // 'moderation callback' is responsible for altering $form_state in a way that
  // the post ends up in a moderation queue. Most callbacks will only want to
  // set or change a value in $form_state.
  if ($form_state['mollom']['require_moderation']) {
    $function = $form_state['mollom']['moderation callback'];
    $function($form, $form_state);
  }
}

/**
 * Form submit handler to clean up internal Mollom values from $form_state['values'].
 *
 * Some form submit handlers blindly take over and save all submitted form
 * values in $form_state['values'] into the database. To prevent Mollom's
 * internal values from being mistakenly stored somewhere else, this submit
 * handler is prepended to the stack of $form['#submit'] handlers of protected
 * forms.
 *
 * @todo Fix Drupal core to remove the need for separately prepended submit
 *   handlers like this one by making form_state_values_clean() invoke a hook.
 * @see http://drupal.org/node/939510
 */
function mollom_form_pre_submit($form, &$form_state) {
  // Some modules are implementing multi-step forms without separate form
  // submit handlers. In case we reach here and the form will be rebuilt, we
  // need to defer our submit handling until final submission.
  if (!empty($form_state['rebuild'])) {
    return;
  }
  // When having passed the form validation stage and reaching the form
  // submission stage, all submitted form values have been processed into
  // $form_state['mollom'] already, so the entire top-level 'mollom' key can be
  // safely removed.
  unset($form_state['values']['mollom']);
}

/**
 * Form submit handler to flush Mollom session and form information from cache.
 */
function mollom_form_submit($form, &$form_state) {
  // Some modules are implementing multi-step forms without separate form
  // submit handlers. In case we reach here and the form will be rebuilt, we
  // need to defer our submit handling until final submission.
  if (!empty($form_state['rebuild'])) {
    return;
  }
  // If an 'entity' and a 'post_id' mapping was provided via
  // hook_mollom_form_info(), try to automatically store Mollom session data.
  if (!empty($form_state['mollom']['entity']) && isset($form_state['mollom']['mapping']['post_id'])) {
    // For new entities, the entity's form submit handler will have added the
    // new entity id value into $form_state['values'], so we need to rebuild the
    // data mapping. We do not care for the actual fields, only for the value of
    // the mapped post_id.
    // Note that most entity forms in Drupal 6 do not insert the entity ID for
    // new entities into the $form. Therefore, this code does not run for them,
    // but instead requires dedicated hook_nodeapi() and hook_comment()
    // implementations.
    $values = mollom_form_get_values($form_state, array(), $form_state['mollom']['mapping']);
    // We only consider non-empty and non-zero values as valid entity ids.
    if (!empty($values['post_id'])) {
      // Save the Mollom session data.
      $data = (object) $form_state['mollom']['response'];
      $data->entity = $form_state['mollom']['entity'];
      $data->id = $values['post_id'];
      $data->form_id = $form_state['mollom']['form_id'];
      $form_state['mollom']['data'] = mollom_data_save($data);
    }
  }
  // Flush Mollom session information from database cache.
  if (!empty($form_state['mollom']['response']['session_id'])) {
    cache_clear_all($form_state['mollom']['response']['session_id'], 'cache_mollom');
  }
}

/**
 * @} End of "defgroup mollom_form_api".
 */

/**
 * Call a remote procedure at the Mollom server.
 *
 * This function automatically adds the information required to authenticate
 * against Mollom.
 *
 * @todo Currently, this function's return value mixes actual values and
 *   error values. We should rewrite the error handling so that calling
 *   functions can properly handle error situations.
 */
function mollom($method, $data = array()) {
  module_load_include('inc', 'mollom');
  $messages = array();

  // Initialize refresh variable.
  $refresh = FALSE;

  // Enable testing mode.
  if (variable_get('mollom_testing_mode', 0)) {
    $data['testing'] = TRUE;
  }

  // Retrieve the list of Mollom servers from the database.
  $servers = variable_get('mollom_servers', array());

  if (empty($servers)) {
    // Retrieve a new list of servers.
    $servers = _mollom_retrieve_server_list();
    // If API keys are invalid, a XML-RPC error code is returned.
    if (!is_array($servers)) {
      return $servers;
    }

    $messages[] = array(
      'Refreshed servers: %servers' => array('%servers' => implode(', ', $servers)),
    );

    // Store the list of servers in the database.
    variable_set('mollom_servers', $servers);
  }

  if (is_array($servers)) {
    // Send the request to the first server; if that fails, try the other
    // servers in the list.
    reset($servers);
    while ($server = current($servers)) {
      $result = xmlrpc($server . '/' . MOLLOM_API_VERSION, $method, $data + _mollom_authentication());

      if ($result === FALSE && ($error = xmlrpc_error())) {
        if ($error->code === MOLLOM_REFRESH) {
          // Avoid endless loops.
          if (!$refresh) {
            $refresh = TRUE;

            // Retrieve a new list of valid Mollom servers.
            $servers = _mollom_retrieve_server_list();
            // If API keys are invalid, the XML-RPC error code is returned.
            // To reach this, we must have had a server list (and therefore
            // valid keys) before, so we do not immediately return (like above),
            // but instead trigger the fallback mode.
            if (!is_array($servers)) {
              break;
            }

            // Reset the list of servers to restart from the first server.
            reset($servers);

            // Update the server list.
            variable_set('mollom_servers', $servers);

            $messages[] = array(
              'Refreshed servers: %servers' => array('%servers' => implode(', ', $servers)),
            );
          }
        }
        elseif ($error->code === MOLLOM_REDIRECT) {
          // Try the next server in the list.
          $next = next($servers);

          $messages[] = array(
            'Server %server redirected to: %next.' => array('%server' => $server, '%next' => $next),
          );
        }
        else {
          $messages[] = array(
            'Error @errno from %server for %method: %message' => array(
              '@errno' => $error->code,
              '%server' => $server,
              '%method' => $method,
              '%message' => $error->message,
            ),
            'Data:<pre>@data</pre>' => array('@data' => $data),
          );

          // Instantly return upon a 'real' error.
          if ($error->code === MOLLOM_ERROR) {
            _mollom_watchdog_multiple($messages, WATCHDOG_ERROR);
            return MOLLOM_ERROR;
          }
          // Otherwise, try the next server.
          next($servers);
        }
      }
      else {
        _mollom_watchdog_multiple($messages, WATCHDOG_DEBUG);
        return $result;
      }
    }
  }

  // If none of the servers worked, activate the fallback mechanism.
  // @todo mollom() can be invoked outside of form processing. _mollom_fallback()
  //   unconditionally invokes form_set_error(), which always displays the
  //   fallback error message. Ideally, we would pass a $verbose argument to
  //   _mollom_fallback(), but for that, we'd have to know here already.
  //   Consequently, mollom() would need that $verbose argument. In the end, we
  //   likely want to either embed the fallback handling into form processing,
  //   or introduce a new helper function that is invoked instead of mollom()
  //   during form processing.
  if ($method != 'mollom.verifyKey') {
    _mollom_fallback();
  }

  // If everything failed, we reset the server list to force Mollom to request
  // a new list.
  variable_del('mollom_servers');

  // Report this error.
  $messages[] = array(
    'All servers unreachable or returning errors. The server list was emptied.' => array(),
  );
  _mollom_watchdog_multiple($messages, WATCHDOG_ERROR);

  return NETWORK_ERROR;
}

/**
 * Log a Mollom system message.
 *
 * @param $parts
 *   A list of message parts. Each item is an associative array whose keys are
 *   log message strings and whose corresponding values are t()-style
 *   replacement token arguments. At least one part is required.
 * @param $severity
 *   The severity of the message, as per RFC 3164. Possible values are
 *   WATCHDOG_ERROR, WATCHDOG_WARNING, etc.
 *
 * @see watchdog()
 */
function _mollom_watchdog($parts, $severity = WATCHDOG_NOTICE) {
  // First message part is required.
  $message = key($parts);
  $arguments = $parts[$message];
  unset($parts[$message]);

  // Hide further message details in the log overview table, if any.
  // @see theme_dblog_message()
  if ($parts) {
    $message = str_pad($message, 56, ' ', STR_PAD_RIGHT);
    $message .= '<br />';
  }

  // Each item in $parts is a part of the log message.
  foreach ($parts as $string => $string_arguments) {
    $message .= $string . "\n";
    $arguments += $string_arguments;
  }

  // Prettify replacement token values, if possible.
  foreach ($arguments as $token => $array) {
    // Only prettify NULL, Booleans, arrays, and objects. All other values can
    // be replaced as is.
    if (is_scalar($array) && !is_bool($array)) {
      continue;
    }
    $flat_value = FALSE;
    // Convert arrays and objects.
    if (isset($array) && !is_scalar($array)) {
      $flat_value = '';
      foreach ($array as $key => $value) {
        // Only convert one-dimensional arrays, or we would lose debugging data.
        if (is_array($value)) {
          $flat_value = FALSE;
          break;
        }
        $value = var_export($value, TRUE);
        // Indent the new value, so there is a visual separation from the last.
        $flat_value .= "  {$key} = {$value}\n";
      }
    }
    // Use string representation of one-dimensional arrays and objects.
    if ($flat_value !== FALSE) {
      $arguments[$token] = $flat_value;
    }
    // Use var_export() representation for NULL, Booleans, and multi-dimensional
    // arrays and objects.
    else {
      $arguments[$token] = var_export($array, TRUE);
    }
  }

  watchdog('mollom', $message, $arguments, $severity);
}

/**
 * Helper function for mollom() to invoke watchdog() with cumulative messages.
 *
 * We do not want false errors to clutter the log, for example, when the server
 * list failed, but we were able to retrieve new servers. We therefore collect
 * all messages and invoke this function in mollom() right before returning any
 * XML-RPC response with the entire stack of collected messages.
 * This is also required for tests to pass.
 */
function _mollom_watchdog_multiple($messages, $severity) {
  foreach ($messages as $message) {
    _mollom_watchdog($message, $severity);
  }
}

/**
 * Returns version information to send with mollom.verifyKey.
 *
 * Retrieves platform and module version information for mollom.verifyKey, which
 * is normally invoked on Mollom's administration pages only.
 *
 * This information is solely used to speed up support requests and technical
 * inquiries. The data may also be aggregated to help the Mollom staff to make
 * decisions on new features or the necessity of back-porting improved
 * functionality to older versions.
 *
 * @return
 *   An array containing:
 *   - platform_name: The name of the Drupal distribution; i.e., "Drupal".
 *   - platform_version: The version of Drupal; e.g., "7.0".
 *   - client_name: The module name; i.e., "Mollom".
 *   - client_version: The version of the module; e.g., "7.x-1.0".
 *
 * @see _mollom_status()
 */
function _mollom_get_version() {
  if ($cache = cache_get('mollom_version')) {
    return $cache->data;
  }

  // Retrieve Drupal distribution and installation profile information.
  include_once './includes/install.inc';
  // Prior to D7, there is no distribution name recorded anywhere, so we have to
  // use "Drupal".
  $profile_info['distribution_name'] = 'Drupal';
  $profile_info['version'] = VERSION;

  // Retrieve Mollom module information.
  $mollom_info = db_result(db_query("SELECT info FROM {system} WHERE type = 'module' AND name = 'mollom'"));
  $mollom_info = unserialize($mollom_info);
  if (empty($mollom_info['version'])) {
    // Manually build a module version string for repository checkouts.
    $mollom_info['version'] = DRUPAL_CORE_COMPATIBILITY . '-1.x-dev';
  }

  $data = array(
    'platform_name' => $profile_info['distribution_name'],
    'platform_version' => $profile_info['version'],
    'client_name' => $mollom_info['name'],
    'client_version' => $mollom_info['version'],
  );
  cache_set('mollom_version', $data);

  return $data;
}

/**
 * Send feedback to Mollom.
 */
function _mollom_send_feedback($session_id, $feedback = 'spam') {
  $result = mollom('mollom.sendFeedback', array(
    'session_id' => $session_id,
    'feedback' => $feedback,
  ));
  _mollom_watchdog(array(
    'Reported %feedback for session id %session.' => array('%session' => $session_id, '%feedback' => $feedback),
  ));
  return $result;
}

/**
 * Fetch the site's Mollom statistics from the API.
 *
 * @param $refresh
 *   A boolean if TRUE, will force the statistics to be re-fetched and stored
 *   in the cache.
 *
 * @return
 *   An array of statistics.
 */
function mollom_get_statistics($refresh = FALSE) {
  $statistics = FALSE;
  $cache = cache_get('mollom:statistics');

  // Only fetch if $refresh is TRUE, the cache is empty, or the cache is expired.
  if ($refresh || !$cache || time() >= $cache->expire) {
    if (_mollom_status() === TRUE) {
      $statistics = drupal_map_assoc(array(
        'total_days',
        'total_accepted',
        'total_rejected',
        'yesterday_accepted',
        'yesterday_rejected',
        'today_accepted',
        'today_rejected',
      ));

      foreach ($statistics as $statistic) {
        $result = mollom('mollom.getStatistics', array('type' => $statistic));
        if ($result === NETWORK_ERROR || $result === MOLLOM_ERROR) {
          // If there was an error, stop fetching statistics and store FALSE
          // in the cache. This will help prevent from making unnecessary
          // requests to Mollom if the service is down or the server cannot
          // connect to the Mollom service.
          $statistics = FALSE;
          break;
        }
        else {
          $statistics[$statistic] = $result;
        }
      }
    }

    // Cache the statistics and set them to expire in one hour.
    cache_set('mollom:statistics', $statistics, 'cache', time() + 3600);
  }
  else {
    $statistics = $cache->data;
  }

  return $statistics;
}

/**
 * Implements hook_content_extra_fields().
 *
 * Allow users of CCK to re-order the CAPTCHA field on node forms through the
 * CCK UI.
 */
function mollom_content_extra_fields($type_name) {
  if ($mollom_form = mollom_form_load($type_name . '_node_form')) {
    $extras['mollom'] = array(
      'label' => t('Mollom'),
      'description' => t('Mollom CAPTCHA or privacy policy link'),
      'weight' => 99,
    );
    return $extras;
  }
}

/**
 * Get the HTML markup for a Mollom CAPTCHA.
 *
 * @param $type
 *   The CAPTCHA type to retrieve, e.g. 'image' or 'audio'.
 * @param $data
 *   An optional array of parameters to send to Mollom when requesting the
 *   CAPTCHA.
 *
 * @return
 *   An array with the following key/value pairs:
 *     - 'data': An array of parameters sent to Mollom when requesting the
 *       CAPTCHA.
 *     - 'response': An array with the response from Mollom.
 *     - 'markup': The markup of the CAPTCHA HTML.
 */
function mollom_get_captcha($type, $data = array()) {
  $data += array(
    'author_ip' => ip_address(),
    'ssl' => isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on',
  );

  // @todo Convert these to actual theme functions?
  $output = '';
  switch ($type) {
    case 'audio':
      $response = mollom('mollom.getAudioCaptcha', $data);
      if ($response) {
        $source = url(base_path() . drupal_get_path('module', 'mollom') . '/mollom-captcha-player.swf', array(
          'query' => array('url' => $response['url']),
          'external' => TRUE,
        ));
        $output = '<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0" width="110" height="50">';
        $output .= '<param name="allowFullScreen" value="false" />';
        $output .= '<param name="movie" value="' . $source . '" />';
        $output .= '<param name="loop" value="false" />';
        $output .= '<param name="menu" value="false" />';
        $output .= '<param name="quality" value="high" />';
        $output .= '<param name="wmode" value="transparent" />';
        $output .= '<param name="bgcolor" value="#ffffff" />';
        $output .= '<embed src="' . $source . '" loop="false" menu="false" quality="high" wmode="transparent" bgcolor="#ffffff" width="110" height="50" align="baseline" allowScriptAccess="sameDomain" allowFullScreen="false" type="application/x-shockwave-flash" pluginspage="http://www.adobe.com/go/getflashplayer_de" />';
        $output .= '</object>';

        $output = '<span class="mollom-captcha-content mollom-audio-captcha">' . $output . '</span>';
        $output .= ' (<a href="#" class="mollom-switch-captcha mollom-image-captcha">' . t('verify using image') . '</a>)';
      }
      break;

    case 'image':
      $response = mollom('mollom.getImageCaptcha', $data);
      if ($response) {
        $captcha = theme('image', $response['url'], t('Type the characters you see in this picture.'), '', NULL, FALSE);
        $output = '<span class="mollom-captcha-content mollom-image-captcha">' . $captcha . '</span>';
        $output .= ' (<a href="#" class="mollom-switch-captcha mollom-audio-captcha">' . t('verify using audio') . '</a>)';
      }
      break;
  }

  return array(
    'data' => $data,
    'response' => $response,
    'markup' => $output,
  );
}

/**
 * Implements hook_mail_alter().
 *
 * Adds a "report as inappropriate" link to e-mails sent after Mollom-protected
 * form submissions.
 */
function mollom_mail_alter(&$message) {
  // Attaches the Mollom report link to any mails with IDs specified from the
  // submitted form's hook_mollom_form_info(). This should ensure that the
  // report link is added to mails sent by actual users and not any mails sent
  // by Drupal since they should never be reported as spam.
  if (!empty($GLOBALS['mollom']['mail ids']) && in_array($message['id'], $GLOBALS['mollom']['mail ids'])) {
    mollom_mail_add_report_link($message);
  }
}

/**
 * Add the 'Report as innapropriate' link to an e-mail message.
 */
function mollom_mail_add_report_link(&$message) {
  if (!empty($GLOBALS['mollom']['response']['session_id'])) {
    $mollom = $GLOBALS['mollom'];
    $data = (object) $mollom['response'];
    $data->entity = 'session';
    $data->id = $mollom['response']['session_id'];
    $data->form_id = $mollom['form_id'];
    mollom_data_save($data);
    $report_link = t('Report as inappropriate: @link', array(
      '@link' => url("mollom/report/{$data->entity}/{$data->id}", array('absolute' => TRUE)),
    ));
    // Until D7, hook_mail_alter() accepts both arrays and strings.
    if (is_array($message['body'])) {
      $message['body'][] = $report_link;
    }
    else {
      $message['body'] .= "\n\n" . $report_link;
    }
  }
}

/**
 * @name mollom_node Node module integration for Mollom.
 * @{
 */

/**
 * Implements hook_mollom_form_list().
 */
function node_mollom_form_list() {
  $forms = array();
  foreach (node_get_types('types') as $type) {
    $form_id = $type->type . '_node_form';
    $forms[$form_id] = array(
      'title' => t('@name form', array('@name' => $type->name)),
      'entity' => 'node',
      'report access callback' => 'node_mollom_report_access',
      'report delete callback' => 'node_mollom_report_delete',
    );
  }
  return $forms;
}

/**
 * Implements hook_mollom_form_info().
 */
function node_mollom_form_info($form_id) {
  // Retrieve internal type from $form_id.
  $nodetype = drupal_substr($form_id, 0, -10);

  $type = node_get_types('type', $nodetype);
  $form_info = array(
    // @todo This is incompatible with node access.
    'bypass access' => array('administer nodes'),
    'bundle' => $type->type,
    'moderation callback' => 'node_mollom_form_moderation',
    'elements' => array(),
    'mapping' => array(
      'post_id' => 'nid',
      'author_name' => 'name',
    ),
  );
  // @see node_perm()
  if ($type->module == 'node') {
    $form_info['bypass access'][] = 'edit any ' . $type->type . ' content';
    $form_info['bypass access'][] = 'delete any ' . $type->type . ' content';
  }
  // @see node_content_form()
  if ($type->has_title) {
    $form_info['elements']['title'] = check_plain($type->title_label);
    $form_info['mapping']['post_title'] = 'title';
  }
  if ($type->has_body) {
    $form_info['elements']['body'] = check_plain($type->body_label);
  }

  // Add text fields.
  if (module_exists('content')) {
    $content_info = content_types($type->type);
    foreach ($content_info['fields'] as $field_name => $field) {
      if ($field['type'] == 'text') {
        $form_info['elements'][$field_name] = check_plain(t($field['widget']['label']));
      }
    }
  }

  return $form_info;
}

/**
 * Implements hook_nodeapi().
 */
function mollom_nodeapi($node, $op) {
  if (in_array($op, array('insert', 'update')) && !empty($GLOBALS['mollom']['entity']) && $GLOBALS['mollom']['entity'] == 'node') {
    $mollom = $GLOBALS['mollom'];
    $data = (object) $mollom['response'];
    $data->entity = 'node';
    $data->id = $node->nid;
    $data->form_id = $mollom['form_id'];
    mollom_data_save($data);
  }
  elseif ($op == 'delete') {
    mollom_data_delete('node', $node->nid);
  }
}

/**
 * Mollom form moderation callback for nodes.
 */
function node_mollom_form_moderation(&$form, &$form_state) {
  $form_state['values']['status'] = 0;
}

/**
 * Implements hook_form_FORMID_alter().
 *
 * Hook into the mass comment administration page and add some operations to
 * communicate ham/spam to the XML-RPC server.
 *
 * @see mollom_node_admin_overview_submit()
 */
function mollom_form_node_admin_content_alter(&$form, $form_state) {
  module_load_include('inc', 'mollom', 'mollom.admin');
  $form['admin']['options']['operation']['#options']['mollom-unpublish'] = t('Report to Mollom and unpublish');
  $form['admin']['options']['operation']['#options']['mollom-delete'] = t('Report to Mollom and delete');
  $form['#validate'][] = 'mollom_node_admin_overview_submit';
}

/**
 * Mollom report access callback; Determine access to report and delete a node.
 */
function node_mollom_report_access($entity, $id) {
  $node = node_load($id);
  return $node && node_access('delete', $node);
}

/**
 * Mollom report delete callback; Deletes a node.
 */
function node_mollom_report_delete($entity, $id) {
  node_delete($id);
}

/**
 * @} End of "name mollom_node".
 */

/**
 * @name mollom_comment Comment module integration for Mollom.
 * @{
 */

/**
 * Implements hook_mollom_form_list().
 */
function comment_mollom_form_list() {
  $forms['comment_form'] = array(
    'title' => t('Comment form'),
    'entity' => 'comment',
    'report access' => array('administer comments'),
    'report delete callback' => 'comment_mollom_report_delete',
  );
  return $forms;
}

/**
 * Implements hook_mollom_form_info().
 */
function comment_mollom_form_info($form_id) {
  $form_info = array(
    'mode' => MOLLOM_MODE_ANALYSIS,
    'bypass access' => array('administer comments'),
    'moderation callback' => 'comment_mollom_form_moderation',
    'elements' => array(
      'subject' => t('Subject'),
      'comment' => t('Comment'),
    ),
    'mapping' => array(
      'post_id' => 'cid',
      'post_title' => 'subject',
      // In D6, comment_form() dynamically uses different form elements for
      // anonymous users, authenticated users, and comment administrators.
      'author_name' => 'name',
      'author_mail' => 'mail',
      'author_url' => 'homepage',
    ),
  );

  return $form_info;
}

/**
 * Implements hook_form_FORMID_alter().
 *
 * When a registered user posts a comment or when a comment administrator edits
 * an existing comment, comment_form() does not define 'name' and 'mail' form
 * elements, so our form element mapping will fail.
 *
 * @see comment_mollom_form_info()
 * @see mollom_comment_form_validate()
 *
 * @todo Remove in D7.
 */
function mollom_form_comment_form_alter(&$form, &$form_state) {
  if (isset($form['author']) || isset($form['admin']['author'])) {
    $form['#validate'][] = 'mollom_comment_form_validate';
  }
}

/**
 * Form validation handler for comment_form().
 *
 * @todo Remove in D7.
 */
function mollom_comment_form_validate($form, &$form_state) {
  // If there were no validation errors, prepare submitted form values for
  // validation via Mollom.
  if (!form_get_errors()) {
    // Author is a registered user or comment is edited by administrator.
    if (isset($form_state['values']['author'])) {
      // Populate 'name' with value of 'author'.
      if (!isset($form_state['values']['name'])) {
        form_set_value(array('#parents' => array('name')), $form_state['values']['author'], $form_state);
      }
      // Populate 'mail' based on corresponding user account.
      if (!isset($form_state['values']['mail'])) {
        // This should already be validated by comment_validate(), but we still
        // double-check that we have a valid account before trying to access it.
        $account = user_load(array('name' => $form_state['values']['author']));
        if ($account) {
          form_set_value(array('#parents' => array('mail')), $account->mail, $form_state);
        }
      }
    }
  }
}

/**
 * Mollom form moderation callback for comments.
 */
function comment_mollom_form_moderation(&$form, &$form_state) {
  $form_state['values']['status'] = COMMENT_NOT_PUBLISHED;
}

/**
 * Implements hook_comment().
 */
function mollom_comment($comment, $op) {
  if (in_array($op, array('insert', 'update')) && !empty($GLOBALS['mollom']['entity']) && $GLOBALS['mollom']['entity'] == 'comment') {
    $mollom = $GLOBALS['mollom'];
    $data = (object) $mollom['response'];
    $data->entity = 'comment';
    $data->id = (isset($comment['cid']) ? $comment['cid'] : $comment->cid);
    $data->form_id = $mollom['form_id'];
    mollom_data_save($data);
  }
  if ($op == 'delete') {
    mollom_data_delete('comment', $comment->cid);
  }
}

/**
 * Implements hook_form_FORMID_alter().
 *
 * Hook into the mass comment administration page and add some operations to
 * communicate ham/spam to the XML-RPC server.
 *
 * @see mollom_comment_admin_overview_submit()
 */
function mollom_form_comment_admin_overview_alter(&$form, $form_state) {
  module_load_include('inc', 'mollom', 'mollom.admin');
  $form['options']['operation']['#options']['mollom-unpublish'] = t('Report to Mollom and unpublish');
  $form['options']['operation']['#options']['mollom-delete'] = t('Report to Mollom and delete');
  $form['#submit'][] = 'mollom_comment_admin_overview_submit';
}

/**
 * Mollom report delete callback; Deletes a comment and its replies.
 *
 * @see comment_confirm_delete_submit()
 */
function comment_mollom_report_delete($entity, $id) {
  module_load_include('inc', 'comment', 'comment.admin');
  $comment = _comment_load($id);
  // Delete the comment and its replies.
  _comment_delete_thread($comment);
  _comment_update_node_statistics($comment->nid);
  // Clear the cache so an anonymous user sees that his comment was deleted.
  cache_clear_all();

  drupal_set_message(t('The comment has been deleted.'));
}

/**
 * @} End of "name mollom_comment".
 */

/**
 * @name mollom_user User module integration for Mollom.
 * @{
 */

/**
 * Implements hook_mollom_form_list().
 */
function user_mollom_form_list() {
  $forms['user_register'] = array(
    'title' => t('User registration form'),
    'entity' => 'user',
  );
  $forms['user_pass'] = array(
    'title' => t('User password request form'),
  );
  return $forms;
}

/**
 * Implements hook_mollom_form_info().
 */
function user_mollom_form_info($form_id) {
  switch ($form_id) {
    case 'user_register':
      $form_info = array(
        'bypass access' => array('administer users'),
        'moderation callback' => 'user_mollom_form_moderation',
        'mapping' => array(
          'post_id' => 'uid',
          'author_name' => 'name',
          'author_mail' => 'mail',
        ),
      );
      return $form_info;

    case 'user_pass':
      $form_info = array(
        'mode' => MOLLOM_MODE_CAPTCHA,
        'bypass access' => array('administer users'),
        'mapping' => array(
          'post_id' => 'uid',
          'author_name' => 'name',
          // The 'name' form element accepts either a username or mail address.
          'author_mail' => 'name',
        ),
      );
      return $form_info;
  }
}

/**
 * Mollom form moderation callback for user accounts.
 */
function user_mollom_form_moderation(&$form, &$form_state) {
  $form_state['values']['status'] = 0;
}

/**
 * @} End of "name mollom_user".
 */

/**
 * @name mollom_contact Contact module integration for Mollom.
 * @{
 */

/**
 * Implements hook_mollom_form_list().
 */
function contact_mollom_form_list() {
  $forms['contact_mail_page'] = array(
    'title' => t('Site-wide contact form'),
  );
  $forms['contact_mail_user'] = array(
    'title' => t('User contact form'),
  );
  return $forms;
}

/**
 * Implements hook_mollom_form_info().
 */
function contact_mollom_form_info($form_id) {
  switch ($form_id) {
    case 'contact_mail_page':
      $form_info = array(
        'mode' => MOLLOM_MODE_ANALYSIS,
        'bypass access' => array('administer site-wide contact form'),
        'mail ids' => array('contact_page_mail'),
        'elements' => array(
          'subject' => t('Subject'),
          'message' => t('Message'),
        ),
        'mapping' => array(
          'post_title' => 'subject',
          'author_name' => 'name',
          'author_mail' => 'mail',
        ),
      );
      return $form_info;

    case 'contact_mail_user':
      $form_info = array(
        'mode' => MOLLOM_MODE_ANALYSIS,
        'bypass access' => array('administer users'),
        'mail ids' => array('contact_user_mail'),
        'elements' => array(
          'subject' => t('Subject'),
          'message' => t('Message'),
        ),
        'mapping' => array(
          'post_title' => 'subject',
        ),
      );
      return $form_info;
  }
}

/**
 * @} End of "name mollom_contact".
 */

/**
 * @name mollom_profile Profile module integration for Mollom.
 * @{
 */

/**
 * Implements hook_mollom_form_info_alter().
 *
 * Adds profile fields exposed on the user registration form.
 */
function profile_mollom_form_info_alter(&$form_info, $form_id) {
  if ($form_id != 'user_register') {
    return;
  }
  // @see profile_form_profile()
  $result = db_query("SELECT name, title FROM {profile_fields} WHERE register = 1 AND type IN ('textfield', 'textarea', 'url', 'list')");
  while ($field = db_fetch_object($result)) {
    $form_info['elements'][$field->name] = check_plain($field->title);
  }
}

/**
 * @} End of "name mollom_profile".
 */