Source

Mozbot-shlomif / mozbot.pl

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
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
#!/usr/bin/perl -wT
# -*- Mode: perl; indent-tabs-mode: nil -*-
# DO NOT REMOVE THE -T ON THE FIRST LINE!!!
#
#                       _           _
#        m o z i l l a |.| o r g   | |
#    _ __ ___   ___ ___| |__   ___ | |_
#   | '_ ` _ \ / _ \_  / '_ \ / _ \| __|
#   | | | | | | (_) / /| |_) | (_) | |_
#   |_| |_| |_|\___/___|_.__/ \___/ \__|
#   ====================================
#
# The contents of this file are subject to the Mozilla Public
# License Version 1.1 (the "License"); you may not use this file
# except in compliance with the License. You may obtain a copy of
# the License at http://www.mozilla.org/MPL/
#
# Software distributed under the License is distributed on an "AS
# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
# implied. See the License for the specific language governing
# rights and limitations under the License.
#
# The Original Code is the Bugzilla Bug Tracking System.
#
# The Initial Developer of the Original Code is Netscape Communications
# Corporation. Portions created by Netscape are
# Copyright (C) 1998 Netscape Communications Corporation. All
# Rights Reserved.
#
# Contributor(s): Harrison Page <harrison@netscape.com>
#                 Terry Weissman <terry@mozilla.org>
#                 Risto Kotalampi <risto@kotalampi.com>
#                 Josh Soref <timeless@bemail.org>
#                 Ian Hickson <mozbot@hixie.ch>
#                 Ken Coar <ken.coar@golux.com>
#                 Adam Di Carlo <adam@onshored.com>
#
# mozbot.pl harrison@netscape.com 1998-10-14
# "irc bot for the gang on #mozilla"
#
# mozbot.pl mozbot@hixie.ch 2000-07-04
# "irc bot engine for anyone" :-)
#
# hack on me! required reading:
#
# Net::IRC web page:
#   http://sourceforge.net/projects/net-irc/
#   (free software)
#   or get it from CPAN @ http://www.perl.com/CPAN
#
# RFC 1459 (Internet Relay Chat Protocol):
#   http://sunsite.cnlab-switch.ch/ftp/doc/standard/rfc/14xx/1459
#
# Please file bugs in Bugzilla, under the 'Webtools' product,
# component 'Mozbot'.  https://bugzilla.mozilla.org/

# TO DO LIST
# XXX Something that checks modules that failed to compile and then
#     reloads them when possible
# XXX an HTML entity convertor for things that speak web page contents
# XXX UModeChange
# XXX minor checks
# XXX throttle nick changing and away setting (from module API)
# XXX compile self before run
# XXX parse mode (+o, etc)
# XXX optimisations
# XXX maybe should catch hangup signal and go to background?
# XXX protect the bot from DOS attacks causing server overload
# XXX protect the server from an overflowing log (add log size limitter
#     or rotation)
# XXX fix the "hack hack hack" bits to be better.


################################
# Initialisation               #
################################

# -- #mozwebtools was here --
#      <Hixie> syntax error at oopsbot.pl line 48, near "; }"
#      <Hixie> Execution of oopsbot.pl aborted due to compilation errors.
#      <Hixie> DOH!
#     <endico> hee hee. nice smily in the error message

# catch nasty occurances
$SIG{'INT'}  = sub { killed('INT'); };
$SIG{'KILL'} = sub { killed('KILL'); };
$SIG{'TERM'} = sub { killed('TERM'); };

# this allows us to exit() without shutting down (by exec($0)ing)
BEGIN { exit() if ((defined($ARGV[0])) and ($ARGV[0] eq '--abort')); }

# pragmas
use strict;
use diagnostics;

# chroot if requested
my $CHROOT = 0;
if ((defined($ARGV[0])) and ($ARGV[0] eq '--chroot')) {
    # chroot
    chroot('.') or die "chroot failed: $!\nAborted";
    # setuid
    # This is hardcoded to use user ids and group ids 60001.
    # You'll want to change this on your system.
    $> = 60001; # setuid nobody
    $) = 60001; # setgid nobody
    shift(@ARGV);
    use lib '/lib';
    $CHROOT = 1;
} elsif ((defined($ARGV[0])) and ($ARGV[0] eq '--assume-chrooted')) {
    shift(@ARGV);
    use lib '/lib';
    $CHROOT = 1;
} else {
    use lib 'lib';
}

# important modules
use Net::IRC 0.7; # 0.7 is not backwards compatible with 0.63 for CTCP responses
use IO::SecurePipe; # internal based on IO::Pipe
use Socket;
use POSIX ":sys_wait_h";
use Carp qw(cluck confess);
use Configuration; # internal
use Mails; # internal

# Net::IRC 0.74+ require Time::HiRes, if its missing, Net::IRC will fail with
# a "No method called "time" for object." error during mozbot startup.

# Note: Net::SMTP is also used, see the sendmail function in Mails.

# force flushing
$|++;

# internal 'constants'
my $USERNAME = "pid-$$";
my $LOGFILEPREFIX;

# variables that should only be changed if you know what you are doing
my $LOGGING = 1; # set to '0' to disable logging
my $LOGFILEDIR; # set this to override the logging output directory

if ($LOGGING) {
    # set up the log directory
    unless (defined($LOGFILEDIR)) {
        if ($CHROOT) {
            $LOGFILEDIR = '/log';
        } else {
            # setpwent doesn't work on Windows, we should wrap this in some OS test
            setpwent; # reset the search settings for the getpwuid call below
            $LOGFILEDIR = (getpwuid($<))[7].'/log';
        }
    }
    "$LOGFILEDIR/$0" =~ /^(.*)$/os; # untaints the evil $0.
    $LOGFILEPREFIX = $1; # for some reason, $0 is considered tainted here, but not in other cases...
    mkdir($LOGFILEDIR, 0700); # if this fails for a bad reason, we'll find out during the next line
}

# begin session log...
debug('-'x80);
debug('mozbot starting up');
debug('compilation took '.days($^T).'.');
if ($CHROOT) {
    debug('mozbot chroot()ed successfully');
}

# secure the environment
#
# XXX could automatically remove the current directory here but I am
# more comfortable with people knowing it is not allowed -- see the
# README file.
if ($ENV{'PATH'} =~ /^(?:.*:)?\.?(?::.*)?$/os) {
    die 'SECURITY RISK. You cannot have \'.\' in the path. See the README. Aborted';
}
$ENV{'PATH'} =~ /^(.*)$/os;
$ENV{'PATH'} = $1; # we have to assume their path is otherwise safe, they called us!
delete (@ENV{'IFS', 'CDPATH', 'ENV', 'BASH_ENV'});


# read the configuration file
my $cfgfile = shift || "$0.cfg";
$cfgfile =~ /^(.*)$/os;
$cfgfile = $1; # untaint it -- we trust this, it comes from the admin.
debug("reading configuration from '$cfgfile'...");

# - setup variables
# note: owner is only used by the Mails module
my ($server, $port, $password, $localAddr, @nicks, @channels, %channelKeys, $owner,
    @ignoredUsers, @ignoredTargets, $ssl);
my $nick = 0;
my $sleepdelay = 60;
my $connectTimeout = 120;
my $delaytime = 1.3; # amount of time to wait between outputs
my $recentMessageCountThreshold = 3; # threshold before we stop outputting
my $recentMessageCountPenalty = 10; # if we hit the threshold, bump it up by this much
my $recentMessageCountLimit = 20; # limit above which the count won't go
my $recentMessageCountDecrementRate = 0.1; # how much to take off per $delaytime
my $variablepattern = '[-_:a-zA-Z0-9]+';
my %users = ('admin' => newPassword('password')); # default password for admin
my %userFlags = ('admin' => 3); # bitmask; 0x1 = admin, 0x2 = delete user a soon as other admin authenticates
my $helpline = 'http://www.mozilla.org/projects/mozbot/'; # used in IRC name and in help
my $serverRestrictsIRCNames = '';
my $serverExpectsValidUsername = '';
my $username = 0; # makes the username default to the pid ($USERNAME)
my @modulenames = ('General', 'Greeting', 'Infobot', 'Parrot');
my $gender = 'female'; #changed to female by special request
my $umode;

# - which variables can be saved.
registerConfigVariables(
    [\$server, 'server'],
    [\$port, 'port'],
    [\$password, 'password'],
    [\$localAddr, 'localAddr'],
    [\@nicks, 'nicks'],
    [\$nick, 'currentnick'], # pointer into @nicks
    [\@channels, 'channels'],
    [\%channelKeys, 'channelKeys'],
    [\@ignoredUsers, 'ignoredUsers'],
    [\@ignoredTargets, 'ignoredTargets'],
    [\@modulenames, 'modules'],
    [\$owner, 'owner'],
    [\$sleepdelay, 'sleep'],
    [\$connectTimeout, 'connectTimeout'],
    [\$delaytime, 'throttleTime'],
    [\%users, 'users'], # usernames => newPassword(passwords)
    [\%userFlags, 'userFlags'], # usernames => bits
    [\$variablepattern, 'variablepattern'],
    [\$helpline, 'helpline'],
    [\$username, 'username'],
    [\$serverRestrictsIRCNames, 'simpleIRCNameServer'],
    [\$serverExpectsValidUsername, 'validUsernameServer'],
    [\$ssl, 'ssl'],
    [\$umode, 'umode'],
    [\$gender, 'gender'],
    [\$Mails::smtphost, 'smtphost'],
);

# - read file
Configuration::Get($cfgfile, configStructure()); # empty gets entire structure

# - check variables are ok
# note. Ensure only works on an interactive terminal (-t).
# It will abort otherwise.
{ my $changed; # scope this variable
$changed = Configuration::Ensure([
    ['Connect to which server?', \$server],
    ['To which port should I connect?', \$port],
    ['Connect to this port using SSL?', \$ssl],
    ['What is the server\'s password? (Leave blank if there isn\'t one.)', \$password],
    ['What channels should I join?', \@channels],
    ['What is the e-mail address of my owner?', \$owner],
    ['What is your SMTP host?', \$Mails::smtphost],
]);

# - check we have some nicks
until (@nicks) {
    $changed = Configuration::Ensure([['What nicks should I use? (I need at least one.)', \@nicks]]) || $changed;
    # the original 'mozbot 2.0' development codename (and thus nick) was oopsbot.
}

# - check current nick pointer is valid
# (we assume that no sillyness has happened with $[ as,
# according to man perlvar, "Its use is highly discouraged".)
$nick = 0 if (($nick > $#nicks) or ($nick < 0));

# - check channel names are all lowercase
foreach (@channels) { $_ = lc; }

# save configuration straight away, to make sure it is possible and to save
# any initial settings on the first run, if anything changed.
if ($changed) {
    debug("saving configuration to '$cfgfile'...");
    save_config_vars([]);
}

} # close the scope for the $changed variable

# ensure Mails is ready
debug("setting up Mails module...");
$Mails::debug = \&debug;
$Mails::owner = \$owner;

# setup the IRC variables
debug("setting up IRC variables...");
my $uptime;
my $irc = Net::IRC->new() or confess("Could not create a new Net::IRC object. Aborting");

# connect
debug("attempting initial connection...");
setup_connection();

# setup the modules array
my @modules; # we initialize it lower down (at the bottom in fact)
my $lastadmin; # nick of last admin to be seen
my %authenticatedUsers; # hash of user@hostname=>users who have authenticated


################################
# Net::IRC handler subroutines #
################################

sub setEventArgs {
    my $event = shift;
    if ($Net::IRC::VERSION == 0.75) {
        # curses. This version of Net::IRC is broken. Work around
        # it here.
        return $event->args(\@_);
    } else {
        return $event->args(\@_);
    }
}

my $lastNick;

# setup connection
sub setup_connection {
    $uptime = time();

    debug("connecting to $server:$port using nick '$nicks[$nick]'..." 
			. ($ssl && lc($ssl) eq 'yes')? "via SSL" : "");
    my ($bot, $mailed);

    $lastNick = undef;

    my $ircname = 'mozbot';
    if ($serverRestrictsIRCNames ne $server) {
        $ircname = "[$ircname] $helpline";
    }

    my $identd = getpwuid($<);
    if ($serverExpectsValidUsername ne $server) {
        $identd = $username || $USERNAME;
    }

    until (inet_aton($server) and # we check this first because Net::IRC::Connection doesn't
           $bot = $irc->newconn(
             Server => $server,
             Port => $port,
             Password => $password ne '' ? $password : undef, # '' will cause PASS to be sent
             Nick => $nicks[$nick],
             Ircname => $ircname,
             Username => $identd,
             LocalAddr => $localAddr,
			 SSL => ($ssl && lc($ssl) eq 'yes') ? 'true' : undef, 
           )) {
        debug("Could not connect. Are you sure '$server:$port' is a valid host?");
        unless (inet_aton($server)) {
            debug('I couldn\'t resolve it.');
        }
        if (defined($localAddr)) {
            debug("Is '$localAddr' the correct address of the interface to use?");
        } else {
            debug("Try editing '$cfgfile' to set 'localAddr' to the address of the interface to use.");
        }
        if ($Net::IRC::VERSION < 0.73) {
            debug("Note that to use 'localAddr' you need Net::IRC version 0.73 or higher (you have $Net::IRC::VERSION)");
        }
        $mailed = Mails::ServerDown($server, $port, $localAddr, $nicks[$nick], $ircname, $identd) unless $mailed;
        sleep($sleepdelay);
        Configuration::Get($cfgfile, configStructure(\$server, \$port, \$password, \@nicks, \$nick, \$owner, \$sleepdelay));
        debug("connecting to $server:$port again...");
    }

    debug("connected! woohoo!");

    # add the handlers
    debug("adding event handlers");

    # $bot->debug(1); # this can help when debugging API stuff

    $bot->add_global_handler([ # Informational messages -- print these to the console
        251, # RPL_LUSERCLIENT
        252, # RPL_LUSEROP
        253, # RPL_LUSERUNKNOWN
        254, # RPL_LUSERCHANNELS
        255, # RPL_LUSERME
        302, # RPL_USERHOST
        375, # RPL_MOTDSTART
        372, # RPL_MOTD
    ], \&on_startup);

    $bot->add_global_handler([ # Informational messages -- print these to the console
        'snotice', # server notices
        461, # need more arguments for PASS command
        409, # noorigin
        405, # toomanychannels  XXX should do something about this!
        404, # cannot send to channel
        403, # no such channel
        401, # no such server
        402, # no such nick
        407, # too many targets
    ], \&on_notice);

    $bot->add_global_handler([ # should only be one command here - when to join channels
        376, # RPL_ENDOFMOTD
        422, # nomotd
    ], \&on_connect);

    $bot->add_handler('welcome', \&on_welcome); # when we connect, to get our nick/umode
    $bot->add_global_handler([ # when to change nick name
        'erroneusnickname',
        433, # ERR_NICKNAMEINUSE
        436, # nick collision
    ], \&on_nick_taken);
    $bot->add_handler('nick', \&on_nick); # when someone changes nick

    $bot->add_global_handler([ # when to give up and go home
        'disconnect', 'kill', # bad connection, booted offline
        465, # ERR_YOUREBANNEDCREEP
    ], \&on_disconnected);
    $bot->add_handler('destroy', \&on_destroy); # when object is GCed.

    $bot->add_handler('msg', \&on_private); # /msg bot hello
    $bot->add_handler('public', \&on_public);  # hello
    $bot->add_handler('notice', \&on_noticemsg); # notice messages
    $bot->add_handler('join', \&on_join); # when someone else joins
    $bot->add_handler('part', \&on_part); # when someone else leaves
    $bot->add_handler('topic', \&on_topic); # when topic changes in a channel
    $bot->add_handler('notopic', \&on_topic); # when topic in a channel is cleared
    $bot->add_handler('invite', \&on_invite); # when someone invites us
    $bot->add_handler('quit', \&on_quit); # when someone quits IRC
    $bot->add_handler('kick', \&on_kick); # when someone (or us) is kicked
    $bot->add_handler('mode', \&on_mode); # when modes change
    $bot->add_handler('umode', \&on_umode); # when modes of user change (by IRCop or ourselves)
    # XXX could add handler for 474, # ERR_BANNEDFROMCHAN

    $bot->add_handler([ # ones we handle to get our hostmask
        311, # whoisuser
    ], \&on_whois);
    $bot->add_handler([ # ones we handle just by outputting to the console
        312, # whoisserver
        313, # whoisoperator
        314, # whowasuser
        315, # endofwho
        316, # whoischanop
        317, # whoisidle
        318, # endofwhois
        319, # whoischannels
    ], \&on_notice);
    $bot->add_handler([ # names (currently just ignored)
        353, # RPL_NAMREPLY "<channel> :[[@|+]<nick> [[@|+]<nick> [...]]]"
    ], \&on_notice);
    $bot->add_handler([ # end of names (we use this to establish that we have entered a channel)
        366, # RPL_ENDOFNAMES "<channel> :End of /NAMES list"
    ], \&on_join_channel);

    $bot->add_handler('cping', \&on_cping); # client to client ping
    $bot->add_handler('crping', \&on_cpong); # client to client ping (response)
    $bot->add_handler('cversion', \&on_version); # version info of mozbot.pl
    $bot->add_handler('csource', \&on_source); # where is mozbot.pl's source
    $bot->add_handler('caction', \&on_me); # when someone says /me
    $bot->add_handler('cgender', \&on_gender); # guess

    $bot->schedule($connectTimeout, \&on_check_connect);

    # and done.
    &Mails::ServerUp($server) if $mailed;

}

# called when the client receives a startup-related message
sub on_startup {
    my ($self, $event) = @_;
    my (@args) = $event->args;
    shift(@args);
    debug(join(' ', @args));
}

# called when the client receives a server notice
sub on_notice {
    my ($self, $event) = @_;
    debug($event->type.': '.join(' ', $event->args));
}

# called when the client receives whois data
sub on_whois {
    my ($self, $event) = @_;
    debug('collecting whois information: '.join('|', $event->args));
    # XXX could cache this information and then autoop people from
    # the bot's host, or whatever
}

my ($nickFirstTried, $nickHadProblem, $nickProblemEscalated) = (0, 0, 0);

# this is called for the welcome message (001) it calls on_set_nick to
# get our nick and on_set_umode to set our umode once we have a nick
sub on_welcome {
    my ($self, $event) = @_;
    on_set_nick($self, $event);
    on_set_umode($self, $event);
}

# this is called both for the welcome message (001) and by the on_nick handler
sub on_set_nick {
    my ($self, $event) = @_;
    ($lastNick) = $event->args; # (args can be either array or scalar, we want the first value)
    # Find nick's index.
    my $newnick = 0;
    $newnick++ while (($newnick < @nicks) and ($lastNick ne $nicks[$newnick]));
    # If nick isn't there, add it.
    if ($newnick >= @nicks) {
        push(@nicks, $lastNick);
    }
    # set variable
    $nick = $newnick;
    debug("using nick '$nicks[$nick]'");

    # try to get our hostname
    $self->whois($nicks[$nick]);

    if ($nickHadProblem) {
        Mails::NickOk($nicks[$nick]) if $nickProblemEscalated;
        $nickHadProblem = 0;
    }

    # save
    ::save_config_vars([\$nick, \@nicks]);
}

sub on_nick_taken {
    my ($self, $event, $nickSlept) = @_, 0;
    return unless $self->connected();

    if ($event->type eq 'erroneusnickname') {
        my ($currentNick, $triedNick, $err) = $event->args; # current, tried, errmsg
        debug("requested nick ('$triedNick') refused by server ('$err')");
    } elsif ($event->type eq 'nicknameinuse') {
        my ($currentNick, $triedNick, $err) = $event->args; # current, tried, errmsg
        debug("requested nick ('$triedNick') already in use ('$err')");
    } else {
        my $type = $event->type;
        my $args = join(' ', $event->args);
        debug("message $type from server: $args");
    }

    if (defined $lastNick) {
        debug("silently abandoning nick change idea :-)");
        return;
    }

    # at this point, we don't yet have a nick, but we need one
    
    if ($nickSlept) {
        debug("waited for a bit -- reading $cfgfile then searching for a nick...");
        Configuration::Get($cfgfile, configStructure(\@nicks, \$nick));
        $nick = 0 if ($nick > $#nicks) or ($nick < 0); # sanitise
        $nickFirstTried = $nick;
    } else {
        if (not $nickHadProblem) {
            $nickHadProblem = 1;
            $nickFirstTried = $nick;
        }
        ++$nick;
        $nick = 0 if $nick > $#nicks; # sanitise

        if ($nick == $nickFirstTried) {
            # looped!
            local $" = ", ";
            debug("could not find an acceptable nick");
            debug("nicks tried: @nicks");

            if (not -t) {
                debug("edit $cfgfile to add more nicks *hint* *hint*");
                $nickProblemEscalated ||= # only e-mail once (returns 0 on failure)
                  Mails::NickShortage($cfgfile, $self->server, $self->port,
                                      $self->username, $self->ircname, @nicks);
                # Note from Shlomi Fish:
                # There was a missing semicolon in the above statement and due
                # to the fact debug(...) was written &debug instead of debug
                # it probably yielded a bitwise AND-operation:
                # x & y.
                debug("going to wait $sleepdelay seconds so as not to overload ourselves.");
                $self->schedule($sleepdelay, \&on_nick_taken, $event, 1); # try again
                return; # otherwise we no longer respond to pings.
            }

            # else, we're terminal bound, ask user for nick
            print "Please suggest a nick (blank to abort): ";
            my $new = <>;
            chomp($new);
            if (not $new) {
                debug("Could not find an acceptable nick");
                exit(1);
            }
            # XXX this could introduce duplicates
            @nicks = (@nicks[0..$nickFirstTried], $new, @nicks[$nickFirstTried+1..$#nicks]);
            $nick += 1; # try the new nick now
            $nickFirstTried = $nick;
        }
    }

    debug("now going to try nick '$nicks[$nick]'");
    save_config_vars([\$nick, \@nicks]);
    $self->nick($nicks[$nick]);
}

#called by on_welcome after we get our nick
sub on_set_umode {
    my ($self, $event) = @_;
    # set usermode for the bot
    if ($umode) {
        debug("using umode: '$umode'");
        $self->mode($self->nick, $umode);
    }
}

sub _load_all_modules {
    my $self = shift;

    my ($modules, $module_names) = @_;

    my @modulesToLoad = @$module_names;

    @$modules = (BotModules::Admin->create('Admin', '')); # admin commands
    @$module_names = ('Admin');

    foreach my $mod_name (@modulesToLoad) {
        # Admin is static and is installed manually above, so skip it.
        next if $mod_name eq 'Admin'; 

        my $result = LoadModule($mod_name);

        if (ref($result)) {
            debug("loaded $mod_name");
        } else {
            debug("failed to load $mod_name", $result);
        }
    }

    return;
}

sub _configure_modules {
    my $self = shift;

    my ($modules) = @_;

    # mass-configure the modules
    debug("loading module configurations...");
    
    my %struct;

    foreach my $module (@$modules) { 
        %struct = (%struct, %{$module->configStructure()}); 
    }

    Configuration::Get($cfgfile, \%struct);

    return;
}

# tell the modules they have joined IRC
sub _tell_modules_about_irc_join {
    my $self = shift;

    my ($modules) = @_;

    my $event = newEvent({
        'bot' => $self,
    });
    foreach my $module (@$modules) {
        $module->JoinedIRC($event);
    }

    # tell the modules to set up the scheduled commands
    debug('setting up scheduler...');
    foreach my $module (@$modules) {
        eval {
            $module->Schedule($event);
        };
        if ($@) {
            debug("Warning: An error occured while loading the module:\n$@");
        }
    }

    return;
}

# called when we connect.
sub on_connect {
    my $self = shift;

    if (defined($self->{'__mozbot__shutdown'})) { # HACK HACK HACK
        debug('Uh oh. I connected anyway, even though I thought I had timed out.');
        debug('I\'m going to increase the timeout time by 20%.');
        $connectTimeout = $connectTimeout * 1.2;
        save_config_vars([\$connectTimeout]);
        $self->quit('having trouble connecting, brb...');
        # XXX we don't call the SpottedQuit handlers here
        return;
    }

    # -- #mozwebtools was here --
    # *** oopsbot (oopsbot@129.59.231.42) has joined channel #mozwebtools
    # *** Mode change [+o oopsbot] on channel #mozwebtools by timeless
    #   <timeless> wow an oopsbot!
    # *** Signoff: oopsbot (oopsbot@129.59.231.42) has left IRC [Leaving]
    #   <timeless> um
    #   <timeless> not very stable.

    _load_all_modules($self, \@modules, \@modulenames);

    _configure_modules($self, \@modules);

    # tell the modules they have joined IRC
    _tell_modules_about_irc_join($self, \@modules);

    # join the channels
    debug('going to join: '.join(',', @channels));
    foreach my $channel (@channels) {
        if (defined($channelKeys{$channel})) {
            $self->join($channel, $channelKeys{$channel});
        } else {
            $self->join($channel);
        }
    }
    @channels = ();

    # enable the drainmsgqueue
    drainmsgqueue($self);
    $self->schedule($delaytime, \&lowerRecentMessageCount);

    # signal that we are connected (see next two functions)
    $self->{'__mozbot__active'} = 1; # HACK HACK HACK

    # all done!
    debug('initialisation took '.days($uptime).'.');
    $uptime = time();

}

sub on_check_connect {
    my $self = shift;
    return if (defined($self->{'__mozbot__shutdown'}) or defined($self->{'__mozbot__active'})); # HACK HACK HACK
    $self->{'__mozbot__shutdown'} = 1; # HACK HACK HACK
    debug("connection timed out -- trying again");
    # XXX we don't call the SpottedQuit handlers here
    foreach (@modules) { $_->unload(); }
    @modules = ();
    $self->quit('connection timed out -- trying to reconnect');
    setup_connection();
}

# if something nasty happens
sub on_disconnected {
    my ($self, $event) = @_;
    return if defined($self->{'__mozbot__shutdown'}); # HACK HACK HACK
    $self->{'__mozbot__shutdown'} = 1; # HACK HACK HACK
    # perform(@_, 'SpottedQuit'); # XXX do we want to do this?
    my($reason) = $event->args;
    if ($reason =~ /Connection timed out/osi
        and ($serverRestrictsIRCNames ne $server
             or $serverExpectsValidUsername ne $server)) {
        # try to set everything up as simple as possible
        $serverRestrictsIRCNames = $server;
        $serverExpectsValidUsername = $server;
        save_config_vars([\$serverRestrictsIRCNames]);
        debug("Hrm, $server is having issues.");
        debug("We're gonna try again with different settings, hold on.");
        debug("The full message from the server was: '$reason'");
    } elsif ($reason =~ /Bad user info/osi and $serverRestrictsIRCNames ne $server) {
        # change our IRC name to something simpler by setting the flag
        $serverRestrictsIRCNames = $server;
        save_config_vars([\$serverRestrictsIRCNames]);
        debug("Hrm, $server didn't like our IRC name.");
        debug("Trying again with a simpler one, hold on.");
        debug("The full message from the server was: '$reason'");
    } elsif ($reason =~ /identd/osi and $serverExpectsValidUsername ne $server) {
        # try setting our username to the actual username
        $serverExpectsValidUsername = $server;
        save_config_vars([\$delaytime]);
        debug("Hrm, $server said something about an identd problem.");
        ebug("Trying again with our real username, hold on.");
        debug("The full message from the server was: '$reason'");
    } elsif ($reason =~ /Excess Flood/osi) {
        # increase the delay by 20%
        $delaytime = $delaytime * 1.2;
        save_config_vars([\$delaytime]);
        debug('Hrm, we it seems flooded the server. Trying again with a delay 20% longer.');
        debug("The full message from the server was: '$reason'");
    } elsif ($reason =~ /Bad Password/osi) {
        debug('Hrm, we don\'t seem to know the server password.');
        debug("The full message from the server was: '$reason'");
        if (-t) {
            print "Please enter the server password: ";
            $password = <>;
            chomp($password);
            save_config_vars([\$password]);
        } else {
            debug("edit $cfgfile to set the password *hint* *hint*");
            debug("going to wait $sleepdelay seconds so as not to overload ourselves.");
            sleep $sleepdelay;
        }
    } else {
        debug("eek! disconnected from network: '$reason'");
    }
    foreach (@modules) { $_->unload(); }
    @modules = ();
    setup_connection();
}

# on_join_channel: called when we join a channel
sub on_join_channel {
    my ($self, $event) = @_;
    my ($nick, $channel) = $event->args;
    $channel = lc($channel);
    push(@channels, $channel);
    save_config_vars([\@channels]);
    debug("joined $channel, about to autojoin modules...");
    foreach (@modules) {
        $_->JoinedChannel(newEvent({
            'bot' => $self,
            'channel' => $channel,
            'target' => $channel,
            'nick' => $nick
        }), $channel);
    }
}

# if something nasty happens
sub on_destroy {
    debug("Connection: garbage collected");
}

sub targetted {
    my ($data, $nick) = @_;
    return $data =~ /^(\s*$nick(?:[\s,:;!?]+|\s*:-\s*|\s*--+\s*|\s*-+>?\s+))(.+)$/is ?
      (defined $2 ? $2 : '') : undef;
}

# on_public: messages received on channels
sub on_public {
    my ($self, $event) = @_;
    my $data = join(' ', $event->args);
    if (defined($_ = targetted($data, quotemeta($nicks[$nick])))) {
        if ($_ ne '') {
            setEventArgs($event, $_);
            $event->{'__mozbot__fulldata'} = $data;
            perform($self, $event, 'Told', 'Baffled');
        } else {
            perform($self, $event, 'Heard');
        }
    } else {
        foreach my $nick (@ignoredTargets) {
            if (defined targetted($data, $nick)) {
                my $channel = toToChannel($self, @{$event->to});
                debug("Ignored (target matched /$nick/): $channel <".$event->nick.'> '.join(' ', $event->args));
                return;
            }
        }
        perform($self, $event, 'Heard');
    }
}

# on_noticemsg: notice messages from the server, some service, or another
# user.  beware!  it's generally Bad Juju to respond to these, but for
# some things (like opn's NickServ) it's appropriate.
sub on_noticemsg {
    my ($self, $event) = @_;
    perform($self, $event, 'Noticed');
}

sub on_private {
    my ($self, $event) = @_;
    my $data = join(' ', $event->args);
    my $nick = quotemeta($nicks[$nick]);
    if (($data =~ /^($nick(?:[-\s,:;.!?]|\s*-+>?\s+))(.+)$/is) and ($2)) {
        # we do this so that you can say 'mozbot do this' in both channels
        # and /query screens alike (otherwise, in /query screens you would
        # have to remember to omit the bot name).
        setEventArgs($event, $2);
    }
    perform($self, $event, 'Told', 'Baffled');
}

# on_me: /me actions (CTCP actually)
sub on_me {
    my ($self, $event) = @_;
    my @data = $event->args;
    my $data = join(' ', @data);
    setEventArgs($event, $data);
    my $nick = quotemeta($nicks[$nick]);
    if ($data =~ /(?:^|[\s":<([])$nick(?:[])>.,?!\s'&":]|$)/is) {
        perform($self, $event, 'Felt');
    } else {
        perform($self, $event, 'Saw');
    }
}

# on_topic: for when someone changes the topic
# also for when the server notifies us of the topic
# ...so we have to parse it carefully.
sub on_topic {
    my ($self, $event) = @_;
    if ($event->userhost eq '@') {
        # server notification
        # need to parse data
        my (undef, $channel, $topic) = $event->args;
        setEventArgs($event, $topic);
        $event->to($channel);
    }
    perform(@_, 'SpottedTopicChange');
}

# on_kick: parse the kick event
sub on_kick {
    my ($self, $event) = @_;
    my ($channel, $from) = $event->args; # from is already set anyway
    my $who = $event->to;
    $event->to($channel);
    foreach (@$who) {
        setEventArgs($event, $_);
        if ($_ eq $nicks[$nick]) {
            perform(@_, 'Kicked');
        } else {
            perform(@_, 'SpottedKick');
        }
    }
}

# Gives lag results for outgoing PINGs.
sub on_cpong {
    my ($self, $event) = @_;
    debug('completed CTCP PING with '.$event->nick.': '.days($event->args->[0]));
    # XXX should be able to use this then... see also Greeting module
    # in standard distribution
}

# -- #mozbot was here --
#   <timeless> $conn->add_handler('gender',\&on_ctcp_gender);
#   <timeless> sub on_ctcp_gender{
#   <timeless>     my (undef, $event)=@_;
#   <timeless>     my $nick=$event->nick;
#      <Hixie>     # timeless this suspense is killing me!
#   <timeless>     $bot->ctcp_reply($nick, 'neuter');
#   <timeless> }

# on_gender: What gender are we?
sub on_gender {
    my ($self, $event) = @_;
    my $nick = $event->nick;
    $self->ctcp_reply($nick, $gender);
}

# on_nick: A nick changed -- was it ours?
sub on_nick {
    my ($self, $event) = @_;
    if ($event->nick eq $nicks[$nick]) {
        on_set_nick($self, $event);
    }
    perform(@_, 'SpottedNickChange');
}

# simple handler for when users do various things and stuff
sub on_join { perform(@_, 'SpottedJoin'); }
sub on_part { perform(@_, 'SpottedPart'); }
sub on_quit { perform(@_, 'SpottedQuit'); }
sub on_invite { perform(@_, 'Invited'); }
sub on_mode { perform(@_, 'ModeChange'); } # XXX need to parse modes # XXX on key change, change %channelKeys hash
sub on_umode { perform(@_, 'UModeChange'); }
sub on_version { perform(@_, 'CTCPVersion'); }
sub on_source { perform(@_, 'CTCPSource'); }
sub on_cping { perform(@_, 'CTCPPing'); }

sub newEvent($) {
    my $event = shift;
    $event->{'time'} = time();
    return $event;
}

sub toToChannel {
    my $self = shift;
    my $channel;
    foreach (@_) {
        if (/^[#&+\$]/os) {
            if (defined($channel)) {
                return '';
            } else {
                $channel = $_;
            }
        } elsif ($_ eq $nicks[$nick]) {
            return '';
        }
    }
    return lc($channel); # if message was sent to one person only, this is it
}

# XXX some code below calls this, on lines marked "hack hack hack". We
# should fix this so that those are supported calls.
sub perform {
    my $self = shift @_;
    my $event = shift @_;
    my $to = $event->to;
    my $channel = toToChannel($self, @$to);
    my $e = newEvent({
        'bot' => $self,
        '_event' => $event, # internal internal internal do not use... ;-)
        'channel' => $channel,
        'from' => $event->nick,
        'target' => $channel || $event->nick,
        'user' => $event->userhost,
        'data' => join(' ', $event->args),
        'fulldata' => defined($event->{'__mozbot__fulldata'}) ? $event->{'__mozbot__fulldata'} : join(' ', $event->args),
        'to' => $to,
        'subtype' => $event->type,
        'firsttype' => $_[0],
        'nick' => $nicks[$nick],
        # level   (set below)
        # type  (set below)
    });
    # updated admin field if person is an admin
    if ($authenticatedUsers{$event->userhost}) {
        if (($userFlags{$authenticatedUsers{$event->userhost}} & 1) == 1) {
            $lastadmin = $event->nick;
        }
        $e->{'userName'} = $authenticatedUsers{$event->userhost};
        $e->{'userFlags'} = $userFlags{$authenticatedUsers{$event->userhost}};
    } else {
        $e->{'userName'} = 0;
    }
    unless (scalar(grep $e->{'user'} =~ /^$_$/gi, @ignoredUsers)) {
        my $continue;
        do {
            my $type = shift @_;
            my $level = 0;
            my @modulesInNextLoop = @modules;
            $continue = 1;
            $e->{'type'} = $type;
            debug("$type: $channel <".$event->nick.'> '.join(' ', $event->args));
            do {
                $level++;
                $e->{'level'} = $level;
                my @modulesInThisLoop = @modulesInNextLoop;
                @modulesInNextLoop = ();
                foreach my $module (@modulesInThisLoop) {
                    my $currentResponse;
                    eval {
                        $currentResponse = $module->mydo($self, $event, $type, $e);
                    };
                    if ($@) {
                        # $@ contains the error
                        debug("ERROR IN MODULE $module->{'_name'}!!!", $@);
                    } elsif (!defined($currentResponse)) {
                        debug("ERROR IN MODULE $module->{'_name'}: invalid response code to event '$type'.");
                    } else {
                        if ($currentResponse > $level) {
                            push(@modulesInNextLoop, $module);
                        }
                        $continue = ($continue and $currentResponse);
                    }
                }
            } while ($continue and @modulesInNextLoop);
        } while ($continue and scalar(@_));
    } else {
        debug('Ignored (from \'' . $event->userhost . "'): $channel <".$event->nick.'> '.join(' ', $event->args));
    }
    doLog($e);
}

sub doLog {
    my $e = shift;
    foreach my $module (@modules) {
        eval {
            $module->Log($e);
        };
        if ($@) {
            # $@ contains the error
            debug("ERROR!!!", $@);
        }
    }
}


################################
# internal utilities           #
################################

my @msgqueue;
my %recentMessages;
my $timeLastSetAway = 0; # the time since the away flag was last set, so that we don't set it repeatedly.

# Use this routine, always, instead of the standard "privmsg" routine.  This
# one makes sure we don't send more than one message every two seconds or so,
# which will make servers not whine about us flooding the channel.
# messages aren't the only type of flood :-( away is included
sub sendmsg {
    my ($self, $who, $msg, $do) = (@_, 'msg');
    unless ((defined($do) and defined($msg) and defined($who) and ($who ne '')) and
            ((($do eq 'msg') and (not ref($msg))) or
             (($do eq 'me') and (not ref($msg))) or
             (($do eq 'notice') and (not ref($msg))) or
             (($do eq 'ctcpSend') and (ref($msg) eq 'ARRAY') and (@$msg >= 2)) or
             (($do eq 'ctcpReply') and (not ref($msg))))) {
        cluck('Wrong arguments passed to sendmsg() - ignored');
    } else {
        $self->schedule($delaytime / 2, \&drainmsgqueue) unless @msgqueue;
        if ($do eq 'msg' or $do eq 'me' or $do eq 'notice') {
            foreach (splitMessageAcrossLines($msg)) {
                push(@msgqueue, [$who, $_, $do]);
            }
        } else {
            push(@msgqueue, [$who, $msg, $do]);
        }
    }
}

# send any pending messages
sub drainmsgqueue {
    my $self = shift;
    return unless $self->connected;
    my $qln = @msgqueue;
    if (@msgqueue > 0) {
        my ($who, $msg, $do) = getnextmsg();
        unless (weHaveSaidThisTooManyTimesAlready($self, \$who, \$msg, \$do)) {
            my $type;
            if ($do eq 'msg') {
                debug("->$who: $msg"); # XXX this makes logfiles large quickly...
                $self->privmsg($who, $msg); # it seems 'who' can be an arrayref and it works
                $type = 'Heard';
            } elsif ($do eq 'me') {
                debug("->$who * $msg"); # XXX
                $self->me($who, $msg);
                $type = 'Saw';
            } elsif ($do eq 'notice') {
                debug("=notice=>$who: $msg");
                $self->notice($who, $msg);
                # $type = 'XXX';
            } elsif ($do eq 'ctcpSend') {
                { local $" = ' '; debug("->$who CTCP PRIVMSG @$msg"); }
                my $type = shift @$msg; # @$msg contains (type, args)
                $self->ctcp($type, $who, @$msg);
                # $type = 'XXX';
            } elsif ($do eq 'ctcpReply') {
                debug("->$who CTCP NOTICE $msg");
                $self->ctcp_reply($who, $msg);
                # $type = 'XXX';
            } else {
                debug("Unknown action '$do' intended for '$who' (content: '$msg') ignored.");
            }
            if (defined($type)) {
                doLog(newEvent({
                    'bot' => $self,
                    '_event' => undef,
                    'channel' => toToChannel($self, $who),
                    'from' => $nicks[$nick],
                    'target' => $who,
                    'user' => undef, # XXX
                    'data' => $msg,
                    'fulldata' => $msg,
                    'to' => $who,
                    'subtype' => undef,
                    'firsttype' => $type,
                    'nick' => $nicks[$nick],
                    'level' => 0,
                    'type' => $type,
                }));
            }
        }
        if (@msgqueue > 0) {
            if ((@msgqueue % 10 == 0) and (time() - $timeLastSetAway > 5 * $delaytime)) {
                bot_longprocess($self, "Long send queue. There were $qln, and I just sent one to $who.");
                $timeLastSetAway = time();
                $self->schedule($delaytime * 4, # because previous one counts as message, plus you want to delay an extra bit regularly
                    \&drainmsgqueue);
            } else {
                $self->schedule($delaytime, \&drainmsgqueue);
            }
        } else {
            bot_back($self); # clear away state
        }
    }
}

sub _we_have_said_emit_debug {
    my($self, $who, $msg, $do) = @_;

    if ($$do eq 'msg') {
        debug("MUTED: ->$$who: $$msg");
    } elsif ($$do eq 'me') {
        debug("MUTED: ->$$who * $$msg"); # XXX
    } elsif ($$do eq 'notice') {
        debug("MUTED: =notice=>$$who: $$msg");
    } elsif ($$do eq 'ctcpSend') {
        local $" = ' ';
        debug("MUTED: ->$$who CTCP PRIVMSG @{$$msg}");
    } elsif ($$do eq 'ctcpReply') {
        debug("MUTED: ->$$who CTCP NOTICE $$msg");
    } else {
        debug("MUTED: Unknown action '$$do' intended for '$$who' (content: '$$msg') ignored.");
    }

    return;
}

sub weHaveSaidThisTooManyTimesAlready {
    my($self, $who, $msg, $do) = @_;
    my $key;
    if ($$do eq 'ctcpSend') {
        local $" = ',';
        $key = "$$who,$$do,@{$$msg}";
    } else {
        $key = "$$who,$$do,$$msg";
    }
    my $count = ++$recentMessages{$key};
    if ($count >= $recentMessageCountThreshold and
        $count < $recentMessageCountThreshold + 1 and
        $$do ne 'ctcpSend') {
        $recentMessages{$key} += $recentMessageCountPenalty;
        my $text = $$msg;
        if (length($msg) > 23) { # arbitrary length (XXX)
            $text = substr($text, 0, 20) . '...';
        }
        $$do = 'me';
        $$msg = "was going to say '$text' but has said it too many times today already";
    } elsif ($count >= $recentMessageCountThreshold) {
        if ($count > $recentMessageCountLimit) {
            # if the message keeps getting output, we'll get to the
            # point where if it stops it doesn't matter because the
            # recent count will be _so_ high we'll never see zero
            # again. So here we put a cap on the recent message count.
            $recentMessages{$key} = $recentMessageCountLimit;
        }

        $self->_we_have_said_emit_debug($who, $msg, $do);

        return 1;
    }
    return 0;
}

sub lowerRecentMessageCount {
    my $self = shift;
    return unless $self->connected;
    foreach my $key (keys %recentMessages) {
        $recentMessages{$key} -= $recentMessageCountDecrementRate;
        if ($recentMessages{$key} <= 0) {
            delete $recentMessages{$key};
        }
    }
    $self->schedule($delaytime, \&lowerRecentMessageCount);
}

# wrap long lines at spaces and hard returns (\n)
# this is for IRC, not for the console -- long can be up to 255
sub splitMessageAcrossLines {
    my ($str) = @_;
    my $MAXPROTOCOLLENGTH = 255;
    my @output;
    # $str could be several lines split with \n, so split it first:
    foreach my $line (split(/\n/, $str)) {
        while (length($line) > $MAXPROTOCOLLENGTH) {
            # position is zero-based index
            my $pos = rindex($line, ' ', $MAXPROTOCOLLENGTH - 1);
            if ($pos < 0) {
                $pos = $MAXPROTOCOLLENGTH - 1;
            }
            push(@output, substr($line, 0, $pos));
            $line = substr($line, $pos);
            $line =~ s/^\s+//gos;
        }
        push(@output, $line) if length($line);
    }
    return @output;
}

# equivalent of shift or pop, but for the middle of the array.
# used by getnextmsg() below to pull the messages out of the
# msgqueue stack and shove them at the end.
sub yank {
    my ($index, $list) = @_;
    my $result = @{$list}[$index];
    @{$list} = (@{$list}[0..$index-1], @{$list}[$index+1..$#{$list}]);
    return $result;
}

# looks at the msgqueue stack and decides which message to send next.
sub getnextmsg {
    my ($who, $msg, $do) = @{shift(@msgqueue)};
    my @newmsgqueue;
    my $index = 0;
    while ($index < @msgqueue) {
        if ($msgqueue[$index]->[0] eq $who) {
            push(@newmsgqueue, yank($index, \@msgqueue));
        } else {
            $index++;
        }
    }
    push(@msgqueue, @newmsgqueue);
    return ($who, $msg, $do);
}

my $markedaway = 0;

# mark bot as being away
sub bot_longprocess {
    my $self = shift;
    debug('[away: '.join(' ',@_).']');
    $self->away(join(' ',@_));
    $markedaway = @_;
}

# mark bot as not being away anymore
sub bot_back {
    my $self = shift;
    $self->away('') if $markedaway;
    $markedaway = 0;
}


# internal routines for IO::Select handling

sub bot_select {
    my ($pipe) = @_;
    $irc->removefh($pipe);
    # enable slurp mode for this function (see man perlvar for $/ documentation)
    local $/;
    undef $/;
    my $data = <$pipe>;
    debug("child ${$pipe}->{'BotModules_PID'} completed ${$pipe}->{'BotModules_ChildType'}".
           (${$pipe}->{'BotModules_Module'}->{'_shutdown'} ?
            ' (nevermind, module has shutdown)': ''));
    kill 9, ${$pipe}->{'BotModules_PID'}; # ensure child is dead
    # non-blocking reap of any pending zombies
    1 while waitpid(-1,WNOHANG) > 0;
    return if ${$pipe}->{'BotModules_Module'}->{'_shutdown'}; # see unload()
    eval {
        ${$pipe}->{'BotModules_Event'}->{'time'} = time(); # update the time field of the event
        ${$pipe}->{'BotModules_Module'}->ChildCompleted(
            ${$pipe}->{'BotModules_Event'},
            ${$pipe}->{'BotModules_ChildType'},
            $data,
            @{${$pipe}->{'BotModules_Data'}}
        );
    };
    if ($@) {
        # $@ contains the error
        debug("ERROR!!!", $@);
    }
    # prevent any memory leaks by cleaning up all the variables we added
    foreach (keys %{${$pipe}}) {
        m/^BotModules_/ && delete(${$pipe}->{$_});
    }
}

sub bot_select_data_available {
    my ($handle) = @_;
    debug("Module ${$handle}->{'BotModules_Module'}->{'_name'} received some data");
    # read data while there is some
    my $fh = '';
    vec($fh, fileno($handle), 1) = 1;
    my $count = 0; # number of bytes read
    my $ready;
    my $data = '';
    my $close = 0;
    while (select($ready = $fh, undef, undef, 0.1) and
           vec($ready, fileno($handle), 1) and
           $count < 1024 and
           not $close) { # read up to 1kb
        sysread($handle, $data, 1, length($data)) or $close = 1;
    } 
    if (not ${$handle}->{'BotModules_Module'}->{'_shutdown'}) {
        eval {
            ${$handle}->{'BotModules_Event'}->{'time'} = time();
            ${$handle}->{'BotModules_Module'}->DataAvailable(
                ${$handle}->{'BotModules_Event'},
                $handle,
                $data,
                $close,
            );
        };
        if ($@) {
            # $@ contains the error
            debug("ERROR!!!", $@);
        }
    } else {
        # module doesn't care, it was shut down
        debug("Dropping data - module is already shut down.");
        $close = 1;
    }
    if ($close) {
        # Note: It's the responsibility of the module to actually
        # close the handle.
        debug("Dropping handle...");
        $irc->removefh($handle);
        # prevent any memory leaks by cleaning up all the variables we added
        foreach (keys %{${$handle}}) {
            m/^BotModules_/ && delete(${$handle}->{$_});
        }
    }
}


# internal routines for console output, stuff

# print debugging info
sub debug {
    my $line;
    foreach (@_) {
        $line = $_; # can't chomp $_ since it is a hardref to the arguments...
        chomp $line; # ...and they are probably a constant string!
        if (-t) {
            print logdate() . " ($$) $line";
        }
        if ($LOGGING) {
            # XXX this file grows without bounds!!!
            if (open(LOG, ">>$LOGFILEPREFIX.$$.log")) {
                print LOG logdate() . " $line\n";
                close(LOG);
                print "\n";
            } else {
                print " [not logged, $!]\n";
            }
        }
    }
}

# logdate: return nice looking date and time stamp
sub logdate {
    my ($sec, $min, $hour, $mday, $mon, $year) = gmtime(shift or time());
    return sprintf("%d-%02d-%02d %02d:%02d:%02d UTC",
                   $year + 1900, $mon + 1, $mday, $hour, $min, $sec);
}

# days: how long ago was that?
sub days {
    my $then = shift;
    # maths
    my $seconds = time() - $then;
    my $minutes = int ($seconds / 60);
    my $hours = int ($minutes / 60);
    my $days = int ($hours / 24);
    # english
    if ($seconds < 60) {
        return sprintf("%d second%s", $seconds, $seconds == 1 ? "" : "s");
    } elsif ($minutes < 60) {
        return sprintf("%d minute%s", $minutes, $minutes == 1 ? "" : "s");
    } elsif ($hours < 24) {
        return sprintf("%d hour%s", $hours, $hours == 1 ? "" : "s");
    } else {
        return sprintf("%d day%s", $days, $days == 1 ? "" : "s");
    }
}

# signal handler
sub killed {
    my($sig) = @_;
    debug("received signal $sig. shutting down...");
    debug('This is evil. You should /msg me a shutdown command instead.');
    debug('WARNING: SHUTTING ME DOWN LIKE THIS CAN CAUSE FORKED PROCESSES TO START UP AS BOTS!!!'); # XXX which we should fix, of course.
    exit(1); # sane exit, including shutting down any modules
}


# internal routines for configuration

my %configStructure; # hash of cfg file keys and associated variable refs

# ok. In strict 'refs' mode, you cannot use strings as refs. Fair enough.
# However, hash keys are _always_ strings. Using a ref as a hash key turns
# it into a string. So we have to keep a virgin copy of the ref around.
#
# So the structure of the %configStructure hash is:
#   "ref" => [ cfgName, ref ]
# Ok?

sub registerConfigVariables {
    my (@variables) = @_;
    foreach (@variables) {
        $configStructure{$_->[0]} = [$_->[1], $_->[0]];
    }
} # are you confused yet?

sub configStructure {
    my (@variables) = @_;
    my %struct;
    @variables = keys %configStructure unless @variables;
    foreach (@variables) {
        confess("Function configStructure was passed something that is either not a ref or has not yet neem registered, so aborted") unless defined($configStructure{$_});
        $struct{$configStructure{$_}[0]} = $configStructure{$_}[1];
    }
    return \%struct;
}

=head2 save_config_vars([ \$variable1, \$variable2, \$variable3... ])

Pass an array reference containing references to the variables. This in turn
will save them inside the configuration.

=cut

sub save_config_vars {
    my $vars_list = shift;

    return Configuration::Save($cfgfile, configStructure(@$vars_list));
}

# internal routines for handling the modules

sub getModule {
    my ($name) = @_;
    foreach my $module (@modules) { # XXX this is not cached as a hash as performance is not a priority here
        return $module if $name eq $module->{'_name'};
    }
    return undef;
}

sub LoadModule {
    my ($name) = @_;
    # sanitize the name
    $name =~ s/[^-a-zA-Z0-9]/-/gos;
    # check the module is not already loaded
    foreach (@modules) {
        if ($_->{'_name'} eq $name) {
            return "Failed [0]: Module already loaded. Don't forget to enable it in the various channels (vars $name channels '+#channelname').";
        }
    }
    # read the module in from a file
    my $filename = "./BotModules/$name.bm"; # bm = bot module
    my $result = open(my $file, "< $filename");
    if ($result) {
        my $code = do {
            local $/ = undef; # enable "slurp" mode
            <$file>; # whole file now here
        };
        if ($code) {
#           if ($code =~ /package\s+\QBotModules::$name\E\s*;/gos) { XXX doesn't work reliably?? XXX
                # eval the file
                $code =~ /^(.*)$/os;
                $code = $1; # completely defeat the tainting mechanism.
                # $code = "# FILE: $filename\n".$code; # "# file 1 '$filename' \n" would be good without Carp.pm
                { no warnings; # as per the warning, but doesn't work??? XXX
                eval($code); }
                if ($@) {
                    # $@ contains the error
                    return "Failed [4]: $@";
                } else {
                    # if ok, then create a module
                    my $newmodule;
                    eval("
                        \$newmodule = BotModules::$name->create('$name', '$filename');
                    ");
                    if ($@) {
                        # $@ contains the error
                        return "Failed [5]: $@";
                    } else {
                        # if ok, then add it to the @modules list
                        push(@modules, $newmodule);
                        push(@modulenames, $newmodule->{'_name'});
                        ::save_config_vars([\@modulenames]);
                        # Done!!!
                        return $newmodule;
                    }
                }
#           } else {
#               return "Failed [3]: Could not find valid module definition line.";
#           }
        } else {
            # $! contains the error
            if ($!) {
                return "Failed [2]: $!";
            } else {
                return "Failed [2]: Module file is empty.";
            }
        }
    } else {
        # $! contains the error
        return "Failed [1]: $!";
    }
}

sub UnloadModule {
    my ($name) = @_;
    # remove the reference from @modules
    my @newmodules;
    my @newmodulenames;
    foreach (@modules) {
        if ($name eq $_->{'_name'}) {
            if ($_->{'_static'}) {
                return 'Cannot unload this module, it is built in.';
            }
            $_->unload();
        } else {
            push(@newmodules, $_);
            push(@newmodulenames, $_->{'_name'});
        }
    }
    if (@modules == @newmodules) {
        return 'Module not loaded. Are you sure you have the right name?';
    } else {
        @modules = @newmodules;
        @modulenames = @newmodulenames;
        ::save_config_vars([\@modulenames]);
        return;
    }
}

# password management functions

sub getSalt {
    # straight from man perlfunc
    return join('', ('.', '/', 0..9, 'A'..'Z', 'a'..'z')[rand 64, rand 64]);
}

sub newPassword {
    my($text) = @_;
    return crypt($text, getSalt());
}

sub checkPassword {
    my($text, $password) = @_;
    return (crypt($text, $password) eq $password);
}

################################
# Base Module                  #
################################

# And now, for my next trick, the base module (duh).

package BotModules;

1; # nothing to see here...

# ENGINE INTERFACE

# create - create a new BotModules object.
# Do not call this yourself. We call it. Ok?
# Do not override this either, unless you know what
# you are doing (I don't, and I wrote it...). If you
# want to add variables to $self, use Initialise.
# The parameter is the name of the module.
sub create {
    my $class = shift;
    my ($name, $filename) = @_;
    my $self = {
        '_name' => $name,
        '_shutdown' => 0, # see unload()
        '_static' => 0, # set to 1 to prevent module being unloaded
        '_variables' => {},
        '_config' => {},
        '_filename' => $filename,
        '_filemodificationtime' => undef,
    };
    bless($self, $class);
    $self->Initialise();
    $self->RegisterConfig();
    return $self;
}

sub DESTROY {
    my $self = shift;
    $self->debug('garbage collected');
}

# called by &::UnloadModule().
# this removes any pointers to the module.
# for example, it stops the scheduler from installing new timers,
# so that the bot [eventually] severs its connection with the module.
sub unload {
    my $self = shift;
    $self->Unload(); # hook for bot modules to use
    $self->{'_shutdown'} = 1; # see doScheduled and bot_select
}

# configStructure - return the hash needed for Configuration module
sub configStructure {
    my $self = shift;
    return $self->{'_config'};
}


# mydo - called to do anything (duh) (no, do, not duh) (oh, ok, sorry)
# We'd rather not call it "do" because Perl has a "do { ... }" keyword.
sub mydo {
    my $self = shift;
    my ($bot, $event, $type, $e) = @_;
    # first, we check that the user is not banned from using this module. If he
    # is, then re give up straight away.
    return 1 if ($self->IsBanned($e));
    # next we check that the module is actually enabled in this channel, and
    # if it is not we quit straight away as well.
    return 1 unless ($e->{'channel'} eq '') or ($self->InChannel($e));
    # Ok, dispatch the event.
    #

    my %dispatch_by_type = 
    (
        (map { $_ => sub { return $self->$type($e, $e->{'from'}, $e->{'data'});}, } qw(CTCPPing CTCPSource CTCPVersion SpottedNickChange SpottedQuit)),
    (map { $_ => sub { return $self->$type($e, $e->{'channel'}, $e->{'data'}, $e->{'from'});}, } qw(ModeChange)),
(map { $_ => sub { return $self->$type($e, $e->{'data'});}, } qw(Baffled Felt Heard Invited Noticed Saw Told)),
    (map { $_ => sub { return $self->$type($e, $e->{'channel'}, $e->{'data'});}, } qw(SpottedKick SpottedTopicChange)),
(map { $_ => sub { return $self->$type($e, $e->{'channel'});}, } qw(Kicked)),
    (map { $_ => sub { return $self->$type($e, $e->{'from'});}, } qw(Authed)),
(map { $_ => sub { return $self->$type($e, $e->{'channel'}, $e->{'from'});}, } qw(GotDeopped GotOpped SpottedDeopping SpottedJoin SpottedOpping SpottedPart)),
    );

    if (my $callback = $dispatch_by_type{$type}) {
        return $callback->();
    } else {
        $self->debug("Unknown action type '$type'. Ignored.");
        # XXX UModeChange (not implemented yet)
        return 1; # could not do it
    }
}


# MODULE API - use these from the your routines.

# prints output to the console
sub debug {
    my $self = shift;
    foreach my $line (@_) {
        ::debug('Module '.$self->{'_name'}.': '.$line);
    }
}

# saveConfig - call this when you change a configuration option. It resaves the config file.
sub saveConfig {
    my $self = shift;
    Configuration::Save($cfgfile, $self->configStructure());
}

# registerVariables - Registers a variable with the config system and the var setting system
# parameters: (
#     [ 'name', persistent ? 1:0, editable ? 1:0, $value ],
#               use undef instead of 0 or 1 to leave as is
#               use undef (or don't mention) the $value to not set the value
# )
sub registerVariables {
    my $self = shift;
    my (@variables) = @_;
    foreach (@variables) {
        $self->{$$_[0]} = $$_[3] if defined($$_[3]);
        if (defined($$_[1])) {
            if ($$_[1]) {
                $self->{'_config'}->{$self->{'_name'}.'::'.$$_[0]} = \$self->{$$_[0]};
            } else {
                delete($self->{'_config'}->{$self->{'_name'}.'::'.$$_[0]});
            }
        }
        $self->{'_variables'}->{$$_[0]} = $$_[2] if defined($$_[2]);
    }
}

# internal implementation of the scheduler
sub doScheduled {
    my $bot = shift;
    my ($self, $event, $time, $times, @data) = @_;
    return if ($self->{'_shutdown'}); # see unload()
    # $self->debug("scheduled event occured; $times left @ $$time second interval");
    eval {
        $event->{'time'} = time(); # update the time field of the event
        $self->Scheduled($event, @data);
        $self->schedule($event, $time, --$times, @data);
    };
    if ($@) {
        # $@ contains the error
        ::debug("ERROR!!!", $@);
    }
}

# schedule - Sets a timer to call Scheduled later
# for events that should be setup at startup, call this from Schedule().
sub schedule {
    my $self = shift;
    my ($event, $time, $times, @data) = @_;
    return if ($times == 0 or $self->{'_shutdown'}); # see unload()
    $times = -1 if ($times < 0); # pass a negative number to have a recurring timer
    my $delay = $time;
    if (ref($time)) {
        if (ref($time) eq 'SCALAR') {
            $delay = $$time;
        } else {
            return; # XXX maybe be useful?
        }
    }
    # if ($delay < 1) {
    #     $self->debug("Vetoed aggressive scheduling; forcing to 1 second minimum");
    #     $delay = 1;
    # }
    $event->{'bot'}->schedule($delay, \&doScheduled, $self, $event, $time, $times, @data);
}

# spawnChild - spawns a child process and adds it to the list of file handles to monitor
# eventually the bot calls ChildCompleted() with the output of the child process.
sub spawnChild {
    my $self = shift;
    my ($event, $command, $arguments, $type, $data) = @_;
    # uses IO::SecurePipe and fork and exec
    # secure, predictable, no dependencies on external code
    # uses fork explicitly (and once implicitly)
    my $pipe = IO::SecurePipe->new();
    if (defined($pipe)) {
        my $child = fork();
        if (defined($child)) {
            if ($child) {
                # we are the parent process
                $pipe->reader();
                ${$pipe}->{'BotModules_Module'} = $self;
                ${$pipe}->{'BotModules_Event'} = {%$event}; # Must be unchanged
                ${$pipe}->{'BotModules_ChildType'} = $type;
                ${$pipe}->{'BotModules_Data'} = $data;
                ${$pipe}->{'BotModules_Command'} = $command;
                ${$pipe}->{'BotModules_Arguments'} = $arguments;
                ${$pipe}->{'BotModules_PID'} = $child;
                $irc->addfh($pipe, \&::bot_select);
                local $" = ' ';
                $self->debug("spawned $child ($command @$arguments)");
                return 0;
            } else {
                eval {
                    # we are the child process
                    # call $command and buffer the output
                    $pipe->writer(); # get writing end of pipe, ready to output the result
                    my $output;
                    if (ref($command) eq 'CODE') {
                        $output = $command->(@$arguments);
                    } else {
                        # it would be nice if some of this was on a timeout...
                        my $result = IO::SecurePipe->new(); # create a new pipe for $command
                        # call $command (implicit fork(), which may of course fail)
                        $result->reader($command, @$arguments);
                        local $/; # to not affect the rest of the program (what little there is)
                        $/ = \(2*1024*1024); # slurp up to two megabytes
                        $output = <$result>; # blocks until child process has finished
                        close($result); # reap child
                    }
                    print $pipe $output if ($output); # output the lot in one go back to parent
                    $pipe->close();
                };
                if ($@) {
                    # $@ contains the error
                    $self->debug('failed to spawn child', $@);
                }

                # -- #mozwebtools was here --
                #       <dawn> when is that stupid bot going to get checked in?
                #   <timeless> after it stops fork bombing
                #       <dawn> which one? yours or hixies?
                #   <timeless> his, mine doesn't fork
                #   <timeless> see topic
                #       <dawn> are there plans to fix it?
                #   <timeless> yes. but he isn't sure exactly what went wrong
                #   <timeless> i think it's basically they fork for wget
                #       <dawn> why don't you help him?
                #   <timeless> i don't understand forking
                #       <dawn> that didn't stop hixie
                #   <timeless> not to mention the fact that his forking doesn't
                #              work on windows
                #       <dawn> you have other machines. techbot1 runs on windows?
                #   <timeless> yeah it runs on windows
                #       <dawn> oh
                #       <dawn> get a real os, man

                # The bug causing the 'fork bombing' was that I only
                # did the following if $@ was true or if the call to
                # 'reader' succeeded -- so if some other error occured
                # that didn't trip the $@ test but still crashed out
                # of the eval, then the script would quite happily
                # continue, and when it eventually died (e.g. because
                # of a bad connection), it would respawn multiple
                # times (as many times as it had failed to fork) and
                # it would succeed in reconnecting as many times as
                # had been configured nicks...

                eval {
                    $0 =~ m/^(.*)$/os; # untaint $0 so that we can call it below:
                    exec { $1 } ($1, '--abort'); # do not call shutdown handlers
                    # the previous line works because exec() bypasses
                    # the perl object garbarge collection and simply
                    # deallocates all the memory in one go. This means
                    # the shutdown handlers (DESTROY and so on) are
                    # never called for this fork. This is good,
                    # because otherwise we would disconnect from IRC
                    # at this point!
                };

                $self->debug("failed to shutdown cleanly!!! $@");
                exit(1); # exit in case exec($0) failed

            }
        } else {
            $self->debug("failed to fork: $!");
        }
    } else {
        $self->debug("failed to open pipe: $!");
    }
    return 1;
}

# registerDataHandle - eventually calls DataAvailable
sub registerDataHandle {
    my $self = shift;
    my ($event, $handle, $details) = @_;
    ${$handle}->{'BotModules_Module'} = $self;
    ${$handle}->{'BotModules_Event'} = $event;
    ${$handle}->{'BotModules_Details'} = $details;
    $irc->addfh($handle, \&::bot_select_data_available);
    my $fileno = fileno($handle);
    $self->debug("listening to filehandle or socket $fileno");
}

# getURI - Downloads a file and then calls GotURI
sub getURI {
    my $self = shift;
    my ($event, $uri, @data) = @_;
    $self->spawnChild($event, 'wget', ['--quiet', '--passive', '--user-agent="Mozilla/5.0 (compatible; mozbot)"',  '--output-document=-', $uri], 'URI', [$uri, @data]);
}

# returns a reference to a module -- DO NOT STORE THIS REFERENCE!!!
sub getModule {
    my $self = shift;
    return ::getModule(@_);
}

# returns a reference to @msgqueue
# manipulating this is probably not a good idea. In particular,
# don't add anything to this array (use the appropriate methods
# instead, those that use ::sendmsg(), below).
sub getMessageQueue {
    my $self = shift;
    return \@msgqueue;
}

# returns the value of $helpline
sub getHelpLine {
    return $helpline;
}

# returns a sorted list of module names
sub getModules {
    return sort(@modulenames);
}

# returns a filename with path suitable to use for logging
sub getLogFilename {
    my $self = shift;
    my($name) = @_;
    return "$LOGFILEDIR/$name";
}

# tellAdmin - may try to talk to an admin.
# NO GUARANTEES! This will PROBABLY NOT reach anyone!
sub tellAdmin {
    my $self = shift;
    my ($event, $data) = @_;
    if ($lastadmin) {
        $self->debug("Trying to tell admin '$lastadmin' this: $data");
        ::sendmsg($event->{'bot'}, $lastadmin, $data);
    } else {
        $self->debug("Wanted to tell an admin '$data', but I've never seen one.");
    }
}

# ctcpSend - Sends a CTCP message to someone
sub ctcpSend {
    my $self = shift;
    my ($event, $type, $data) = @_;
    ::sendmsg($event->{'bot'}, $event->{'target'}, [$type, $data], 'ctcpSend');
}

# ctcpReply - Sends a CTCP reply to someone
sub ctcpReply {
    my $self = shift;
    my ($event, $type, $data) = @_;
    unless (defined($type)) {
        cluck('No type passed to ctcpReply - ignored');
    }
    if (defined($data)) {
        ::sendmsg($event->{'bot'}, $event->{'from'}, "$type $data", 'ctcpReply');
    } else {
        ::sendmsg($event->{'bot'}, $event->{'from'}, $type, 'ctcpReply');
    }
}

# notice - Sends a notice to a channel or person
sub notice {
    my $self = shift;
    my ($event, $data) = @_;
    ::sendmsg($event->{'bot'}, $event->{'target'}, $data, 'notice');
}

# say - Sends a message to the channel
sub say {
    my $self = shift;
    my ($event, $data) = @_;
    return unless defined $event->{'target'};
    $data =~ s/^\Q$event->{'target'}\E: //gs;
    ::sendmsg($event->{'bot'}, $event->{'target'}, $data);
}

# privsay - Sends message to person or channel directly
# only use this if its time-senstive, otherwise you should use say
sub privsay {
	my $self = shift;
    my ($event, $data) = @_;
	return unless defined $event->{'target'};
	$data =~ s/^\Q$event->{'target'}\E: //gs;
	$event->{'bot'}->privmsg($event->{'target'}, $data);
}

# announce - Sends a message to every channel
sub announce {
    my $self = shift;
    my ($event, $data) = @_;
    foreach (@{$self->{'channels'}}) {
        ::sendmsg($event->{'bot'}, $_, $data);
    }
}

# directSay - Sends a message to the person who spoke
sub directSay {
    my $self = shift;
    my ($event, $data) = @_;
    ::sendmsg($event->{'bot'}, $event->{'from'}, $data);
}

# channelSay - Sends a message to the channel the message came from, IFF it came from a channel.
sub channelSay {
    my $self = shift;
    my ($event, $data) = @_;
    ::sendmsg($event->{'bot'}, $event->{'channel'}, $data) if $event->{'channel'};
}

# -- #mozilla was here --
#      <richb> timeless: it's focal review time, and they are working out
#              where to allocate the money.
#      <richb> timeless: needless to say i have a vested interest in this.
#       <leaf> there's money in this?
#   <timeless> richb yes; leaf always
#       <leaf> how come nobody told me?
#   <timeless> because leaf doesn't need money
#   <timeless> for leaf it grows on trees
#       <leaf> *wince*

# emote - Sends an emote to the channel
sub emote {
    my $self = shift;
    my ($event, $data) = @_;
    ::sendmsg($event->{'bot'}, $event->{'target'}, $data, 'me');
}

# directEmote - Sends an emote to the person who spoke
sub directEmote {
    my $self = shift;
    my ($event, $data) = @_;
    ::sendmsg($event->{'bot'}, $event->{'from'}, $data, 'me');
}

# sayOrEmote - calls say() or emote() depending on whether the string starts with /me or not.
sub sayOrEmote {
    my $self = shift;
    my ($event, $data) = @_;
    if ($data =~ /^\/me\s+/osi) {
        $data =~ s/^\/me\s+//gosi;
        $self->emote($event, $data);
    } else {
        $self->say($event, $data);
    }
}

# directSayOrEmote - as sayOrEmote() but calls the direct versions instead
sub directSayOrEmote {
    my $self = shift;
    my ($event, $data) = @_;
    if ($data =~ /^\/me\s+/osi) {
        $data =~ s/^\/me\s+//gosi;
        $self->directEmote($event, $data);
    } else {
        $self->directSay($event, $data);
    }
}

# isAdmin - Returns true if the person is an admin
sub isAdmin {
    my $self = shift;
    my ($event) = @_;
    return (($event->{'userName'}) and (($event->{'userFlags'} & 1) == 1));
}

# setAway - Set the bot's 'away' flag. A blank message will mark the bot as back.
# Note: If you need this you are doing something wrong!!!
sub setAway {
    my $self = shift;
    my ($event, $message) = @_;
    $event->{'bot'}->away($message);
}

# setNick - Set the bot's nick.
# Note: Best not to use this too much, especially not based on user input,
# as it is not throttled. XXX
sub setNick {
    my $self = shift;
    my ($event, $value) = @_;
    $event->{'bot'}->nick($value);
}

sub mode {
    my $self = shift;
    my ($event, $channel, $mode, $arg) = @_;
    $event->{'bot'}->mode($channel, $mode, $arg);
}

sub kick {
    my $self = shift;
    my ($event, $channel, $who, $reason) = @_;
    $event->{'bot'}->kick($channel, $who, $reason);
}

sub invite {
    my $self = shift;
    my ($event, $who, $channel) = @_;
    $event->{'bot'}->invite($who, $channel);
}

# pretty printer for turning lists of varying length strings into
# lists of roughly equal length strings without losing any data
sub prettyPrint {
    my $self = shift;
    my ($preferredLineLength, $prefix, $indent, $divider, @input) = @_;
    # sort numerically descending by length
    @input = sort {length($b) <=> length($a)} @input;
    # if we have a prefix defined, it goes first (duh)
    unshift(@input, $prefix) if defined($prefix);
    my @output;
    my $index;
    while (@input) {
        push(@output, $indent . shift(@input));
        $index = 0;
        while (($index <= $#input) and
               ((length($output[$#output]) + length($input[$#input])) < $preferredLineLength)) {
            # does this one fit?
            if ((length($output[$#output]) + length($input[$index])) < $preferredLineLength) {
                if (defined($prefix)) {
                    # don't stick the divider between the prefix and the first item
                    undef($prefix);
                } else {
                    $output[$#output] .= $divider;
                }
                $output[$#output] .= splice(@input, $index, 1);
            } else {
                $index++;
            }
        }
    }
    return @output;
}

# wordWrap routines which takes a list and wraps it. A less pretty version
# of prettyPrinter, but it keeps the order.
sub wordWrap {
    my $self = shift;
    my ($preferredLineLength, $prefix, $indent, $divider, @input) = @_;
    unshift(@input, $prefix) if defined($prefix);
    $indent = '' unless defined($indent);
    my @output;
    while (@input) {
        push(@output, $indent . shift(@input));
        while (($#input >= 0) and
               ((length($output[$#output]) + length($input[0])) < $preferredLineLength)) {
            $output[$#output] .= $divider . shift(@input);
        }
    }
    return @output;
}

sub unescapeXML {
    my $self = shift;
    my ($string) = @_;
    $string =~ s/&apos;/'/gos;
    $string =~ s/&quot;/"/gos;
    $string =~ s/&lt;/</gos;
    $string =~ s/&gt;/>/gos;
    $string =~ s/&amp;/&/gos;
    $string =~ s/&\#(\d+);/convertASCIICode($1)/ges;
    return $string;
}

sub convertASCIICode {
    my $code = shift;
    return chr($code) if ($code > 31 and $code < 127);
    return "&#$code;";
}

sub days {
    my $self = shift;
    my ($then) = @_;
    return ::days($then);
}

# return the argument if it is a valid regular expression,
# otherwise quotes the argument and returns that.
sub sanitizeRegexp {
    my $self = shift;
    my ($regexp) = @_;
    if (defined($regexp)) {
        eval {
            '' =~ /$regexp/;
        };
        $self->debug("regexp |$regexp| returned error |$@|, quoting...") if $@;
        return $@ ? quotemeta($regexp) : $regexp;
    } else {
        $self->debug("blank regexp, returning wildcard regexp //...");
        return '';
    }
}


# MODULE INTERFACE (override these)

# Initialise - Called when the module is loaded
sub Initialise {
    my $self = shift;
}

# Schedule - Called after bot is set up, to set up any scheduled tasks
# use $self->schedule($event, $delay, $times, $data)
# where $times is 1 for a single event, -1 for recurring events,
# and a +ve number for an event that occurs that many times.
sub Schedule {
    my $self = shift;
    my ($event) = @_;
}

# JoinedIRC - Called before joining any channels (but after module is setup)
# this does not get called for dynamically loaded modules
sub JoinedIRC {
    my $self = shift;
    my ($event) = @_;
}

sub JoinedChannel {
    my $self = shift;
    my ($event, $channel) = @_;
    if ($self->{'autojoin'}) {
        push(@{$self->{'channels'}}, $channel)
          unless ((scalar(grep $_ eq $channel, @{$self->{'channels'}})) or
                  (scalar(grep $_ eq $channel, @{$self->{'channelsBlocked'}})));
        $self->saveConfig();
    }
}

# Called by the Admin module's Kicked and SpottedPart handlers
sub PartedChannel {
    my $self = shift;
    my ($event, $channel) = @_;
    if ($self->{'autojoin'}) {
        my %channels = map { $_ => 1 } @{$self->{'channels'}};
        if ($channels{$channel}) {
            delete($channels{$channel});
            @{$self->{'channels'}} = keys %channels;
            $self->saveConfig();
        }
    }
}

sub InChannel {
    my $self = shift;
    my ($event) = @_;
    return scalar(grep $_ eq $event->{'channel'}, @{$self->{'channels'}});
    # XXX could be optimised - cache the list into a hash.
}

sub IsBanned {
    my $self = shift;
    my ($event) = @_;
    return 0 if scalar(grep { $_ = $self->sanitizeRegexp($_); $event->{'user'} =~ /^$_$/ } @{$self->{'allowusers'}});
    return      scalar(grep { $_ = $self->sanitizeRegexp($_); $event->{'user'} =~ /^$_$/ } @{$self->{'denyusers'}});
}

# Baffled - Called for messages prefixed by the bot's nick which we don't understand
sub Baffled {
    my $self = shift;
    my ($event, $message) = @_;
    return 1;
}

# Told - Called for messages prefixed by the bot's nick
sub Told {
    my $self = shift;
    my ($event, $message) = @_;
    return 1;
}

# Noticed - Called for notice messages
sub Noticed {
    my $self = shift;
    my ($event, $message) = @_;
    return 1;
}

# Heard - Called for all messages
sub Heard {
    my $self = shift;
    my ($event, $message) = @_;
    return 1;
}

# Felt - Called for all emotes containing bot's nick
sub Felt {
    my $self = shift;
    my ($event, $message) = @_;
    return 1;
}

# -- #mozilla was here --
# * bryner tries to imagine the need for NS_TWIPS_TO_MILES
#<Ben_Goodger> bryner: yeah, that isn't even a metric unit. should
#              be NS_TWIPS_TO_KILOMETERS
#     <bryner> there's that too
#<Ben_Goodger> oh
#<Ben_Goodger> really?
#     <bryner> yep
#<Ben_Goodger> o_O
#     <bryner> for when we use mozilla for surveying and such
#  <pinkerton> lol

# BTW. They aren't kidding. See:
# http://lxr.mozilla.org/seamonkey/search?string=NS_TWIPS_TO_KILOMETERS

# Saw - Called for all emotes
sub Saw {
    my $self = shift;
    my ($event, $message) = @_;
    return 1;
}

# Invited - Called when bot is invited into another channel
sub Invited {
    my $self = shift;
    my ($event, $channel) = @_;
    return 1;
}

# Kicked - Called when bot is kicked out of a channel
sub Kicked {
    my $self = shift;
    my ($event, $channel) = @_;
    return 1;
}

# ModeChange - Called when channel or bot has a mode flag changed
sub ModeChange {
    my $self = shift;
    my ($event, $what, $change, $who) = @_;
    return 1;
}

# GotOpped - Called when bot is opped
sub GotOpped {
    my $self = shift;
    my ($event, $channel, $who) = @_;
    return 1;
}

# GotDeopped - Called when bot is deopped
sub GotDeopped {
    my $self = shift;
    my ($event, $channel, $who) = @_;
    return 1;
}

# SpottedNickChange - Called when someone changes their nick
# Remember that you cannot use directSay here, since $event
# has the details of the old nick. And 'say' is useless
# since the channel is the old userhost string... XXX
sub SpottedNickChange {
    my $self = shift;
    my ($event, $from, $to) = @_;
    return 1;
}

# Authed - Called when someone authenticates with us.
# Remember that you cannot use say here, since this
# cannot actually be done in a channel...
sub Authed {
    my $self = shift;
    my ($event, $who) = @_;
    return 1;
}

# SpottedTopicChange - Called when someone thinks someone else said something funny
sub SpottedTopicChange {
    my $self = shift;
    my ($event, $channel, $new) = @_;
    return 1;
}

# SpottedJoin - Called when someone joins a channel
sub SpottedJoin {
    my $self = shift;
    my ($event, $channel, $who) = @_;
    return 1;
}

# SpottedPart - Called when someone leaves a channel
sub SpottedPart {
    my $self = shift;
    my ($event, $channel, $who) = @_;
    return 1;
}

# SpottedKick - Called when someone leaves a channel forcibly
sub SpottedKick {
    my $self = shift;
    my ($event, $channel, $who) = @_;
    return 1;
}

# SpottedQuit - Called when someone leaves a server
# can't use say or directSay: no channel involved, and
# user has quit (obviously). XXX
sub SpottedQuit {
    my $self = shift;
    my ($event, $who, $why) = @_;
    return 1;
}

# CTCPPing - Called when we receive a CTCP Ping.
sub CTCPPing {
    my $self = shift;
    my ($event, $who, $what) = @_;
    return 1;
}

# CTCPVersion - Called when we receive a CTCP Version.
sub CTCPVersion {
    my $self = shift;
    my ($event, $who, $what) = @_;
    return 1;
}

# CTCPSource - Called when we receive a CTCP Source.
sub CTCPSource {
    my $self = shift;
    my ($event, $who, $what) = @_;
    return 1;
}

# SpottedOpping - Called when someone is opped
sub SpottedOpping {
    my $self = shift;
    my ($event, $channel, $who) = @_;
    return 1;
}

# SpottedDeopping - Called when someone is... deopped, maybe?
sub SpottedDeopping {
    my $self = shift;
    my ($event, $channel, $who) = @_;
    return 1;
}

# Scheduled - Called when a scheduled timer triggers
sub Scheduled {
    my $self = shift;
    my ($event, @data) = @_;
    if (ref($data[0]) eq 'CODE') {
        $data[0]->($event, @data);
    } else {
        $self->debug('Unhandled scheduled event... :-/');
    }
}

# ChildCompleted - Called when a child process has quit
sub ChildCompleted {
    my $self = shift;
    my ($event, $type, $output, @data) = @_;
    if ($type eq 'URI') {
        my $uri = shift(@data);
        $self->GotURI($event, $uri, $output, @data);
    }
}

# DataAvailable - Called when a handle registered with
# registerDataHandle has made data available
sub DataAvailable {
    my $self = shift;
    my ($event, $handle, $data, $close) = @_;
    # do nothing
}

# GotURI - Called when a requested URI has been downloaded
sub GotURI {
    my $self = shift;
    my ($event, $uri, $contents, @data) = @_;
}

# Help - Called to fully explain the module (return hash of command/description pairs)
# the string given for the '' key should be a module description
sub Help {
    my $self = shift;
    my ($event) = @_;
    return {};
}

# RegisterConfig - Called when initialised, should call registerVariables
sub RegisterConfig {
    my $self = shift;
    $self->registerVariables(
      # [ name, save?, settable?, value ]
        ['channels',        1, 1, []],
        ['channelsBlocked', 1, 1, []], # the channels in which this module will not autojoin regardless
        ['autojoin',        1, 1, 1],
        ['allowusers',      1, 1, []],
        ['denyusers',       1, 1, []],
    );
}

use Mozbot::Constants;

# Set - called to set a variable to a particular value.
sub Set {
    my $self = shift;
    my ($event, $variable, $value) = @_;
    if ($self->{'_variables'}->{$variable}) {
        if ((not defined($self->{$variable})) or (not ref($self->{$variable}))) {
            $self->{$variable} = $value;
        } elsif (ref($self->{$variable}) eq 'SCALAR') {
            ${$self->{$variable}} = $value;
        } elsif (ref($self->{$variable}) eq 'ARRAY') {
            if ($value =~ /^([-+])(.*)$/so) {
                if ($1 eq '+') {
                    push(@{$self->{$variable}}, $2);
                } else {
                    # We don't want to change the reference!!!
                    # Other variables might be pointing to there,
                    # it is *those* vars that affect the app.
                    my @oldvalue = @{$self->{$variable}};
                    @{$self->{$variable}} = ();
                    foreach (@oldvalue) {
                        push(@{$self->{$variable}}, $_) unless ($2 eq $_);
                    }
                    # XXX no feedback if nothing is done
                }
            } else {
                # not the right format dude!
                return $SET_VAR__WRONG_FORMAT_FOR_ARRAY;
            }
        } elsif (ref($self->{$variable}) eq 'HASH') {
            if ($value =~ /^\+(.)(.*)\1(.*)$/so) {
                $self->{$variable}->{$2} = $3;
                return -2 if $1 =~ /[a-zA-Z]/so;
            } elsif ($value =~ /^\-(.*)$/so) {
                # XXX no feedback if nothing is done
                delete($self->{$variable}->{$1});
            } else {
                # not the right format dude!
                return $SET_VAR__WRONG_FORMAT_FOR_HASH; 
            }
        } else {
            # please do not try to set coderefs or other types we cannot handle.
            return $SET_VAR__CANNOT_HANDLE_TYPE; 
        }
    } else {
        # please do not try to set unknown (unintroduced ?) variables
        return $SET_VAR__UNKNOWN_VAR; 
    }
    $self->saveConfig();
    return $SET_VAR__SUCCESS;
}

# Get - called to get a particular variable
sub Get {
    my $self = shift;
    my ($event, $variable) = @_;
    return $self->{$variable};
}

# Log - Called for every event
sub Log {
    my $self = shift;
    my ($event) = @_;
}

# Log - Called for every event
sub Unload {
    my $self = shift;
}


################################
# Admin Module                 #
################################

package BotModules::Admin;

use vars qw(@ISA);
@ISA = qw(BotModules);

use Mozbot::Constants;

# Initialise - Called when the module is loaded
sub Initialise {
    my $self = shift;
    $self->{'_fileModifiedTimes'} = {};
    $self->{'_static'} = 1;
}

# RegisterConfig - Called when initialised, should call registerVariables
sub RegisterConfig {
    my $self = shift;
    $self->SUPER::RegisterConfig(@_);
    $self->registerVariables(
      # [ name, save?, settable?, value ]
        ['allowInviting', 1, 1, 1], # by default, anyone can invite a bot into their channel
        ['allowChannelAdmin', 1, 1, 0], # by default, one cannot admin from a channel
        ['sourceCodeCheckDelay', 1, 1, 20], # by default, wait 20 seconds between source code checks
        ['files', 1, 1, [$0, 'lib/Mails.pm', 'lib/Configuration.pm', 'lib/IO/SecurePipe.pm']], # files to check for source code changes
        ['channels', 0, 0, undef], # remove the 'channels' internal variable...
        ['autojoin', 0, 0, 0], # remove the 'autojoin' internal variable...
        ['errorMessagesMaxLines', 1, 1, 5], # by default, only have 5 lines in error messages, trim middle if more
    );
    # now add in all the global variables...
    foreach (keys %configStructure) {
        $self->registerVariables([$configStructure{$_}[0], 0, 1, $configStructure{$_}[1]]) if (ref($configStructure{$_}[1]) =~ /^(?:SCALAR|ARRAY|HASH)$/go);
    }
}

# saveConfig - make sure we also save the main config variables...
sub saveConfig {
    my $self = shift;
    $self->SUPER::saveConfig(@_);
    ::save_config_vars([]);
}

# Set - called to set a variable to a particular value.
sub Set {
    my $self = shift;
    my ($event, $variable, $value) = @_;
    # First let's special case some magic variables...
    if ($variable eq 'currentnick') {
        $self->setNick($event, $value);
        $self->say($event, "Attempted to change nick to '$value'.");
        return -1;
    } elsif ($variable eq 'nicks') {
        if ($value =~ /^([-+])(.*)$/so) {
            if ($1 eq '+') {
                # check it isn't there already and is not ''
                my $value = $2;
                if ($value eq '') {
                    $self->say($event, "The empty string is not a valid nick.");
                    return -1;
                }
                my $thenick = 0;
                $thenick++ while (($thenick < @nicks) and ($value ne $nicks[$thenick]));
                if ($thenick < @nicks) {
                    $self->say($event, "That nick (value) is already on the list of possible nicks.");
                    return -1;
                }
            } else {
                if ($2 eq $nicks[$nick]) {
                    $self->say($event, "You cannot remove the current nick ('$nicks[$nick]') from the list of allowed nicks... Change the 'currentnick' variable first!");
                    return -1;
                }
            }
        }
    } elsif ($variable eq 'umode') {
        $self->mode($event, $nicks[$nick], $value, '');
        $self->say($event, "Attempted to change current umode to '$value'.");
    }
    return $self->SUPER::Set($event, $variable, $value);
}

sub _DefaultGet {
    my $self = shift;
    my ($event, $variable) = @_;

    # else, check for known global variables...
    my $configStructure = ::configStructure();

    return
          defined($configStructure->{$variable})
        ? $configStructure->{$variable}
        : $self->SUPER::Get($event, $variable)
        ;
}

# Get - called to get a particular variable.
sub Get {
    my $self = shift;
    my ($event, $variable) = @_;

    # First let's special case some magic variables...
    if ($variable eq 'currentnick') {
        return $event->{'nick'};
    } elsif ($variable eq 'users') {
        my @users = sort keys %users;
        return \@users;
    } else {
        return $self->_DefaultGet($event, $variable);
    }
}

# Schedule - called when bot connects to a server, to install any schedulers
# use $self->schedule($event, $delay, $times, $data)
# where $times is 1 for a single event, -1 for recurring events,
# and a +ve number for an event that occurs that many times.
sub Schedule {
    my $self = shift;
    my ($event) = @_;
    $self->schedule($event, \$self->{'sourceCodeCheckDelay'}, -1, {'action'=>'source'});
    $self->SUPER::Schedule($event);
}

my %extra_admin_result =
(
    "" => 'The administration module is used to perform tasks that fundamentally affect the bot.',
    shutdown => 'Shuts the bot down completely.',
    shutup => q{Clears the output queue (you actually have to say 'shutup please\' or nothing will happen).},
    restart => 'Shuts the bot down completely then restarts it, so that any source changes take effect.',
    cycle => 'Makes the bot disconnect from the server then try to reconnect.',
    changepassword => q{Change a user's password: changepassword <user> <newpassword> <newpassword>},
    vars => q{Manage variables: vars [<module> [<variable> ['<value>']]], say 'vars' for more details.},
    join => 'Makes the bot attempt to join a channel. The same effect can be achieved using /invite. Syntax: join <channel>',
    part => 'Makes the bot leave a channel. The same effect can be achieved using /kick. Syntax: part <channel>',
    load => 'Loads a module from disk, if it is not already loaded: load <module>',
    unload => 'Unloads a module from memory: load <module>',
    reload => 'Unloads and then loads a module: reload <module>',
    bless => q{Sets the 'admin' flag on a registered user. Syntax: bless <user>},
    unbless => q{Resets the 'admin' flag on a registered user. Syntax: unbless <user>},
    deleteuser => q{Deletes a user from the bot. Syntax: deleteuser <username>},
);

sub Help {
    my $self = shift;
    my ($event) = @_;
    my %result =
    (
        'auth' => q{Authenticate yourself. Append the word 'quiet' after your password if you don't want confirmation. Syntax: auth <username> <password> [quiet]},
        'password' => 'Change your password: password <oldpassword> <newpassword> <newpassword>',
        'newuser' => 'Registers a new username and password (with no privileges). Syntax: newuser <username> <newpassword> <newpassword>',
    );
    if ($self->isAdmin($event)) {
        %result = (%result, %extra_admin_result);
    }
    return \%result;
}

sub _authenticate_in_told {
    my $self = shift;

    my ($user, $password, $is_quiet) = @_;

    my $event = $self->_d_event;
    my $message = $self->_d_message;

    if (defined($users{$user})) {
        if (::checkPassword($password, $users{$user})) {
            $authenticatedUsers{$event->{'user'}} = $user;
            if (not defined($is_quiet)) {
                $self->directSay($event, "Hi $user!");
            }
            ::perform($event->{'bot'}, $event->{'_event'}, 'Authed'); # hack hack hack
        } else {
            $self->directSay($event, "No...");
        }
    } else {
        $self->directSay($event, 
            (
                "You have not been added as a user yet. "
                . "Try the 'newuser' command "
                . "(see 'help newuser' for details)."
            )
        );
    }

    return 0;
}

=head2 $self->_event_say($text_string)

Call $self->say($self->_d_event(), $text_string);

=cut

sub _event_say {
    my $self = shift;

    my ($text) = @_;

    return $self->say($self->_d_event(), $text);
}

sub _event_say_several {
    my ($self, $messages) = @_;

    foreach my $msg (@$messages) {
        $self->_event_say($msg);
    }

    return;
}

sub _change_password_in_told {
    my $self = shift;

    my ($old_pass, $new_pass, $new_pass_copy) = @_;
    
    my $event = $self->_d_event;
    my $message = $self->_d_message;

    if ($authenticatedUsers{$event->{'user'}}) {
        if ($new_pass ne $new_pass_copy) {
            $self->_event_say('New passwords did not match. Try again.');
        } elsif (::checkPassword(
                $old_pass, $users{$authenticatedUsers{$event->{'user'}}}
            )) {
            $users{$authenticatedUsers{$event->{'user'}}} = ::newPassword($new_pass);
            delete($authenticatedUsers{$event->{'user'}});
            $self->_event_say('Password changed. Please reauthenticate.');
            $self->saveConfig();
        } else {
            delete($authenticatedUsers{$event->{'user'}});
            $self->_event_say(
                'That is not your current password. Please reauthenticate.'
            );
        }
    }

    return 0;
}

sub _new_user_in_told {
    my $self = shift;

    my ($username, $new_pass, $new_pass_copy) = @_;

    my $event = $self->_d_event;
    my $message = $self->_d_message;

    if (defined($users{$username})) {
        $self->_event_say('That user already exists in my list, you can\'t add them again!');
    } elsif ( $new_pass ne $new_pass_copy ) {
        $self->_event_say('New passwords did not match. Try again.');
    } elsif ($username) {
        $users{$username} = ::newPassword($new_pass);
        $userFlags{$username} = 0;
        $self->directSay($event, "New user '$username' added with password '$new_pass' and no rights.");
        $self->saveConfig();
    } else {
        $self->_event_say('That is not a valid user name.');
    }

    return 0;
}

# Delegated event
sub _d_event {
    my $self = shift;

    return $self->{_d_event};
}

# Delegated message.
sub _d_message {
    my $self = shift;

    return $self->{_d_message};
}

sub _in_channel {
    my $self = shift;

    return ($self->_d_event->{'channel'});
}


sub _handle_user_and_password_messages
{
    my $self = shift;

    my $message = $self->_d_message;

    my @checks =
    (
        {
            method => "_authenticate_in_told",
            test =>
            sub { 
                $message =~ /^\s*auth\s+($variablepattern)\s+($variablepattern)(\s+quiet)?\s*$/osi
            },
        },
        {
            method => "_change_password_in_told",
            test => 
            sub {
                $message =~ /^\s*password\s+($variablepattern)\s+($variablepattern)\s+($variablepattern)\s*$/osi
            },
        },
        {
            method => "_new_user_in_told",
            test => 
            sub {
                $message =~ /^\s*new\s*user\s+($variablepattern)\s+($variablepattern)\s+($variablepattern)\s*$/osi
            },
        },
    );

    foreach my $check (@checks)
    {
        if (my @matches = $check->{'test'}->())
        {
            if ($self->_in_channel())
            {
                return 0;
            }
            else
            {
                my $method = $check->{'method'};
                return $self->$method(@matches);
            }
        }
    }

    return 1;
}

sub _handle_delete_user_event {
    my $self = shift;

    my ($doomedUser) = @_;

    my $event = $self->_d_event;

    if (not defined($users{$doomedUser})) {
        $self->_event_say(
            "I don't know of a user called '$doomedUser', sorry."
        );
    } else {
        # check user is not last admin
        my $count;
        if (($userFlags{$doomedUser} & 1) == 1) {
            # deleting an admin. Count how many are left.
            $count = 0;
            foreach my $user (keys %users) {
                ++$count if ($user ne $doomedUser and
                    ($userFlags{$user} & 1) == 1);
            }
        } else {
            # not deleting an admin. We know there is an admin in there, it's
            # the user doing the deleting. So we're safe.
            $count = 1;
        }
        if ($count) {
            $self->deleteUser($doomedUser);
            $self->_event_say("User '$doomedUser' deleted.");
        } else {
            $self->_event_say("Can't delete user '$doomedUser', that would leave you with no admins!");
        }
    }

    return;
}

sub _handle_sd_or_restart_event {
    my $self = shift;

    my ($rest_of_message, $args) = @_;

    my $event = $self->_d_event;

    if ($rest_of_message =~ /\A,?\s+please\s*[?!.]*\s*\z/osi) {
        if (defined($args->{'please_msg'})) {
            $self->_event_say($args->{please_msg});
        }

        my $method = ucfirst($args->{event_name});

        $self->$method(
            $event, 
            sprintf(
                "I was told to %s by %s%s",
                $args->{'event_name'},
                $event->{'from'},
                $args->{'reason_suffix'},
            )
        );
    } else {
        $self->_event_say(
            "If you really want me to $args->{event_name}, use the magic word.",
        );
        $self->schedule($event, 7, 1, 'i.e., please.');
    }

    return;
}

sub _QuitFromReason {
    my $self = shift;

    my ($reason) = @_;

    my $event = $self->_d_event;

    $event->{'bot'}->quit($reason);

    return;
}


sub Shutdown {
    my $self = shift;

    my ($event, $reason) = @_;

    # XXX should do something like &::perform($event->{'bot'}, $event->{'_event'}, 'SpottedQuit'); # hack hack hack
    #     ...but it should have the right channel/nick/reason info
    # XXX we don't unload the modules here?

    $self->_QuitFromReason($reason);

    exit(0);
}

my %shutdown_or_restart_events =
(
    'restart' => {
        reason_suffix => " -- brb", 
    },
    'shutdown' => {
        reason_suffix => ". :-( ", 
        please_msg => 'But of course. Have a nice day!',
    },
);

sub _get_shutdown_action_args {
    my ($self, $action) = @_;

    return
    {
        %{$shutdown_or_restart_events{$action}},
        'event_name' => $action,
    };
}

sub _handle_sd_or_restart_action {
    my ($self, $action, $rest_of_command) = @_;

    return $self->_handle_sd_or_restart_event(
        $rest_of_command,
        $self->_get_shutdown_action_args($action),
    );
}

sub _handle_admin_change_passsword_event {
    my $self = shift;

    my ($username, $new_pass, $new_pass_copy) = @_;

    my $event = $self->_d_event;

    if (not defined($users{$username})) {
        $self->_event_say("I don't know of a user called '$username', sorry.");
    } elsif ($new_pass ne $new_pass_copy) {
        $self->_event_say('New passwords did not match. Try again.');
    } else {
        $users{$username} = ::newPassword($new_pass);
        my $count = 0;
        foreach my $user (keys %authenticatedUsers) {
            if ($authenticatedUsers{$user} eq $username) {
                delete($authenticatedUsers{$user});
                ++$count;
            }
        }
        if ($count) {
            $self->_event_say("Password changed for user '$username'. They must reauthenticate.");
        } else {
            $self->_event_say("Password changed for user '$username'.");
        }
        $self->saveConfig();
    }

    return;
}

sub _handle_admin_shut_up_event {
    my $self = shift;

    my $lost = @msgqueue;
    @msgqueue = ();

    $self->_event_say(
          $lost
        ? "Ok, threw away $lost messages."
        : q{But I wasn't saying anything!}
    );

    return;
}

sub _handle_module_loading_event {
    my $self = shift;

    my ($action, $module_name) = @_;

    my $event = $self->_d_event;

    # Call LoadModule , UnloadModule, ReloadModule
    my $method = ucfirst($action)."Module";
    $self->$method($event, $module_name, 1);

    return;
}

sub _handle_admin_event {
    my $self = shift;

    my $message = $self->_d_message;
    my $event = $self->_d_event;

    my @matches;

    my ($action, $rest, $module_name);

    if (($action, $rest) = 
        $message =~ /^\s*(shutdown|restart)(.*)\z/osi) {
        return $self->_handle_sd_or_restart_action($action, $rest);
    }
    elsif (@matches = $message =~ /^\s*delete\s*user\s+($variablepattern)\s*$/osi) {
        my ($doomedUser) = @matches;

        $self->_handle_delete_user_event($doomedUser);
    } elsif (@matches = $message =~ /^\s*change\s*password\s+($variablepattern)\s+($variablepattern)\s+($variablepattern)\s*$/osi) {
        my ($username, $new_pass, $new_pass_copy) = @matches;

        $self->_handle_admin_change_passsword_event(
            $username, $new_pass, $new_pass_copy
        );
    } elsif ($message =~ /^\s*(?:shut\s*up,?\s+please)\s*[?!.]*\s*$/osi) {
        $self->_handle_admin_shut_up_event();
    } elsif ($message =~ /^\s*cycle(?:\s+please)?\s*[?!.]*\s*$/osi) {
        my $reason = 'I was told to cycle by '.$event->{'from'}.'. BRB!';
        # XXX should do something like &::perform($event->{'bot'}, $event->{'_event'}, 'SpottedQuit'); # hack hack hack
        #     ...but it should have the right channel/nick/reason info
        # XXX we don't unload the modules here?
        $self->_QuitFromReason($reason);
        Configuration::Get($cfgfile, ::configStructure());
    } elsif ($message =~ /^\s*join\s+([&#+][^\s]+)(?:\s+please)?\s*[?!.]*\s*$/osi) {
        $self->Invited($event, $1);
    } elsif ($message =~ /^\s*part\s+([&#+][^\s]+)(?:\s+please)?\s*[?!.]*\s*$/osi) {
        $event->{'bot'}->part("$1 :I was told to leave by $event->{'from'}. :-(");
    } elsif ($message =~ /^\s*bless\s+('?)($variablepattern)\1\s*$/osi) {
        if (defined($users{$2})) {
            $userFlags{$2} = $userFlags{$2} || 1;
            $self->saveConfig();
            $self->_event_say("Ok, $2 is now an admin.");
        } else {
            $self->_event_say('I don\'t know that user. Try the \'newuser\' command (see \'help newuser\' for details).');
        }
    } elsif ($message =~ /^\s*unbless\s+('?)($variablepattern)\1\s*$/osi) {
        if (defined($users{$2})) {
            $userFlags{$2} = $userFlags{$2} &~ 1;
            $self->saveConfig();
            $self->_event_say("Ok, $2 is now a mundane luser.");
        } else {
            $self->_event_say('I don\'t know that user. Check your spelling!');
        }
    } elsif (($action, $module_name) =
        $message =~ 
        /^\s*(reload|unload|load)\s+(?:'?)($variablepattern)\1\s*$/osi) {
        $self->_handle_module_loading_event($action, $module_name);
    } elsif ($message =~ /^\s*vars(?:\s+($variablepattern)(?:\s+($variablepattern)(?:\s+'(.*)')?)?|(.*))?\s*$/osi) {
        $self->Vars($1, $2, $3, $4);
    } else {
        return $self->SUPER::Told($event, $message);
    }

    return 0;
}

sub _is_d_event_admin {
    my $self = shift;

    return $self->isAdmin($self->_d_event());
}

sub _Told_main {
    my $self = shift;

    my $event = $self->_d_event;
    my $message = $self->_d_message;

    my @args = ($event, $message);

    if (not $self->{allowChannelAdmin} || ($event->{channel} eq ''))
    {
        return $self->SUPER::Told(@args);
    } elsif (!$self->_handle_user_and_password_messages()) {
        return 0;
    } elsif ($self->_is_d_event_admin) {
        return $self->_handle_admin_event();
    } else {
        return $self->SUPER::Told(@args);
    }
}

# Told - Called for messages prefixed by the bot's nick
sub Told {
    my $self = shift;

    my ($event, $message) = @_;

    $self->{_d_event} = $event;
    $self->{_d_message} = $message;

    my $ret = $self->_Told_main();

    delete($self->{_d_event});
    delete($self->{_d_message});

    return $ret;
}

sub Scheduled {
    my $self = shift;
    my ($event, $type) = @_;
    if ((ref($type) eq 'HASH') and ($type->{'action'} eq 'source')) {
        $self->CheckSource($event);
    } elsif (ref($type)) {
        $self->SUPER::Scheduled(@_);
    } else {
        $self->directSay($event, $type);
    }
}

# remove any (other) temporary administrators when an admin authenticates
sub Authed {
    my $self = shift;
    my ($event, $who) = @_;
    if ($self->isAdmin($event)) {
        foreach (keys %userFlags) {
            if ((($userFlags{$_} & 2) == 2) and ($authenticatedUsers{$event->{'user'}} ne $_)) {
                $self->deleteUser($_);
                $self->directSay($event, "Temporary administrator '$_' removed from user list.");
            }
        }
    }
    return $self->SUPER::Authed(@_); # this should not stop anything else happening
}

# SpottedQuit - Called when someone leaves a server
sub SpottedQuit {
    my $self = shift;
    my ($event, $who, $why) = @_;
    delete($authenticatedUsers{$event->{'user'}});
    # XXX this doesn't deal with a user who has authenticated twice.
    return $self->SUPER::SpottedQuit(@_);
}

sub CheckSource {
    my $self = shift;
    my ($event) = @_;
    foreach my $file (@{$self->{'files'}}) {
        my $lastModifiedTime = $self->{'_fileModifiedTimes'}->{$file};
        my ($dev, $ino, $mode, $nlink, $uid, $gid, $rdev, $size, $atime, $mtime, $ctime, $blksize, $blocks)
            = stat($file);
        $self->{'_fileModifiedTimes'}->{$file} = $mtime;
        if (defined($lastModifiedTime) and ($mtime > $lastModifiedTime)) {
            $self->debug("Noticed that source code of $file had changed");
            # compile new bot using perl -cwT XXX
            if (1) { # XXX replace 1 with "did compile succeed" test
                $self->Restart($event, 'someone seems to have changed my source code. brb, unless I get a compile error!');
            } else {
                # tellAdmin that it did not compile XXX
                # debug that it did not compile
            }
        }
    }
    my @updatedModules;
    foreach my $module (@modules) {
        if ($module->{'_filename'}) {
            my $lastModifiedTime = $module->{'_fileModificationTime'};
            my ($dev, $ino, $mode, $nlink, $uid, $gid, $rdev, $size, $atime, $mtime, $ctime, $blksize, $blocks)
                = stat($module->{'_filename'});
            $module->{'_fileModificationTime'} = $mtime;
            if (defined($lastModifiedTime) and ($mtime > $lastModifiedTime)) {
                push(@updatedModules, $module->{'_name'});
            }
        }
    }
    foreach my $module (@updatedModules) {
        $self->ReloadModule($event, $module, 0);
    }
}

sub Restart {
    my $self = shift;
    my ($event, $reason) = @_;
    # XXX should do something like &::do($event->{'bot'}, $event->{'_event'}, 'SpottedQuit'); # hack hack hack
    #     ...but it should have the right channel/nick/reason info
    #     ...and it is broken if called from CheckSource, which is a
    #     scheduled event handler, since $event is then a very basic
    #     incomplete hash.
    # XXX we don't unload modules here?
    $self->_QuitFromReason($reason);
    # Note that `exec' will not call our `END' blocks, nor will it
    # call any `DESTROY' methods in our objects. So we fork a child to
    # do that first.
    my $parent = $$;
    my $child = fork();
    if (defined($child)) {
        if ($child) {
            # we are the parent process who is
            # about to exec($0), so wait for
            # child to shutdown.
            $self->debug("spawned $child to handle shutdown...");
            waitpid($child, 0);
        } else {
            # we are the child process who is
            # in charge of shutting down cleanly.
            $self->debug("initiating shutdown for parent process $parent...");
            exit(0);
        }
    } else {
        $self->debug("failed to fork: $!");
    }
    $self->debug("About to defer to a new $0 process...");
    # we have done our best to shutdown, so go for it!
    eval {
        $0 =~ m/^(.*)$/os; # untaint $0 so that we can call it below (as $1)
        if ($CHROOT) {
            exec { $1 } ($1, '--assume-chrooted', $cfgfile);
        } else {
            exec { $1 } ($1, $cfgfile);
        }
        # I am told (by some nice people in #perl on Efnet) that our
        # memory is all cleared up for us. So don't worry that even
        # though we don't call DESTROY in _this_ instance, we leave
        # memory behind.
    };
    $self->debug("That failed!!! Bailing out to prevent all hell from breaking loose! $@ :-|");
    exit(1); # we never get here unless exec fails
}

sub _VarsHelp {
    my $self = shift;

    return $self->_event_say_several(
        [
            'The \'vars\' command gives you an interface to the module variables in the bot.',
            'To list the variables in a module: vars <module>',
            'To get the value of a variable: vars <module> <variable>',
            'To set the value of a variable: vars <module> <variable> \'<value>\'',
            'Note the quotes around the value. They are required. If the value contains quotes itself, that is fine.',
        ],
    );
}

sub _VarsNonsense {
    my $self = shift;

    return $self->_event_say_several(
        [
            'I didn\'t quite understand that. Try just \'vars\' on its own for help.',
            'If you are trying to set a variable, don\'t forget the quotes around the value!',
        ]
    );
}

sub _stringify_list_of_vals {
    my ($self, $values) = @_;

    return join(", ", map { qq{'$_'} } @$values)
}

sub _ModuleHasVarsString {
    my ($self, $modulename, $variables) = @_;

    if (@$variables) {
        return "Module '$modulename' has the following published variables: "
            . $self->_stringify_list_of_vals($variables);
    } else {
        return "Module '$modulename' has no settable variables.";
    }
}

sub _GetActiveModuleVariables {
    my ($self, $module) = @_;

    my $vars_dict = $module->{'_variables'};

    # then enumerate its variables
    return [grep { $vars_dict->{$_} } sort keys(%{$vars_dict})];
}


sub _Vars_ShowVarValue {
    my ($self, $modulename, $module, $variable) = @_;

    my $event = $self->_d_event;

    my $value = $module->Get($event, $variable);

    if (! defined($value)) {
        # we don't know that variable
        $self->_event_say(
              $module->{'_variables'}->{$variable}
            ? "Variable '$variable' in module '$modulename' is write-only, sorry."
            : "Module '$modulename' does not have a variable '$variable' as far as I can tell."
        );
        return;
    }

    my $type = ref($value);

    my $say_that_var_is = sub {
        my $text = shift;
        return $self->_event_say(
            "Variable '$variable' in module '$modulename' is $text"
        );
    };

    if ($type eq 'SCALAR') {
        $say_that_var_is->("set to: '$$value'");
    } elsif ($type eq 'ARRAY') {
        # XXX need a 'maximum number of items' feature to prevent 
        # flooding ourselves to pieces (or is shutup please enough?)
        if (@$value) {
            $say_that_var_is->(
                  "a list with the following values: "
                  .  $self->_stringify_list_of_vals($value)
            );
        } else {
            $say_that_var_is->("an empty list.");
        }
    } elsif ($type eq 'HASH') {
        # XXX need a 'maximum number of items' feature to prevent 
        # flooding ourselves to pieces (or is shutup please enough?)
        $say_that_var_is->("a hash with the following values:");
        foreach (sort keys %$value) {
            $self->_event_say("  '$_' => '".($value->{$_}).'\' ');
        }
        $self->_event_say("End of dump of variable '$variable'.");
    } else {
        $say_that_var_is->("set to: '$value'");
    }

    return;
}


sub _Vars_AssignVar {
    my $self = shift;

    my ($modulename, $module, $variable, $value) = @_;

    my $event = $self->_d_event;

    my $result = $module->Set($event, $variable, $value);

    if (!defined($result)) {
        $result = $SET_VAR__SUCCESS;
    }

    my %dispatch = 
    (
        $SET_VAR__SUCCESS => sub {
            $self->_event_say("Variable '$variable' in module '$modulename' has changed.");
        },
        $SET_VAR__CANNOT_HANDLE_TYPE => sub {
            $self->_event_say("Variable '$variable' is of type ".ref($module->{$variable}).' and I do not know how to set that kind of variable!');
        },
        $SET_VAR__UNKNOWN_VAR => sub {
            if ($module->{$variable}) { # well we do, but only to read
                $self->_event_say("Variable '$variable' in module '$modulename' is read-only, sorry.");
            } else { # not known
                $self->_event_say("Module '$modulename' does not have a variable '$variable' as far as I can tell.");
            }
        },
        $SET_VAR__WRONG_FORMAT_FOR_ARRAY => sub {
            $self->_event_say("Variable '$variable' is a list. To add to a list, please use the '+' symbol before the value (vars <module> <variable> '+<value>'). To remove from a list, use the '-' symbol (vars <module> <variable> '-<value>').");
        },
        $SET_VAR__WRONG_FORMAT_FOR_HASH => sub {
            $self->_event_say("Variable '$variable' is a hash. To add to a hash, please use the '+' symbol before the '|key|value' pair (vars <module> <variable> '+|<key>|<value>').  The separator symbol ('|' in this example) could be anything. To remove from a list, use the '-' symbol (vars <module> <variable> '-<key>').");
        },
        $SET_VAR__USED_LETTER_TO_DELIMIT_SECTIONS => sub {
            $self->_event_say("Variable '$variable' in module '$modulename' has changed, but may not be what you expect since it appears to me that you used a letter to delimit the sections. I hope that is what you meant to do...");
        },
    );

    if (my $callback = $dispatch{$result}) {
        $callback->();
    }
    elsif ($result > 0) { # negative = success
        $self->_event_say("Variable '$variable' in module '$modulename' could not be set for some reason unknown to me.");
    }

    return;
}

sub _Vars_HandleWithValidModule {
    my $self = shift;

    my ($modulename, $module, $variable, $value) = @_;

    my $event = $self->_d_event;

    if (!defined($variable)) {
        # else list variables
        # then list 'em
        $self->_event_say(
            $self->_ModuleHasVarsString(
                $modulename, 
                $self->_GetActiveModuleVariables($module)
            )
        );

        return;
    }

    if (defined($value)) {
        $self->_Vars_AssignVar($modulename, $module, $variable, $value);
    } else {
        # else give variable's current value
        $self->_Vars_ShowVarValue($modulename, $module, $variable);
    }

    return;
}

# handles the 'vars' command
sub Vars {
    my $self = shift;

    my ($modulename, $variable, $value, $nonsense) = @_;

    my $event = $self->_d_event;

    if (defined($modulename)) {
        my $module = $self->getModule($modulename);

        if (!defined($module)) { # complain no module
            $self->_event_say("I didn't recognise that module name ('$modulename'). Try just 'vars' on its own for help.");

            return;
        }

        $self->_Vars_HandleWithValidModule(
            $modulename, $module, $variable, $value
        );
    } elsif ($nonsense) {
        $self->_VarsNonsense();
    } else {
        # else give help
        $self->_VarsHelp();
    }

    return;
}

# This is also called when we are messaged a 'join' command
sub Invited {
    my $self = shift;
    my ($event, $channelName) = @_;
    # $channelName is the name as requested and as should be /joined.
    # This is important so that case is kept in the list of channels
    # on the server should the bot join first.
    my $channel = lc($channelName);
    if (grep $_ eq $channel, @channels) {
        $self->directSay($event, "I thought I was already *in* channel $channel! Oh well.");
    }
    if ($self->isAdmin($event) || $self->{'allowInviting'}) {
        $self->debug("Joining $channel, since I was invited.");
        if (defined($channelKeys{$channel})) {
            $event->{'bot'}->join($channel, $channelKeys{$channel});
        } else {
            $event->{'bot'}->join($channel);
        }
    } else {
        $self->debug($event->{'from'}." asked me to join $channel, but I refused.");
        $self->directSay($event, "Please contact one of my administrators if you want me to join $channel.");
        $self->tellAdmin($event, "Excuse me, but ".$event->{'from'}." asked me to join $channel. I thought you should know.");
    }
    return $self->SUPER::Invited($event, $channel);
}

sub Kicked {
    my $self = shift;
    my ($event, $channel) = @_;
    $self->debug("kicked from $channel by ".$event->{'from'});
    $self->debug('about to autopart modules...');
    foreach (@modules) {
        $_->PartedChannel($event, $channel);
    }
    return $self->SUPER::Kicked($event, $channel);
}

sub SpottedPart {
    my $self = shift;
    my ($event, $channel, $who) = @_;
    if (lc $who eq lc $event->{'nick'}) {
        $self->debug("parted $channel");
        $self->debug('about to autopart modules...');
        foreach (@modules) {
            $_->PartedChannel($event, $channel);
        }
    }
    return $self->SUPER::SpottedPart($event, $channel, $who);
}

sub PartedChannel {
    my $self = shift;
    my ($event, $channel) = @_;
    $channel = lc($channel);
    my %channels = map { $_ => 1 } @channels;
    delete($channels{$channel});
    @channels = keys %channels;
    ::save_config_vars([\@channels]);
    return $self->SUPER::PartedChannel($event, $channel);
}

sub LoadModule {
    my $self = shift;
    my ($event, $name, $requested) = @_;
    my $newmodule = ::LoadModule($name);
    if (ref($newmodule)) {
        # configure module
        $newmodule->{'channels'} = [@channels];
        Configuration::Get($cfgfile, $newmodule->configStructure());
        eval {
            $newmodule->Schedule($event);
        };
        if ($@) {
            $self->debug("Warning: An error occured while loading the module:\n$@");
            if ($requested) {
                $self->say($event, "Warning: an error occured while loading module '$name'. Ignored.");
            }
        }
        $newmodule->saveConfig();
        $self->debug("Successfully loaded module '$name'.");
        if ($requested) {
            $self->say($event, "Loaded module '$name'.");
        }
    } else {
        if ($requested) { # it failed, $newmodule contains error message
            my @errors = split(/[\n\r]/os, $newmodule);
            if (scalar(@errors) > $self->{'errorMessagesMaxLines'}) {
                # remove lines from the middle if the log is too long
                @errors = (@errors[0..int($self->{'errorMessagesMaxLines'} / 2)-1], '...', @errors[-(int($self->{'errorMessagesMaxLines'} / 2))..-1]);
            }
            local $" = "\n";
            $self->say($event, "@errors");
        }
        $self->debug($newmodule);
    }
}

sub UnloadModule {
    my $self = shift;
    my ($event, $name, $requested) = @_;
    my $result = ::UnloadModule($name);
    if (defined($result)) { # failed
        if ($requested) {
            $self->say($event, $result);
        } else {
            $self->debug($result);
        }
    } else {
        if ($requested) {
            $self->say($event, "Unloaded module '$name'.");
        } else {
            $self->debug("Successfully unloaded module '$name'.");
        }
    }
}

sub ReloadModule {
    my $self = shift;
    # XXX there used to be a memory leak around this code. It seems to be fixed
    # now. However if your bot process suddenly balloons to 90M+, here would be a good
    # place to start looking. Of course if that happens and you never reloaded modules
    # then it is also a good time to remove this comment... ;-)
    $self->UnloadModule(@_);
    $self->LoadModule(@_);
}

sub deleteUser {
    my $self = shift;
    my ($who) = @_;
    delete($userFlags{$who});
    delete($users{$who});
    # if they authenticated, remove the entry to prevent dangling links
    foreach my $user (keys %authenticatedUsers) {
        if ($authenticatedUsers{$user} eq $who) {
            delete($authenticatedUsers{$user});
        }
    }
    $self->saveConfig();
}


################################
# Startup (aka main)           #
################################

package main;

# -- #mozilla was here --
#       <zero> is the bug with zilla hanging on startup on every
#              platform fixed in today's nightlies?
#       <leaf> no
#      <alecf> heh
#       <leaf> NEVER
#       <leaf> we're shipping with it.
#    <andreww> helps hide our other bugs

# Do this at the very end, so we can intersperse "my" initializations outside
# of routines above and be assured that they will run.

debug('starting up command loop...');

END { debug('perl is shutting down...'); }

$irc->start();

# -- #mozilla was here --
#      <alecf> Maybe I'll file a bug about netcenter and that will
#              get some attention
#      <alecf> "Browser won't render home.netscape.com.. because it
#              won't start up"
#    <andreww> alecf how about "cant view banner ads - wont start up"
#      <alecf> even better
#  <pinkerton> all bugs are dependent on this one!

# *** Disconnected from irc.mozilla.org
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.