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
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725
10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809
10810
10811
10812
10813
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
10875
10876
10877
10878
10879
10880
10881
10882
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
10899
10900
10901
10902
10903
10904
10905
10906
10907
10908
10909
10910
10911
10912
10913
10914
10915
10916
10917
10918
10919
10920
10921
10922
10923
10924
10925
10926
10927
10928
10929
10930
10931
10932
10933
10934
10935
10936
10937
10938
10939
10940
10941
10942
10943
10944
10945
10946
10947
10948
10949
10950
10951
10952
10953
10954
10955
10956
10957
10958
10959
10960
10961
10962
10963
10964
10965
10966
10967
10968
10969
10970
10971
10972
10973
10974
10975
10976
10977
10978
10979
10980
10981
10982
10983
10984
10985
10986
10987
10988
10989
10990
10991
10992
10993
10994
10995
10996
10997
10998
10999
11000
11001
11002
11003
11004
11005
11006
11007
11008
11009
11010
11011
11012
11013
11014
11015
11016
11017
11018
11019
11020
11021
11022
11023
11024
11025
11026
11027
11028
11029
11030
11031
11032
11033
11034
11035
11036
11037
11038
11039
11040
11041
11042
11043
11044
11045
11046
11047
11048
11049
11050
11051
11052
11053
11054
11055
11056
11057
11058
11059
11060
11061
11062
11063
11064
11065
11066
11067
11068
11069
11070
11071
11072
11073
11074
11075
11076
11077
11078
11079
11080
11081
11082
11083
11084
11085
11086
11087
11088
11089
11090
11091
11092
11093
11094
11095
11096
11097
11098
11099
11100
11101
11102
11103
11104
11105
11106
11107
11108
11109
11110
11111
11112
11113
11114
11115
11116
11117
11118
11119
11120
11121
11122
11123
11124
11125
11126
11127
11128
11129
11130
11131
11132
11133
11134
11135
11136
11137
11138
11139
11140
11141
11142
11143
11144
11145
11146
11147
11148
11149
11150
11151
11152
11153
11154
11155
11156
11157
11158
11159
11160
11161
11162
11163
11164
11165
11166
11167
11168
11169
11170
11171
11172
11173
11174
11175
11176
11177
11178
11179
11180
11181
11182
11183
11184
11185
11186
11187
11188
11189
11190
11191
11192
11193
11194
11195
11196
11197
11198
11199
11200
11201
11202
11203
11204
11205
11206
11207
11208
11209
11210
11211
11212
11213
11214
11215
11216
11217
11218
11219
11220
11221
11222
11223
11224
11225
11226
11227
11228
11229
11230
11231
11232
11233
11234
11235
11236
11237
11238
11239
11240
11241
11242
11243
11244
11245
11246
11247
11248
11249
11250
11251
11252
11253
11254
11255
11256
11257
11258
11259
11260
11261
11262
11263
11264
11265
11266
11267
11268
11269
11270
11271
11272
11273
11274
11275
11276
11277
11278
11279
11280
11281
11282
11283
11284
11285
11286
11287
11288
11289
11290
11291
11292
11293
11294
11295
11296
11297
11298
11299
11300
11301
11302
11303
11304
11305
11306
11307
11308
11309
11310
11311
11312
11313
11314
11315
11316
11317
11318
11319
11320
11321
11322
11323
11324
11325
11326
11327
11328
11329
11330
11331
11332
11333
11334
11335
11336
11337
11338
11339
11340
11341
11342
11343
11344
11345
11346
11347
11348
11349
11350
11351
11352
11353
11354
11355
11356
11357
11358
11359
11360
11361
11362
11363
11364
11365
11366
11367
11368
11369
11370
11371
11372
11373
11374
11375
11376
11377
11378
11379
11380
11381
11382
11383
11384
11385
11386
11387
11388
11389
11390
11391
11392
11393
11394
11395
11396
11397
11398
11399
11400
11401
11402
11403
11404
11405
11406
11407
11408
11409
11410
11411
11412
11413
11414
11415
11416
11417
11418
11419
11420
11421
11422
11423
11424
11425
11426
11427
11428
11429
11430
11431
11432
11433
11434
11435
11436
11437
11438
11439
11440
11441
11442
11443
11444
11445
11446
11447
11448
11449
11450
11451
11452
11453
11454
11455
11456
11457
11458
11459
11460
11461
11462
11463
11464
11465
11466
11467
11468
11469
11470
11471
11472
11473
11474
11475
11476
11477
11478
11479
11480
11481
11482
11483
11484
11485
11486
11487
11488
11489
11490
11491
11492
11493
11494
11495
11496
11497
11498
11499
11500
11501
11502
11503
11504
11505
11506
11507
11508
11509
11510
11511
11512
11513
11514
11515
11516
11517
11518
11519
11520
11521
11522
11523
11524
11525
11526
11527
11528
11529
11530
11531
11532
11533
11534
11535
11536
11537
11538
11539
11540
11541
11542
11543
11544
11545
11546
11547
11548
11549
11550
11551
11552
11553
11554
11555
11556
11557
11558
11559
11560
11561
11562
11563
11564
11565
11566
11567
11568
11569
11570
11571
11572
11573
11574
11575
11576
11577
11578
11579
11580
11581
11582
11583
11584
11585
11586
11587
11588
11589
11590
11591
11592
11593
11594
11595
11596
11597
11598
11599
11600
11601
11602
11603
11604
11605
11606
11607
11608
11609
11610
11611
11612
11613
11614
11615
11616
11617
11618
11619
11620
11621
11622
11623
11624
11625
11626
11627
11628
11629
11630
11631
11632
11633
11634
11635
11636
11637
11638
11639
11640
11641
11642
11643
11644
11645
11646
11647
11648
11649
11650
11651
11652
11653
11654
11655
11656
11657
11658
11659
11660
11661
11662
11663
11664
11665
11666
11667
11668
11669
11670
11671
11672
11673
11674
11675
11676
11677
11678
11679
11680
11681
11682
11683
11684
11685
11686
11687
11688
11689
11690
11691
11692
11693
11694
11695
11696
11697
11698
11699
11700
11701
11702
11703
11704
11705
11706
11707
11708
11709
11710
11711
11712
11713
11714
11715
11716
11717
11718
11719
11720
11721
11722
11723
11724
11725
11726
11727
11728
11729
11730
11731
11732
11733
11734
11735
11736
11737
11738
11739
11740
11741
11742
11743
11744
11745
11746
11747
11748
11749
11750
11751
11752
11753
11754
11755
11756
11757
11758
11759
11760
11761
11762
11763
11764
11765
11766
11767
11768
11769
11770
11771
11772
11773
11774
11775
11776
11777
11778
11779
11780
11781
11782
11783
11784
11785
11786
11787
11788
11789
11790
11791
11792
11793
11794
11795
11796
11797
11798
11799
11800
11801
11802
11803
11804
11805
11806
11807
11808
11809
11810
11811
11812
11813
11814
11815
11816
11817
11818
11819
11820
11821
11822
11823
11824
11825
11826
11827
11828
11829
11830
11831
11832
11833
11834
11835
11836
11837
11838
11839
11840
11841
11842
11843
11844
11845
11846
11847
11848
11849
11850
11851
11852
11853
11854
11855
11856
11857
11858
11859
11860
11861
11862
11863
11864
11865
11866
11867
11868
11869
11870
11871
11872
11873
11874
11875
11876
11877
11878
11879
11880
11881
11882
11883
11884
11885
11886
11887
11888
11889
11890
11891
11892
11893
11894
11895
11896
11897
11898
11899
11900
11901
11902
11903
11904
11905
11906
11907
11908
11909
11910
11911
11912
11913
11914
11915
11916
11917
11918
11919
11920
11921
11922
11923
11924
11925
11926
11927
11928
11929
11930
11931
11932
11933
11934
11935
11936
11937
11938
11939
11940
11941
11942
11943
11944
11945
11946
11947
11948
11949
11950
11951
11952
11953
11954
11955
11956
11957
11958
11959
11960
11961
11962
11963
11964
11965
11966
11967
11968
11969
11970
11971
11972
11973
11974
11975
11976
11977
11978
11979
11980
11981
11982
11983
11984
11985
11986
11987
11988
11989
11990
11991
11992
11993
11994
11995
11996
11997
11998
11999
12000
12001
12002
12003
12004
12005
12006
12007
12008
12009
12010
12011
12012
12013
12014
12015
12016
12017
12018
12019
12020
12021
12022
12023
12024
12025
12026
12027
12028
12029
12030
12031
12032
12033
12034
12035
12036
12037
12038
12039
12040
12041
12042
12043
12044
12045
12046
12047
12048
12049
12050
12051
12052
12053
12054
12055
12056
12057
12058
12059
12060
12061
12062
12063
12064
12065
12066
12067
12068
12069
|
/*
*************************************************************************
ArmageTron -- Just another Tron Lightcycle Game in 3D.
Copyright (C) 2000 Manuel Moos (manuel@moosnet.de)
**************************************************************************
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
***************************************************************************
*/
#include "eTeam.h"
#include "tMemManager.h"
#include "ePlayer.h"
//#include "tInitExit.h"
#include "tConfiguration.h"
#include "eNetGameObject.h"
#include "rConsole.h"
#include "eTimer.h"
#include "tSysTime.h"
#include "rFont.h"
#include "uMenu.h"
#include "tToDo.h"
#include "rScreen.h"
#include <string>
#include <fstream>
#include <iostream>
#include <deque>
#include <algorithm>
#include "rRender.h"
#include "rSysdep.h"
#include "nAuthentication.h"
#include "tDirectories.h"
#include "eVoter.h"
#include "tReferenceHolder.h"
#include "tRandom.h"
#include "uInputQueue.h"
#include "nServerInfo.h"
#include "tRecorder.h"
#include "nConfig.h"
#include "nNetwork.h"
#include "../tron/gCycle.h"
#include "../tron/gZone.h"
#include "../tron/gGame.h"
#include "eGrid.h"
#include <time.h>
//!RACE FILE
#include "../tron/gRace.h"
#include "../tron/gRotation.h"
#include "eBannedWords.h"
int se_lastSaidMaxEntries = 8;
// call on commands that only work on the server; quit if it returns true
bool se_NeedsServer(char const * command, std::istream & s, bool strict )
{
if ( sn_GetNetState() != nSERVER && ( strict || sn_GetNetState() != nSTANDALONE ) )
{
tString rest;
rest.ReadLine( s );
con << tOutput("$only_works_on_server", command, rest );
return true;
}
return false;
}
tColoredString & operator << (tColoredString &s,const ePlayer &p)
{
return s << tColoredString::ColorString(p.rgb[0]/15.0,
p.rgb[1]/15.0,
p.rgb[2]/15.0)
<< p.Name();
}
tColoredString & operator << (tColoredString &s,const ePlayerNetID &p)
{
return s << p.GetColoredName();
}
std::ostream & operator << (std::ostream &s,const ePlayerNetID &p)
{
return s << p.GetColoredName();
}
eAccessLevelHolder::eAccessLevelHolder()
{
accessLevel = tAccessLevel_Default;
}
void eAccessLevelHolder::SetAccessLevel( tAccessLevel level )
{
// sanity check. The access level must not be set higher than that of the current context.
// since accessLevel is private, all access level changes need to run over this function;
// it is therefore impossible to get access level escalation bugs without memory overwrites
// or, of course, evil intentions.
if ( level < tCurrentAccessLevel::GetAccessLevel() )
{
con << "INTERNAL ERROR, security violation attempted. Clamping it.\n";
st_Breakpoint();
accessLevel = tCurrentAccessLevel::GetAccessLevel();
}
accessLevel = level;
}
tCONFIG_ENUM( eCamMode );
tList<ePlayerNetID> se_PlayerNetIDs;
static ePlayer* se_Players = NULL;
// tracking play time (in minutes). These times are tracked on the client and yes, you can "cheat" and increase them to get access to servers you are not ready for.
// total play time, network or not
static REAL se_playTimeTotal = 60*8;
static tConfItem< REAL > se_playTimeTotalConf( "PLAY_TIME_TOTAL", se_playTimeTotal );
// total online time
static REAL se_playTimeOnline = 60*8;
static tConfItem< REAL > se_playTimeOnlineConf( "PLAY_TIME_ONLINE", se_playTimeOnline );
// total online team time
static REAL se_playTimeTeam = 60*8;
static tConfItem< REAL > se_playTimeTeamConf( "PLAY_TIME_TEAM", se_playTimeTeam );
// total play time, network or not
static REAL se_minPlayTimeTotal = 0;
static nSettingItem< REAL > se_minPlayTimeTotalConf( "MIN_PLAY_TIME_TOTAL", se_minPlayTimeTotal );
// total online time
static REAL se_minPlayTimeOnline = 0;
static nSettingItem< REAL > se_minPlayTimeOnlineConf( "MIN_PLAY_TIME_ONLINE", se_minPlayTimeOnline );
// total online team time
static REAL se_minPlayTimeTeam = 0;
static nSettingItem< REAL > se_minPlayTimeTeamConf( "MIN_PLAY_TIME_TEAM", se_minPlayTimeTeam );
static bool se_assignTeamAutomatically = true;
static tSettingItem< bool > se_assignTeamAutomaticallyConf( "AUTO_TEAM", se_assignTeamAutomatically );
static bool se_specSpam = true;
static tSettingItem< bool > se_specSpamConf( "AUTO_TEAM_SPEC_SPAM", se_specSpam );
static bool se_allowTeamChanges = true;
static tSettingItem< bool > se_allowTeamChangesConf( "ALLOW_TEAM_CHANGE", se_allowTeamChanges );
static bool se_chatLogWriteTeam = false;
static tSettingItem< bool > se_chatLogWriteTeamConf( "CHATLOG_WRITE_TEAM", se_chatLogWriteTeam );
static bool se_enableChat = true; //flag indicating whether chat should be allowed at all (logged in players can always chat)
static tSettingItem< bool > se_enaChat("ENABLE_CHAT", se_enableChat);
static tString se_hiddenPlayerPrefix ("0xaaaaaa");
static tConfItemLine se_hiddenPlayerPrefixConf( "PLAYER_LIST_HIDDEN_PLAYER_PREFIX", se_hiddenPlayerPrefix );
static tConfItemFunc Rename_conf("RENAME", &ForceName);
static tAccessLevelSetter Rename_confLevel( Rename_conf, tAccessLevel_Moderator );
static bool se_ctfcommands = true;
static tConfItem< bool > se_ctfCommandsConf("FLAG_CONTROLS", se_ctfcommands);
static tReferenceHolder< ePlayerNetID > se_PlayerReferences;
int ladder_highscore_output=1;
static tSettingItem<int> ldd_rout("LADDER_HIGHSCORE_OUTPUT",
ladder_highscore_output);
class PasswordStorage
{
public:
tString username; // name of the user the password belongs to
tString methodCongested; // method of scrambling
nKrawall::nScrambledPassword password;
bool save;
PasswordStorage(): save(false) {}
};
static bool operator == ( PasswordStorage const & a, PasswordStorage const & b )
{
return
a.username == b.username &&
a.methodCongested == b.methodCongested;
}
static tArray<PasswordStorage> S_passwords;
// if set, user names of non-authenticated players are left as they are,
// and usernames of authenticated players get a 0: prepended.
// if unsed, usernames of non-authenticated players get all special characters escaped (especially all @)
// and usernames of authenticated players get left as they are (with all special characters except the last
// escaped.)
#if defined(KRAWALL_SERVER)
bool se_legacyLogNames = false;
#else
bool se_legacyLogNames = true;
#endif
static tSettingItem<bool> se_llnConf("LEGACY_LOG_NAMES", se_legacyLogNames );
// transform special characters in name to escape sequences
static std::string se_EscapeName( tString const & original, bool keepAt = true )
{
std::ostringstream filter;
int lastC = 'x';
for( int i = 0; i < original.Len()-1; ++i )
{
unsigned int c = static_cast< unsigned char >( original[i] );
// a valid character
switch (c)
{
// characters to escape
case ' ':
filter << "\\_";
break;
case '@':
if ( keepAt )
{
filter << '@';
}
else
{
filter << "\\@";
}
break;
case '\\':
case '%':
case ':':
filter.put('\\');
filter.put(c);
break;
case 'x':
// color codes?
if ( lastC == '0' )
{
filter << "\\x";
break;
}
default:
if ( 0x20 < c && 0x7f >= c )
{
// normal ascii, print
filter.put(c);
}
else
{
// encode as hexcode
filter << '%' << std::hex << std::uppercase << std::setfill('0') << std::setw(2) << c;
}
}
lastC = c;
}
// done! wrap up stream as string.
return filter.str();
}
#ifdef KRAWALL_SERVER
// reverses se_EscapeName (left inverse only, UnEscape(Escape(x)) == x, but not Escape(UnEscape(y)) == y. )
static std::string se_UnEscapeName( tString const & original )
{
std::ostringstream filter;
int lastC = 'x';
for( int i = 0; i < original.Len()-1; ++i )
{
int c = original[i];
if ( lastC == '\\' )
{
if ( c == '_' )
{
c = ' ';
}
filter.put(c);
// don't chain escapes
c = 'x';
}
else if ( c == '%' )
{
// decode hex code
char hex[3];
hex[0] = original[i+1];
hex[1] = original[i+2];
hex[2] = 0;
i += 2;
int decoded;
std::istringstream s(hex);
s >> std::hex >> decoded;
tASSERT( !s.fail() );
filter.put(decoded);
}
else if ( c != '\\' )
{
filter.put(c);
}
lastC = c;
}
// done! wrap up stream as string.
return filter.str();
}
#endif
// generate the user name for an unauthenticated user
static tString se_UnauthenticatedUserName( tString const & name )
{
tString ret;
ePlayerNetID::FilterName( name, ret );
if ( se_legacyLogNames )
{
return ret;
}
else
{
return tString( se_EscapeName( ret, false ).c_str() );
}
}
void se_DeletePasswords()
{
S_passwords.SetLen(0);
st_SaveConfig();
/*
REAL timeout = tSysTimeFloat() + 3;
while(tSysTimeFloat() < timeout){
sr_ResetRenderState(true);
rViewport::s_viewportFullscreen.Select();
sr_ClearGL();
uMenu::GenericBackground();
REAL w=16*3/640.0;
REAL h=32*3/480.0;
//REAL middle=-.6;
Color(1,1,1);
DisplayText(0,.8,w,h,tOutput("$network_opts_deletepw_complete"));
sr_SwapGL();
}
*/
tConsole::Message("$network_opts_deletepw_complete", tOutput(), 5);
}
class tConfItemPassword:public tConfItemBase
{
public:
tConfItemPassword():tConfItemBase("PASSWORD") {}
~tConfItemPassword() {}
// write the complete passwords
virtual void WriteVal(std::ostream &s)
{
int i;
bool first = 1;
for (i = S_passwords.Len()-1; i>=0; i--)
{
PasswordStorage &storage = S_passwords[i];
if (storage.save )
{
if (!first)
s << "PASSWORD ";
first = false;
s << "1 ";
nKrawall::WriteScrambledPassword(storage.password, s);
s << " " << storage.methodCongested;
s << " " << storage.username;
if ((i - 1) >= 0)
s << "\n";
}
}
if (first)
s << "0 ";
}
// read one password
virtual void ReadVal(std::istream &s)
{
// static char in[20];
int test;
s >> test;
if (test != 0)
{
PasswordStorage &storage = S_passwords[S_passwords.Len()];
nKrawall::ReadScrambledPassword(s, storage.password);
s >> storage.methodCongested;
storage.username.ReadLine(s);
storage.save = true;
// check for duplicates
for( int i = S_passwords.Len() - 2; i >= 0; --i )
{
PasswordStorage &other = S_passwords[i];
if ( other == storage )
{
storage.save = false;
break;
}
}
}
}
virtual void FetchVal(tString &val){};
};
static tConfItemPassword se_p;
// username menu item
class eMenuItemUserName: public uMenuItemString
{
public:
eMenuItemUserName(uMenu *M,tString &c):
uMenuItemString(M,"$login_username","$login_username_help",c) {}
virtual ~eMenuItemUserName() {}
virtual bool Event(SDL_Event &e)
{
#ifndef DEDICATED
if (e.type==SDL_KEYDOWN &&
(e.key.keysym.sym==SDLK_KP_ENTER || e.key.keysym.sym==SDLK_RETURN))
{
// move on to password menu item
MyMenu()->SetSelected(0);
return true;
}
else
#endif
return uMenuItemString::Event(e);
}
};
// password request menu item, with *** display
class eMenuItemPassword: public uMenuItemString
{
public:
static bool entered;
eMenuItemPassword(uMenu *M,tString &c):
uMenuItemString(M,"$login_password_title","$login_password_help",c)
{
entered = false;
}
virtual ~eMenuItemPassword() {}
virtual void Render(REAL x,REAL y,REAL alpha=1,bool selected=0)
{
tString* pwback = content;
tString star;
for (int i=content->Len()-2; i>=0; i--)
star << "*";
content = ☆
uMenuItemString::Render(x,y, alpha, selected);
content = pwback;
}
virtual bool Event(SDL_Event &e)
{
#ifndef DEDICATED
if (e.type==SDL_KEYDOWN &&
(e.key.keysym.sym==SDLK_KP_ENTER || e.key.keysym.sym==SDLK_RETURN))
{
entered = true;
MyMenu()->Exit();
return true;
}
else
#endif
return uMenuItemString::Event(e);
}
};
bool eMenuItemPassword::entered;
static bool tr()
{
return true;
}
// password storage mode
int se_PasswordStorageMode = 0; // 0: store in memory, -1: don't store, 1: store on file
static tConfItem<int> pws("PASSWORD_STORAGE",
"$password_storage_help",
se_PasswordStorageMode);
static void PasswordCallback( nKrawall::nPasswordRequest const & request,
nKrawall::nPasswordAnswer & answer )
{
int i;
tString& username = answer.username;
const tString& message = request.message;
nKrawall::nScrambledPassword& scrambled = answer.scrambled;
bool failure = request.failureOnLastTry;
if ( request.method != "md5" && request.method != "bmd5" && request.method != "sha1")
{
con << "INTERNAL ERROR: Unknown password scrambling method requested.";
answer.aborted = true;
return;
}
// find the player with the given username:
/*
ePlayer* p = NULL;
for (i = MAX_PLAYERS-1; i>=0 && !p; i--)
{
ePlayer * perhaps = ePlayer::PlayerConfig(i);
tString filteredName;
ePlayerNetID::FilterName( perhaps->name, filteredName );
if ( filteredName == username )
p = perhaps;
}
// or the given raw name
for (i = MAX_PLAYERS-1; i>=0 && !p; i--)
{
ePlayer * perhaps = ePlayer::PlayerConfig(i);
if ( perhaps->name == username )
p = perhaps;
}
// or just any player, what the heck.
if (!p)
p = ePlayer::PlayerConfig(0);
*/
// try to find the username in the saved passwords
tString methodCongested = request.method + '|' + request.prefix + '|' + request.suffix;
PasswordStorage *storage = NULL;
for (i = S_passwords.Len()-1; i>=0; i--)
{
PasswordStorage & candidate = S_passwords(i);
if (answer.username == candidate.username &&
methodCongested == candidate.methodCongested
)
storage = &candidate;
}
if (!storage)
{
// find an empty slot
for (i = S_passwords.Len()-1; i>=0; i--)
if (S_passwords(i).username.Len() < 1)
storage = &S_passwords(i);
if (!storage)
storage = &S_passwords[S_passwords.Len()];
failure = true;
}
static char const * section = "PASSWORD_MENU";
tRecorder::Playback( section, failure );
tRecorder::Record( section, failure );
// immediately return the stored password if it was not marked as wrong:
if (!failure)
{
if ( storage )
{
answer.username = storage->username;
answer.scrambled = storage->password;
}
answer.automatic = true;
return;
}
else
storage->username.Clear();
// scramble input for recording
uInputScrambler scrambler;
// password was not stored. Request it from user:
uMenu login(message, false);
// password storage;
tString password;
eMenuItemPassword pw(&login, password);
eMenuItemUserName us(&login, username);
us.SetColorMode( rTextField::COLOR_IGNORE );
uMenuItemSelection<int> storepw(&login,
"$login_storepw_text",
"$login_storepw_help",
se_PasswordStorageMode);
storepw.NewChoice("$login_storepw_dont_text",
"$login_storepw_dont_help",
-1);
storepw.NewChoice("$login_storepw_mem_text",
"$login_storepw_mem_help",
0);
storepw.NewChoice("$login_storepw_disk_text",
"$login_storepw_disk_help",
1);
uMenuItemExit cl(&login, "$login_cancel", "$login_cancel_help" );
login.SetSelected(1);
// check if the username the server sent us matches one of the players'
// global IDs. If it does we can directly select the password menu
// menu entry since the user probably just wants to enter the password.
for(int i = 0; i < MAX_PLAYERS; ++i)
{
tString const &id = se_Players[i].globalID;
if(username.Len() <= 1 || id.Len() <= username.Len() || id(username.Len() - 1) != '@')
{
continue;
}
bool match = true;
for(int j = username.Len() - 2; j >= 0; --j)
{
if(username(j) != id(j))
{
match = false;
break;
}
}
if(match)
{
login.SetSelected(0);
}
}
// force a small console while we are in here
rSmallConsoleCallback cb(&tr);
se_ChatState( ePlayerNetID::ChatFlags_Menu, true );
login.Enter();
// return username/scrambled password
{
// scramble password
request.ScramblePassword( nKrawall::nScrambleInfo( username ), password, scrambled );
// if S_login still exists, we were not canceled
answer.aborted = !eMenuItemPassword::entered;
// clear the PW from memory
for (i = password.Len()-2; i>=0; i--)
password(i) = 'a';
if (se_PasswordStorageMode >= 0)
{
storage->username = username;
storage->methodCongested = methodCongested;
storage->password = scrambled;
storage->save = (se_PasswordStorageMode > 0);
}
}
se_ChatState( ePlayerNetID::ChatFlags_Menu, false );
}
#ifdef DEDICATED
#ifndef KRAWALL_SERVER
// the following function really is only supposed to be called from here and nowhere else
// (access right escalation risk):
static void se_AdminLogin_ReallyOnlyCallFromChatKTHNXBYE( ePlayerNetID * p )
{
// elevate access rights. We are currently in the context of player chat,
// therefore in his security context, but we need to log the player on,
// and that requires superior rights.
{
tCurrentAccessLevel elevator( tAccessLevel_Owner, true );
p->BeLoggedIn();
}
sn_ConsoleOut("You have been logged in!\n",p->Owner());
tString serverLoginMessage;
serverLoginMessage << "Remote admin login for user \"" << p->GetUserName() << "\" accepted.\n";
sn_ConsoleOut(serverLoginMessage, 0);
}
#endif
#endif
// flags indicating whether shouting should be the default chat action; if not, it's /team.
enum eShoutDefault
{
eShoutDefault_Team = 0, // default to /team chat
eShoutDefault_Shout = 1, // default to /shout chat
eShoutDefault_ShoutAndOverride = 2 // default to /shout chat and override access level restrictions
};
tCONFIG_ENUM( eShoutDefault );
static eShoutDefault se_shoutSpectator=eShoutDefault_Shout;
tSettingItem< eShoutDefault > se_shoutSpectatorConf( "DEFAULT_SHOUT_SPECTATOR", se_shoutSpectator );
static eShoutDefault se_shoutPlayer=eShoutDefault_Shout;
tSettingItem< eShoutDefault > se_shoutPlayerConf( "DEFAULT_SHOUT_PLAYER", se_shoutPlayer );
#ifdef KRAWALL_SERVER
// minimal access level to shout
static tAccessLevel se_shoutAccessLevel = tAccessLevel_Program;
static tSettingItem< tAccessLevel > se_shoutAccessLevelConf( "ACCESS_LEVEL_SHOUT", se_shoutAccessLevel );
static tAccessLevelSetter se_shoutAccessLevelConfLevel( se_shoutAccessLevelConf, tAccessLevel_Owner );
// minimal access level to play
static tAccessLevel se_playAccessLevel = tAccessLevel_Program;
static tSettingItem< tAccessLevel > se_playAccessLevelConf( "ACCESS_LEVEL_PLAY", se_playAccessLevel );
static tAccessLevelSetter se_playAccessLevelConfLevel( se_playAccessLevelConf, tAccessLevel_Owner );
// minimal sliding access level to play (slides up as soon as enoughpeople of higher access level get authenticated )
static tAccessLevel se_playAccessLevelSliding = tAccessLevel_Program;
static tSettingItem< tAccessLevel > se_playAccessLevelSlidingConf( "ACCESS_LEVEL_PLAY_SLIDING", se_playAccessLevelSliding );
static tAccessLevelSetter se_playAccessLevelSlidingConfLevel( se_playAccessLevelSlidingConf, tAccessLevel_Owner );
// that many high level players are reuqired to drag the access level up
static tAccessLevel se_playAccessLevelSliders = tAccessLevel_4;
static tSettingItem< tAccessLevel > se_playAccessLevelSlidersConf( "ACCESS_LEVEL_PLAY_SLIDERS", se_playAccessLevelSliders );
static tAccessLevelSetter se_playAccessLevelSlidersConfLevel( se_playAccessLevelSlidersConf, tAccessLevel_Owner );
static tAccessLevel se_accessLevelRequiredToPlay = tAccessLevel_Program;
static void UpdateAccessLevelRequiredToPlay()
{
int newAccessLevel = se_accessLevelRequiredToPlay;
// clamp to bounds
if ( newAccessLevel < se_playAccessLevelSliding )
newAccessLevel = se_playAccessLevelSliding;
if ( newAccessLevel > se_playAccessLevel )
newAccessLevel = se_playAccessLevel;
bool changed = true;
while ( changed )
{
changed = false;
// count players above and on the current access level
int countAbove = 0, countOn = 0;
for ( int i = se_PlayerNetIDs.Len()-1; i>=0; --i )
{
ePlayerNetID* player = se_PlayerNetIDs(i);
// don't count AIs and spectators
if ( !player->IsHuman() || !player->NextTeam() )
continue;
if ( player->GetAccessLevel() < newAccessLevel )
{
countAbove++;
}
else if ( player->GetAccessLevel() == newAccessLevel )
{
countOn++;
}
}
if ( countAbove >= se_playAccessLevelSliders && newAccessLevel > se_playAccessLevelSliding )
{
// if enough players are above the current level, increase it
newAccessLevel --;
changed = true;
}
else if ( countOn + countAbove < se_playAccessLevelSliders && newAccessLevel < se_playAccessLevel )
{
// if not enough players are on or above the current level to support it, decrease it
newAccessLevel ++;
changed = true;
}
}
if ( se_accessLevelRequiredToPlay != newAccessLevel )
{
sn_ConsoleOut( tOutput( "$access_level_play_changed",
tCurrentAccessLevel::GetName( se_accessLevelRequiredToPlay ),
tCurrentAccessLevel::GetName( static_cast< tAccessLevel >( newAccessLevel ) ) ) );
se_accessLevelRequiredToPlay = static_cast< tAccessLevel >( newAccessLevel );
}
}
tAccessLevel ePlayerNetID::AccessLevelRequiredToPlay()
{
return se_accessLevelRequiredToPlay;
}
// maximal user level whose accounts can be hidden from other users
static tAccessLevel se_hideAccessLevelOf = tAccessLevel_Program;
static tSettingItem< tAccessLevel > se_hideAccessLevelOfConf( "ACCESS_LEVEL_HIDE_OF", se_hideAccessLevelOf );
static tAccessLevelSetter se_hideAccessLevelOfConfLevel( se_hideAccessLevelOfConf, tAccessLevel_Owner );
// but they are only hidden to players with a lower access level than this
static tAccessLevel se_hideAccessLevelTo = tAccessLevel_Armatrator;
static tSettingItem< tAccessLevel > se_hideAccessLevelToConf( "ACCESS_LEVEL_HIDE_TO", se_hideAccessLevelTo );
static tAccessLevelSetter se_hideAccessLevelToConfLevel( se_hideAccessLevelToConf, tAccessLevel_Owner );
// determines whether hider can hide from seeker
static bool se_Hide( ePlayerNetID const * hider, tAccessLevel currentLevel )
{
tASSERT( hider );
return
hider->GetAccessLevel() <= se_hideAccessLevelOf &&
hider->StealthMode() &&
currentLevel > se_hideAccessLevelTo;
}
// determines whether hider can hide from seeker
static bool se_Hide( ePlayerNetID const * hider, ePlayerNetID const * seeker )
{
if ( !seeker )
{
return se_Hide( hider, tCurrentAccessLevel::GetAccessLevel() );
}
if ( seeker == hider )
{
return false;
}
return se_Hide( hider, seeker->GetAccessLevel() );
}
static bool se_CanHide ( ePlayerNetID const * hider )
{
return hider->GetAccessLevel() <= se_hideAccessLevelOf;
}
#endif
typedef bool (*CANHIDEFUNC)( ePlayerNetID const * hider );
typedef bool (*HIDEFUNC)( ePlayerNetID const * hider, ePlayerNetID const * seeker );
// secret console messages: If CanHideFunc returns false it is displayed to everyone. Else, for each player we apply HideFunc, to see if one can hide his message to the other. The two exceptions get a message anyway.
void se_SecretConsoleOut( tOutput const & message, ePlayerNetID const * hider, HIDEFUNC HideFunc, ePlayerNetID const * exception1 = 0, ePlayerNetID const * exception2 = 0, CANHIDEFUNC CanHideFunc = 0 )
{
// high enough access levels are never secret
if ( CanHideFunc != 0 && !(*CanHideFunc)( hider ) )
{
sn_ConsoleOut( message );
}
else
{
bool canSee[ MAXCLIENTS+1 ];
for( int i = MAXCLIENTS; i>=0; --i )
{
canSee[i] = false;
}
// well, the admin will want to see it.
canSee[0] = true;
// look which clients have someone who can see the message
for ( int i = se_PlayerNetIDs.Len()-1; i>=0; --i )
{
ePlayerNetID* player = se_PlayerNetIDs(i);
if ( player == exception1 || player == exception2 || !(*HideFunc)( hider, player ) )
{
canSee[ player->Owner() ] = true;
}
}
// and send it
for( int i = MAXCLIENTS; i>=0; --i )
{
if ( canSee[i] )
{
sn_ConsoleOut( message, i );
}
}
}
}
#ifdef KRAWALL_SERVER
static eLadderLogWriter se_authorityBlurbWriter("AUTHORITY_BLURB", true);
static void ResultCallback( nKrawall::nCheckResult const & result )
{
tString username = result.username;
tString authority = result.authority;
bool success = result.success;
ePlayerNetID * player = dynamic_cast< ePlayerNetID * >( static_cast< nNetObject * >( result.user ) );
if ( !player || player->Owner() <= 0 )
{
// nobody to authenticate
return;
}
tString authName = username + "@" + authority;
// seach for double login
for ( int i = se_PlayerNetIDs.Len()-1; i>=0; --i )
{
ePlayerNetID* player2 = se_PlayerNetIDs(i);
if ( player2->IsAuthenticated() && player2->GetRawAuthenticatedName() == authName )
{
sn_ConsoleOut( tOutput("$login_request_failed_dup"), player->Owner() );
return;
}
}
if (success)
{
player->Authenticate( authName, result.accessLevel );
// log blurb to ladderlog. This is not important for debug playback,
// so we just don't record it. Once more is done with the blurb,
// we need to change that.
for ( std::deque< tString >::const_iterator i = result.blurb.begin(); i != result.blurb.end(); ++i )
{
std::istringstream s( static_cast< char const * >( *i ) );
tString token, rest;
s >> token;
rest.ReadLine( s );
se_authorityBlurbWriter << token << player->GetFilteredAuthenticatedName() << rest;
se_authorityBlurbWriter.write();
}
}
else
{
if ( sn_GetNetState() == nSERVER )
{
tOutput out( tOutput("$login_failed_message", result.error ) );
sn_ConsoleOut( out, player->Owner() );
con << out;
// redo automatic logins immedeately
if ( result.automatic )
{
nAuthentication::RequestLogin( authority ,username , *player, "$login_request_failed" );
}
}
}
// continue with scheduled logon messages
ePlayerNetID::RequestScheduledLogins();
}
#else
/*
static bool se_Hide( ePlayerNetID const * hider, tAccessLevel currentLevel )
{
return false;
}
*/
static bool se_Hide( ePlayerNetID const * hider, ePlayerNetID const * seeker )
{
return false;
}
#endif
// determines whether hider can hide from seeker
/*
static bool se_Hide( ePlayerNetID const * hider )
{
tASSERT( hider );
return se_Hide( hider, tCurrentAccessLevel::GetAccessLevel() );
}
*/
// menu item to silence selected players
class eMenuItemSilence: public uMenuItemToggle
{
public:
eMenuItemSilence(uMenu *m, ePlayerNetID* p )
: uMenuItemToggle( m, tOutput(""),tOutput("$silence_player_help" ), p->AccessSilenced() )
{
this->title.Clear();
this->title.SetTemplateParameter(1, p->GetColoredName() );
this->title << "$silence_player_text";
player_ = p;
}
~eMenuItemSilence()
{
}
private:
tCONTROLLED_PTR( ePlayerNetID ) player_; // keep player referenced
};
// menu where you can silence players
void ePlayerNetID::SilenceMenu()
{
uMenu menu( "$player_police_silence_text" );
int size = se_PlayerNetIDs.Len();
eMenuItemSilence** items = tNEW( eMenuItemSilence* )[ size ];
int i;
for ( i = size-1; i>=0; --i )
{
ePlayerNetID* player = se_PlayerNetIDs[ i ];
if ( player->IsHuman() )
{
items[i] = tNEW( eMenuItemSilence )( &menu, player );
}
else
{
items[i] = 0;
}
}
menu.Enter();
for ( i = size - 1; i>=0; --i )
{
if( items[i] ) delete items[i];
}
delete[] items;
}
static bool se_silenceEnemies = false;
static tConfItem<bool> se_silenceEnemiesConf( "SILENCE_ENEMIES", se_silenceEnemies );
void ePlayerNetID::PoliceMenu()
{
uMenu menu( "$player_police_text" );
uMenuItemToggle silenceenemies(&menu, "$player_police_silence_enemies_enable", "$player_police_silence_enemies_help", se_silenceEnemies);
uMenuItemFunction kick( &menu, "$player_police_kick_text", "$player_police_kick_help", eVoter::KickMenu );
uMenuItemFunction silence( &menu, "$player_police_silence_text", "$player_police_silence_help", ePlayerNetID::SilenceMenu );
menu.Enter();
}
#ifndef DEDICATED
static char const * default_instant_chat[]=
{
"/team \\",
"/msg \\",
"/me \\",
"LOL!",
"/team 1 Yes Oui Ja",
"/team 0 No Non Nein",
"/team I'm going in!",
"Give the rim a break; hug a tree instead.",
"Lag is a myth. It is only in your brain.",
"Rubber kills gameplay!",
"Every time you double bind, God kills a kitten.",
"http://www.armagetronad.net",
"Only idiots keep their instant chat at default values.",
"/me wanted to download pr0n, but only got this stupid game.",
"Speed for weaks!",
"This server sucks! I'm going home.",
"Grind EVERYTHING! And 180 some more!",
"/me has an interesting mental disorder.",
"Ah, a nice, big, roomy box all for me!",
"Go that way! No, the other way!",
"WD! No points!",
"/me is a noob.",
"/me just installed this game and still doesn't know how to talk.",
"/team You all suck, I want a new team.",
"Are you the real \"Player 1\"?",
NULL
};
#endif
ePlayer * ePlayer::PlayerConfig(int p)
{
uPlayerPrototype *P = uPlayerPrototype::PlayerConfig(p);
return dynamic_cast<ePlayer*>(P);
// return (ePlayer*)P;
}
void ePlayer::StoreConfitem(tConfItemBase *c)
{
tASSERT(CurrentConfitem < PLAYER_CONFITEMS);
configuration[CurrentConfitem++] = c;
}
void ePlayer::DeleteConfitems()
{
while (CurrentConfitem>0)
{
CurrentConfitem--;
tDESTROY(configuration[CurrentConfitem]);
}
}
uActionPlayer *ePlayer::se_instantChatAction[MAX_INSTANT_CHAT];
static const tString& se_UserName()
{
srand( (unsigned)time( NULL ) );
static tString ret( getenv( "USER" ) );
return ret;
}
ePlayer::ePlayer()
{
nAuthentication::SetUserPasswordCallback(&PasswordCallback);
#ifdef KRAWALL_SERVER
nAuthentication::SetLoginResultCallback (&ResultCallback);
#endif
lastTooltip_ = -100;
nameTeamAfterMe = false;
favoriteNumberOfPlayersPerTeam = 3;
CurrentConfitem = 0;
bool getUserName = false;
if ( id == 0 )
{
name = se_UserName();
getUserName = ( name.Len() > 1 );
}
if ( !getUserName )
name << "Player " << id+1;
// default global ID so logins are redirected to the forums
globalID = "@forums";
#ifndef DEDICATED
tString confname;
confname << "PLAYER_"<< id+1;
StoreConfitem(tNEW(tConfItemLine) (confname,
"$player_name_confitem_help",
name));
confname.Clear();
confname << "TEAMNAME_"<< id+1;
StoreConfitem(tNEW(tConfItemLine) (confname,
"$team_name_confitem_help",
teamname));
confname.Clear();
confname << "USER_"<< id+1;
StoreConfitem(tNEW(tConfItemLine) (confname,
"$player_user_confitem_help",
globalID));
confname.Clear();
confname << "AUTO_LOGIN_"<< id+1;
StoreConfitem(tNEW(tConfItem<bool>)(confname,
"$auto_login_confitem_help",
autoLogin));
autoLogin = false;
confname.Clear();
confname << "CAMCENTER_"<< id+1;
centerIncamOnTurn=true;
StoreConfitem(tNEW(tConfItem<bool>)
(confname,
"$camcenter_help",
centerIncamOnTurn) );
confname.Clear();
startCamera=CAMERA_SMART;
confname << "START_CAM_"<< id+1;
StoreConfitem(tNEW(tConfItem<eCamMode>) (confname,
"$start_cam_help",
startCamera));
confname.Clear();
confname << "START_FOV_"<< id+1;
startFOV=90;
StoreConfitem(tNEW(tConfItem<int>) (confname,
"$start_fov_help",
startFOV));
confname.Clear();
confname.Clear();
confname << "SMART_GLANCE_CUSTOM_"<< id+1;
smartCustomGlance=true;
StoreConfitem(tNEW(tConfItem<bool>) (confname,
"$camera_smart_glance_custom_help",
smartCustomGlance));
confname.Clear();
int i;
for(i=CAMERA_COUNT-1; i>=0; i--)
{
confname << "ALLOW_CAM_"<< id+1 << "_" << i;
StoreConfitem(tNEW(tConfItem<bool>) (confname,
"$allow_cam_help",
allowCam[i]));
allowCam[i]=true;
confname.Clear();
}
for(i=MAX_INSTANT_CHAT-1; i>=0; i--)
{
confname << "INSTANT_CHAT_STRING_" << id+1 << '_' << i+1;
StoreConfitem(tNEW(tConfItemLine) (confname,
"$instant_chat_string_help",
instantChatString[i]));
confname.Clear();
}
for(i=0; i < MAX_INSTANT_CHAT; i++)
{
if (!default_instant_chat[i])
break;
instantChatString[i]=default_instant_chat[i];
}
confname << "SPECTATOR_MODE_"<< id+1;
StoreConfitem(tNEW(tConfItem<bool>)(confname,
"$spectator_mode_help",
spectate));
spectate=false;
confname.Clear();
confname << "HIDE_IDENTITY_"<< id+1;
StoreConfitem(tNEW(tConfItem<bool>)(confname,
"$hide_identity_confitem_help",
stealth));
stealth=false;
confname.Clear();
confname << "NAME_TEAM_AFTER_PLAYER_"<< id+1;
StoreConfitem(tNEW(tConfItem<bool>)(confname,
"$name_team_after_player_help",
nameTeamAfterMe));
nameTeamAfterMe=false;
confname.Clear();
confname << "FAV_NUM_PER_TEAM_PLAYER_"<< id+1;
StoreConfitem(tNEW(tConfItem<int>)(confname,
"$fav_num_per_team_player_help",
favoriteNumberOfPlayersPerTeam ));
favoriteNumberOfPlayersPerTeam = 3;
confname.Clear();
confname << "AUTO_INCAM_"<< id+1;
autoSwitchIncam=false;
StoreConfitem(tNEW(tConfItem<bool>) (confname,
"$auto_incam_help",
autoSwitchIncam));
confname.Clear();
confname << "CAMWOBBLE_"<< id+1;
wobbleIncam=false;
StoreConfitem(tNEW(tConfItem<bool>) (confname,
"$camwobble_help",
wobbleIncam));
confname.Clear();
confname << "COLOR_B_"<< id+1;
StoreConfitem(tNEW(tConfItem<int>) (confname,
"$color_b_help",
rgb[2]));
confname.Clear();
confname << "COLOR_G_"<< id+1;
StoreConfitem(tNEW(tConfItem<int>) (confname,
"$color_g_help",
rgb[1]));
confname.Clear();
confname << "COLOR_R_"<< id+1;
StoreConfitem(tNEW(tConfItem<int>) (confname,
"$color_r_help",
rgb[0]));
confname.Clear();
confname << "PLAYER_RANDOM_COLOR_"<< id+1;
colorRandomization=0;
StoreConfitem(tNEW(tConfItem<int>) (confname,
"$player_random_color_help",
colorRandomization));
confname.Clear();
#endif
tRandomizer & randomizer = tRandomizer::GetInstance();
//static int r = rand() / ( RAND_MAX >> 2 ) + se_UserName().Len();
static int r = randomizer.Get(4) + se_UserName().Len();
int cid = ( r + id ) % 4;
static REAL R[MAX_PLAYERS]= {1,.2,.2,1};
static REAL G[MAX_PLAYERS]= {.2,1,.2,1};
static REAL B[MAX_PLAYERS]= {.2,.2,1,.2};
rgb[0]=int(R[cid]*15);
rgb[1]=int(G[cid]*15);
rgb[2]=int(B[cid]*15);
cam=NULL;
}
ePlayer::~ePlayer()
{
tCHECK_DEST;
DeleteConfitems();
}
#ifndef DEDICATED
void ePlayer::Render()
{
if (cam) cam->Render();
// present tooltip help
double now = tSysTimeFloat();
if( se_GameTime() > 1 && now-lastTooltip_ > 1 && !rConsole::CenterDisplayActive() )
{
if( uActionTooltip::Help( ID()+1 ) || uActionTooltip::Help( 0 ) || VetoActiveTooltip(ID()+1) )
lastTooltip_ = now;
else
lastTooltip_ = now+60;
}
}
#endif
static void se_RequestLogin( ePlayerNetID * p );
// check whether a special username is banned
#ifdef KRAWALL_SERVER
static bool se_IsUserBanned( ePlayerNetID * p, tString const & name );
#endif
// receive a "login wanted" message from client
static void se_LoginWanted( nMessage & m )
{
#ifdef KRAWALL_SERVER
// read player
ePlayerNetID * p;
m >> p;
if ( p && m.SenderID() == p->Owner() && !p->IsAuthenticated() )
{
// read wanted flag
m >> p->loginWanted;
tString authName;
// read authentication name
m >> authName;
p->SetRawAuthenticatedName( authName );
// check for stupid bans
if ( se_IsUserBanned( p, authName ) )
{
return;
}
se_RequestLogin( p );
}
#else
sn_ConsoleOut( tOutput( "$login_not_supported" ), m.SenderID() );
#endif
}
static nDescriptor se_loginWanted(204,se_LoginWanted,"AuthWanted");
// request authentication initiation from the client (if p->loginWanted is set)
static void se_WantLogin( ePlayer * lp )
{
// only meaningful on client
if( sn_GetNetState() != nCLIENT )
{
return;
}
// don't send if the server won't understand anyway
static nVersionFeature authentication( 15 );
if( !authentication.Supported(0) )
{
return;
}
tASSERT(lp);
ePlayerNetID *p = lp->netPlayer;
if ( !p )
{
return;
}
nMessage *m = new nMessage( se_loginWanted );
// write player
*m << p;
// write flag and name
*m << p->loginWanted;
// write authentication name
*m << lp->globalID;
m->Send( 0 );
// reset flag
p->loginWanted = false;
}
void ePlayer::SendAuthNames()
{
// only meaningful on client
if( sn_GetNetState() != nCLIENT )
{
return;
}
for(int i=MAX_PLAYERS-1; i>=0; i--)
{
se_WantLogin( ePlayer::PlayerConfig(i) );
}
}
// on the server, this should request logins from all players who registered.
static void se_RequestLogin( ePlayerNetID * p )
{
tString userName = p->GetUserName();
tString authority;
if ( p->Owner() != 0 && p->loginWanted )
{
#ifdef KRAWALL_SERVER
if ( p->GetRawAuthenticatedName().Len() > 1 )
{
nKrawall::SplitUserName( p->GetRawAuthenticatedName(), userName, authority );
}
p->loginWanted =
!nAuthentication::RequestLogin( authority,
userName,
*p,
authority.Len() > 1 ? tOutput( "$login_request", authority ) : tOutput( "$login_request_local" ) );
#endif
}
}
void ePlayerNetID::RequestScheduledLogins()
{
for( int i = se_PlayerNetIDs.Len()-1; i>=0; --i )
{
se_RequestLogin( se_PlayerNetIDs(i) );
}
}
void ePlayer::LogIn()
{
// only meaningful on client
if( sn_GetNetState() != nCLIENT )
{
return;
}
// mark all players as wanting to log in
for(int i=MAX_PLAYERS-1; i>=0; i--)
{
ePlayer * lp = ePlayer::PlayerConfig(i);
if ( lp && lp->netPlayer )
{
lp->netPlayer->loginWanted = true;
se_WantLogin( lp );
}
}
}
bool se_highlightMyName = false;
static void se_DisplayChatLocally( ePlayerNetID* p, const tString& say )
{
#ifdef DEBUG_X
if (strstr( say, "BUG" ) )
{
st_Breakpoint();
}
#endif
tColoredString actualMessage(say);
if ( p && !p->IsSilenced() && se_enableChat )
{
//tColoredString say2( say );
//say2.RemoveHex();
tColoredString message;
message << *p;
message << tColoredString::ColorString(1,1,.5);
if (se_highlightMyName && (actualMessage.Contains(p->GetName())))
{
tString strOld = p->GetName();
tColoredString strReplace;
strReplace << p->GetColoredName() << tColoredString::ColorString(1,1,.5);
message << ": " << actualMessage.Replace(strOld, strReplace) << "\n";
}
else
message << ": " << actualMessage << "\n";
con << message;
}
}
static void se_DisplayChatLocallyClient( ePlayerNetID* p, const tString& message )
{
if ( p && !p->IsSilenced() && se_enableChat )
{
tColoredString actualMessage(message);
bool sentFromTeamMember = false;
if(se_silenceEnemies)
{
rViewportConfiguration *viewportConfiguration = rViewportConfiguration::CurrentViewportConfiguration();
if(viewportConfiguration == 0) return;
for ( int viewport = viewportConfiguration->num_viewports-1; viewport >= 0; --viewport )
{
ePlayer* player = ePlayer::PlayerConfig( sr_viewportBelongsToPlayer[ viewport ] );
if ( !player )
continue;
ePlayerNetID *me = player->netPlayer;
if ( me )
{
if ( se_silenceEnemies )
{
// If we're dead, display all chat
if ( ( !me->Object() || !me->Object()->Alive() ) || me->CurrentTeam() == p->CurrentTeam() )
sentFromTeamMember = true;
}
}
}
}
if ( se_silenceEnemies && !sentFromTeamMember )
return;
if ( p->CurrentTeam() )
{
if ( p->Object() && !p->Object()->Alive() )
con << tOutput("$dead_console_decoration");
}
else con << tOutput("$spectator_console_decoration");
if (se_highlightMyName && actualMessage.Contains(p->GetName()))
{
tString strOld = p->GetName();
tColoredString strReplace;
strReplace << p->GetColoredName() << tColoredString::ColorString(1,1,.5);
actualMessage = actualMessage.Replace(strOld, strReplace);
}
con << actualMessage << "\n";
}
}
static nVersionFeature se_chatRelay( 3 );
//!todo: lower this number or increase network version before next release
static nVersionFeature se_chatHandlerClient( 6 );
// chat message from client to server
void handle_chat( nMessage& );
static nDescriptor chat_handler(200,handle_chat,"Chat");
// checks whether text_to_search contains search_for_text
bool Contains( const tString & search_for_text, const tString & text_to_search )
{
int m = strlen(search_for_text);
int n = strlen(text_to_search);
int a, b;
for (b=0; b<=n-m; ++b)
{
for (a=0; a<m && search_for_text[a] == text_to_search[a+b]; ++a)
;
if (a>=m)
// a match has been found
return true;
}
return false;
}
// function that returns one of the player names
typedef tString const & (ePlayerNetID::*SE_NameGetter)() const;
// function that filters strings
typedef tString (*SE_NameFilter)( tString const & );
// identity filter
static tString se_NameFilterID( tString const & name )
{
return name;
}
// function that filters players
typedef bool (*SE_NameHider)( ePlayerNetID const * hider, ePlayerNetID const * seeker );
// non-hider
static bool se_NonHide( ePlayerNetID const * hider, ePlayerNetID const * seeker )
{
return false;
}
// the other filter is ePlayerNetID::FilterName
// search for exact or partial matches in player names
ePlayerNetID * CompareBufferToPlayerNames
( const tString & nameRaw,
int & num_matches,
ePlayerNetID * requester,
SE_NameGetter GetName, // = &ePlayerNetID::GetName,
SE_NameFilter Filter, // = &se_NameFilterID,
SE_NameHider Hider )// = &se_NonHide )
{
num_matches = 0;
ePlayerNetID * match = 0;
// also filter input string
tString name = (*Filter)( nameRaw );
// run through all players and look for a match
for ( int a = se_PlayerNetIDs.Len()-1; a>=0; --a )
{
ePlayerNetID* toMessage = se_PlayerNetIDs(a);
if ( (*Hider)( toMessage, requester ) )
{
continue;
}
tString playerName = (*Filter)( (toMessage->*GetName)() );
// exact match?
if ( playerName == name )
{
num_matches = 1;
return toMessage;
}
if ( Contains(name, playerName))
{
match= toMessage; // Doesn't matter that this is wrote over everytime, when we only have one match it will be there.
num_matches+=1;
}
}
// return result
return match;
}
ePlayerNetID * ePlayerNetID::FindPlayerByName( tString const & name, ePlayerNetID * requester, bool print )
{
int num_matches = 0;
// try filtering the names before comparing them, this makes the matching case-insensitive
SE_NameFilter Filter = &ePlayerNetID::FilterName;
// look for matches in the filtered screen names
ePlayerNetID * ret = CompareBufferToPlayerNames( name, num_matches, requester, &ePlayerNetID::GetName, Filter, &se_NonHide );
if ( ret && num_matches == 1 )
{
return ret;
}
// look for matches in the exact screen names.
// No check for prior matches here, because the previous
// search was less specific.
ret = CompareBufferToPlayerNames( name, num_matches, requester, &ePlayerNetID::GetName, &se_NameFilterID, &se_NonHide );
if ( ret && num_matches == 1 )
{
return ret;
}
#ifdef KRAWALL_SERVER
// nothing found? try the user names.
if ( !ret )
{
ret = CompareBufferToPlayerNames( name, num_matches, requester, &ePlayerNetID::GetUserName, &se_NameFilterID, &se_Hide );
}
if ( ret && num_matches == 1 )
{
return ret;
}
// still nothing found? user names again
if ( !ret )
{
ret = CompareBufferToPlayerNames( name, num_matches, requester, &ePlayerNetID::GetUserName, Filter, &se_Hide );
}
if ( ret && num_matches == 1 )
{
return ret;
}
#endif
// More than than one match for the current buffer. Complain about that.
else if (num_matches > 1)
{
tOutput toSender( "$msg_toomanymatches", name );
if (print)
{
if ( requester )
sn_ConsoleOut(toSender,requester->Owner() );
else
con << toSender;
}
return NULL;
}
// 0 matches. The user can't spell. Complain about that, too.
else
{
tOutput toSender( "$msg_nomatch", name );
if (print)
{
if ( requester )
sn_ConsoleOut(toSender,requester->Owner() );
else
con << toSender;
}
return NULL;
}
return 0;
}
static ePlayerNetID * se_FindPlayerInChatCommand( ePlayerNetID * sender, char const * command, std::istream & s )
{
tString player;
s >> player;
if (player == "" )
{
sn_ConsoleOut( tOutput( "$chatcommand_requires_player", command ), sender ? sender->Owner() : 0 );
return 0;
}
return ePlayerNetID::FindPlayerByName( player, sender );
}
ePlayerNetID * ePlayerNetID::FindPlayerById(int owner_id)
{
if (owner_id >= 0)
{
for(int i = 0; i < se_PlayerNetIDs.Len(); i++)
{
ePlayerNetID *p = se_PlayerNetIDs[i];
if (p)
{
if (p->Owner() == owner_id)
return p;
}
}
}
return NULL;
}
// chat message from server to client
void handle_chat_client( nMessage & );
static nDescriptor chat_handler_client(203,handle_chat_client,"Chat Client");
void handle_chat_client(nMessage &m)
{
if(sn_GetNetState()!=nSERVER)
{
unsigned short id;
m.Read(id);
tColoredString say;
m >> say;
tJUST_CONTROLLED_PTR< ePlayerNetID > p=dynamic_cast<ePlayerNetID *>(nNetObject::ObjectDangerous(id));
se_DisplayChatLocallyClient( p, say );
}
}
// appends chat message to something
template< class TARGET >
void se_AppendChat( TARGET & out, tString const & message )
{
if ( message.Len() <= se_SpamMaxLen*2 || se_SpamMaxLen == 0 )
out << message;
else
{
tString cut( message );
cut.SetLen( se_SpamMaxLen*2 );
out << cut;
}
}
// builds a colored chat string
static tColoredString se_BuildChatString( ePlayerNetID const * sender, tString const & message )
{
tColoredString console;
console << *sender;
console << tColoredString::ColorString(1,1,.5) << ": ";
se_AppendChat( console, message );
return console;
}
// Build a colored /team message
static tColoredString se_BuildChatString( eTeam const *team, ePlayerNetID const *sender, tString const &message )
{
tColoredString console;
console << *sender;
if( !team )
{
// foo --> Spectatos: message
console << tColoredString::ColorString(1,1,.5) << " --> " << tOutput("$player_spectator_message");
}
else if (sender->CurrentTeam() == team)
{
// foo --> Teammates: some message here
console << tColoredString::ColorString(1,1,.5) << " --> ";
// We don't << team here, because we want "Teammates" to show instead of the team name
console << tColoredString::ColorString( team->R() / 15.0, team->G() / 15.0, team->B() / 15.0 ) << tOutput("$player_team_message");
}
else
{
// foo (Red Team) --> Blue Team: some message here
eTeam *senderTeam = sender->CurrentTeam();
console << tColoredString::ColorString(1,1,.5) << " (";
console << *senderTeam;
console << tColoredString::ColorString(1,1,.5) << ") --> ";
console << *team;
}
console << tColoredString::ColorString(1,1,.5) << ": ";
se_AppendChat( console, message );
return console;
}
// builds a colored chat /msg string
static tColoredString se_BuildChatString( ePlayerNetID const * sender, ePlayerNetID const * receiver, tString const & message )
{
tColoredString console;
console << *sender;
console << tColoredString::ColorString(1,1,.5) << " --> ";
console << *receiver;
console << tColoredString::ColorString(1,1,.5) << ": ";
se_AppendChat( console, message );
return console;
}
// prepares a chat message with a specific total text originating from the given player
static nMessage* se_ServerControlledChatMessageConsole( ePlayerNetID const * player, tString const & toConsole )
{
tASSERT( player );
nMessage *m=tNEW(nMessage) (chat_handler_client);
m->Write( player->ID() );
*m << toConsole;
return m;
}
// prepares a chat message with a chat string (only the message, not the whole console line) originating from the given player
static nMessage* se_ServerControlledChatMessage( ePlayerNetID const * sender, tString const & message )
{
tASSERT( sender );
return se_ServerControlledChatMessageConsole( sender, se_BuildChatString( sender, message ) );
}
// prepares a chat message with a chat message originating from the given player to the given receiver
static nMessage* se_ServerControlledChatMessage( ePlayerNetID const * sender, ePlayerNetID const * receiver, tString const & message )
{
tASSERT( sender );
tASSERT( receiver );
return se_ServerControlledChatMessageConsole( sender, se_BuildChatString( sender, receiver, message ) );
}
// prepares a chat message with a chat message originating from the given player to the given team
static nMessage* se_ServerControlledChatMessage( eTeam const * team, ePlayerNetID const * sender, tString const & message )
{
tASSERT( sender );
return se_ServerControlledChatMessageConsole( sender, se_BuildChatString(team, sender, message) );
}
// pepares a chat message the client has to put together
static nMessage* se_NewChatMessage( ePlayerNetID const * player, tString const & message )
{
tASSERT( player );
nMessage *m=tNEW(nMessage) (chat_handler);
m->Write( player->ID() );
se_AppendChat( *m, message );
return m;
}
// prepares a very old style chat message: just a regular remote console output message
static nMessage* se_OldChatMessage( tString const & line )
{
return sn_ConsoleOutMessage( line + "\n" );
}
// prepares a very old style chat message: just a regular remote console output message
static nMessage* se_OldChatMessage( ePlayerNetID const * player, tString const & message )
{
tASSERT( player );
return se_OldChatMessage( se_BuildChatString( player, message ) );
}
// sends the full chat line to receiver, marked as originating from <sender> so
// it can be silenced.
// ( the client will see <fullLine> resp. <sender name> : <forOldClients> if it is pre-0.2.8 and at least 0.2.6 )
void se_SendChatLine( ePlayerNetID* sender, const tString& fullLine, const tString& forOldClients, int receiver )
{
tString retStr(fullLine);
if (eBannedWords::BadWordTrigger(sender, retStr))
return;
// create chat messages
// send them to the users, depending on what they understand
if ( sn_Connections[ receiver ].socket )
{
if ( se_chatHandlerClient.Supported( receiver ) )
{
tJUST_CONTROLLED_PTR< nMessage > mServerControlled = se_ServerControlledChatMessageConsole( sender, retStr );
mServerControlled->Send( receiver );
}
else if ( se_chatRelay.Supported( receiver ) )
{
tJUST_CONTROLLED_PTR< nMessage > mNew = se_NewChatMessage( sender, forOldClients );
mNew->Send( receiver );
}
else
{
tJUST_CONTROLLED_PTR< nMessage > mOld = se_OldChatMessage( retStr );
mOld->Send( receiver );
}
}
}
// sends the full chat line to all connected clients, marked as originating from <sender> so
// it can be silenced.
// ( the client will see <fullLine> resp. <sender name> : <forOldClients> if it is pre-0.2.8 and at least 0.2.6 )
void se_BroadcastChatLine( ePlayerNetID* sender, const tString& line, const tString& forOldClients )
{
tString retStr(line);
if (eBannedWords::BadWordTrigger(sender, retStr))
return;
// create chat messages
tJUST_CONTROLLED_PTR< nMessage > mServerControlled = se_ServerControlledChatMessageConsole( sender, retStr );
tJUST_CONTROLLED_PTR< nMessage > mNew = se_NewChatMessage( sender, forOldClients );
tJUST_CONTROLLED_PTR< nMessage > mOld = se_OldChatMessage( retStr );
// send them to the users, depending on what they understand
for ( int user = MAXCLIENTS; user > 0; --user )
{
if ( sn_Connections[ user ].socket )
{
if ( se_chatHandlerClient.Supported( user ) )
mServerControlled->Send( user );
else if ( se_chatRelay.Supported( user ) )
mNew->Send( user );
else
mOld->Send( user );
}
}
}
// send the chat of player p to all connected clients after properly formatting it
// ( the clients will see <player>: <say>
void se_BroadcastChat( ePlayerNetID* sender, const tString& say )
{
tString retStr(say);
if (eBannedWords::BadWordTrigger(sender, retStr))
return;
// create chat messages
tJUST_CONTROLLED_PTR< nMessage > mServerControlled = se_ServerControlledChatMessage( sender, retStr );
tJUST_CONTROLLED_PTR< nMessage > mNew = se_NewChatMessage( sender, retStr );
tJUST_CONTROLLED_PTR< nMessage > mOld = se_OldChatMessage( sender, retStr );
// send them to the users, depending on what they understand
for ( int user = MAXCLIENTS; user > 0; --user )
{
if ( sn_Connections[ user ].socket )
{
if ( se_chatHandlerClient.Supported( user ) )
mServerControlled->Send( user );
else if ( se_chatRelay.Supported( user ) )
mNew->Send( user );
else
mOld->Send( user );
}
}
}
// sends a private message from sender to receiver, and really sends it to eavesdropper (will usually be equal to receiver)
void se_SendPrivateMessage( ePlayerNetID const * sender, ePlayerNetID const * receiver, ePlayerNetID const * eavesdropper, tString const & message )
{
tASSERT( sender );
tASSERT( receiver );
// determine receiver client id
int cid = eavesdropper->Owner();
// determine wheter the receiver knows about the server controlled chat message
if ( se_chatHandlerClient.Supported( cid ) )
{
// send server controlled message
se_ServerControlledChatMessage( sender, receiver, message )->Send( cid );
}
else
{
tColoredString say;
say << tColoredString::ColorString(1,1,.5) << "( --> ";
say << *receiver;
say << tColoredString::ColorString(1,1,.5) << " ) ";
say << message;
// format message containing receiver
if ( se_chatRelay.Supported( cid ) )
{
// send client formatted message
se_NewChatMessage( sender, say )->Send( cid );
}
else
{
// send console out message
se_OldChatMessage( sender, say )->Send( cid );
}
}
}
// Sends a /team message
void se_SendTeamMessage( eTeam const * team, ePlayerNetID const * sender ,ePlayerNetID const * receiver, tString const & message )
{
tASSERT( receiver );
tASSERT( sender );
int clientID = receiver->Owner();
if ( clientID == 0 )
return;
if ( se_chatHandlerClient.Supported( clientID ) )
{
se_ServerControlledChatMessage( team, sender, message )->Send( clientID );
}
else
{
tColoredString say;
say << tColoredString::ColorString(1,1,.5) << "( " << *sender;
if( !team )
{
// foo --> Spectatos: message
say << tColoredString::ColorString(1,1,.5) << " --> " << tOutput("$player_spectator_message");
}
else if (sender->CurrentTeam() == team)
{
// ( foo --> Teammates ) some message here
say << tColoredString::ColorString(1,1,.5) << " --> ";
say << tColoredString::ColorString(team->R()/15.0,team->G()/15.0,team->B()/15.0) << tOutput("$player_team_message");;
}
// ( foo (Blue Team) --> Red Team ) some message
else
{
eTeam *senderTeam = sender->CurrentTeam();
say << tColoredString::ColorString(1,1,.5) << " (";
say << *team;
say << tColoredString::ColorString(1,1,.5) << " ) --> ";
say << senderTeam;
}
say << tColoredString::ColorString(1,1,.5) << " ) ";
say << message;
// format message containing receiver
if ( se_chatRelay.Supported( clientID ) )
// send client formatted message
se_NewChatMessage( sender, say )->Send( clientID );
else
// send console out message
se_OldChatMessage( sender, say )->Send( clientID );
if (se_chatLogWriteTeam)
{
se_SaveToChatLogC(say);
}
}
}
// returns a player ( not THE player, there may be more ) belonging to a user ID
/*
static ePlayerNetID * se_GetPlayerFromUserID( int uid )
{
// run through all players and look for a match
for ( int a = se_PlayerNetIDs.Len()-1; a>=0; --a )
{
ePlayerNetID * p = se_PlayerNetIDs(a);
if ( p && p->Owner() == uid )
return p;
}
// found nothing
return 0;
}
*/
// returns a player ( not THE player, there may be more ) belonging to a user ID that is still alive
// static
ePlayerNetID * se_GetAlivePlayerFromUserID( int uid )
{
// run through all players and look for a match
for ( int a = se_PlayerNetIDs.Len()-1; a>=0; --a )
{
ePlayerNetID * p = se_PlayerNetIDs(a);
if ( p && p->Owner() == uid &&
( ( p->Object() && p->Object()->Alive() ) ) )
return p;
}
// found nothing
return 0;
}
#ifndef KRAWALL_SERVER
//The Base Remote Admin Password
static tString sg_adminPass( "NONE" );
static tConfItemLine sg_adminPassConf( "ADMIN_PASS", sg_adminPass );
#endif
#ifdef DEDICATED
// console with filter for remote admin output redirection
class eAdminConsoleFilter:public tConsoleFilter
{
public:
eAdminConsoleFilter( int netID )
:netID_( netID )
{
}
~eAdminConsoleFilter()
{
sn_ConsoleOut( message_, netID_ );
}
private:
// we want to come first, the admin should get unfiltered output
virtual int DoGetPriority() const
{
return -100;
}
// don't actually filter; take line and add it to the message sent to the admin
virtual void DoFilterLine( tString &line )
{
//tColoredString message;
message_ << tColoredString::ColorString(1,.3,.3) << tOutput("$admin_command_tag") << tColoredString::ColorString(1,1,1) << line << "\n";
// don't let message grow indefinitely
unsigned long len = message_.Len();
tRecorderSync< unsigned long >::Archive( "_MESSAGE_LEN", 3, len );
if (len > 600)
{
sn_ConsoleOut( message_, netID_ );
message_.Clear();
}
}
int netID_; // the network user ID to send the result to
tColoredString message_; // the console message for the remote administrator
};
static tString se_InterceptCommands;
static tConfItemLine se_InterceptCommandsConf( "INTERCEPT_COMMANDS", se_InterceptCommands );
static bool se_interceptUnknownCommands = false;
static tSettingItem<bool> se_interceptUnknownCommandsConf("INTERCEPT_UNKNOWN_COMMANDS",
se_interceptUnknownCommands);
static bool se_legacyLadderlogCommand = true;
static tSettingItem<bool> se_legacyLadderlogCommandConf("LEGACY_LADDERLOG_COMMAND",
se_legacyLadderlogCommand);
// minimal access level for /admin
static tAccessLevel se_adminAccessLevel = tAccessLevel_Moderator;
static tSettingItem< tAccessLevel > se_adminAccessLevelConf( "ACCESS_LEVEL_ADMIN", se_adminAccessLevel );
static tAccessLevelSetter se_adminAccessLevelConfLevel( se_adminAccessLevelConf, tAccessLevel_Owner );
static eLadderLogWriter se_commandWriter( "COMMAND", true );
void handle_command_intercept( ePlayerNetID *p, tString const & command, std::istream & s, tString const & say )
{
tString commandArguments;
commandArguments.ReadLine( s );
if (!se_legacyLadderlogCommand)
{
se_commandWriter << command << p->GetLogName();
se_commandWriter << nMachine::GetMachine(p->Owner()).GetIP() << p->GetAccessLevel();
se_commandWriter << commandArguments;
se_commandWriter.write();
}
if (se_legacyLadderlogCommand && command=="/cmd")
{
se_commandWriter << p->GetLogName();
se_commandWriter << nMachine::GetMachine(p->Owner()).GetIP() << p->GetAccessLevel();
se_commandWriter << commandArguments;
se_commandWriter.write();
}
con << "[cmd] " << p->GetLogName() << ": " << say << '\n';
}
#ifdef KRAWALL_SERVER
// minimal access level for /op/deop
static tAccessLevel se_opAccessLevel = tAccessLevel_TeamLeader;
static tSettingItem< tAccessLevel > se_opAccessLevelConf( "ACCESS_LEVEL_OP", se_opAccessLevel );
static tAccessLevelSetter se_opAccessLevelConfLevel( se_opAccessLevelConf, tAccessLevel_Owner );
// maximal result thereof
static tAccessLevel se_opAccessLevelMax = tAccessLevel_Moderator;
static tSettingItem< tAccessLevel > se_opAccessLevelMaxConf( "ACCESS_LEVEL_OP_MAX", se_opAccessLevelMax );
static tAccessLevelSetter se_opAccessLevelMaxConfLevel( se_opAccessLevelMaxConf, tAccessLevel_Owner );
static tAccessLevel se_opAccessLevelMin = tAccessLevel_Punished;
static tSettingItem< tAccessLevel > se_opAccessLevelMinConf( "ACCESS_LEVEL_OP_MIN", se_opAccessLevelMin );
static tAccessLevelSetter se_opAccessLevelMinConfLevel( se_opAccessLevelMinConf, tAccessLevel_Owner );
static bool se_CanChangeAccess( ePlayerNetID * admin, ePlayerNetID * victim, char const * command )
{
tASSERT( admin );
tASSERT( victim );
if ( admin->GetAccessLevel() > se_opAccessLevel ) // Can he even use this command?
{
sn_ConsoleOut( tOutput( "$access_level_op_denied", command ), admin->Owner() );
}
else if ( victim == admin )
{
sn_ConsoleOut( tOutput( "$access_level_op_self", command ), admin->Owner() );
}
else if ( admin->GetAccessLevel() >= victim->GetAccessLevel() )
{
sn_ConsoleOut( tOutput( "$access_level_op_overpowered", command ), admin->Owner() );
}
else
{
return true;
}
return false;
}
// an operation that changes the access level of another player
typedef void (*OPFUNC)( ePlayerNetID * admin, ePlayerNetID * victim, tAccessLevel accessLevel );
static void se_ChangeAccess( ePlayerNetID * admin, std::istream & s, char const * command, OPFUNC F )
{
bool isexplicit = false;
ePlayerNetID * victim = se_FindPlayerInChatCommand( admin, command, s );
if ( victim && se_CanChangeAccess( admin, victim, command ) )
{
// read optional access level, this part is merly a copypaste from the /shuffle code
int level = se_opAccessLevelMax;
if ( victim->IsAuthenticated() )
{
level = victim->GetAccessLevel();
}
char first;
s >> first;
if ( !s.eof() && !s.fail() )
{
isexplicit = true;
s.unget();
int newLevel = 0;
s >> newLevel;
if ( first == '+' || first == '-' )
{
level += newLevel;
}
else
{
level = newLevel;
}
}
s >> level;
// Make a last safety check on the given AL, then DON'T TOUCH IT ANYMORE
if ( level <= admin->GetAccessLevel() )
level = admin->GetAccessLevel() + 1;
tAccessLevel accessLevel;
accessLevel = static_cast< tAccessLevel >( level );
if ( accessLevel == victim->GetAccessLevel() )
{
if ( isexplicit )
{
sn_ConsoleOut( tOutput( "$access_level_op_same", command ), admin->Owner() );
}
else
{
sn_ConsoleOut( tOutput( "$access_level_op_unclear", command ), admin->Owner() );
}
}
else if ( accessLevel > admin->GetAccessLevel() )
{
(*F)( admin, victim, accessLevel );
}
}
}
// Promote changes the access rights of an already authed player
void se_Promote( ePlayerNetID * admin, ePlayerNetID * victim, tAccessLevel accessLevel )
{
if ( accessLevel > se_opAccessLevelMin )
{
accessLevel = se_opAccessLevelMin;
}
if ( accessLevel < tCurrentAccessLevel::GetAccessLevel() + 1 )
{
accessLevel = static_cast< tAccessLevel >( tCurrentAccessLevel::GetAccessLevel() + 1 );
}
if ( victim->IsAuthenticated() )
{
tAccessLevel oldAccessLevel = victim->GetAccessLevel();
victim->SetAccessLevel( accessLevel );
if ( accessLevel < oldAccessLevel )
{
se_SecretConsoleOut( tOutput( "$access_level_promote",
victim->GetLogName(),
tCurrentAccessLevel::GetName( accessLevel ),
admin->GetLogName() ), victim, &se_Hide, admin, 0, &se_CanHide );
}
else if ( accessLevel > oldAccessLevel )
{
se_SecretConsoleOut( tOutput( "$access_level_demote",
victim->GetLogName(),
tCurrentAccessLevel::GetName( accessLevel ),
admin->GetLogName() ), victim, &se_Hide, admin, 0, &se_CanHide );
}
}
}
// our operations of this kind: op grants access
void se_OpBase( ePlayerNetID * admin, ePlayerNetID * victim, char const * command, tAccessLevel accessLevel )
{
tString authName = victim->GetUserName() + "@L_OP";
if ( victim->IsAuthenticated() )
{
authName = victim->GetRawAuthenticatedName();
}
if ( accessLevel < se_opAccessLevelMax )
accessLevel = se_opAccessLevelMax;
// no use authenticating an AI :)
if ( !victim->IsHuman() )
{
sn_ConsoleOut( tOutput( "$access_level_op_denied_ai", command ), admin->Owner() );
}
victim->Authenticate( authName, accessLevel, admin );
}
void se_Op( ePlayerNetID * admin, ePlayerNetID * victim, tAccessLevel level )
{
int accessLevel = admin->GetAccessLevel() + 1;
// respect passed in level
if ( accessLevel < level )
{
accessLevel = level;
}
if ( victim->IsAuthenticated() )
{
se_Promote( admin, victim, static_cast< tAccessLevel >( accessLevel ) );
}
else
{
se_OpBase( admin, victim, "/op", static_cast< tAccessLevel >( accessLevel ) );
}
}
// DeOp takes it away
void se_DeOp( ePlayerNetID * admin, std::istream & s, char const * command )
{
ePlayerNetID * victim = se_FindPlayerInChatCommand( admin, command, s );
if ( victim && se_CanChangeAccess ( admin, victim, command ) )
{
if ( victim->IsAuthenticated() )
{
victim->DeAuthenticate( admin );
}
else
{
sn_ConsoleOut( tOutput( "$access_level_op_same", command ), admin->Owner() );
}
}
}
// log out
static void se_AdminLogout( ePlayerNetID * p, char const * command )
{
#ifdef KRAWALL_SERVER
// revoke the other kind of authentication as well
if ( p->IsAuthenticated() )
{
p->DeAuthenticate();
}
else
{
sn_ConsoleOut( tOutput( "$access_level_op_same", command ), p->Owner() );
}
#else
if ( p->IsLoggedIn() )
{
sn_ConsoleOut("You have been logged out!\n",p->Owner());
se_adminLogoutWriter << p->GetUserName() << nMachine::GetMachine(p->Owner()).GetIP();
se_adminLogoutWriter.write();
}
p->BeNotLoggedIn();
#endif
}
// Changes the access level of a player, from console or other anonymous sources
// and which is not to be called when you can call an OPFUNC
// This isn't meant to be an user command, rather a simple switch between promoting and logging in, so make necessary checks yourself
void se_AnonOp( ePlayerNetID * victim, tAccessLevel accessLevel, bool messages=true )
{
if ( !victim->IsHuman() )
{
return;
}
if ( victim->IsAuthenticated() )
{
if ( accessLevel > tAccessLevel_Authenticated )
{
accessLevel = tAccessLevel_Authenticated;
}
tAccessLevel oldAccessLevel = victim->GetAccessLevel();
victim->SetAccessLevel( accessLevel );
if ( accessLevel < oldAccessLevel && messages )
{
se_SecretConsoleOut( tOutput( "$access_level_promote_anon",
victim->GetLogName(),
tCurrentAccessLevel::GetName( accessLevel )
), victim, &se_Hide, 0, 0, &se_CanHide );
}
else if ( accessLevel > oldAccessLevel && messages )
{
se_SecretConsoleOut( tOutput( "$access_level_demote_anon",
victim->GetLogName(),
tCurrentAccessLevel::GetName( accessLevel )
), victim, &se_Hide, 0, 0, &se_CanHide );
}
}
else
{
tString authName = victim->GetUserName() + "@L_OP";
if ( victim->IsAuthenticated() )
{
authName = victim->GetRawAuthenticatedName();
}
victim->Authenticate( authName, accessLevel, 0, messages );
}
}
// Console command for it
void se_OpConf( std::istream &s )
{
if ( se_NeedsServer( "OP", s ) )
{
return;
}
ePlayerNetID * victim = se_FindPlayerInChatCommand( 0, "OP", s );
bool isexplicit = false;
if ( victim )
{
// read optional access level, this part is merly a copypaste from the /shuffle code
int level = se_opAccessLevelMax;
if ( victim->IsAuthenticated() )
{
level = victim->GetAccessLevel();
}
char first;
s >> first;
if ( !s.eof() && !s.fail() )
{
isexplicit = true;
s.unget();
int newLevel = 0;
s >> newLevel;
if ( first == '+' || first == '-' )
{
level += newLevel;
}
else
{
level = newLevel;
}
}
s >> level;
tAccessLevel accessLevel;
accessLevel = static_cast< tAccessLevel >( level );
if ( accessLevel == victim->GetAccessLevel() )
{
if ( isexplicit )
{
sn_ConsoleOut( tOutput( "$access_level_op_same", "OP" ), 0 );
}
else
{
sn_ConsoleOut( tOutput( "$access_level_op_unclear", "OP" ), 0 );
}
}
else
{
se_AnonOp( victim, accessLevel );
}
}
}
static tConfItemFunc se_opConf( "OP", &se_OpConf );
static tAccessLevelSetter se_opConfLevel( se_opConf, tAccessLevel_Owner );
static void se_DeOpFunc(std::istream &s)
{
if ( se_NeedsServer( "DEOP", s ) )
{
return;
}
tString params;
s >> params;
ePlayerNetID *player = ePlayerNetID::FindPlayerByName(params);
if (!player) return;
se_AdminLogout(player, "DEOP");
}
static tConfItemFunc se_DeOpFuncConf("DEOP", &se_DeOpFunc);
// minimal access level for /team management
static tAccessLevel se_teamAccessLevel = tAccessLevel_TeamLeader;
static tSettingItem< tAccessLevel > se_teamAccessLevelConf( "ACCESS_LEVEL_TEAM", se_teamAccessLevel );
static tAccessLevelSetter se_teamAccessLevelConfLevel( se_teamAccessLevelConf, tAccessLevel_Owner );
// returns the team managed by an admin
static eTeam * se_GetManagedTeam( ePlayerNetID * admin )
{
// the team to invite to is, of course, the team the admin is in.
eTeam * team = admin->CurrentTeam();
ePlayerNetID::eTeamSet const & invitations = admin->GetInvitations();
// unless, of course, he is in no team, then let him relay the one invitation
// he has.
if ( !team && invitations.size() == 1 )
{
team = *invitations.begin();
}
return team;
}
// checks
static bool se_CanManageTeam( ePlayerNetID * admin, bool emergency )
{
// check regular access level
if ( admin->GetAccessLevel() <= se_teamAccessLevel )
{
return true;
}
// check emergency
if ( !emergency )
{
return false;
}
// emergency: /invite and /unlock must be available to a player with
// maximal access rights on the team, otherwise teams may become
// locked and orphaned, without a chance to get new members.
// no team? Nothing to manage
eTeam * team = admin->CurrentTeam();
if ( !team )
{
return false;
}
// check for players of a higher level
for( int i = team->NumPlayers()-1; i >= 0; --i )
{
ePlayerNetID * otherPlayer = team->Player(i);
if ( otherPlayer->IsHuman() && otherPlayer->GetAccessLevel() < admin->GetAccessLevel() )
{
return false;
}
}
return true;
}
// invite/uninvite a player
typedef void (eTeam::*INVITE)( ePlayerNetID * victim );
static void se_Invite( char const * command, ePlayerNetID * admin, std::istream & s, INVITE invite )
{
if ( se_CanManageTeam( admin, invite == &eTeam::Invite ) )
{
// get the team the admin can manage
eTeam * team = se_GetManagedTeam( admin );
if ( team )
{
ePlayerNetID * victim = se_FindPlayerInChatCommand( admin, command, s );
if ( victim )
{
// invite/uninvite him
(team->*invite)( victim );
}
}
else
{
sn_ConsoleOut( tOutput( "$invite_no_team", command ), admin->Owner() );
}
}
else
{
sn_ConsoleOut( tOutput( "$access_level_op_denied", command ), admin->Owner() );
}
}
// changes private party status of a team
static void se_Lock( char const * command, ePlayerNetID * admin, std::istream & s, bool lock )
{
if ( se_CanManageTeam( admin, !lock ) )
{
// get the team the admin can manage
eTeam * team = se_GetManagedTeam( admin );
if ( team )
{
team->SetLocked( lock );
}
else
{
sn_ConsoleOut( tOutput( "$invite_no_team", command ), admin->Owner() );
}
}
else
{
sn_ConsoleOut( tOutput( "$access_level_op_denied", command ), admin->Owner() );
}
}
#else // KRAWALL
// returns the team managed by an admin
static eTeam * se_GetManagedTeam( ePlayerNetID * admin )
{
return admin->CurrentTeam();
}
#endif // KRAWALL
static eLadderLogWriter se_adminLoginWriter("ADMIN_LOGIN", false);
static eLadderLogWriter se_adminLogoutWriter("ADMIN_LOGOUT", false);
// the following function really is only supposed to be called from here and nowhere else
// (access right escalation risk):
// log in (via admin password or hash based login)
static void se_AdminLogin_ReallyOnlyCallFromChatKTHNXBYE( ePlayerNetID * p, std::istream & s )
{
tString params("");
params.ReadLine( s );
#ifndef KRAWALL_SERVER
if ( params == "" )
return;
#endif
// trim whitespace
// for the trunk:
// params.Trim();
// here,we have to do the work manually
{
int lastNonSpace = params.Len() - 2;
while ( lastNonSpace >= 0 && isblank(params[lastNonSpace]) )
{
--lastNonSpace;
}
if ( lastNonSpace < params.Len() - 2 )
{
params = params.SubStr( 0, lastNonSpace + 1 );
}
}
#ifndef KRAWALL_SERVER
// the password is not stored in the recording, hence we have to store the
// result of the password test
bool accept = true;
static const char * section = "REMOTE_LOGIN";
if ( !tRecorder::Playback( section, accept ) )
accept = ( params == sg_adminPass && sg_adminPass != "NONE" );
tRecorder::Record( section, accept );
//change this later to read from a password file or something...
//or integrate it with auth if we ever get that done...
if ( accept )
{
// the following function really is only supposed to be called from here and nowhere else
// (access right escalation risk)
se_AdminLogin_ReallyOnlyCallFromChatKTHNXBYE( p );
se_adminLoginWriter << p->GetUserName() << nMachine::GetMachine(p->Owner()).GetIP();
se_adminLoginWriter.write();
}
else
{
tString failedLogin;
sn_ConsoleOut("Login denied!\n",p->Owner());
failedLogin << "Remote admin login for user \"" << p->GetUserName();
failedLogin << "\" using password \"" << params << "\" rejected.\n";
sn_ConsoleOut(failedLogin, 0);
}
#else
if ( sn_GetNetState() == nSERVER && p->Owner() != sn_myNetID )
{
if ( p->IsAuthenticated() )
{
sn_ConsoleOut( "$login_request_redundant", p->Owner() );
return;
}
if ( p->GetRawAuthenticatedName().Len() <= 1 || params.StrPos("@") >= 0 )
{
if ( params.StrPos( "@" ) >= 0 )
{
p->SetRawAuthenticatedName( params );
}
else
{
p->SetRawAuthenticatedName( p->GetUserName() + "@" + params );
}
}
// check for stupid bans
if ( se_IsUserBanned( p, p->GetRawAuthenticatedName() ) )
{
return;
}
p->loginWanted = true;
se_RequestLogin( p );
}
#endif
}
// handy command to get load login stuff for players
static void se_Login_Call(std::istream &s)
{
tString params;
s >> params;
ePlayerNetID *player = ePlayerNetID::FindPlayerByName(params);
if (!player) return;
se_AdminLogin_ReallyOnlyCallFromChatKTHNXBYE(player, s);
}
static tConfItemFunc se_Login_Conf("LOGIN", &se_Login_Call);
static tAccessLevelSetter se_Login_ConfLevel( se_Login_Conf, tAccessLevel_Moderator );
static void se_Logout_Call(std::istream &s)
{
tString params;
s >> params;
ePlayerNetID *player = ePlayerNetID::FindPlayerByName(params);
if (!player) return;
se_AdminLogout(player, "LOGOUT");
}
static tConfItemFunc se_Logout_Conf("LOGOUT", &se_Logout_Call);
static tAccessLevelSetter se_Logout_ConfLevel( se_Logout_Conf, tAccessLevel_Moderator );
static eLadderLogWriter se_adminCommandWriter("ADMIN_COMMAND", false);
static bool sr_adminLog = false;
static tConfItem<bool> sr_consoleLogConf("ADMIN_LOG", sr_adminLog);
// access level a user has to have to be able to see what's being typed at /admin
static tAccessLevel se_consoleSpyAccessLevel = tAccessLevel_Moderator;
static tSettingItem< tAccessLevel > se_consoleSpyAccessLevelConf( "ACCESS_LEVEL_SPY_CONSOLE", se_consoleSpyAccessLevel );
static tAccessLevelSetter se_consoleSpyAccessLevelConfLevel( se_consoleSpyAccessLevelConf, tAccessLevel_Owner );
static bool se_cannotSeeConsole( ePlayerNetID const *, ePlayerNetID const * seeker )
{
return seeker->GetAccessLevel() > se_consoleSpyAccessLevel;
}
// /admin chat command
static void se_AdminAdmin( ePlayerNetID * p, std::istream & s )
{
if ( p->GetAccessLevel() > se_adminAccessLevel )
{
sn_ConsoleOut( tOutput( "$access_level_admin_denied" ), p->Owner() );
return;
}
tString str;
str.ReadLine(s);
std::istringstream astream(&str(0));
int cLevel = tConfItemBase::AccessLevel(astream);
//no need to write commands that may not work or commands that they can't use.
if ((p->GetAccessLevel() <= cLevel) && (cLevel >= 0))
{
se_adminCommandWriter << p->GetUserName() << nMachine::GetMachine(p->Owner()).GetIP() << p->GetAccessLevel() << str;
se_adminCommandWriter.write();
}
if (sr_adminLog == true)
{
std::ofstream o;
if ( tDirectories::Var().Open(o, "adminlog.txt", std::ios::app) )
{
o << st_GetCurrentTime("[%Y/%m/%d-%H:%M:%S] ") << p->GetUserName() << " " << p->GetAccessLevel() << " " << str << "\n";
}
}
tColoredString msg;
msg << tColoredString::ColorString(1,0,0) << "Remote admin command" << tColoredString::ColorString(-1,-1,-1) << " by " << tColoredString::ColorString(1,1,.5) << p->GetUserName() << tColoredString::ColorString(-1,-1,-1) << ": " << tColoredString::ColorString(.5,.5,1) << str << "\n";
se_SecretConsoleOut( msg, p, &se_cannotSeeConsole, p );
std::istringstream stream(&str(0));
// install filter
eAdminConsoleFilter consoleFilter( p->Owner() );
try
{
// forbid CASACL
tCasaclPreventer preventer;
tConfItemBase::LoadLine(stream);
}
catch (tAbortLoading)
{
con << tOutput("$config_abort");
}
}
static eLadderLogWriter se_invalidCommandWriter("INVALID_COMMAND", false);
static void handle_chat_admin_commands( ePlayerNetID * p, tString const & command, tString const & say, std::istream & s, eChatSpamTester &spam )
{
if (command == "/login")
{
// Really, there's no reason one would log in and log out all the time
spam.factor_ = 1;
if ( spam.Block() )
{
return;
}
// the following function really is only supposed to be called from here and nowhere else
// (access right escalation risk)
se_AdminLogin_ReallyOnlyCallFromChatKTHNXBYE( p, s );
}
else if (command == "/logout")
{
spam.factor_ = 1;
if( spam.Block() )
{
return;
}
se_AdminLogout( p, command );
}
#ifdef KRAWALL_SERVER
else if ( command == "/op" )
{
se_ChangeAccess( p, s, "/op", &se_Op );
}
else if ( command == "/deop" )
{
se_DeOp( p, s, "/deop" );
}
else if ( command == "/invite" )
{
spam.factor_ = 0.4;
if( spam.Block() )
{
return;
}
se_Invite( command, p, s, &eTeam::Invite );
}
else if ( command == "/uninvite" )
{
spam.factor_ = 0.4;
if( spam.Block() )
{
return;
}
se_Invite( command, p, s, &eTeam::UnInvite );
}
else if ( command == "/lock" )
{
spam.factor_ = 0.4;
if( spam.Block() )
{
return;
}
se_Lock( command, p, s, true );
}
else if ( command == "/unlock" )
{
spam.factor_ = 0.4;
if( spam.Block() )
{
return;
}
se_Lock( command, p, s, false );
}
#endif
else if ( command == "/admin" )
{
se_AdminAdmin( p, s );
}
else
{
if (se_invalidCommandWriter.isEnabled() )
{
tString str;
str.ReadLine(s);
se_invalidCommandWriter << command << p->GetUserName() << nMachine::GetMachine(p->Owner()).GetIP() << p->GetAccessLevel() << str;
se_invalidCommandWriter.write();
}
if (se_interceptUnknownCommands)
{
handle_command_intercept(p, command, s, say);
}
else
{
sn_ConsoleOut( tOutput( "$chat_command_unknown", command ), p->Owner() );
}
}
}
#else // DEDICATED
// returns the team managed by an admin
static eTeam * se_GetManagedTeam( ePlayerNetID * admin )
{
return admin->CurrentTeam();
}
#endif // DEDICATED
static bool se_silenceDead = false;
static tSettingItem<bool> se_silenceDeadConf("SILENCE_DEAD", se_silenceDead);
// help message printed out to whoever asks for it
static tString se_helpMessage("");
static tConfItemLine se_helpMessageConf("HELP_MESSAGE",se_helpMessage);
static bool se_helpMessageType = false;
static tSettingItem<bool> se_helpMessageTypeConf("HELP_MESSAGE_TYPE", se_helpMessageType);
// time during which no repeaded chat messages are printed
REAL se_alreadySaidTimeout=5.0;
static tSettingItem<REAL> se_alreadySaidTimeoutConf("SPAM_PROTECTION_REPEAT",
se_alreadySaidTimeout);
#ifndef KRAWALL_SERVER
// flag set to allow players to shuffle themselves up in a team
static bool se_allowShuffleUp=false;
static tSettingItem<bool> se_allowShuffleUpConf("TEAM_ALLOW_SHUFFLE_UP",
se_allowShuffleUp);
#else
static tAccessLevel se_shuffleUpAccessLevel = tAccessLevel_TeamMember;
static tSettingItem< tAccessLevel > se_shuffleUpAccessLevelConf( "ACCESS_LEVEL_SHUFFLE_UP", se_shuffleUpAccessLevel );
static tAccessLevelSetter se_shuffleUpAccessLevelConfLevel( se_shuffleUpAccessLevelConf, tAccessLevel_Owner );
#endif
#ifdef KRAWALL_SERVER
static tAccessLevel se_substituteAccessLevel = tAccessLevel_TeamLeader;
static tSettingItem< tAccessLevel > se_substituteAccessLevelConf( "ACCESS_LEVEL_SUBSTITUTE", se_substituteAccessLevel );
static tAccessLevelSetter se_substituteAccessLevelConfLevel( se_substituteAccessLevelConf, tAccessLevel_Owner );
#endif
static bool se_silenceDefault = false; // flag indicating whether new players should be silenced
// minimal access level for chat
tAccessLevel se_chatAccessLevel = tAccessLevel_Program;
static tSettingItem< tAccessLevel > se_chatAccessLevelConf( "ACCESS_LEVEL_CHAT", se_chatAccessLevel );
static tAccessLevelSetter se_chatAccessLevelConfLevel( se_chatAccessLevelConf, tAccessLevel_Owner );
// time between public chat requests, set to 0 to disable
REAL se_chatRequestTimeout = 60;
static tSettingItem< REAL > se_chatRequestTimeoutConf( "ACCESS_LEVEL_CHAT_TIMEOUT", se_chatRequestTimeout );
// access level a spectator has to have to be able to listen to /team messages
static tAccessLevel se_teamSpyAccessLevel = tAccessLevel_Moderator;
static tSettingItem< tAccessLevel > se_teamSpyAccessLevelConf( "ACCESS_LEVEL_SPY_TEAM", se_teamSpyAccessLevel );
static tAccessLevelSetter se_teamSpyAccessLevelConfLevel( se_teamSpyAccessLevelConf, tAccessLevel_Owner );
// access level a user has to have to be able to listen to /msg messages
static tAccessLevel se_msgSpyAccessLevel = tAccessLevel_Owner;
static tSettingItem< tAccessLevel > se_msgSpyAccessLevelConf( "ACCESS_LEVEL_SPY_MSG", se_msgSpyAccessLevel );
static tAccessLevelSetter se_msgSpyAccessLevelConfLevel( se_msgSpyAccessLevelConf, tAccessLevel_Owner );
// access level a user has to have to get IP addresses in /players output
static tAccessLevel se_ipAccessLevel = tAccessLevel_Armatrator;
static tSettingItem< tAccessLevel > se_ipAccessLevelConf( "ACCESS_LEVEL_IPS", se_ipAccessLevel );
static tAccessLevelSetter se_ipAccessLevelConfLevel( se_ipAccessLevelConf, tAccessLevel_Owner );
static tAccessLevel se_nVerAccessLevel = tAccessLevel_Moderator;
static tSettingItem< tAccessLevel > se_nVerAccessLevelConf( "ACCESS_LEVEL_NVER", se_nVerAccessLevel );
static tAccessLevelSetter se_nVerAccessLevelConfLevel( se_nVerAccessLevelConf, tAccessLevel_Owner );
static tSettingItem<bool> se_silAll("SILENCE_DEFAULT",
se_silenceDefault);
// checks whether a player is silenced, giving him appropriate warnings if he is
bool IsSilencedWithWarning( ePlayerNetID const * p )
{
if ( !se_enableChat && ! p->IsLoggedIn() )
{
// everyone except the admins is silenced
sn_ConsoleOut( tOutput( "$spam_protection_silenceall" ), p->Owner() );
return true;
}
else if ( p->IsSilenced() )
{
if(se_silenceDefault)
{
// player is silenced, but all players are silenced by default
sn_ConsoleOut( tOutput( "$spam_protection_silenced_default" ), p->Owner() );
}
else
{
// player is specially silenced
sn_ConsoleOut( tOutput( "$spam_protection_silenced" ), p->Owner() );
}
return true;
}
return false;
}
// returns true if the player is allowed to shout
static bool se_CheckAccessLevelShoutNoWarn( ePlayerNetID * p )
{
#ifdef KRAWALL_SERVER
eShoutDefault shout = se_GetManagedTeam( p ) ? se_shoutPlayer : se_shoutSpectator;
if( shout == eShoutDefault_ShoutAndOverride )
{
return true;
}
// check if the player has the right to shout
return p->GetAccessLevel() <= se_shoutAccessLevel;
#else
return true;
#endif
}
// returns true if the player is allowed to shout
static bool se_CheckAccessLevelShout( ePlayerNetID * p )
{
if( !se_CheckAccessLevelShoutNoWarn( p ) )
{
sn_ConsoleOut( tOutput("$access_level_shout_denied" ), p->Owner() );
return false;
}
else
{
return true;
}
}
// /me chat commant
static void se_ChatMe( ePlayerNetID * p, std::istream & s, eChatSpamTester & spam )
{
// check for global chat access right
if ( !se_CheckAccessLevelShout( p ) )
{
return;
}
if ( IsSilencedWithWarning(p) || spam.Block() )
{
return;
}
tString msg;
msg.ReadLine( s );
tColoredString console;
console << tColoredString::ColorString(1,1,1) << "* ";
console << *p;
console << tColoredString::ColorString(1,1,.5) << " " << msg;
console << tColoredString::ColorString(1,1,1) << " *";
tColoredString forOldClients;
forOldClients << tColoredString::ColorString(1,1,1) << "*"
<< tColoredString::ColorString(1,1,.5) << msg
<< tColoredString::ColorString(1,1,1) << "*";
se_BroadcastChatLine( p, console, forOldClients );
console << "\n";
sn_ConsoleOut(console,0);
tString str;
str << p->GetUserName() << " /me " << msg;
se_SaveToChatLog(str);
se_SaveToChatLogC(console);
return;
}
// /teamleave chat command: leaves the current team
static void se_ChatTeamLeave( ePlayerNetID * p )
{
if ( se_assignTeamAutomatically )
{
sn_ConsoleOut(tOutput("$player_teamleave_disallowed"), p->Owner() );
return;
}
if(!p->TeamChangeAllowed())
{
sn_ConsoleOut(tOutput("$player_disallowed_teamchange"), p->Owner() );
return;
}
eTeam * leftTeam = p->NextTeam();
if ( leftTeam )
{
if ( !leftTeam )
leftTeam = p->CurrentTeam();
if ( leftTeam->NumPlayers() > 1 )
{
sn_ConsoleOut( tOutput( "$player_leave_team_wish",
tColoredString::RemoveColors(p->GetName()),
tColoredString::RemoveColors(leftTeam->Name()) ) );
}
else
{
sn_ConsoleOut( tOutput( "$player_leave_game_wish",
tColoredString::RemoveColors(p->GetName()) ) );
}
}
p->SetTeamWish(0);
}
static bool se_filterColorTeam=false;
tSettingItem< bool > se_coloredTeamConf( "FILTER_COLOR_TEAM", se_filterColorTeam );
static bool se_filterDarkColorTeam=false;
tSettingItem< bool > se_coloredDarkTeamConf( "FILTER_DARK_COLOR_TEAM", se_filterDarkColorTeam );
// reads a network ID from the stream, either the number or my user name
static unsigned short se_ReadUser( std::istream &s, ePlayerNetID * requester = 0 )
{
// read name of player to be kicked
tString name;
s >> name;
// try to convert it into a number and reference it as that
int num = name.toInt();
if ( num >= 1 && num <= MAXCLIENTS && sn_Connections[num].socket )
{
return num;
}
else
{
// standard name lookup
ePlayerNetID * p = ePlayerNetID::FindPlayerByName( name, requester );
if ( p )
{
return p->Owner();
}
}
return 0;
}
// regular chat; reaches all players
static void se_ChatShout( ePlayerNetID * p, tString const & say, eChatSpamTester & spam )
{
if ( !se_CheckAccessLevelShout( p ) )
{
return;
}
// check for spam
if ( spam.Block() )
{
return;
}
if ( say.Len() <= se_SpamMaxLen+2 && !IsSilencedWithWarning(p) )
{
se_BroadcastChat( p, say );
se_DisplayChatLocally( p, say);
tString s;
s << p->GetUserName() << ' ' << say;
se_SaveToChatLog(s);
tColoredString message;
message << *p;
message << tColoredString::ColorString(1,1,.5);
message << ": " << say << "\n";
se_SaveToChatLogC(message);
}
}
static void se_ChatShout( ePlayerNetID * p, std::istream & s, eChatSpamTester & spam )
{
// parse string
tString say;
say.ReadLine( s );
// delegate
se_ChatShout( p, say, spam );
}
// /team chat commant: talk to your team
static void se_ChatTeam( ePlayerNetID * p, tString msg, eChatSpamTester & spam )
{
eTeam *currentTeam = se_GetManagedTeam( p );
// team messages are less spammy than public chat, take care of that.
// we don't care too much about AI players (but don't remove them from the denominator because we're too lazy to count the total number of human players).
spam.factor_ = ( currentTeam ? currentTeam->NumHumanPlayers() : 1 )/REAL( se_PlayerNetIDs.Len() );
// silencing only affects spectators here
if ( ( !currentTeam && IsSilencedWithWarning(p) ) || spam.Block() )
{
return;
}
// Apply filters if we don't already
if ( se_filterColorTeam )
msg = tColoredString::RemoveColors ( msg, false );
else if ( se_filterDarkColorTeam )
msg = tColoredString::RemoveColors ( msg, true );
// Log message to server (and in previous revisions, the sender)
tColoredString messageForServerAndSender = se_BuildChatString(currentTeam, p, msg);
messageForServerAndSender << "\n";
if (currentTeam != NULL) // If a player has just joined the game, he is not yet on a team. Sending a /team message will crash the server
{
sn_ConsoleOut(messageForServerAndSender, 0);
// Send message to team-mates
int numTeamPlayers = currentTeam->NumPlayers();
for (int teamPlayerIndex = 0; teamPlayerIndex < numTeamPlayers; teamPlayerIndex++)
{
se_SendTeamMessage(currentTeam, p, currentTeam->Player(teamPlayerIndex), msg);
}
// check for other players who are authorized to hear the message
for( int i = se_PlayerNetIDs.Len() - 1; i >=0; --i )
{
ePlayerNetID * admin = se_PlayerNetIDs(i);
if (
// two cases:
(
// You are a speccing admin, and you aren't invited to anything:
se_GetManagedTeam( admin ) == 0 &&
admin->GetAccessLevel() <= se_teamSpyAccessLevel
) ||
(
// You are invited and spectating
admin->CurrentTeam() == NULL &&
// invited players are also authorized
currentTeam->IsInvited( admin )
)
)
{
se_SendTeamMessage(currentTeam, p, admin, msg);
}
}
}
else
{
sn_ConsoleOut(messageForServerAndSender, 0);
// check for other spectators
for( int i = se_PlayerNetIDs.Len() - 1; i >=0; --i )
{
ePlayerNetID * spectator = se_PlayerNetIDs(i);
if ( se_GetManagedTeam( spectator ) == 0 )
{
se_SendTeamMessage(currentTeam, p, spectator, msg);
}
}
}
//add /team to chatlog
if (se_chatLogWriteTeam)
{
tString str;
str << p->GetUserName() << " /team " << msg;
se_SaveToChatLog(str);
}
}
// /team chat commant: talk to your team
static void se_ChatTeam( ePlayerNetID * p, std::istream &s, eChatSpamTester & spam )
{
tString msg;
msg.ReadLine( s );
se_ChatTeam( p, msg, spam );
}
// /enemy chat command: talk to enemies
static void se_ChatEnemy(ePlayerNetID *p, std::istream &s, eChatSpamTester &spam)
{
// read the message
tString message;
message.ReadLine( s, true );
switch (sn_GetNetState())
{
case nSERVER:
{
tColoredString send;
send << p->GetColoredName();
send << tColoredString::ColorString( 1,1,.5 );
send << " --> ";
send << tColoredString::ColorString( 1,0,0 );
send << "Enemies";
send << tColoredString::ColorString( 1,1,.5 );
send << ": " << message << "\n";
// display it
sn_ConsoleOut( send );
break;
}
}
}
static void se_ChatReport( ePlayerNetID * p, std::istream & s )
{
tString msg;
tOutput reportPlayer;
msg.ReadLine(s);
if (msg.Filter() != "")
{
tString reporMsg;
reporMsg << st_GetCurrentTime("[%Y/%m/%d-%H:%M:%S]");
reporMsg << " ";
reporMsg << p->GetMachine().GetIP();
reporMsg << " ";
reporMsg << p->GetUserName();
reporMsg << " ";
reporMsg << msg;
reporMsg << "\n";
std::ofstream o;
if (tDirectories::Var().Open(o, "reports.txt", std::ios::app))
{
o << reporMsg;
reportPlayer << "$chat_message_report_respond_ok";
reportPlayer << msg << "\n";
}
else
{
reportPlayer << "$chat_message_report_respond_no";
}
o.close();
}
else
{
reportPlayer << "$chat_message_report_message_empty";
}
sn_ConsoleOut(reportPlayer, p->Owner());
}
static int se_ReportsCount()
{
int count = 0;
std::ifstream i;
if (tDirectories::Var().Open(i, "reports.txt"))
{
while (!i.eof())
{
std::string sayLine;
std::getline(i, sayLine);
std::istringstream s(sayLine);
tString params;
params.ReadLine(s);
if (params.Filter() != "")
count++;
}
}
i.close();
return count;
}
static tArray<tString> se_ReportsMessages()
{
tArray<tString> reports;
std::ifstream i;
if (tDirectories::Var().Open(i, "reports.txt"))
{
while (!i.eof())
{
std::string sayLine;
std::getline(i, sayLine);
std::istringstream s(sayLine);
tString params;
params.ReadLine(s);
int pos = 0;
if (params.Filter() != "")
reports.Insert(params);
}
}
i.close();
return reports;
}
tAccessLevel se_AccessLevelReportsRead = tAccessLevel_Default;
static tSettingItem<tAccessLevel> se_AccessLevelReportsReadConf("ACCESS_LEVEL_REPORTS_READ", se_AccessLevelReportsRead);
tAccessLevel se_AccessLevelReportsClear = tAccessLevel_Admin;
static tSettingItem<tAccessLevel> se_AccessLevelReportsClearConf("ACCESS_LEVEL_REPORTS_CLEAR", se_AccessLevelReportsClear);
static void se_ChatReadReport( ePlayerNetID * p, std::istream & s )
{
tString type;
s >> type;
if ((type == "") || (type.ToLower() == "list"))
{
tOutput msg;
msg.SetTemplateParameter(1, se_ReportsCount());
msg << "$read_reports_count";
sn_ConsoleOut(msg, p->Owner());
}
else if (type.ToLower() == "read")
{
if (p->GetAccessLevel() > se_AccessLevelReportsRead)
{
sn_ConsoleOut(tOutput("$read_reports_access_no_read"), p->Owner());
return;
}
tString lineNoStr;
s >> lineNoStr;
if (lineNoStr.Filter() == "")
{
sn_ConsoleOut(tOutput("$chat_message_report_read_usage"), p->Owner());
return;
}
int lineNo = atoi(lineNoStr);
int index = lineNo - 1;
tArray<tString> report_messages = se_ReportsMessages();
if ((index < 0) || (index >= report_messages.Len()))
{
sn_ConsoleOut(tOutput("$chat_message_report_read_none", lineNo), p->Owner());
return;
}
tString msg = report_messages[index];
int pos = 0;
tString date = msg.ExtractNonBlankSubString(pos);
tString ip = msg.ExtractNonBlankSubString(pos);
tString user = msg.ExtractNonBlankSubString(pos);
tString report = msg.SubStr(pos + 1);
tString pMsg;
pMsg << date << " ";
pMsg << "Line " << lineNo << " | ";
pMsg << user << ": ";
pMsg << report << "\n";
sn_ConsoleOut(pMsg, p->Owner());
}
else if (type.ToLower() == "clear")
{
if (p->GetAccessLevel() > se_AccessLevelReportsClear)
{
sn_ConsoleOut(tOutput("$read_reports_access_no_clear"), p->Owner());
return;
}
std::ofstream o;
if (tDirectories::Var().Open(o, "reports.txt"))
{
o << "\n";
}
o.close();
sn_ConsoleOut(tOutput("$read_reports_cleared"), p->Owner());
}
}
/**
* Let's just leave it at default at moderators level.
* This way only moderators or lower level users can view chat messages from this person.
* Meaning so, the sending must be a moderator or lower level user (lower level have higher powers).
*/
static int se_accessLevelViewChats = 2;
static tSettingItem<int> se_accessLevelViewChatsConf("ACCESS_LEVEL_VIEW_CHATS", se_accessLevelViewChats);
// /chat commant: talk to the people with the same or lower(better) access level
static void se_ChatPlayer( ePlayerNetID * p, std::istream & s, eChatSpamTester & spam )
{ // odd, the refactored original did not check for silence. Probably by design.
if ( /* IsSilencedWithWarning(player) || */ spam.Block() ) return;
if (p && (p->GetAccessLevel() <= se_accessLevelViewChats))
{
// read the rest of the message
tString msg_core;
msg_core.ReadLine(s);
for(int i = 0; i < se_PlayerNetIDs.Len(); i++)
{
ePlayerNetID *receiver = se_PlayerNetIDs[i];
/**
* Ensure that this message will only be sent to players
* with similar access level as the sender.
*/
if (receiver && (receiver->GetAccessLevel() <= se_accessLevelViewChats))
{
// build chat string
tColoredString sendOther;
sendOther << tColoredString::ColorString( 1,1,.5 );
sendOther << "*";
// get access level name and add it before rest of information
sendOther << tCurrentAccessLevel::GetName(p->GetAccessLevel());
sendOther << tColoredString::ColorString( 1,1,.5 );
sendOther << "* ";
sendOther << p->GetColoredName();
sendOther << tColoredString::ColorString( 1,1,.5 );
sendOther << ": 0x66ffff";
sendOther << msg_core << "\n";
// display it to the player with equal access level
sn_ConsoleOut(sendOther, receiver->Owner());
}
}
}
}
// /msg chat commant: talk to anyone team
static void se_ChatMsg( ePlayerNetID * p, std::istream & s, eChatSpamTester & spam )
{
// odd, the refactored original did not check for silence. Probably by design.
if ( /* IsSilencedWithWarning(player) || */ spam.Block() )
{
return;
}
// Check for player
ePlayerNetID * receiver = se_FindPlayerInChatCommand( p, "/msg", s );
// One match, send it.
if ( receiver )
{
// extract rest of message: it is the true message to send
std::ws(s);
// read the rest of the message
tString msg_core;
msg_core.ReadLine(s);
// build chat string
tColoredString toServer = se_BuildChatString( p, receiver, msg_core );
toServer << '\n';
if ( p->CurrentTeam() == receiver->CurrentTeam() || !IsSilencedWithWarning(p) )
{
// log locally
sn_ConsoleOut(toServer,0);
// log to sender's console
sn_ConsoleOut(toServer, p->Owner());
// send to receiver
if ( p->Owner() != receiver->Owner() )
se_SendPrivateMessage( p, receiver, receiver, msg_core );
// let admins of sufficient rights eavesdrop
for( int i = se_PlayerNetIDs.Len() - 1; i >=0; --i )
{
ePlayerNetID * admin = se_PlayerNetIDs(i);
if ( admin != receiver && admin != p && admin->GetAccessLevel() <= se_msgSpyAccessLevel )
{
se_SendPrivateMessage( p, receiver, admin, msg_core );
}
}
}
}
}
static void se_SendTo( std::string const & message, ePlayerNetID * receiver )
{
if ( receiver )
{
sn_ConsoleOut(message.c_str(), receiver->Owner());
}
else
{
con << message;
}
}
// prints an indented team member with position marker
static void se_SendTeamMember( ePlayerNetID const * player, int indent, std::ostream & tos, int index, int width )
{
tos << '#' << std::setw( width ) << index+1 << ' ';
// send team name
for( int i = indent-1; i >= 0; --i )
{
tos << ' ';
}
tos << *player << "\n";
}
// list teams with their formation
static void se_ListTeam( ePlayerNetID * receiver, eTeam * team )
{
std::ostringstream tos;
// send team name
tos << team->GetColoredName();
if ( team->IsLocked() )
{
tos << " " << tOutput( "$invite_team_locked_list" );
}
tos << ":\n";
// send team members
int teamMembers = team->NumPlayers();
int width = teamMembers >= 10 ? 2 : 1;
int indent = 0;
// print left wing, the odd team members
for( int i = (teamMembers/2)*2-1; i>=0; i -= 2 )
{
se_SendTeamMember( team->Player(i), indent, tos, i, width );
indent += 2;
}
// print right wing, the even team members
for( int i = 0; i < teamMembers; i += 2 )
{
se_SendTeamMember( team->Player(i), indent, tos, i, width );
indent -= 2;
}
tos << "\n";
se_SendTo( tos.str(), receiver );
}
static void se_ListTeams( ePlayerNetID * receiver )
{
int numTeams = 0;
for ( int i = eTeam::teams.Len() - 1; i >= 0; --i )
{
eTeam * team = eTeam::teams[i];
if ( team->NumPlayers() > 1 || team->IsLocked() )
{
numTeams++;
se_ListTeam( receiver, team );
}
}
if ( numTeams == 0 )
{
se_SendTo( std::string( tString( tOutput("$no_real_teams") ) ), receiver );
}
}
static void teams_conf(std::istream &s)
{
se_ListTeams( 0 );
}
static tConfItemFunc teams("TEAMS",&teams_conf);
// /teams gives a teams list
static void se_ChatTeams( ePlayerNetID * p )
{
se_ListTeams( p );
}
void se_ListPastChatters(ePlayerNetID * receiver);
static void se_ListPlayers( ePlayerNetID * receiver, std::istream &s, tString command )
{
tString search;
bool doSearch = false;
search.ReadLine( s );
tToLower( search );
if ( search.Len() > 1 )
doSearch = true;
bool hidden = false;
int count = 0;
for ( int i2 = se_PlayerNetIDs.Len()-1; i2>=0; --i2 )
{
ePlayerNetID* p2 = se_PlayerNetIDs(i2);
tColoredString tos;
if ( doSearch )
tos << " ";
tos << p2->Owner();
tos << ": ";
if ( p2->GetAccessLevel() < tAccessLevel_Default && !se_Hide( p2, receiver ) )
{
#ifdef KRAWALL_SERVER
hidden = p2->GetAccessLevel() <= se_hideAccessLevelOf && p2->StealthMode();
#else
hidden = false;
#endif
tos << p2->GetColoredName()
<< tColoredString::ColorString( -1, -1, -1)
<< " ( ";
if ( hidden )
tos << se_hiddenPlayerPrefix;
#ifdef KRAWALL_SERVER
tos << p2->GetFilteredAuthenticatedName();
if ( hidden )
tos << tColoredString::ColorString( -1 ,-1 ,-1 )
<< ", "
<< se_hiddenPlayerPrefix;
else
tos << ", ";
#endif
tos << tCurrentAccessLevel::GetName( p2->GetAccessLevel() );
if ( hidden )
tos << tColoredString::ColorString( -1 ,-1 ,-1 );
tos << " )";
}
else
{
tos << p2->GetColoredName() << tColoredString::ColorString(1,1,1) << " ( )";
}
if ( ( p2->Owner() != 0 && tCurrentAccessLevel::GetAccessLevel() <= se_ipAccessLevel ) || ( p2->Owner() != 0 && p2->Owner() == receiver->Owner() ) )
{
tString IP = p2->GetMachine().GetIP();
if ( IP.Len() > 1 )
{
tos << ", IP = " << IP;
}
}
if ( ( p2->Owner() != 0 && tCurrentAccessLevel::GetAccessLevel() <= se_nVerAccessLevel ) || ( p2->Owner() != 0 && p2->Owner() == receiver->Owner() ) )
{
tos << ", " << sn_GetClientVersionString( sn_Connections[ p2->Owner() ].version.Max() ) << " (ID: " << sn_Connections[ p2->Owner() ].version.Max() << ")";
}
tos << "\n";
if ( !doSearch )
{
sn_ConsoleOut( tos, receiver->Owner() );
count++;
}
else
{
tString tosLowercase( tColoredString::RemoveColors(tos) );
tToLower( tosLowercase );
// looks quite like a hack, but i guess it's faster( esp. for me :) ) than checking on each parameter individually
if ( tosLowercase.StrPos( search ) != -1 )
{
count++;
if ( count == 1 )
{
sn_ConsoleOut( tOutput( "$player_list_search", command, search ) , receiver->Owner() );
}
sn_ConsoleOut( tos, receiver->Owner() );
}
}
}
if ( doSearch && !count )
{
sn_ConsoleOut( tOutput( "$player_list_search_no_results", command, search ) , receiver->Owner() );
}
else if ( doSearch )
{
sn_ConsoleOut( tOutput( "$player_list_search_end", command, count ) , receiver->Owner() );
}
else
{
sn_ConsoleOut( tOutput( "$player_list_end", command, count ) , receiver->Owner() );
if(tCurrentAccessLevel::GetAccessLevel() < tAccessLevel_DefaultAuthenticated)
se_ListPastChatters(receiver);
}
}
static void players_conf(std::istream &s)
{
se_ListPlayers( 0, s, tString("PLAYERS") );
}
static tConfItemFunc players("PLAYERS",&players_conf);
static tAccessLevelSetter players_AccessLevel( players, tAccessLevel_Owner );
// /players gives a player list
static void se_ChatPlayers( ePlayerNetID * p, std::istream &s, tString command )
{
se_ListPlayers( p, s, command );
}
// team shuffling: reorders team formation
static void se_ChatShuffle( ePlayerNetID * p, std::istream & s )
{
// team position shuffling. Allow players to change their team setup.
// syntax:
// /teamshuffle: shuffles you all the way to the outside.
// /teamshuffle <pos>: shuffles you to position pos
// /teamshuffle +/-<dist>: shuffles you dist to the outside/inside
// con << msgRest << "\n";
int IDNow = p->TeamListID();
int len = eTeam::maxPlayers;
if (!p->CurrentTeam())
{
// players start on the outside by default
if( IDNow < 0 )
{
IDNow = len-1;
}
}
else
{
len = p->CurrentTeam()->NumPlayers();
}
// but read the target position as additional parameter
int IDWish = len-1; // default to shuffle to the outside
// peek at the first nonwhite character
std::ws( s );
char first = s.get();
if ( !s.eof() && !s.fail() )
{
s.unget();
int shuffle = 0;
s >> shuffle;
if ( s.fail() )
{
sn_ConsoleOut( tOutput("$player_shuffle_error"), p->Owner() );
return;
}
if ( first == '+' || first == '-' )
{
IDWish = IDNow;
IDWish += shuffle;
}
else
{
IDWish = shuffle-1;
}
}
if (IDWish < 0)
IDWish = 0;
if (IDWish >= len)
IDWish = len-1;
if( !p->CurrentTeam() || IDWish < IDNow )
{
#ifndef KRAWALL_SERVER
if ( !se_allowShuffleUp )
{
sn_ConsoleOut(tOutput("$player_noshuffleup"), p->Owner());
return;
}
#else
if ( p->GetAccessLevel() > se_shuffleUpAccessLevel )
{
sn_ConsoleOut(tOutput("$access_level_shuffle_up_denied", tCurrentAccessLevel::GetName(se_shuffleUpAccessLevel), tCurrentAccessLevel::GetName(p->GetAccessLevel())), p->Owner());
return;
}
#endif
}
if( IDNow == IDWish )
{
sn_ConsoleOut(tOutput("$player_noshuffle"), p->Owner());
return;
}
if( p->CurrentTeam() )
{
// really shuffle
p->CurrentTeam()->Shuffle( IDNow, IDWish );
se_ListTeam( p, p->CurrentTeam() );
}
else
{
// just store the shuffle wish for later
p->SetShuffleWish( IDWish );
}
}
void ePlayerNetID::SetShuffleWish( int pos )
{
tASSERT( !CurrentTeam() );
if ( GetShuffleSpam().ShouldAnnounce() )
{
sn_ConsoleOut( GetShuffleSpam().ShuffleMessage( this, pos+1 ) );
}
teamListID = pos;
}
// substitute: swap 2 players within a team
static void se_ChatSubstitute( ePlayerNetID * p, std::istream & s );
class eHelpTopic
{
tString m_shortdesc, m_text;
// singleton accessor
static std::map<tString, eHelpTopic> & GetHelpTopics();
public:
eHelpTopic() {}
eHelpTopic(tString const &shortdesc, tString const &text) : m_shortdesc(shortdesc), m_text(text)
{
}
void write(tColoredString &s) const
{
s << tColoredString::ColorString(.5,.5,1.) << tOutput(&m_shortdesc[0]) << ":\n" << tOutput(&m_text[0]) << '\n';
}
static void addHelpTopic(std::istream &s)
{
tString name, shortdesc, text;
s >> name >> shortdesc;
if(s.fail())
{
if(tConfItemBase::printErrors)
{
con << tOutput("$add_help_topic_usage");
}
return;
}
s >> text;
GetHelpTopics()[name] = eHelpTopic(shortdesc, text);
if(tConfItemBase::printChange)
{
con << tOutput("$add_help_topic_success", name);
}
}
static void removeHelpTopic(std::istream &s)
{
tString name;
s >> name;
if(GetHelpTopics().erase(name))
{
if(tConfItemBase::printChange)
{
con << tOutput("$remove_help_topic_success", name);
}
}
else
{
if(tConfItemBase::printErrors)
{
con << tOutput("$remove_help_topic_notfound", name);
}
}
}
private:
static void listTopics(tColoredString &s, tString const &base, std::map<tString, eHelpTopic>::const_iterator begin, std::map<tString, eHelpTopic>::const_iterator const &end)
{
bool printed_start = false;
for(; begin != end; ++begin)
{
if(!begin->first.StartsWith(base))
{
continue;
}
// would be easier with std::string...
if(begin->first.SubStr(base.Len() - 1).StrPos("_") >= 0)
{
// don't print subcommands
continue;
}
if(!printed_start)
{
printed_start = true;
s << tOutput("$help_topics_list_start");
}
s << tColoredString::ColorString(.5,.5,1.) << begin->first << tColoredString::ColorString(1.,1.,.5) << ": " << tOutput(&begin->second.m_shortdesc[0]) << "\n";
}
}
public:
static void listTopics(tColoredString &s, tString const &base=tString())
{
listTopics(s, base, GetHelpTopics().begin(), GetHelpTopics().end());
}
static void printTopic(tColoredString &s, tString const &name)
{
std::map<tString, eHelpTopic>::const_iterator iter = GetHelpTopics().find(name);
if(iter != GetHelpTopics().end())
{
iter->second.write(s);
listTopics(s, name + "_");
}
else
{
s << tOutput("$help_topic_not_found", name);
}
}
};
static void se_makeDefaultHelpTopic( std::map<tString, eHelpTopic> & helpTopics, char const *topic)
{
tString topicStr(topic);
tString helpTopic(tString("$help_") + topicStr);
helpTopics[topicStr] = eHelpTopic(helpTopic + "_shortdesc", helpTopic + "_text");
}
// singleton accessor implementation
static std::map<tString, eHelpTopic> & FillHelpTopics()
{
static std::map<tString, eHelpTopic> helpTopics;
se_makeDefaultHelpTopic(helpTopics, "commands");
se_makeDefaultHelpTopic(helpTopics, "commands_chat");
se_makeDefaultHelpTopic(helpTopics, "commands_team");
#ifdef KRAWALL_SERVER
se_makeDefaultHelpTopic(helpTopics, "commands_auth");
se_makeDefaultHelpTopic(helpTopics, "commands_auth_levels");
se_makeDefaultHelpTopic(helpTopics, "commands_tourney");
#else
se_makeDefaultHelpTopic(helpTopics, "commands_ra");
#endif
se_makeDefaultHelpTopic(helpTopics, "commands_misc");
se_makeDefaultHelpTopic(helpTopics, "commands_pp");
return helpTopics;
}
// singleton accessor implementation
std::map<tString, eHelpTopic> & eHelpTopic::GetHelpTopics()
{
static std::map<tString, eHelpTopic> & helpTopics = FillHelpTopics();
return helpTopics;
}
static tConfItemFunc add_help_topic_conf("ADD_HELP_TOPIC",&eHelpTopic::addHelpTopic);
static tConfItemFunc remove_help_topic_conf("REMOVE_HELP_TOPIC",&eHelpTopic::removeHelpTopic);
static tString se_helpIntroductoryBlurb;
static tConfItemLine se_helpIntroductoryBlurbConf("HELP_INTRODUCTORY_BLURB",se_helpIntroductoryBlurb);
static void se_Help( ePlayerNetID * sender, ePlayerNetID * receiver, std::istream & s )
{
std::ws(s);
tColoredString reply;
if(s.eof() || s.fail())
{
if(se_helpIntroductoryBlurb.Len() > 1)
{
reply << se_helpIntroductoryBlurb << "\n\n";
}
eHelpTopic::listTopics(reply);
}
else
{
tString name;
s >> name;
eHelpTopic::printTopic(reply, name);
}
if ( sender == receiver )
{
// just send a console message, the player asked for help himself
sn_ConsoleOut(reply, receiver->Owner());
}
else
{
// send help disguised as a chat message (with disabled spam limit)
int spamMaxLenBack = se_SpamMaxLen;
se_SpamMaxLen = 0;
se_SendChatLine(sender, reply, reply, receiver->Owner());
se_SpamMaxLen = spamMaxLenBack;
}
}
static void se_HelpFunc(std::istream &s)
{
ePlayerNetID *p = 0;
if (se_helpMessageType)
{
sn_ConsoleOut(se_helpMessage + "\n", p->Owner());
}
else se_Help( p, p, s );
}
static tConfItemFunc se_HelpFuncConf("HELP", &se_HelpFunc);
static tAccessLevel se_rtfmAccessLevel = tAccessLevel_Moderator;
static tSettingItem< tAccessLevel > se_rtfmAccessLevelConf( "ACCESS_LEVEL_RTFM", se_rtfmAccessLevel );
static tAccessLevelSetter se_rtfmAccessLevelConfLevel( se_rtfmAccessLevelConf, tAccessLevel_Owner );
#ifdef DEDICATED
static void se_Rtfm( tString const &command, ePlayerNetID *p, std::istream &s, eChatSpamTester &spam )
{
#ifdef KRAWALL_SERVER
if ( p->GetAccessLevel() > se_rtfmAccessLevel )
{
sn_ConsoleOut(tOutput("$access_level_rtfm_denied", tCurrentAccessLevel::GetName(se_rtfmAccessLevel), tCurrentAccessLevel::GetName(p->GetAccessLevel())), p->Owner());
return;
}
#else
if (!p->IsLoggedIn())
{
sn_ConsoleOut(tOutput("$rtfm_denied"));
return;
}
#endif
if(IsSilencedWithWarning(p))
{
return;
}
if(spam.Block())
{
return;
}
ePlayerNetID *newbie = se_FindPlayerInChatCommand(p, command, s);
if(newbie)
{
// somewhat hacky, but what the hack...
tString str;
str.ReadLine(s);
std::istringstream s1(&str(0)), s2(&str(0));
tColoredString name;
name << *p << tColoredString::ColorString(1,1,1);
tColoredString newbie_name;
newbie_name << *newbie << tColoredString::ColorString(1,1,1);
tString announcement( tOutput("$rtfm_announcement", str, name, newbie_name) );
se_BroadcastChatLine( p, announcement, announcement );
con << announcement;
se_Help(p, newbie, s1);
// avoid sending you the same doc twice if you tell yourself to rtfm :)
if ( newbie != p )
{
se_Help(p, p, s2);
}
}
}
#endif
#if defined(DEDICATED) && defined(KRAWALL_SERVER)
void se_ListAdmins( ePlayerNetID *, std::istream &s, tString command );
#endif
tString customInvalidCommands("");
static tSettingItem<tString> customInvalidCommandsConf("CUSTOM_INVALID_COMMANDS", customInvalidCommands);
static eLadderLogWriter se_customInvalidCommandWriter("CUSTOM_INVALID_COMMAND", false);
#ifdef DEDICATED
static bool sn_ClientDownloadSettings = true;
static tSettingItem<bool> sn_ClientDownloadSettingsConf("CLIENT_DOWNLOAD_SETTINGS", sn_ClientDownloadSettings);
#endif
void handle_chat( nMessage &m )
{
nTimeRolling currentTime = tSysTimeFloat();
unsigned short id;
m.Read(id);
tColoredString say;
m >> say;
tJUST_CONTROLLED_PTR< ePlayerNetID > p=dynamic_cast<ePlayerNetID *>(nNetObject::ObjectDangerous(id));
// register player activity
if ( p )
p->lastActivity_ = currentTime;
if(sn_GetNetState()==nSERVER)
{
if (p)
{
// for the duration of this function, set the access level to the level of the user.
tCurrentAccessLevel levelOverride( p->GetAccessLevel(), true );
// check if the player is owned by the sender to avoid cheating
if( p->Owner() != m.SenderID() )
{
Cheater( m.SenderID() );
nReadError();
return;
}
eChatSpamTester spam( p, say );
if (say.StartsWith("/"))
{
std::string sayStr(say);
std::istringstream s(sayStr);
tString command;
s >> command;
// filter to lowercase
tToLower( command );
tConfItemBase::EatWhitespace(s);
// now, s is ready for reading the rest of the message.
#ifdef DEDICATED
if (se_InterceptCommands.StrPos(command) != -1)
{
handle_command_intercept(p, command, s, say);
return;
}
else
#endif
if (command == "/me")
{
spam.lastSaidType_ = eChatMessageType_Me;
spam.say_ = spam.say_.SubStr(4); // cut /me prefix
se_ChatMe( p, s, spam );
return;
}
else if (command == "/teamname")
{
tString teamname(((const char*)say)+10);
p->SetTeamname(teamname);
return;
}
else if (command == "/teamleave")
{
spam.lastSaidType_ = eChatMessageType_Command;
se_ChatTeamLeave( p );
return;
}
else if (command == "/teamshuffle" || command == "/shuffle")
{
spam.lastSaidType_ = eChatMessageType_Command;
se_ChatShuffle( p, s );
return;
}
#ifdef KRAWALL_SERVER
else if (command == "/substitute" || command == "/sub")
{
spam.lastSaidType_ = eChatMessageType_Command;
se_ChatSubstitute( p, s );
return;
}
#endif
else if (command == "/team")
{
spam.lastSaidType_ = eChatMessageType_Team;
se_ChatTeam( p, s, spam );
return;
}
else if (command == "/enemy" || command == "/enemies")
{
spam.lastSaidType_ = eChatMessageType_Public;
se_ChatEnemy( p, s, spam );
return;
}
else if (command == "/chat")
{
spam.lastSaidType_ = eChatMessageType_Public;
se_ChatPlayer( p, s, spam );
return;
}
else if (command == "/report")
{
spam.factor_ = 1;
if ( spam.Block() )
{
return;
}
spam.lastSaidType_ = eChatMessageType_Public;
se_ChatReport( p, s );
return;
}
else if (command == "/reports")
{
spam.lastSaidType_ = eChatMessageType_Public;
se_ChatReadReport( p, s );
return;
}
else if (command == "/msg")
{
spam.lastSaidType_ = eChatMessageType_Private;
se_ChatMsg( p, s, spam );
return;
}
else if (command == "/shout")
{
spam.lastSaidType_ = eChatMessageType_Public;
spam.say_ = spam.say_.SubStr(7); // cut /shout prefix
se_ChatShout( p, s, spam );
return;
}
else if ((command == "/drop") && (se_ctfcommands != 0))
{
spam.lastSaidType_= eChatMessageType_Command;
p->DropFlag();
return;
}
else if ((command == "/pass") && (se_ctfcommands != 0))
{
spam.lastSaidType_= eChatMessageType_Command;
p->PassFlag(s);
return;
}
else if (command == "/players" || command == "/listplayers")
{
spam.lastSaidType_= eChatMessageType_Command;
se_ChatPlayers( p, s, command );
return;
}
#if defined(DEDICATED) && defined(KRAWALL_SERVER)
else if (command == "/admins" || command == "/listadmins")
{
spam.lastSaidType_ = eChatMessageType_Command;
se_ListAdmins( p, s, command );
return;
}
#endif
else if (command == "/vote" || command == "/callvote")
{
spam.lastSaidType_ = eChatMessageType_Command;
eVoter::HandleChat( p, s );
return;
}
else if (command == "/teams")
{
spam.lastSaidType_ = eChatMessageType_Command;
se_ChatTeams( p );
return;
}
else if (command == "/myteam")
{
spam.lastSaidType_ = eChatMessageType_Command;
eTeam *currentTeam = se_GetManagedTeam( p );
if( currentTeam )
{
se_ListTeam( p, currentTeam );
}
return;
}
else if (command == "/help")
{
spam.lastSaidType_ = eChatMessageType_Command;
if (se_helpMessageType)
{
sn_ConsoleOut(se_helpMessage + "\n", p->Owner());
}
else se_Help( p, p, s );
return;
}
// the commands below (mp and cq) are the ones to use for add/remove/list items in the queueing list
else if (((command == "/mq") || (command == "/cq") || (command == "/ms") || (command == "/cs") || (command == "/q")) && (rotationtype != gROTATION_NEVER))
{
sg_AddqueueingItems(p, s, command);
return;
}
// commands below are for displaying items in map rotation (mr) or config rotation (cr)
else if (((command == "/mr") || (command == "/msr") || (command == "/cr") || (command == "/csr")) && (rotationtype != gROTATION_NEVER))
{
sg_DisplayRotationList(p, s, command);
return;
}
else if ((command == "/qs") && (rotationtype != gROTATION_NEVER))
{
QueueShowPlayer(p);
return;
}
else if ((command == "/rotation") && (rotationtype != gROTATION_NEVER))
{
RotationShowPlayer(p, s);
return;
}
#ifdef DEDICATED
// download the server settings
else if (command == "/dlsettings")
{
if (sn_ClientDownloadSettings)
tConfItemBase::DownloadSettings_To(p->Owner());
else
sn_ConsoleOut("Clients are not allowed to download server settings.\n", p->Owner());
return;
}
// download the public config files
else if ((command == "/dlcfg") || (command == "/getcfg"))
{
tString configFile;
s >> configFile;
tConfItemBase::DownloadConfig_To(configFile, p->Owner());
return;
}
else if ( command == "/rtfm" || command == "/teach" )
{
spam.lastSaidType_ = eChatMessageType_Command;
se_Rtfm( command, p, s, spam );
return;
}
else
{
spam.lastSaidType_ = eChatMessageType_Command;
handle_chat_admin_commands( p, command, say, s, spam );
return;
}
#endif
}
else
{
std::string sayStr(say);
std::istringstream s(sayStr);
tString chat_command;
s >> chat_command;
// filter to lowercase
tToLower( chat_command );
tConfItemBase::EatWhitespace(s);
if (chat_command == "!race")
{
if (!sg_RaceTimerEnabled)
{
tString message;
message << "0xff7777RACE_TIMER_ENABLED must be enabled to use this command.\n";
sn_ConsoleOut(message, p->Owner());
return;
}
tString command;
s >> command;
gRace::RaceChat(p, command, s);
return;
}
else
{
if (customInvalidCommands != "")
{
tArray<tString>invalidCommands = customInvalidCommands.Split(";");
if (invalidCommands.Len() > 0)
{
for(int i = 0; i < invalidCommands.Len(); i++)
{
tString cmdExt = invalidCommands[i];
if ((cmdExt != "") && chat_command.StartsWith(cmdExt))
{
tString params;
params.ReadLine(s);
se_customInvalidCommandWriter << chat_command << p->GetUserName() << nMachine::GetMachine(p->Owner()).GetIP() << p->GetAccessLevel() << params;
se_customInvalidCommandWriter.write();
return;
}
}
}
}
}
}
// well, that leaves only regular, boring chat.
eShoutDefault shout = se_GetManagedTeam( p ) ? se_shoutPlayer : se_shoutSpectator;
if( shout != eShoutDefault_Team && se_CheckAccessLevelShoutNoWarn( p ) )
{
// if it's the default and the player is allowed to, shout it out
se_ChatShout( p, say, spam );
}
else
{
// otherwise, fall back to team chat.
se_ChatTeam( p, say, spam );
}
}
}
else
{
se_DisplayChatLocally( p, say );
}
}
// check if a string is a legal player name
// a name is only legal if it contains at least one non-witespace character.
static bool IsLegalPlayerName( tString const & name )
{
tString userName = se_UnauthenticatedUserName( name );
if ( userName.Len() <= 1 )
return false;
// strip colors
tString stripped( tColoredString::RemoveColors( name ) );
// and count non-whitespace characters
for ( int i = stripped.Len()-2; i>=0; --i )
{
if ( !isblank( stripped(i) ) )
return true;
}
return false;
}
void ePlayerNetID::Chat(const tString &s_orig)
{
tColoredString s( s_orig );
s.NetFilter();
#ifndef DEDICATED
// check for direct console commands
if( s_orig.StartsWith("/console") )
{
// direct commands are executed at owner level
tCurrentAccessLevel level( tAccessLevel_Owner, true );
tString params("");
if (s_orig.StrPos(" ") == -1)
return;
else
params = s_orig.SubStr(s_orig.StrPos(" ") + 1);
if ( tRecorder::IsPlayingBack() )
{
tConfItemBase::LoadPlayback();
}
else
{
std::stringstream s(static_cast< char const * >( params ) );
tConfItemBase::LoadAll(s);
}
}
//Not sure if this is a good short handle. Maybe something like /colors? Then introduce the basic list if no parameters are sent, but if a players name is sent give that players colors alone.
else if( s_orig.StartsWith("/listcolors") || s_orig.StartsWith("/colors") )
{
con << "Player Colors: \n";
se_listPlayerColors();
}
else
#endif
{
tString retStr(s);
if (eBannedWords::BadWordTrigger(this, retStr))
return;
s = tColoredString(retStr);
switch (sn_GetNetState())
{
case nCLIENT:
{
se_NewChatMessage( this, s )->BroadCast();
break;
}
case nSERVER:
{
se_BroadcastChat( this, s );
// falling through on purpose
// break;
}
default:
{
se_DisplayChatLocally( this, s );
break;
}
}
}
}
//return the playernetid for a given name
/*
static ePlayerNetID* identifyPlayer(tString inname)
{
for(int i=0; i<se_PlayerNetIDs.Len(); i++)
{
ePlayerNetID *p = se_PlayerNetIDs[i];
if( inname == p->GetUserName() )
return p;
}
return NULL;
}
*/
// identify a local player
ePlayerNetID *se_GetLocalPlayer()
{
for(int i=0; i<se_PlayerNetIDs.Len(); i++)
{
ePlayerNetID *p = se_PlayerNetIDs[i];
if( p->Owner() == sn_myNetID )
return p;
}
return NULL;
}
static tString sg_AdminName("Admin");
bool restrictAdminName(tString const &newValue)
{
tString filteredname = newValue.Filter();
if (filteredname != "")
return true;
else
return false;
}
static tSettingItem<tString> sg_AdminNameConf("ADMIN_NAME", sg_AdminName, &restrictAdminName);
static void ConsoleSay_conf(std::istream &s)
{
// read the message
tString message;
message.ReadLine( s, true );
switch (sn_GetNetState())
{
case nCLIENT:
{
ePlayerNetID *me = se_GetLocalPlayer();
if (me)
me->Chat( message );
break;
}
case nSERVER:
{
tColoredString send;
send << tColoredString::ColorString( 1,0,0 );
send << sg_AdminName;
send << tColoredString::ColorString( 1,1,.5 );
send << ": " << message << "\n";
// display it
sn_ConsoleOut( send );
se_SaveToChatLog(sg_AdminName + " " + message);
se_SaveToChatLogC(send);
break;
}
default:
{
ePlayerNetID *me = se_GetLocalPlayer();
if ( me )
se_DisplayChatLocally( me, message );
break;
}
}
}
static tConfItemFunc ConsoleSay_c("SAY",&ConsoleSay_conf);
static void ConsoleSpeakAsAdmin_conf(std::istream &s)
{
// read the message
tString message;
message.ReadLine( s, true );
switch (sn_GetNetState())
{
case nCLIENT:
{
ePlayerNetID *me = se_GetLocalPlayer();
if (me)
me->Chat( message );
break;
}
case nSERVER:
{
tColoredString send;
send << tColoredString::ColorString( 1,0,0 );
send << "Admin";
send << tColoredString::ColorString( 1,1,.5 );
send << ": " << message << "\n";
// display it
sn_ConsoleOut( send );
break;
}
default:
{
ePlayerNetID *me = se_GetLocalPlayer();
if ( me )
se_DisplayChatLocally( me, message );
break;
}
}
}
static tConfItemFunc ConsoleSpeakAsAdmin_c("SPEAK_AS_ADMIN",&ConsoleSpeakAsAdmin_conf);
static void ConsoleEnemy_conf(std::istream &s)
{
// read the message
tString message;
message.ReadLine( s, true );
switch (sn_GetNetState())
{
case nCLIENT:
{
ePlayerNetID *me = se_GetLocalPlayer();
if (me)
me->Chat( message );
break;
}
case nSERVER:
{
tColoredString send;
send << tColoredString::ColorString( 1,0,0 );
send << "Admin";
send << tColoredString::ColorString( 1,1,.5 );
send << " --> ";
send << tColoredString::ColorString( 1,0,0 );
send << "Enemies";
send << tColoredString::ColorString( 1,1,.5 );
send << ": " << message << "\n";
// display it
sn_ConsoleOut( send );
break;
}
default:
{
ePlayerNetID *me = se_GetLocalPlayer();
if ( me )
se_DisplayChatLocally( me, message );
break;
}
}
}
static tConfItemFunc ConsoleEnemy_c("SPEAK_TO_ENEMIES",&ConsoleEnemy_conf);
static void ConsoleEveryone_conf(std::istream &s)
{
// read the message
tString message;
message.ReadLine( s, true );
switch (sn_GetNetState())
{
case nCLIENT:
{
ePlayerNetID *me = se_GetLocalPlayer();
if (me)
me->Chat( message );
break;
}
case nSERVER:
{
tColoredString send;
send << tColoredString::ColorString( 1,0,0 );
send << "Admin";
send << tColoredString::ColorString( 1,1,.5 );
send << " --> ";
send << tColoredString::ColorString( 0,1,1 );
send << "Everyone";
send << tColoredString::ColorString( 1,1,.5 );
send << ": " << message << "\n";
// display it
sn_ConsoleOut( send );
break;
}
default:
{
ePlayerNetID *me = se_GetLocalPlayer();
if ( me )
se_DisplayChatLocally( me, message );
break;
}
}
}
static tConfItemFunc ConsoleEveryone_c("SPEAK_TO_EVERYONE",&ConsoleEveryone_conf);
static void ConsoleAnnounce_conf(std::istream &s)
{
// read the message
tString message;
message.ReadLine( s, true );
switch (sn_GetNetState())
{
case nCLIENT:
{
ePlayerNetID *me = se_GetLocalPlayer();
if (me)
me->Chat( message );
break;
}
case nSERVER:
{
tColoredString send;
send << tColoredString::ColorString( 0,0.5,1 );
send << "Announcement";
send << tColoredString::ColorString( 1,1,.5 );
send << ": ";
send << tColoredString::ColorString( 1,1,.5 );
send << message << "\n";
// display it
sn_ConsoleOut( send );
break;
}
default:
{
ePlayerNetID *me = se_GetLocalPlayer();
if ( me )
se_DisplayChatLocally( me, message );
break;
}
}
}
static tConfItemFunc ConsoleAnnounce_c("ANNOUNCE",&ConsoleAnnounce_conf);
struct eChatInsertionCommand
{
tString insertion_;
eChatInsertionCommand( tString const & insertion )
: insertion_( insertion )
{}
};
bool se_tabCompletion = true;
bool se_tabCompletionWithColors = false;
static char const * const se_chatNormalCommands[] = {
"/msg ",
"/invite ",
"/uninvite ",
"/teach ",
"/rtfm ",
"/op ",
"/deop ",
"/vote kick ",
"/vote suspend ",
"/players "
};
static char const * const se_chatCmdCommands[] = {
"/admin ",
"/console "
};
//! The tab completion function for in-chat mode
static void ChatTabCompletition(tString &strString, int &curserPos)
{
if (!se_tabCompletion) return;
tArray<tString> msgsExt = strString.Split(" ");
tArray<ePlayerNetID *> foundPlayers;
tString newString;
tColoredString breaker;
breaker << tColoredString::ColorString(1,1,.5);
int cusPos = 0;
bool isFirst = true;
bool isChat = false;
bool isAdmin = false;
int i = 0;
for (i = sizeof(se_chatNormalCommands)/sizeof(se_chatNormalCommands[0]) - 1; i >= 0; --i)
{
if (strString.StartsWith(se_chatNormalCommands[i]))
{
isChat = true;
break;
}
}
i = 0;
for (i = sizeof(se_chatCmdCommands)/sizeof(se_chatCmdCommands[0]) - 1; i >= 0; --i)
{
if (strString.StartsWith(se_chatCmdCommands[i]))
{
isAdmin = true;
break;
}
}
for(int i = 0; i < msgsExt.Len(); i++)
{
tString word = msgsExt[i];
cusPos += word.Len() - 1;
if (cusPos == curserPos)
{
if (isAdmin)
{
tString found_command = tConfItemBase::FindConfigItem(word.Filter());
if (found_command != "")
word = found_command + " ";
}
else
{
ePlayerNetID *p = NULL;
//p = ePlayerNetID::FindPlayerByName(word);
for(int j = 0; j < se_PlayerNetIDs.Len(); j++)
{
p = se_PlayerNetIDs[j];
if (p && p->IsActive())
{
if (p->GetName().Filter().Contains(word.Filter()))
{
foundPlayers.Insert(p);
continue;
}
if (p->GetLogName().Filter().Contains(word.Filter()))
{
foundPlayers.Insert(p);
continue;
}
}
}
if (foundPlayers.Len() == 1)
{
p = foundPlayers[0];
if (p && p->IsActive())
{
if (isFirst && !isChat)
word = (se_tabCompletionWithColors ? p->GetColoredName() + breaker : p->GetName()) + ": ";
else
word = (se_tabCompletionWithColors ? p->GetColoredName() + breaker : p->GetName()) + " ";
}
}
else if (foundPlayers.Len() > 1)
{
for(int k = 0; k < foundPlayers.Len(); k++)
{
p = foundPlayers[k];
if (p && p->IsActive() && p->GetName().Filter() == word.Filter())
{
if (isFirst && !isChat)
word = (se_tabCompletionWithColors ? p->GetColoredName() + breaker : p->GetName()) + ": ";
else
word = (se_tabCompletionWithColors ? p->GetColoredName() + breaker : p->GetName()) + " ";
break;
}
}
}
}
}
cusPos++;
if ((i + 1) == msgsExt.Len())
newString << word;
else
newString << word << " ";
if ((i > 0) && isFirst) isFirst = false;
}
strString = newString;
curserPos = newString.Len();
}
static bool se_displayScoresDuringChat = false;
bool se_BlockScores = false;
static tConfItem<bool> se_displayScoresDuringChatConf("DISPLAY_SCORES_DURING_CHAT", se_displayScoresDuringChat);
static std::deque<tString> se_chatHistory; // global since the class doesn't live beyond the execution of the command
static int se_chatHistoryMaxSize=10; // maximal size of chat history
static tSettingItem< int > se_chatHistoryMaxSizeConf("HISTORY_SIZE_CHAT",se_chatHistoryMaxSize);
class eMenuItemChat : uMenuItemStringWithHistory
{
ePlayer *me;
public:
eMenuItemChat(uMenu *M,tString &c,ePlayer *Me):
uMenuItemStringWithHistory(M,"$chat_title_text","",c, se_SpamMaxLen, se_chatHistory, se_chatHistoryMaxSize),me(Me) {}
virtual ~eMenuItemChat() { }
//virtual void Render(REAL x,REAL y,REAL alpha=1,bool selected=0);
virtual bool Event(SDL_Event &e)
{
#ifndef DEDICATED
if (e.type==SDL_KEYDOWN &&
(e.key.keysym.sym==SDLK_KP_ENTER || e.key.keysym.sym==SDLK_RETURN))
{
for(int i=se_PlayerNetIDs.Len()-1; i>=0; i--)
{
ePlayerNetID *p =se_PlayerNetIDs[i];
if (p && (p->pID == me->ID()))
{
p->Chat(*content);
break;
}
}
se_BlockScores = false;
MyMenu()->Exit();
return true;
}
else if (e.type == SDL_KEYDOWN && e.key.keysym.sym == SDLK_TAB)
{
ChatTabCompletition(*content, cursorPos);
}
else if (e.type==SDL_KEYDOWN &&
uActionGlobal::IsBreakingGlobalBind(e.key.keysym.sym))
{
return su_HandleEvent(e, true);
}
else if (e.type==SDL_KEYDOWN &&
e.key.keysym.sym == SDLK_ESCAPE)
{
// escape needs to be handled by the surrounding menu, otherwise it
// probably brings up the ingame menu via global bind.
se_BlockScores = false;
return false;
}
else
{
if ( uMenuItemStringWithHistory::Event(e) )
{
return true;
}
// exclude modifier keys from possible control triggers
else if ( e.key.keysym.sym < SDLK_NUMLOCK || e.key.keysym.sym > SDLK_COMPOSE )
{
if (!se_displayScoresDuringChat)
se_BlockScores = true;
// maybe it's an instant chat button?
try
{
return su_HandleEvent(e, false);
}
catch ( eChatInsertionCommand & insertion )
{
if ( content->Len() + insertion.insertion_.Len() <= maxLength_ )
{
*content = content->SubStr( 0, cursorPos ) + insertion.insertion_ + content->SubStr( cursorPos );
cursorPos += insertion.insertion_.Len()-1;
}
return true;
}
}
}
#endif // DEDICATED
return false;
}
};
void se_ChatState(ePlayerNetID::ChatFlags flag, bool cs)
{
for(int i=se_PlayerNetIDs.Len()-1; i>=0; i--)
{
ePlayerNetID *p = se_PlayerNetIDs[i];
if (p->Owner()==sn_myNetID && p->pID >= 0)
{
p->SetChatting( flag, cs );
}
}
}
static ePlayer * se_chatterPlanned=NULL;
static ePlayer * se_chatter =NULL;
static tString se_say;
static void do_chat()
{
if (se_chatterPlanned)
{
su_ClearKeys();
se_chatter=se_chatterPlanned;
se_chatterPlanned=NULL;
se_ChatState( ePlayerNetID::ChatFlags_Chat, true);
sr_con.SetHeight(15,false);
se_SetShowScoresAuto(false);
uMenu chat_menu("",false);
eMenuItemChat s(&chat_menu,se_say,se_chatter);
chat_menu.SetCenter(-.75);
chat_menu.SetBot(-2);
chat_menu.SetTop(-.7);
chat_menu.Enter();
se_ChatState( ePlayerNetID::ChatFlags_Chat, false );
sr_con.SetHeight(7,false);
se_SetShowScoresAuto(true);
}
se_chatter=NULL;
se_chatterPlanned=NULL;
}
static void chat( ePlayer * chatter, tString const & say )
{
se_chatterPlanned = chatter;
se_say = say;
st_ToDo(&do_chat);
}
static void chat( ePlayer * chatter )
{
chat( chatter, tString() );
}
static bool se_allowControlDuringChat = false;
static nSettingItem<bool> se_allowControlDuringChatConf("ALLOW_CONTROL_DURING_CHAT",se_allowControlDuringChat);
uActionPlayer se_toggleSpectator("TOGGLE_SPECTATOR", -7);
bool ePlayer::Act(uAction *act,REAL x)
{
eGameObject *object=NULL;
if ( act == &se_toggleSpectator && x > 0 )
{
spectate = !spectate;
con << tOutput(spectate ? "$player_toggle_spectator_on" : "$player_toggle_spectator_off", name );
if ( !spectate )
{
ePlayerNetID::Update();
}
return true;
}
else if (!se_chatter && s_chat==*reinterpret_cast<uActionPlayer *>(act))
{
if(x>0)
{
chat( this );
}
return true;
}
else
{
if ( x > 0 )
{
int i;
uActionPlayer* pact = reinterpret_cast<uActionPlayer *>(act);
for(i = MAX_INSTANT_CHAT - 1; i >= 0; i--)
{
uActionPlayer* pcompare = se_instantChatAction[i];
if (pact == pcompare && x>=0)
{
for(int j = se_PlayerNetIDs.Len() - 1; j >= 0; j--)
{
if (se_PlayerNetIDs(j)->pID==ID())
{
tString say = instantChatString[i];
bool sendImmediately = true;
if ( say.Len() > 2 && say[say.Len()-2] == '\\' )
{
// cut away trailing slash and note for later
// that the message should not be sent immediately.
say = say.SubStr( 0, say.Len()-2 );
sendImmediately = false;
}
if ( se_chatter == this )
{
if (!se_displayScoresDuringChat)
se_BlockScores = true;
else
se_BlockScores = false;
// a chat is already active, insert the chat string
throw eChatInsertionCommand( say );
}
else
{
if ( sendImmediately )
{
// fire out chat string immediately
se_PlayerNetIDs(j)->Chat(say);
}
else
{
// chat with instant chat string as template
chat( this, say );
}
se_BlockScores = false;
}
return true;
}
}
}
}
}
// no other command should get through during chat
if ( se_chatter && !se_allowControlDuringChat )
return false;
int i;
for(i=se_PlayerNetIDs.Len()-1; i>=0; i--)
if (se_PlayerNetIDs[i]->pID==id && se_PlayerNetIDs[i]->object)
object=se_PlayerNetIDs[i]->object;
bool objectAct = false; // set to true if an action of the object was triggered
bool ret = ((cam && cam->Act(reinterpret_cast<uActionCamera *>(act),x)) ||
( objectAct = (object && se_GameTime()>=0 && object->Act(reinterpret_cast<uActionPlayer *>(act),x))));
if (bool(netPlayer) && (objectAct || !se_chatter))
netPlayer->Activity();
return ret;
}
}
rViewport * ePlayer::PlayerViewport(int p)
{
if (!PlayerConfig(p)) return NULL;
for (int i=rViewportConfiguration::CurrentViewportConfiguration()->num_viewports-1; i>=0; i--)
if (sr_viewportBelongsToPlayer[i] == p)
return rViewportConfiguration::CurrentViewport(i);
return NULL;
}
bool ePlayer::PlayerIsInGame(int p)
{
return PlayerViewport(p) && PlayerConfig(p);
}
// veto function for tooltips that require a controllable game object
bool ePlayer::VetoActiveTooltip(int player)
{
// check if the player exists and controls a living object
if( player == 0 )
{
return true;
}
ePlayer * p = PlayerConfig(player-1);
if ( !p )
{
return true;
}
ePlayerNetID * pn = p->netPlayer;
if ( !pn )
{
return true;
}
eNetGameObject *o = pn->Object();
if (!o || !o->Alive())
{
return true;
}
return false;
}
static tConfItemBase *vpbtp[MAX_VIEWPORTS];
void ePlayer::Init()
{
se_Players = tNEW( ePlayer[MAX_PLAYERS] );
int i;
for(i=MAX_INSTANT_CHAT-1; i>=0; i--)
{
tString id;
id << "INSTANT_CHAT_";
id << i+1;
tOutput desc;
desc.SetTemplateParameter(1, i+1);
desc << "$input_instant_chat_text";
tOutput help;
help.SetTemplateParameter(1, i+1);
help << "$input_instant_chat_help";
ePlayer::se_instantChatAction[i]=tNEW(uActionPlayer) (id, desc, help, 100);
//,desc, "Issues a special instant chat macro.");
}
for(i=MAX_VIEWPORTS-1; i>=0; i--)
{
tString id;
id << "VIEWPORT_TO_PLAYER_";
id << i+1;
vpbtp[i] = tNEW(tConfItem<int>(id,"$viewport_belongs_help",
s_newViewportBelongsToPlayer[i]));
s_newViewportBelongsToPlayer[i]=i;
}
}
void ePlayer::Exit()
{
int i;
for(i=MAX_INSTANT_CHAT-1; i>=0; i--)
tDESTROY(ePlayer::se_instantChatAction[i]);
for(i=MAX_VIEWPORTS-1; i>=0; i--)
tDESTROY(vpbtp[i]);
delete[] se_Players;
se_Players = NULL;
}
uActionPlayer ePlayer::s_chat("CHAT",-8);
// only display chat in multiplayer games
static bool se_ChatTooltipVeto(int)
{
return sn_GetNetState() == nSTANDALONE;
}
uActionTooltip ePlayer::s_chatTooltip(ePlayer::s_chat, 1, &se_ChatTooltipVeto);
uActionTooltip s_toggleSpectatorTooltip(se_toggleSpectator, 1, &se_ChatTooltipVeto);
int pingCharity = 100;
static const int maxPingCharity = 300;
static void sg_ClampPingCharity( int & pingCharity )
{
if (pingCharity < 0 )
pingCharity = 0;
if (pingCharity > maxPingCharity )
pingCharity = maxPingCharity;
}
static void sg_ClampPingCharity( unsigned short & pingCharity )
{
if (pingCharity > maxPingCharity )
pingCharity = maxPingCharity;
}
static void sg_ClampPingCharity()
{
sg_ClampPingCharity( ::pingCharity );
}
static int IMPOSSIBLY_LOW_SCORE=(-1 << 31);
static nSpamProtectionSettings se_chatSpamSettings( 1.0f, "SPAM_PROTECTION_CHAT", tOutput("$spam_protection") );
class eMachineDecoratorSpam: public nMachineDecorator
{
public:
nSpamProtection chatSpam;
eShuffleSpamTester shuffleSpam;
eChatLastSaid lastSaid;
eMachineDecoratorSpam( nMachine & m ): nMachineDecorator( m ), chatSpam( se_chatSpamSettings ) {}
virtual void OnDestroy()
{
delete this;
}
virtual void OnBan()
{
// Don't punish the player with restrictive spam checks when they
// return from their ban.
chatSpam.ResetSpam();
}
};
static eMachineDecoratorSpam & se_GetSpam( ePlayerNetID & p )
{
nMachine & machine = p.GetMachine();
eMachineDecoratorSpam * spam = machine.GetDecorator< eMachineDecoratorSpam >();
if( !spam )
{
spam = tNEW(eMachineDecoratorSpam)( machine );
}
return *spam;
}
nSpamProtection & ePlayerNetID::GetChatSpam()
{
return se_GetSpam( *this ).chatSpam;
}
eChatLastSaid & ePlayerNetID::GetLastSaid()
{
return se_GetSpam( *this ).lastSaid;
}
eShuffleSpamTester & ePlayerNetID::GetShuffleSpam()
{
return se_GetSpam( *this ).shuffleSpam;
}
struct LastChatData
{
LastChatData(nMachine const & machine_, eChatSaidEntry const & entry_)
:machine(&machine_), entry(&entry_)
{
}
nMachine const * machine;
eChatSaidEntry const * entry;
};
void se_ListPastChatters(ePlayerNetID * receiver)
{
static const unsigned int MaxReport = 3;
std::vector<LastChatData> report;
// list dead connections
for(nMachine::iterator m; m.Valid(); ++m)
{
nMachine & machine = *m;
eMachineDecoratorSpam * spam = machine.GetDecorator<eMachineDecoratorSpam>();
if(spam && spam->lastSaid.Disconnected())
{
eChatLastSaid::SaidList const & said = spam->lastSaid.LastSaid();
eChatSaidEntry const * recentLastSaid = NULL;
for(int i = said.size()-1; i >= 0; --i)
{
eChatSaidEntry const & lastSaid = said[i];
if(lastSaid.Type() != eChatMessageType_Team && lastSaid.Type() != eChatMessageType_Private)
{
if(!recentLastSaid || recentLastSaid->Time() < lastSaid.Time())
recentLastSaid = &lastSaid;
}
}
if(recentLastSaid)
{
// mark chat spam as disconnected
se_GetSpam(*receiver).lastSaid.MarkDisconnected();
// put report in list
report.push_back(LastChatData(machine, *recentLastSaid));
// let it bubble up
for(int j = report.size()-1; j > 0; --j)
{
if(report[j].entry->Time() > report[j-1].entry->Time())
{
std::swap(report[j-1], report[j]);
}
}
// cull reports
if(report.size() > MaxReport)
report.pop_back();
}
}
}
// and print
if(report.size() > 0)
{
sn_ConsoleOut( tOutput( "$player_list_disconnected" ), receiver->Owner() );
}
for(std::vector<LastChatData>::iterator iter = report.begin(); iter != report.end(); ++iter)
{
tColoredString line;
LastChatData const & data = *iter;
eChatSaidEntry const & lastSaid = *(data.entry);
if ( tCurrentAccessLevel::GetAccessLevel() <= se_ipAccessLevel )
{
tString IP = data.machine->GetIP();
if ( IP.Len() > 1 )
{
line << "IP = " << IP << "; ";
}
}
line << lastSaid.PlayerName() << ": " << lastSaid.Said() << "\n";
sn_ConsoleOut( line, receiver->Owner() );
}
}
ePlayerNetID::ePlayerNetID(int p):nNetObject(),listID(-1), teamListID(-1), timeCreated_( tSysTimeFloat() ), allowTeamChange_(false), registeredMachine_(0), pID(p)
{
flagOverrideChat = false;
flagChatState = false;
// default access level
lastAccessLevel = tAccessLevel_Default;
favoriteNumberOfPlayersPerTeam = 1;
nameTeamAfterMe = false;
r = g = b = 15;
greeted = true;
chatting_ = false;
spectating_ = false;
stealth_ = false;
chatFlags_ = 0;
disconnected = false;
suspended_ = false;
roundsSuspended_ = 0;
suspendReason_ = "";
substitute = NULL;
loginWanted = false;
if (p>=0)
{
ePlayer *P = ePlayer::PlayerConfig(p);
if (P)
{
SetName( P->Name() );
teamname = P->Teamname();
r= P->rgb[0];
g= P->rgb[1];
b= P->rgb[2];
sg_ClampPingCharity();
pingCharity=::pingCharity;
loginWanted = P->autoLogin;
}
}
se_PlayerNetIDs.Add(this,listID);
object=NULL;
gRacePlayer *racePlayer = new gRacePlayer(this);
//sg_OutputOnlinePlayers();
/*
if(sn_GetNetState()!=nSERVER)
ping=sn_Connections[0].ping;
else
*/
ping=0; // hehe! server has no ping.
lastSync=tSysTimeFloat();
RequestSync();
score=0;
lastScore_=IMPOSSIBLY_LOW_SCORE;
// rubberstatus=0;
MyInitAfterCreation();
if(sn_GetNetState()==nSERVER)
RequestSync();
}
ePlayerNetID::ePlayerNetID(nMessage &m):nNetObject(m),listID(-1), teamListID(-1), timeCreated_( tSysTimeFloat() )
, allowTeamChange_(false), registeredMachine_(0)
{
flagOverrideChat = false;
flagChatState = false;
// default access level
lastAccessLevel = tAccessLevel_Default;
greeted =false;
chatting_ =false;
suspended_ = false;
roundsSuspended_ = 0;
suspendReason_ = "";
stealth_ =false;
disconnected=false;
chatFlags_ =0;
r = g = b = 15;
nameTeamAfterMe = false;
teamname = "";
substitute = NULL;
pID=-1;
se_PlayerNetIDs.Add(this,listID);
object=NULL;
gRacePlayer *racePlayer = new gRacePlayer(this);
//sg_OutputOnlinePlayers();
ping=sn_Connections[m.SenderID()].ping;
lastSync=tSysTimeFloat();
loginWanted = false;
score=0;
lastScore_=IMPOSSIBLY_LOW_SCORE;
// rubberstatus=0;
}
void ePlayerNetID::Activity()
{
// the player was active; therefore, he cannot possibly be chatting_ or disconnected.
// but do nothing if we are in client mode and the player is not local to this computer
if (sn_GetNetState() != nSERVER && Owner() != ::sn_myNetID)
return;
if (chatting_ || disconnected)
{
#ifdef DEBUG
con << *this << " showed activity and lost chat status.\n";
#endif
RequestSync();
}
chatting_ = disconnected = false;
// store time
this->lastActivity_ = tSysTimeFloat();
}
static int se_maxPlayersPerIP = 4;
static tSettingItem<int> se_maxPlayersPerIPConf( "MAX_PLAYERS_SAME_IP", se_maxPlayersPerIP );
// should unworthy spectators be kicked if the server is full?
static bool se_kickUnworthy=false;
tSettingItem< bool > se_kickUnworthyConf( "KEEP_PLAYER_SLOT", se_kickUnworthy );
// access level needed to grant immunity against all forms of idle kicks
static tAccessLevel se_autokickImmunity = tAccessLevel_TeamLeader;
static tSettingItem< tAccessLevel > se_autokickImmunityConf( "ACCESS_LEVEL_AUTOKICK_IMMUNITY", se_autokickImmunity );
// compares the worth of two players. Returns 1 if the first is better, -1 if the second is better, 0 if they are equal.
static int se_comparePlayerWorth( ePlayerNetID * a, ePlayerNetID * b, int nullPointerSign=1 )
{
// check for NULL pointers
if( !a )
{
if ( !b )
{
return 0;
}
else
{
return -nullPointerSign;
}
}
else
{
if ( !b )
{
return nullPointerSign;
}
}
// potential players > spectators
if ( !se_GetManagedTeam( a ) )
{
if( se_GetManagedTeam( b ) )
{
return -1;
}
}
else
{
if( !se_GetManagedTeam( b ) )
{
return 1;
}
}
// actual players > potential players
if ( !a->CurrentTeam() )
{
if( b->CurrentTeam() )
{
return -1;
}
}
else
{
if( !b->CurrentTeam() )
{
return 1;
}
}
// access level counts
#ifdef KRAWALL_SERVER
if( a->GetAccessLevel() < b->GetAccessLevel() )
{
return 1;
}
else if( a->GetAccessLevel() > b->GetAccessLevel() )
{
return -1;
}
#endif
// players with login process > players without
if( !nAuthentication::LoginInProcess( a ) )
{
if( nAuthentication::LoginInProcess( b ) )
{
return -1;
}
}
else
{
if( !nAuthentication::LoginInProcess( b ) )
{
return 1;
}
}
// players online for shorter times are more worthy
if( a->GetTimeCreated() < b->GetTimeCreated() )
{
return 1;
}
else if( a->GetTimeCreated() > b->GetTimeCreated() )
{
return 1;
}
return 0;
}
// the user that last logged in; spare him.
static int se_kickUnworthySpare=-1;
// clear out one unworthy spectator
static void se_KickUnworthy()
{
int userToSpare=se_kickUnworthySpare;
static REAL banForMinutes = 0;
static double roundBegin = -1;
double lastRoundBegin = roundBegin;
// each player joining increases the ban, rounds passing decrease it
if( userToSpare >= 0 )
{
banForMinutes += .05f;
}
else
{
banForMinutes *= 0.875;
roundBegin = tSysTimeFloat();
}
// nothing to do?
if( !se_kickUnworthy || sn_NumUsers() < sn_MaxUsers() )
{
return;
}
// find the most worthy player for each client
ePlayerNetID * mostWorthy[MAXCLIENTS+2];
for( int i = MAXCLIENTS+1; i >= 0; --i )
{
mostWorthy[i] = NULL;
}
for( int i = se_PlayerNetIDs.Len() - 1; i >=0; --i )
{
ePlayerNetID * p = se_PlayerNetIDs(i);
ePlayerNetID * & rival = mostWorthy[p->Owner()];
if( se_comparePlayerWorth( p, rival ) > 0 )
{
rival = p;
}
}
// find the most unworthy client
int mostUnworthyUser = 0;
for( int i = MAXCLIENTS; i >= 1; --i )
{
// NULL players are actually more worthy here now
ePlayerNetID * player = mostWorthy[i];
if( ( i != userToSpare && sn_Connections[i].socket ) &&
// don't kick players with immune access level
!( player && se_autokickImmunity >= player->GetAccessLevel() ) &&
// give players one round to sign in
!( player && nAuthentication::LoginInProcess(player) && player->GetTimeCreated() >= lastRoundBegin ) &&
( !mostUnworthyUser || se_comparePlayerWorth( mostWorthy[mostUnworthyUser], mostWorthy[i], -1 ) > 0 ) )
{
mostUnworthyUser = i;
}
}
// take care not to auto-kick someone with a high access level
if( mostUnworthyUser )
{
tString name;
ePlayerNetID * player = mostWorthy[mostUnworthyUser];
if( player )
{
mostWorthy[mostUnworthyUser]->PrintName( name );
}
else
{
name = "?";
}
con << tOutput( "$network_kill_unworthy_log", name, banForMinutes );
if( banForMinutes > 1 )
{
nMachine::GetMachine( mostUnworthyUser ).Ban( banForMinutes*60,
tString(
tOutput( "$network_kill_unworthy_banreason" ) ) );
sn_DisconnectUser( mostUnworthyUser, tOutput( "$network_kill_unworthy_ban", banForMinutes ) );
}
else
{
sn_DisconnectUser( mostUnworthyUser, tOutput( "$network_kill_unworthy" ) );
}
}
}
// array of players in legacy spectator mode: they have been
// deleted by their clients, but no new player has popped up for them yet
static tJUST_CONTROLLED_PTR< ePlayerNetID > se_legacySpectators[MAXCLIENTS+2];
static void se_ClearLegacySpectator( int owner )
{
ePlayerNetID * player = se_legacySpectators[ owner ];
// fully remove player
if ( player )
{
player->RemoveFromGame();
}
se_legacySpectators[ owner ] = NULL;
}
static void se_PlayerLoginLogoutCallback()
{
// clear the legacy spectator when a client enters or leaves
se_ClearLegacySpectator( nCallbackLoginLogout::User() );
// always keep one slot free
if( nCallbackLoginLogout::Login() )
{
se_kickUnworthySpare=nCallbackLoginLogout::User();
st_ToDo( se_KickUnworthy );
}
}
static nCallbackLoginLogout se_playerLoginLogoutCallback( se_PlayerLoginLogoutCallback );
void ePlayerNetID::MyInitAfterCreation()
{
this->CreateVoter();
this->silenced_ = se_silenceDefault;
this->renameAllowed_ = true;
// register with machine and kick user if too many players are present
if ( Owner() != 0 && sn_GetNetState() == nSERVER )
{
this->RegisterWithMachine();
// reset spam timer
GetChatSpam().ResetTime();
if ( se_maxPlayersPerIP < nMachine::GetMachine(Owner()).GetPlayerCount() )
{
// kill them
sn_DisconnectUser( Owner(), "$network_kill_too_many_players" );
// technically has the same effect as the above function, but we also want
// to abort registering this player object and this exception will do that as well.
throw nKillHim();
}
// clear old legacy spectator that may be lurking around
se_ClearLegacySpectator( Owner() );
// get silenced state and suspension count
eVoter *voter = eVoter::GetPersistentVoter( Owner() );
if ( voter )
{
suspended_ = voter->suspended_;
silenced_ = voter->silenced_;
}
}
this->wait_ = 0;
this->lastActivity_ = tSysTimeFloat();
}
void ePlayerNetID::InitAfterCreation()
{
MyInitAfterCreation();
}
bool ePlayerNetID::ClearToTransmit(int user) const
{
return ( ( !nextTeam || nextTeam->HasBeenTransmitted( user ) ) &&
( !currentTeam || currentTeam->HasBeenTransmitted( user ) ) ) ;
}
ePlayerNetID::~ePlayerNetID()
{
// se_PlayerNetIDs.Remove(this,listID);
if ( sn_GetNetState() == nSERVER && disconnected )
{
tOutput mess;
tColoredString name;
name << *this << tColoredString::ColorString(1,.5,.5);
mess.SetTemplateParameter(1, name);
mess.SetTemplateParameter(2, score);
mess << "$player_left_game";
sn_ConsoleOut(mess);
}
nextTeam = NULL; // this will force autosubstitution if this feature is active
ApplySubstitution();
UnregisterWithMachine();
RemoveFromGame();
ClearObject();
ClearRespawn();
//con << "Player info sent.\n";
for(int i=MAX_PLAYERS-1; i>=0; i--)
{
ePlayer *p = ePlayer::PlayerConfig(i);
if (p && static_cast<ePlayerNetID *>(p->netPlayer)==this)
p->netPlayer=NULL;
}
if ( currentTeam )
{
currentTeam->RemovePlayer( this );
}
}
static void player_removed_from_game_handler(nMessage &m)
{
// and the ID of the player that was removed
unsigned short id;
m.Read(id);
ePlayerNetID* p = dynamic_cast< ePlayerNetID* >( nNetObject::ObjectDangerous( id ) );
if ( p && sn_GetNetState() != nSERVER )
{
p->RemoveFromGame();
}
}
static nDescriptor player_removed_from_game(202,&player_removed_from_game_handler,"player_removed_from_game");
static eLadderLogWriter se_playerLeftWriter("PLAYER_LEFT", true);
static eLadderLogWriter se_playerAILeftWriter("PLAYER_AI_LEFT", true);
void ePlayerNetID::RemoveFromGame()
{
// unregister with the machine
this->UnregisterWithMachine();
// release voter
eVoter *voter = eVoter::GetPersistentVoter( Owner() );
if ( voter )
voter->RemoveFromGame();
// log scores
LogScoreDifference();
//bool logLeave = false;
if ( sn_GetNetState() != nCLIENT )
{
nameFromClient_ = nameFromServer_;
nMessage *m=new nMessage(player_removed_from_game);
m->Write(this->ID());
m->BroadCast();
if ( listID >= 0 )
{
if ( ( IsSpectating() || IsSuspended() || !se_assignTeamAutomatically ) && ( se_assignTeamAutomatically || se_specSpam ) && CurrentTeam() == NULL )
{
// get colored player name
tColoredString playerName;
playerName << *this << tColoredString::ColorString(1,.5,.5);
// announce a generic leave
sn_ConsoleOut( tOutput( "$player_left_spectator", playerName ) );
}
/*
if ( IsHuman() && sn_GetNetState() == nSERVER && NULL != sn_Connections[Owner()].socket )
{
logLeave = true;
}
*/
if( IsHuman() )
{
se_playerLeftWriter << userName_ << nMachine::GetMachine(Owner()).GetIP();
se_playerLeftWriter.write();
this->LogActivity(ACTIVITY_LEFT);
}
else
{
se_playerAILeftWriter << userName_;
se_playerAILeftWriter.write();
}
}
}
if (gRacePlayer::PlayerExists(this))
{
gRacePlayer *rPlayer = gRacePlayer::GetPlayer(this);
if (rPlayer)
{
rPlayer->ErasePlayer();
}
}
gQueuePlayers *qPlayer = gQueuePlayers::GetData(this);
if (qPlayer) qPlayer->RemovePlayer();
se_PlayerNetIDs.Remove(this, listID);
SetTeamWish( NULL );
SetTeam( NULL );
UpdateTeam();
ControlObject( NULL );
ClearRespawn();
}
bool ePlayerNetID::ActionOnQuit()
{
tControlledPTR< ePlayerNetID > holder( this );
// clear legacy spectator
se_ClearLegacySpectator( Owner() );
this->RemoveFromGame();
return true;
}
void ePlayerNetID::ActionOnDelete()
{
tControlledPTR< ePlayerNetID > holder( this );
if ( sn_GetNetState() == nSERVER )
{
// get the number of players registered from this client
// int playerCount = nMachine::GetMachine(Owner()).GetPlayerCount();
int playerCount = 0;
for ( int i = se_PlayerNetIDs.Len()-1; i >= 0; --i )
{
if ( se_PlayerNetIDs[i]->Owner() == Owner() )
playerCount++;
}
// if this is the last player, store it
if ( playerCount == 1 )
{
// log scores
LogScoreDifference();
// clear legacy spectator
se_ClearLegacySpectator( Owner() );
// store new legacy spectator
se_legacySpectators[ Owner() ] = this;
spectating_ = true;
// quit team already
SetTeamWish( NULL );
SetTeam( NULL );
UpdateTeam();
// and kill controlled object
ControlObject( NULL );
// inform other clients that the player left
TakeOwnership();
RequestSync();
return;
}
}
// standard behavior: just get us out of here
this->RemoveFromGame();
}
void ePlayerNetID::PrintName(tString &s) const
{
s << "ePlayerNetID nr. " << ID() << ", name " << GetName();
}
bool ePlayerNetID::AcceptClientSync() const
{
return true;
}
#ifdef KRAWALL_SERVER
tString se_GetAuthorityFromGid ( const tString gid )
{
int pos;
if ( ( pos = gid.StrPos( "@" ) ) != -1 )
{
return gid.SubStr( pos +1 );
}
return gid;
}
// changes various user aspects
template< class P > class eUserConfig: public tConfItemBase
{
public:
typedef typename std::map< tString, P > Properties;
P Get(tString const & name ) const
{
typename Properties::const_iterator iter = properties.find( name );
if ( iter != properties.end() )
{
return (*iter).second;
}
return GetDefault();
}
Properties GetMap () const
{
return properties;
}
protected:
eUserConfig( char const * name )
: tConfItemBase( name )
{
requiredLevel = tAccessLevel_Owner;
}
virtual P ReadRawVal(tString const & name, std::istream &s) const = 0;
virtual P GetDefault() const = 0;
virtual void TransformName( tString & name ) const {}
virtual void ReadVal(std::istream &s)
{
tString name;
s >> name;
if ( name == "" )
{
tString usageKey("$");
usageKey += GetTitle();
usageKey += "_usage";
tToLower( usageKey );
con << tOutput( (const char *)usageKey );
return;
}
TransformName( name );
P value = ReadRawVal(name, s);
properties[name] = value;
}
Properties properties;
private:
virtual void WriteVal(std::ostream &s)
{
tASSERT(0);
}
virtual void FetchVal(tString &val){};
virtual bool Writable()
{
return false;
}
virtual bool Save()
{
return false;
}
// CAN this be saved at all?
virtual bool CanSave()
{
return false;
}
};
// changes the access level of a player
class eUserLevel: public eUserConfig< tAccessLevel >
{
public:
eUserLevel()
: eUserConfig< tAccessLevel >( "USER_LEVEL" )
{
requiredLevel = tAccessLevel_Owner;
}
tAccessLevel GetDefault() const
{
return tAccessLevel_DefaultAuthenticated;
}
virtual tAccessLevel ReadRawVal(tString const & name, std::istream &s) const
{
int levelInt;
s >> levelInt;
tAccessLevel level = static_cast< tAccessLevel >( levelInt );
if ( s.fail() )
{
if(printErrors)
{
con << tOutput( "$user_level_usage" );
}
return GetDefault();
}
if(printChange)
{
con << tOutput( "$user_level_change", name, tCurrentAccessLevel::GetName( level ) );
}
return level;
}
virtual void TransformName( tString & name ) const
{
name = se_EscapeName( name ).c_str();
}
};
static eUserLevel se_userLevel;
class eAuthorityLevel: public eUserConfig< tAccessLevel >
{
public:
eAuthorityLevel()
: eUserConfig< tAccessLevel >( "AUTHORITY_LEVEL" )
{
requiredLevel = tAccessLevel_Owner;
}
tAccessLevel GetDefault() const
{
return tAccessLevel_DefaultAuthenticated;
}
virtual tAccessLevel ReadRawVal(tString const & name, std::istream &s) const
{
int levelInt;
s >> levelInt;
tAccessLevel level = static_cast< tAccessLevel >( levelInt );
if ( s.fail() || name.StrPos( "@" ) != -1 )
{
if(printErrors)
{
con << tOutput( "$authority_level_usage" );
}
return GetDefault();
}
if(printChange)
{
con << tOutput( "$authority_level_change", name, tCurrentAccessLevel::GetName( level ) );
}
return level;
}
};
static eAuthorityLevel se_authorityLevel;
#ifdef KRAWALL_SERVER
static tAccessLevel se_adminListMinAccessLevel = tAccessLevel_Moderator;
static tSettingItem< tAccessLevel > se_adminListMinAccessLevelConf( "ADMIN_LIST_MIN_ACCESS_LEVEL", se_adminListMinAccessLevel );
static tAccessLevelSetter se_adminListMinAccessLevelConfLevel( se_adminListMinAccessLevelConf, tAccessLevel_Owner );
static tAccessLevel se_accessLevelListAdmins = tAccessLevel_Moderator; /* This command is sensible, especially if admin rights are set to an
* account that can still be registered at.
*/
static tSettingItem< tAccessLevel > se_accessLevelListAdminsConf( "ACCESS_LEVEL_LIST_ADMINS", se_accessLevelListAdmins );
static tAccessLevelSetter se_accessLevelListAdminsConfLevel( se_accessLevelListAdminsConf, tAccessLevel_Owner );
static tAccessLevel se_accessLevelListAdminsSeeEveryone = tAccessLevel_Moderator;
static tSettingItem< tAccessLevel > se_accessLevelListAdminsSeeEveryoneConf( "ACCESS_LEVEL_LIST_ADMINS_SEE_EVERYONE", se_accessLevelListAdminsSeeEveryone );
static tAccessLevelSetter se_accessLevelListAdminsSeeEveryoneConfLevel( se_accessLevelListAdminsSeeEveryoneConf, tAccessLevel_Owner );
static int se_adminListColors_BestRed = 15;
static tSettingItem< int > se_adminListColors_BetterRed_Conf( "ADMIN_LIST_COLORS_BEST_RED", se_adminListColors_BestRed );
static int se_adminListColors_WorstRed = 15;
static tSettingItem< int > se_adminListColors_WorstRed_Conf( "ADMIN_LIST_COLORS_WORST_RED", se_adminListColors_WorstRed );
static int se_adminListColors_BestGreen = 0;
static tSettingItem< int > se_adminListColors_BetterGreen_Conf( "ADMIN_LIST_COLORS_BEST_GREEN", se_adminListColors_BestGreen );
static int se_adminListColors_WorstGreen = 15;
static tSettingItem< int > se_adminListColors_WorstGreen_Conf( "ADMIN_LIST_COLORS_WORST_GREEN", se_adminListColors_WorstGreen );
static int se_adminListColors_BestBlue = 0;
static tSettingItem< int > se_adminListColors_BetterBlue_Conf( "ADMIN_LIST_COLORS_BEST_BLUE", se_adminListColors_BestBlue );
static int se_adminListColors_WorstBlue = 7;
static tSettingItem< int > se_adminListColors_WorstBlue_Conf( "ADMIN_LIST_COLORS_WORST_BLUE", se_adminListColors_WorstBlue );
void se_ListAdmins ( ePlayerNetID * receiver, std::istream &s, tString command )
{
// What's going to be sent ? But wait..are we sending anything at all?
if ( receiver != 0 && receiver->GetAccessLevel() > se_accessLevelListAdmins )
{
sn_ConsoleOut( tOutput("$chat_command_accesslevel", command,
tCurrentAccessLevel::GetName( receiver->GetAccessLevel() ),
tCurrentAccessLevel::GetName( se_accessLevelListAdmins ) ),
receiver->Owner() );
return;
}
int client = receiver ? receiver->Owner() : 0;
bool canSeeEverything = false;
if ( receiver == 0 || receiver->GetAccessLevel() <= se_accessLevelListAdminsSeeEveryone )
{
canSeeEverything = true;
}
int firstNumber, secondNumber;
bool gotFirstNumber = true, gotSecondNumber = true;
s >> firstNumber;
if ( s.fail() )
{
gotFirstNumber = false;
gotSecondNumber = false;
}
else
{
s >> secondNumber;
if ( s.fail() )
{
gotSecondNumber = false;
}
}
int userCount = 0, authorityCount = 0;
std::set< tAccessLevel > accessLevelsToList;
if ( gotFirstNumber && !gotSecondNumber )
{
if ( canSeeEverything || firstNumber <= se_adminListMinAccessLevel )
{
accessLevelsToList.insert( static_cast<tAccessLevel>( firstNumber ) );
}
else
{
sn_ConsoleOut( tOutput( "$admin_list_cant_see", command ), client );
return;
}
}
else if ( ( gotFirstNumber && gotSecondNumber ) || ( !gotFirstNumber && !gotSecondNumber ) )
{
int lowest, highest;
if ( !gotFirstNumber && !gotSecondNumber )
{
lowest = 0;
highest = se_adminListMinAccessLevel;
}
else
{
if ( secondNumber > firstNumber )
{
lowest = firstNumber;
highest = secondNumber;
}
else
{
lowest = secondNumber;
highest = firstNumber;
}
if ( !canSeeEverything && highest > se_adminListMinAccessLevel )
{
sn_ConsoleOut( tOutput("$admin_list_cant_see"), client );
return;
}
}
for ( int al = lowest; al <= highest; ++al )
{
accessLevelsToList.insert( static_cast<tAccessLevel>(al) );
}
}
// Now browse trough all users in se_userLevel and sort them by access level in adminLevelsMap, then output it
typedef std::map< tString, tString > aSetOfAdmins;
typedef std::map< tAccessLevel, aSetOfAdmins > AdminLevelsMap;
AdminLevelsMap adminLevelsMap;
tString user;
tAccessLevel accessLevel;
AdminLevelsMap::iterator usersAccessLevelInSet;
eUserLevel::Properties gidMap = se_userLevel.GetMap();
for ( eUserLevel::Properties::iterator iter = gidMap.begin(); iter != gidMap.end(); ++iter )
{
tColoredString userinfo, lowerUser;
user = (*iter).first;
accessLevel = (*iter).second;
if ( accessLevelsToList.find( accessLevel ) != accessLevelsToList.end() )
{
// Prepare a string with the info about that user
// userinfo << " " << user;
usersAccessLevelInSet = adminLevelsMap.find( accessLevel );
if ( usersAccessLevelInSet == adminLevelsMap.end() )
{
adminLevelsMap[ accessLevel ] = aSetOfAdmins();
usersAccessLevelInSet = adminLevelsMap.find( accessLevel );
}
aSetOfAdmins & theRightSet = (*usersAccessLevelInSet).second;
lowerUser = user;
tToLower( lowerUser );
theRightSet[ lowerUser ] = user;
userCount++;
}
}
// Do it again for authorities
eAuthorityLevel::Properties authoritiesMap = se_authorityLevel.GetMap();
for ( eUserLevel::Properties::iterator iter = authoritiesMap.begin(); iter != authoritiesMap.end(); ++iter )
{
tColoredString userinfo, lowerUser;
user = (*iter).first;
accessLevel = (*iter).second;
if ( accessLevelsToList.find( accessLevel ) != accessLevelsToList.end() )
{
// Prepare a string with the info about that user
usersAccessLevelInSet = adminLevelsMap.find( accessLevel );
if ( usersAccessLevelInSet == adminLevelsMap.end() )
{
adminLevelsMap[ accessLevel ] = aSetOfAdmins();
usersAccessLevelInSet = adminLevelsMap.find( accessLevel );
}
aSetOfAdmins & theRightSet = (*usersAccessLevelInSet).second;
lowerUser = user;
tToLower( lowerUser );
user = tOutput ( "$admin_list_authoritylevel", user );
lowerUser = tString( "AAA" ) << lowerUser;
theRightSet[ lowerUser ] = user;
authorityCount++;
}
}
// Now we have'em sorted by access level, it's show-time!
// for each access level out there
AdminLevelsMap::iterator it;
int numberOfAccessLevelsShown = adminLevelsMap.size() -1;
int advancement = 0;
REAL red, green, blue;
tColoredString accessLevelColor;
tColoredString output;
for ( it = adminLevelsMap.begin(); it != adminLevelsMap.end(); ++it )
{
output = "";
// First, print the access level's name
tAccessLevel accessLevel = (*it).first;
// Find the appropriate color for it
if (numberOfAccessLevelsShown <= 0)
numberOfAccessLevelsShown = 1;
red = (
se_adminListColors_BestRed * ( numberOfAccessLevelsShown - advancement )
+ se_adminListColors_WorstRed * ( advancement )
) / 16.0 / numberOfAccessLevelsShown;
green = (
se_adminListColors_BestGreen * ( numberOfAccessLevelsShown - advancement )
+ se_adminListColors_WorstGreen * ( advancement )
) / 16.0 / numberOfAccessLevelsShown;
blue = (
se_adminListColors_BestBlue * ( numberOfAccessLevelsShown - advancement )
+ se_adminListColors_WorstBlue * ( advancement )
) / 16.0 / numberOfAccessLevelsShown;
accessLevelColor << tColoredString::ColorString( red, green, blue );
output << accessLevelColor
<< tCurrentAccessLevel::GetName( accessLevel ) << ": ";
// accessLevelColor = "";
// Then print the admin's names
for ( aSetOfAdmins::iterator userIt = (*it).second.begin(); userIt != (*it).second.end(); ++userIt )
{
if ( userIt == (*it).second.begin() )
{
output << (*userIt).second;
}
else
{
output << ", " << (*userIt).second;
}
}
output << "\n";
sn_ConsoleOut( output, client );
++advancement;
}
tOutput sumup;
sumup = "";
sn_ConsoleOut( tOutput( "$admin_list_end", command, userCount, authorityCount, static_cast<int>( adminLevelsMap.size() ) ), client );
}
static void se_ListAdmins_conf( std::istream &s )
{
se_ListAdmins( 0, s, tString( "PLAYERS" ) );
}
static tConfItemFunc se_ListAdminsConf("ADMINS",&se_ListAdmins_conf);
static tAccessLevelSetter se_ListAdminsConfLevel( se_ListAdminsConf, tAccessLevel_Owner );
#endif
// reserves a nickname
class eReserveNick: public eUserConfig< tString >
{
#ifdef DEBUG
#ifdef KRAWALL_SERVER
static void TestEscape( char const * t )
{
tString test(t);
tString esc(se_EscapeName( test, false ).c_str());
tString rev(se_UnEscapeName( esc ).c_str());
tASSERT( test == rev );
}
#endif
static void TestEscape()
{
#ifdef KRAWALL_SERVER
TestEscape("ä@%bla:");
TestEscape("a b@%bl%:");
TestEscape("a\\_b@%bl%:");
#endif
}
#endif
public:
eReserveNick()
: eUserConfig< tString >( "RESERVE_SCREEN_NAME" )
{
#ifdef DEBUG
TestEscape();
#endif
}
// filter the name so it is compatible with old school user names; those
// will be used later for comparison
virtual void TransformName( tString & name ) const
{
name = ePlayerNetID::FilterName( name );
}
tString GetDefault() const
{
return tString();
}
virtual tString ReadRawVal(tString const & name, std::istream &s) const
{
tString user;
s >> user;
if ( user == "" )
{
con << tOutput( "$reserve_screen_name_usage" );
return GetDefault();
}
user = se_UnEscapeName( user ).c_str();
con << tOutput( "$reserve_screen_name_change", name, user );
return user;
}
};
static eReserveNick se_reserveNick;
// authentication alias to map a local account to a global one
class eAlias: public eUserConfig< tString >
{
public:
eAlias()
: eUserConfig< tString >( "USER_ALIAS" )
{
}
tString GetDefault() const
{
return tString();
}
virtual tString ReadRawVal(tString const & name, std::istream &s) const
{
tString alias;
s >> alias;
if ( alias == "" )
{
con << tOutput( "$user_alias_usage" );
return GetDefault();
}
alias = se_UnEscapeName( alias ).c_str();
con << tOutput( "$alias_change", name, alias );
return alias;
}
};
static eAlias se_alias;
// bans for players too stupid to disable autologin
class eBanUser: public eUserConfig< bool >
{
public:
eBanUser()
: eUserConfig< bool >( "BAN_USER" )
{
}
// unbans the user again
void UnBan( tString const & name )
{
properties[name] = false;
con << tOutput( "$unban_user_message", name );
}
void List()
{
bool one = false;
for ( Properties::iterator i = properties.begin(); i != properties.end(); ++i )
{
if ( (*i).second )
{
if ( one )
{
con << ", ";
}
con << (*i).first;
one = true;
}
}
if ( one )
{
con << "\n";
}
}
bool GetDefault() const
{
return false;
}
virtual bool ReadRawVal(tString const & name, std::istream &s) const
{
con << tOutput( "$ban_user_message", name );
return true;
}
};
static eBanUser se_banUser;
// check whether a special username is banned
static bool se_IsUserBanned( ePlayerNetID * p, tString const & name )
{
if( se_banUser.Get( name ) )
{
sn_KickUser( p->Owner(), tOutput( "$network_kill_banned", 60, "" ) );
return true;
}
return false;
}
class eUnBanUser: public eUserConfig< bool >
{
public:
eUnBanUser( )
: eUserConfig< bool >( "UNBAN_USER" )
{
}
bool GetDefault() const
{
return false;
}
virtual bool ReadRawVal(tString const & name, std::istream &s) const
{
se_banUser.UnBan(name);
return false;
}
};
static eUnBanUser se_unBanUser;
static void se_ListBannedUsers( std::istream & )
{
se_banUser.List();
}
static tConfItemFunc sn_listBanConf("BAN_USER_LIST",&se_ListBannedUsers);
static void se_CheckAccessLevel( tAccessLevel & level, tString const & authName )
{
tAccessLevel newLevel;
tString authority;
tString user;
nKrawall::SplitUserName( authName, user, authority );
newLevel = se_authorityLevel.Get( authority );
if ( newLevel < level || newLevel > tAccessLevel_DefaultAuthenticated )
{
level = newLevel;
}
newLevel = se_userLevel.Get( authName );
if ( newLevel < level || newLevel > tAccessLevel_DefaultAuthenticated )
{
level = newLevel;
}
}
static tAccessLevel se_announceLoginAccessLevel = tAccessLevel_Default;
static tSettingItem< tAccessLevel > se_announceLoginAccessLevelConf( "ACCESS_LEVEL_ANNOUNCE_LOGIN", se_announceLoginAccessLevel );
static tAccessLevelSetter se_announceLoginAccessLevelConfLevel( se_announceLoginAccessLevelConf, tAccessLevel_Owner );
static bool se_HideLoginAnnouncement( ePlayerNetID const *hider, ePlayerNetID const *seeker )
{
return hider->GetAccessLevel() > se_announceLoginAccessLevel || se_Hide( hider, seeker );
}
static bool se_CanHideLoginAnnouncement( ePlayerNetID const *hider )
{
return hider->GetAccessLevel() > se_announceLoginAccessLevel || se_CanHide( hider );
}
static void se_AnnounceLogin( tOutput const &out, ePlayerNetID const *player, ePlayerNetID const *admin )
{
HIDEFUNC hideFunc = &se_HideLoginAnnouncement;
CANHIDEFUNC canHideFunc = &se_CanHideLoginAnnouncement;
// /op and /deop don't need to account for ACCESS_LEVEL_ANNOUNCE_LOGIN.
if ( admin )
{
hideFunc = &se_Hide;
canHideFunc = &se_CanHide;
}
se_SecretConsoleOut( out, player, hideFunc, admin, player, canHideFunc );
}
void ePlayerNetID::Authenticate( tString const & authName, tAccessLevel accessLevel_, ePlayerNetID const * admin, bool messages )
{
tString newAuthenticatedName( se_EscapeName( authName ).c_str() );
// no use authenticating an AI :)
if ( !IsHuman() )
{
return;
}
if ( !IsAuthenticated() )
{
// reset spam timer
GetChatSpam().ResetTime();
// elevate access level for registered users
se_CheckAccessLevel( accessLevel_, newAuthenticatedName );
rawAuthenticatedName_ = authName;
//! Race hack
authenticatedname = authName;
tString alias = se_alias.Get( newAuthenticatedName );
if ( alias != "" )
{
rawAuthenticatedName_ = alias;
//! Race hack
authenticatedname = alias;
newAuthenticatedName = GetFilteredAuthenticatedName();
authenticatedname = GetFilteredAuthenticatedName();
// elevate access level again according to the new alias
se_CheckAccessLevel( accessLevel_, newAuthenticatedName );
}
// check for stupid bans
if ( se_IsUserBanned( this, newAuthenticatedName ) )
{
return;
}
// minimal access level
if ( accessLevel_ > tAccessLevel_Authenticated )
{
accessLevel_ = static_cast< tAccessLevel >( tAccessLevel_Program - 1 );
}
{
// authorize access level change (careful, don't blindly copy/paste to other places)
tCurrentAccessLevel level( tAccessLevel_Owner, true );
// take over the access level
SetAccessLevel( accessLevel_ );
}
tString order( "" );
if ( admin )
{
order = tOutput( "$login_message_byorder",
admin->GetLogName() );
}
if ( IsHuman() )
{
if ( GetAccessLevel() != tAccessLevel_Default )
{
tOutput out( "$login_message_special", GetName(), newAuthenticatedName, tCurrentAccessLevel::GetName( GetAccessLevel() ), order );
se_AnnounceLogin( out, this, admin );
}
else
{
tOutput out( "$login_message", GetName(), newAuthenticatedName, order );
se_AnnounceLogin( out, this, admin );
}
SetLoggedIn(true);
}
}
GetScoreFromDisconnectedCopy();
// force update (removed again to fix name change possibility during a round)
// UpdateName();
}
void ePlayerNetID::DeAuthenticate( ePlayerNetID const * admin )
{
if ( IsAuthenticated() )
{
if ( admin )
{
tOutput out( "$logout_message_deop", GetName(), GetFilteredAuthenticatedName(), admin->GetLogName() );
se_AnnounceLogin( out, this, admin );
}
else
{
tOutput out( "$logout_message", GetName(), GetFilteredAuthenticatedName() );
se_AnnounceLogin( out, this, admin );
}
SetLoggedIn(false);
}
// force falling back to regular user name on next update
SetAccessLevel( tAccessLevel_Default );
rawAuthenticatedName_ = "";
//! Race hack
authenticatedname = "";
// force update (removed again to fix name change possibility during a round)
// UpdateName();
}
bool ePlayerNetID::IsAuthenticated() const
{
return int(GetAccessLevel()) <= int(tAccessLevel_Authenticated);
}
#endif
// create our voter or find it
void ePlayerNetID::CreateVoter()
{
// only count nonlocal players with voting support as voters
if ( sn_GetNetState() != nCLIENT && this->Owner() != 0 && sn_Connections[ this->Owner() ].version.Max() >= 3 )
{
eVoter *voter = eVoter::GetPersistentVoter( Owner() );
if ( voter )
voter->PlayerChanged();
}
}
void ePlayerNetID::WriteSync(nMessage &m)
{
lastSync=tSysTimeFloat();
nNetObject::WriteSync(m);
m.Write(r);
m.Write(g);
m.Write(b);
// write ping charity; spectators get a fake (high) value
if ( currentTeam || nextTeam )
m.Write(pingCharity);
else
m.Write(1000);
if ( sn_GetNetState() == nCLIENT )
{
m << nameFromClient_;
}
else
{
m << nameFromServer_;
}
//if(sn_GetNetState()==nSERVER)
m << ping;
bool tempChat = chatting_;
if (flagOverrideChat)
{
tempChat = flagChatState;
}
// pack chat, spectator and stealth status together
unsigned short flags = ( tempChat ? 1 : 0 ) | ( spectating_ ? 2 : 0 ) | ( stealth_ ? 4 : 0 );
m << flags;
m << score;
m << static_cast<unsigned short>(disconnected);
m << nextTeam;
m << currentTeam;
m << favoriteNumberOfPlayersPerTeam;
m << nameTeamAfterMe;
m << teamname;
}
extern float sg_flagDropTime;
void ePlayerNetID::DropFlag()
{
if (sg_flagDropTime < 0)
{
return;
}
gCycle *cycle = dynamic_cast<gCycle *>(object);
if (cycle)
{
if (cycle->flag_)
{
cycle->flag_->OwnerDropped();
}
}
}
void ePlayerNetID::PassFlag(std::istream &s)
{
gCycle *cycle = dynamic_cast<gCycle *>(object);
if (cycle)
{
if (cycle->Alive() && cycle->flag_)
{
tString name;
s >> name;
cycle->flag_->PassTheFlag(name);
}
}
}
// makes sure the passed string is not longer than the given maximum
static void se_CutString( tColoredString & string, int maxLen )
{
if (string.Len() > maxLen )
{
string.SetLen(maxLen);
string[string.Len()-1]='\0';
string.RemoveTrailingColor();
}
}
static void se_CutString( tString & string, int maxLen )
{
se_CutString( reinterpret_cast< tColoredString & >( string ), maxLen );
}
static bool se_bugColorOverflow=true;
tSettingItem< bool > se_bugColorOverflowColor( "BUG_COLOR_OVERFLOW", se_bugColorOverflow );
void Clamp( unsigned short & colorComponent )
{
if ( colorComponent > 15 )
colorComponent = 15;
}
// function prototype for character testing functions
typedef bool TestCharacter( char c );
// strips characters matching a test beginnings and ends of names
static void se_StripMatchingEnds( tString & stripper, TestCharacter & beginTester, TestCharacter & endTester )
{
int len = stripper.Len() - 1;
int first = 0, last = len;
// eat whitespace from beginnig and end
while ( first < len && beginTester( stripper[first] ) ) ++first;
while ( last > 0 && ( !stripper[last] || endTester(stripper[last] ) ) ) --last;
// strip everything?
if ( first > last )
{
stripper = "";
return;
}
// strip
if ( first > 0 || last < stripper.Len() - 1 )
stripper = stripper.SubStr( first, last + 1 - first );
}
// removed convenience function, VisualC 6 cannot cope with it...
// strips characters matching a test beginnings and ends of names
//static void se_StripMatchingEnds( tString & stripper, TestCharacter & tester )
//{
// se_StripMatchingEnds( stripper, tester, tester );
//}
// function wrapper for what may be a macro
static bool se_IsBlank( char c )
{
return isblank( c );
}
// enf of player names should neither be space or :
static bool se_IsInvalidNameEnd( char c )
{
return isblank( c ) || c == ':' || c == '.';
}
// filter name ends
static void se_StripNameEnds( tString & name )
{
se_StripMatchingEnds( name, se_IsBlank, se_IsInvalidNameEnd );
}
static bool se_allowImposters = false;
static tSettingItem< bool > se_allowImposters1( "ALLOW_IMPOSTERS", se_allowImposters );
static tSettingItem< bool > se_allowImposters2( "ALLOW_IMPOSTORS", se_allowImposters );
// test if a user name is used by anyone else than the passed player
static bool se_IsNameTaken( tString const & name, ePlayerNetID const * exception )
{
if ( name.Len() <= 1 )
return false;
if ( !se_allowImposters )
{
// check for other players with the same name
for (int i = se_PlayerNetIDs.Len()-1; i >= 0; --i )
{
ePlayerNetID * player = se_PlayerNetIDs(i);
if ( player != exception )
{
if ( name == player->GetUserName() || name == ePlayerNetID::FilterName( player->GetName() ) )
return true;
}
}
}
#ifdef KRAWALL_SERVER
// check for reserved nicknames
{
tString reservedFor = se_reserveNick.Get( name );
if ( reservedFor != "" &&
( !exception || exception->GetAccessLevel() >= tAccessLevel_Default ||
exception->GetRawAuthenticatedName() != reservedFor ) )
{
return true;
}
}
#endif
return false;
}
static bool se_filterColorNames=false;
tSettingItem< bool > se_coloredNamesConf( "FILTER_COLOR_NAMES", se_filterColorNames );
static bool se_filterDarkColorNames=false;
tSettingItem< bool > se_coloredDarkNamesConf( "FILTER_DARK_COLOR_NAMES", se_filterDarkColorNames );
static bool se_stripNames=true;
tSettingItem< bool > se_stripConf( "FILTER_NAME_ENDS", se_stripNames );
static bool se_stripMiddle=true;
tSettingItem< bool > se_stripMiddleConf( "FILTER_NAME_MIDDLE", se_stripMiddle );
// do the optional filtering steps
static void se_OptionalNameFilters( tString & remoteName, int owner )
{
// filter colors
if ( se_filterColorNames )
{
remoteName = tColoredString::RemoveColors( remoteName, false );
}
else if ( se_filterDarkColorNames )
{
remoteName = tColoredString::RemoveColors( remoteName, true );
}
// don't do the fancy stuff on the client, it only makes names on score tables and
// console messages go out of sync.
if ( sn_GetNetState() == nCLIENT )
return;
// strip whitespace
if ( se_stripNames )
se_StripNameEnds( remoteName );
if ( se_stripMiddle )
{
// first, scan for double whitespace
bool whitespace=false;
int i;
for ( i = 0; i < remoteName.Len()-1; ++i )
{
bool newWhitespace=isblank(remoteName[i]);
if ( newWhitespace && whitespace )
{
// yes, double whitespace there. Filter it out.
whitespace=newWhitespace=false;
tString copy;
for ( i = 0; i < remoteName.Len()-1; ++i )
{
char c = remoteName[i];
newWhitespace=isblank(c);
if ( !whitespace || !newWhitespace )
{
copy+=c;
}
whitespace=newWhitespace;
}
remoteName=copy;
// abort loop.
break;
}
whitespace=newWhitespace;
}
}
// zero strings or color code only strings are illegal
if ( !IsLegalPlayerName( remoteName ) )
{
tString oldName = remoteName;
// revert to old name if possible
if ( IsLegalPlayerName( oldName ) )
{
remoteName = oldName;
}
else
{
// or replace it by a default value
remoteName = "Player ";
remoteName << owner;
}
}
}
void ePlayerNetID::ReadSync(nMessage &m)
{
// check whether this is the first sync
bool firstSync = ( this->ID() == 0 );
nNetObject::ReadSync(m);
m.Read(r);
m.Read(g);
m.Read(b);
if ( !se_bugColorOverflow )
{
// clamp color values
Clamp(r);
Clamp(g);
Clamp(b);
}
m.Read(pingCharity);
sg_ClampPingCharity(pingCharity);
// name as sent from the other end
tString & remoteName = ( sn_GetNetState() == nCLIENT ) ? nameFromServer_ : nameFromClient_;
// name handling
{
// read and shorten name, but don't update it yet
m >> remoteName;
// filter
se_OptionalNameFilters( remoteName, Owner() );
// remove all colors from name
tString colorlessName = tColoredString::RemoveColors(remoteName, false);
// check if the colorless name's length is longer than the limited length
if (colorlessName.Len() > 16)
{
se_CutString( remoteName, 16 );
}
}
// directly apply name changes sent from the server, they are safe.
if ( sn_GetNetState() != nSERVER )
{
UpdateName();
}
REAL p;
m >> p;
if (sn_GetNetState()!=nSERVER)
ping=p;
// if (!m.End())
{
// read chat and spectator status
unsigned short flags;
m >> flags;
if (Owner() != ::sn_myNetID)
{
bool newChat = ( ( flags & 1 ) != 0 );
bool newSpectate = ( ( flags & 2 ) != 0 );
bool newStealth = ( ( flags & 4 ) != 0 );
if ( chatting_ != newChat || spectating_ != newSpectate || newStealth != stealth_ )
lastActivity_ = tSysTimeFloat();
chatting_ = newChat;
spectating_ = newSpectate;
stealth_ = newStealth;
}
}
// if (!m.End())
{
if(sn_GetNetState()!=nSERVER)
m >> score;
else
{
int s;
m >> s;
}
}
if (!m.End())
{
unsigned short newdisc;
m >> newdisc;
if (Owner() != ::sn_myNetID && sn_GetNetState()!=nSERVER)
disconnected = newdisc;
}
if (!m.End())
{
if ( nSERVER != sn_GetNetState() )
{
eTeam *newCurrentTeam, *newNextTeam;
m >> newNextTeam;
m >> newCurrentTeam;
// update team
tJUST_CONTROLLED_PTR< eTeam > oldTeam( currentTeam );
if ( newCurrentTeam != currentTeam )
{
if ( newCurrentTeam )
{
// automatically removed player from currentTeam
newCurrentTeam->AddPlayerDirty( this );
newCurrentTeam->UpdateProperties();
}
else
{
currentTeam->RemovePlayer( this );
}
}
// update nextTeam
nextTeam = newNextTeam;
// update properties of the old current team in all cases
if ( oldTeam )
{
oldTeam->UpdateProperties();
}
}
else
{
eTeam* t;
m >> t;
m >> t;
}
m >> favoriteNumberOfPlayersPerTeam;
m >> nameTeamAfterMe;
}
if (!m.End())
{
m >> teamname;
}
// con << "Player info updated.\n";
// make sure we did not accidentally overwrite values
// ePlayer::Update();
// update the team
if ( nSERVER == sn_GetNetState() )
{
if ( nextTeam )
nextTeam->UpdateProperties();
if ( currentTeam )
currentTeam->UpdateProperties();
}
// first sync message
if ( firstSync && sn_GetNetState() == nSERVER )
{
UpdateName();
#ifndef KRAWALL_SERVER
GetScoreFromDisconnectedCopy();
#endif
//FindDefaultTeam();
SetDefaultTeam();
RequestSync();
}
}
nNOInitialisator<ePlayerNetID> ePlayerNetID_init(201,"ePlayerNetID");
nDescriptor &ePlayerNetID::CreatorDescriptor() const
{
return ePlayerNetID_init;
}
void ePlayerNetID::ControlObject(eNetGameObject *c)
{
if (bool(object) && c!=object)
ClearObject();
if (!c)
{
return;
}
object=c;
c->team = currentTeam;
if (bool(object))
object->SetPlayer(this);
#ifdef DEBUG
//con << "Player " << name << " controlles new object.\n";
#endif
NewObject();
}
void ePlayerNetID::ClearRespawn()
{
eGrid *grid = eGrid::CurrentGrid();
if (!grid) return;
const tList<eGameObject>& gameObjects = grid->GameObjects();
for (int i=gameObjects.Len()-1;i>=0;i--)
{
gRespawnZoneHack *resZone = dynamic_cast<gRespawnZoneHack *>(gameObjects[i]);
if (resZone)
{
if (resZone->DeadPlayer() == this)
{
resZone->Finish();
break;
}
}
}
}
void ePlayerNetID::ClearObject()
{
if (object)
{
tJUST_CONTROLLED_PTR< eNetGameObject > x=object;
object=NULL;
x->RemoveFromGame();
x->SetPlayer( NULL );
}
#ifdef DEBUG
//con << "Player " << name << " controlles nothing.\n";
#endif
}
void ePlayerNetID::Greet()
{
if (!greeted)
{
tOutput o;
o.SetTemplateParameter(1, GetName() );
o.SetTemplateParameter(2, sn_programVersion);
o << "$player_welcome";
tString s;
s << o;
s << "\n";
if (ladder_highscore_output)
{
GreetHighscores(s);
s << "\n";
}
//std::cout << s;
sn_ConsoleOut(s,Owner());
greeted=true;
}
}
eNetGameObject *ePlayerNetID::Object() const
{
return object;
}
void se_SaveToPlayersLog(tOutput const &out)
{
if (sn_GetNetState()!=nCLIENT && !tRecorder::IsPlayingBack())
{
std::ofstream o;
if ( tDirectories::Var().Open(o, "players_log.txt", std::ios::app) )
{
std::stringstream s;
s << st_GetCurrentTime("%Y/%m/%d-%H:%M:%S ");
s << out << std::endl;
o << s.str();
}
}
}
/*
* This is the function to log the activities of players
* by the numbers from the following:
*
* 0 - left game
* 1 - entered game
* 2 - entered game as spectator
* 3 - joined spectator from grid
* 4 - entered game from spectator
* 5 - finished race
* 6 - died
*/
static bool se_LogPlayersActivitys = false;
static tSettingItem<bool> se_LogPlayersActivitysConf("LOG_PLAYERS_ACTIVITIES", se_LogPlayersActivitys);
void ePlayerNetID::LogActivity(int activity_type)
{
if (!se_LogPlayersActivitys) return;
tOutput out;
out << this->GetUserName();
out << " ";
out << activity_type;
se_SaveToPlayersLog(out);
}
static bool se_consoleLadderLog = false;
static tSettingItem< bool > se_consoleLadderLogConf( "CONSOLE_LADDER_LOG", se_consoleLadderLog );
static bool se_ladderlogDecorateTS = false;
static tSettingItem< bool > se_ladderlogDecorateTSConf( "LADDERLOG_DECORATE_TIMESTAMP", se_ladderlogDecorateTS );
extern bool sn_decorateTS; // from nNetwork.cpp
void se_SaveToLadderLog( tOutput const & out )
{
if (se_consoleLadderLog)
{
std::cout << "[L";
if(sn_decorateTS)
{
std::cout << st_GetCurrentTime(" TS=%Y/%m/%d-%H:%M:%S");
}
std::cout << "] " << out << std::endl;
}
if (sn_GetNetState()!=nCLIENT && !tRecorder::IsPlayingBack())
{
std::ofstream o;
if ( tDirectories::Var().Open(o, "ladderlog.txt", std::ios::app) )
{
std::stringstream s;
if(se_ladderlogDecorateTS)
{
s << st_GetCurrentTime("%Y/%m/%d-%H:%M:%S ");
}
s << out << std::endl;
sr_InputForScripts( s.str().c_str() );
o << s.str();
}
}
}
static bool se_chatLog = false;
static bool se_chatLogColors = false;
static tSettingItem<bool> se_chatLogConf("CHAT_LOG", se_chatLog);
static tSettingItem<bool> se_chatLogColorsConf("CHAT_LOG_COLORS", se_chatLogColors);
static eLadderLogWriter se_chatWriter("CHAT", false);
void se_SaveToChatLog(tOutput const &out)
{
tString colStr(out);
eBannedWords::BadWordTrigger(colStr);
if(sn_GetNetState() != nCLIENT && !tRecorder::IsPlayingBack())
{
if(se_chatWriter.isEnabled())
{
se_chatWriter << out;
se_chatWriter.write();
}
if(se_chatLog)
{
std::ofstream o;
if ( tDirectories::Var().Open(o, "chatlog.txt", std::ios::app) )
{
o << st_GetCurrentTime("[%Y/%m/%d-%H:%M:%S] ") << colStr << std::endl;
}
}
}
}
void se_SaveToChatLogC(tOutput const &out)
{
tString colStr(out);
eBannedWords::BadWordTrigger(colStr);
if(sn_GetNetState() != nCLIENT && !tRecorder::IsPlayingBack())
{
if(se_chatLogColors)
{
std::ofstream o;
if ( tDirectories::Var().Open(o, "chatlog_colors.txt", std::ios::app) )
{
o << st_GetCurrentTime("[%Y/%m/%d-%H:%M:%S] ") << colStr;// << std::endl;
}
}
}
}
std::list<eLadderLogWriter *> &eLadderLogWriter::writers()
{
static std::list<eLadderLogWriter *> list;
return list;
}
eLadderLogWriter::eLadderLogWriter(char const *ID, bool enabledByDefault) :
id(ID),
enabled(enabledByDefault),
conf(new tSettingItem<bool>(&(tString("LADDERLOG_WRITE_") + id)(0),
enabled)),
cache(id)
{
writers().push_back(this);
}
eLadderLogWriter::~eLadderLogWriter()
{
if(conf)
{
delete conf;
}
// generic algorithms aren't exactly easier to understand than regular
// code, but anyways, let's try one...
std::list<eLadderLogWriter *> list = writers();
list.erase(std::find_if(list.begin(), list.end(), std::bind2nd(std::equal_to<eLadderLogWriter *>(), this)));
}
static bool se_ladderlogEnabled = false;
static tSettingItem<bool> se_ladderlogEnabledConf("LADDERLOG_ENABLED", se_ladderlogEnabled);
void eLadderLogWriter::write()
{
if(enabled && se_ladderlogEnabled)
{
se_SaveToLadderLog(cache);
}
cache = id;
}
void eLadderLogWriter::setAll(bool enabled)
{
std::list<eLadderLogWriter *> list = writers();
std::list<eLadderLogWriter *>::iterator end = list.end();
for(std::list<eLadderLogWriter *>::iterator iter = list.begin(); iter != end; ++iter)
{
(*iter)->enabled = enabled;
}
}
static void LadderLogWriteAll(std::istream &s)
{
bool enabled;
s >> enabled;
if(s.fail())
{
if(tConfItemBase::printErrors)
{
con << tOutput("$ladderlog_write_all_usage") << '\n';
}
return;
}
if(tConfItemBase::printChange)
{
if(enabled)
{
con << tOutput("$ladderlog_write_all_enabled") << '\n';
}
else
{
con << tOutput("$ladderlog_write_all_disabled") << '\n';
}
}
eLadderLogWriter::setAll(enabled);
}
static tConfItemFunc LadderLogWriteAllConf("LADDERLOG_WRITE_ALL", &LadderLogWriteAll);
void se_SaveToScoreFile(const tOutput &o)
{
tString s(o);
#ifdef DEBUG
if (sn_GetNetState()!=nCLIENT)
{
#else
if (sn_GetNetState()==nSERVER && !tRecorder::IsPlayingBack())
{
#endif
std::ofstream o;
if ( tDirectories::Var().Open(o, "scorelog.txt", std::ios::app) )
o << tColoredString::RemoveColors(s);
}
#ifdef DEBUG
}
#else
}
#endif
/* this doesn't work. Will be put to use later.
void ePlayerNetID::SetRubber(ePlayerNetID *player, REAL rubber)
{
gCycle * target;
target->SetPlayer(player);
target->SetRubber(rubber);
}
*/
void ePlayerNetID::AddScore(int points,
const tOutput& reasonwin,
const tOutput& reasonlose,
bool shouldPrint)
{
if (points==0)
return;
score += points;
if (currentTeam)
currentTeam->AddScore( points );
tColoredString name;
name << *this << tColoredString::ColorString(-1,-1,-1);
tOutput message;
message.SetTemplateParameter(1, name);
message.SetTemplateParameter(2, points > 0 ? points : -points);
if (points>0)
{
if (reasonwin.IsEmpty())
message << "$player_win_default";
else
message.Append(reasonwin);
}
else
{
if (reasonlose.IsEmpty())
message << "$player_lose_default";
else
message.Append(reasonlose);
}
if (shouldPrint)
sn_ConsoleOut(message);
RequestSync(true);
se_SaveToScoreFile(message);
}
int ePlayerNetID::TotalScore() const
{
if ( currentTeam )
{
return score;// + currentTeam->Score() * 5;
}
else
{
return score;
}
}
void ePlayerNetID::SwapPlayersNo(int a,int b)
{
if (0>a || se_PlayerNetIDs.Len()<=a)
return;
if (0>b || se_PlayerNetIDs.Len()<=b)
return;
if (a==b)
return;
ePlayerNetID *A=se_PlayerNetIDs(a);
ePlayerNetID *B=se_PlayerNetIDs(b);
se_PlayerNetIDs(b)=A;
se_PlayerNetIDs(a)=B;
A->listID=b;
B->listID=a;
}
void ePlayerNetID::SortByScore()
{
// bubble sort (AAARRGGH! but good for lists that change not much)
bool inorder = false;
while ( !inorder )
{
inorder = true;
for( int i = se_PlayerNetIDs.Len() - 2; i >= 0; i-- )
{
ePlayerNetID *a = se_PlayerNetIDs( i );
ePlayerNetID *b = se_PlayerNetIDs( i + 1 );
if ( a->TotalScore() < b->TotalScore() || ( a->TotalScore() == b->TotalScore() && !a->CurrentTeam() && b->CurrentTeam() ) )
{
SwapPlayersNo( i, i + 1 );
inorder = false;
}
}
}
}
void ePlayerNetID::ResetScore()
{
int i;
for(i=se_PlayerNetIDs.Len()-1; i>=0; i--)
{
se_PlayerNetIDs(i)->score=0;
if (sn_GetNetState()==nSERVER)
se_PlayerNetIDs(i)->RequestSync();
}
for(i=eTeam::teams.Len()-1; i>=0; i--)
{
eTeam::teams(i)->ResetScore();
if (sn_GetNetState()==nSERVER)
eTeam::teams(i)->RequestSync();
}
ResetScoreDifferences();
}
// flag memorizing whether the scores already have been rendered this frame
static bool se_alreadyDisplayedScores = false;
static bool show_scores=false;
void ePlayerNetID::DisplayScores()
{
// block displaying scores during chat mode
if (se_BlockScores)
{
se_alreadyDisplayedScores = false;
show_scores = false;
return;
}
if( !show_scores || !se_mainGameTimer || se_alreadyDisplayedScores )
{
return;
}
se_alreadyDisplayedScores = true;
sr_ResetRenderState(true);
REAL W=sr_screenWidth;
REAL H=sr_screenHeight;
REAL MW=400;
REAL MH=(MW*3)/4;
if(W>MW)
W=MW;
if(H>MH)
H=MH;
#ifndef DEDICATED
if (sr_glOut)
{
::Color(1,1,1);
rTextField c(-.7,.6,10/W,18/H);
// print team ranking if there actually is a team with more than one player
int maxPlayers = 20;
for ( int i = eTeam::teams.Len() - 1; i >= 0; --i )
{
if ( eTeam::teams[i]->NumPlayers() > 1 ||
( eTeam::teams[i]->NumPlayers() == 1 && eTeam::teams[i]->Player(0)->Score() != eTeam::teams[i]->Score() ) )
{
c << eTeam::Ranking();
c << "\n";
maxPlayers -= ( eTeam::teams.Len() > 6 ? 6 : eTeam::teams.Len() ) + 2;
break;
}
}
// print player ranking
c << Ranking( maxPlayers );
}
#endif
}
tString ePlayerNetID::Ranking( int MAX, bool cut )
{
SortByScore();
tColoredString ret;
if (se_PlayerNetIDs.Len()>0)
{
ret.SetPos(2, cut);
ret << tColoredString::ColorString(1,.5,.5);
ret << tOutput("$player_scoretable_name");
ret << tColoredString::ColorString(-1,-1,-1);
ret.SetPos(19, cut );
ret << tOutput("$player_scoretable_alive");
ret.SetPos(26, cut );
ret << tOutput("$player_scoretable_score");
ret.SetPos(33, cut );
ret << tOutput("$player_scoretable_ping");
ret.SetPos(39, cut );
ret << tOutput("$player_scoretable_team");
ret.SetPos(56, cut );
ret << "\n";
int max = se_PlayerNetIDs.Len();
// wasting the last line with ... is as stupid if it stands for only
// one player
if ( MAX == max + 1 )
MAX = max;
if ( max > MAX && MAX > 0 )
{
max = MAX ;
}
for(int i=0; i<max; i++)
{
tColoredString line;
ePlayerNetID *p=se_PlayerNetIDs(i);
// tColoredString name( p->GetColoredName() );
// name.SetPos(16, cut );
// This line is example of how we manually get the player color... could come in useful.
// line << tColoredString::ColorString( p->r/15.0, p->g/15.0, p->b/15.0 ) << name << tColoredString::ColorString(1,1,1);
// however, using the streaming operator is a lot cleaner. The example is left, as it really can be usefull in some situations.
if (p->IsChatting())
line << tColoredString::ColorString(-1,-1,-1) << "*";
line.SetPos(2, cut);
line << *p;
line.SetPos(19, false );
if ( p->Object() && p->Object()->Alive() )
{
line << tColoredString::ColorString(0,1,0) << tOutput("$player_scoretable_alive_yes") << tColoredString::ColorString(-1,-1,-1);
}
else
{
line << tColoredString::ColorString(1,0,0) << tOutput("$player_scoretable_alive_no") << tColoredString::ColorString(-1,-1,-1);
}
line.SetPos(26, cut );
line << p->score;
if (p->IsActive())
{
line.SetPos(33, cut );
//line << "ping goes here";
line << int(p->ping*1000);
line.SetPos(39, cut );
if ( p->currentTeam )
{
//tString teamtemp = p->currentTeam->Name();
//teamtemp.RemoveHex();
//Not sure why we need to filter the color here.
// line << tColoredString::RemoveColors(p->currentTeam->Name());
line << p->currentTeam->GetColoredName();
line.SetPos(56, cut );
}
}
else
line << tOutput("$player_scoretable_inactive");
ret << line << "\n";
}
if ( max < se_PlayerNetIDs.Len() )
{
ret << "...\n";
}
}
else
ret << tOutput("$player_scoretable_nobody");
return ret;
}
static eLadderLogWriter se_onlinePlayerWriter("ONLINE_PLAYER", false);
static eLadderLogWriter se_onlineAIWriter( "ONLINE_AI", true);
static eLadderLogWriter se_onlineTeamWriter( "ONLINE_TEAM", true );
static eLadderLogWriter se_playerColoredNameWriter("PLAYER_COLORED_NAME", false);
static eLadderLogWriter se_numHumansWriter("NUM_HUMANS", false);
void ePlayerNetID::RankingLadderLog()
{
SortByScore();
int num_humans = 0;
int max = se_PlayerNetIDs.Len();
for(int i = 0; i < max; ++i)
{
ePlayerNetID *p = se_PlayerNetIDs(i);
if (p)
{
bool isHuman = p->IsHuman();
if (isHuman)
{
se_onlinePlayerWriter << p->GetLogName();
se_onlinePlayerWriter << p->Owner();
// add player color to the message
se_onlinePlayerWriter << p->r << p->g << p->b;
// add the player's access level to the message
se_onlinePlayerWriter << p->GetAccessLevel();
// write out if they logged in or not
se_onlinePlayerWriter << (p->HasLoggedIn()?1:0);
if(p->IsActive())
{
se_onlinePlayerWriter << p->ping;
if(p->currentTeam)
{
se_onlinePlayerWriter << FilterName(p->currentTeam->Name());
++num_humans;
}
}
else
{
se_onlinePlayerWriter << "";
}
se_onlinePlayerWriter.write();
}
else
{
se_onlineAIWriter << p->GetLogName();
se_onlineAIWriter << p->CurrentTeam()->Name().Filter();
se_onlineAIWriter << p->Score();
se_onlineAIWriter.write();
}
}
}
for(int j = 0; j < eTeam::teams.Len(); j++)
{
eTeam *team = eTeam::teams[j];
if (team)
{
// AI teams are boring
if (!team->IsHuman())
continue;
se_onlineTeamWriter << team->Name().Filter();
se_onlineTeamWriter << team->Name();
se_onlineTeamWriter.write();
}
}
se_numHumansWriter << num_humans;
se_numHumansWriter.write();
for(int i = 0; i < max; i++)
{
ePlayerNetID *p = se_PlayerNetIDs[i];
if (p)
{
tColoredString colouredName;
colouredName << p->GetColoredName();
se_playerColoredNameWriter << p->GetUserName() << colouredName;
se_playerColoredNameWriter.write();
}
}
}
static eLadderLogWriter se_playerGridPosWriter("PLAYER_GRIDPOS", false);
void ePlayerNetID::GridPosLadderLog()
{
if(!se_playerGridPosWriter.isEnabled())
{
return;
}
if (se_PlayerNetIDs.Len()>0)
{
int max = se_PlayerNetIDs.Len();
for(int i=0; i<max; i++)
{
ePlayerNetID *p=se_PlayerNetIDs(i);
if (p->IsActive() && p->currentTeam && p->Object() && p->Object()->Alive() )
{
gCycle *pCycle = dynamic_cast<gCycle *>(p->Object());
se_playerGridPosWriter << p->GetUserName();
se_playerGridPosWriter << pCycle->MapPosition().x << pCycle->MapPosition().y;
se_playerGridPosWriter << pCycle->MapDirection().x << pCycle->MapDirection().y;
se_playerGridPosWriter << pCycle->verletSpeed_;
se_playerGridPosWriter << pCycle->GetRubber() << sg_rubberCycle;
if (pCycle && pCycle->Team()) se_playerGridPosWriter << FilterName(pCycle->Team()->Name());
else se_playerGridPosWriter << " ";
se_playerGridPosWriter.write();
}
}
}
}
static eLadderLogWriter se_OnlinePlayersAliveWriter("ONLINE_PLAYERS_ALIVE", true);
static eLadderLogWriter se_OnlinePlayersDeadWriter("ONLINE_PLAYERS_DEAD", true);
static eLadderLogWriter se_OnlinePlayersCountWriter("ONLINE_PLAYERS_COUNT", true);
void ePlayerNetID::OnlineStatsLadderLog()
{
int humans = 0;
int ais = 0;
int h_alive = 0;
int a_alive = 0;
int h_dead = 0;
int a_dead = 0;
for(int i = 0; i < se_PlayerNetIDs.Len(); i++)
{
ePlayerNetID *p = se_PlayerNetIDs[i];
if (p)
{
if (p->IsHuman())
humans++;
else
ais++;
if (p->Object())
{
if (p->Object()->Alive())
{
se_OnlinePlayersAliveWriter << p->GetLogName();
if (p->IsHuman())
h_alive++;
else
a_alive++;
}
else
{
se_OnlinePlayersDeadWriter << p->GetLogName();
if (p->IsHuman())
h_dead++;
else
a_dead++;
}
}
}
}
se_OnlinePlayersCountWriter << humans << ais << h_alive << a_alive << h_dead << a_dead;
se_OnlinePlayersCountWriter.write();
se_OnlinePlayersAliveWriter.write();
se_OnlinePlayersDeadWriter.write();
}
void ePlayerNetID::ClearAll()
{
for(int i=MAX_PLAYERS-1; i>=0; i--)
{
ePlayer *local_p=ePlayer::PlayerConfig(i);
if (local_p)
local_p->netPlayer = NULL;
}
}
static bool se_VisibleSpectatorsSupported()
{
static nVersionFeature se_visibleSpectator(13);
return sn_GetNetState() != nCLIENT || se_visibleSpectator.Supported(0);
}
// @param spectate if true
void ePlayerNetID::SpectateAll( bool spectate )
{
for(int i=MAX_PLAYERS-1; i>=0; i--)
{
ePlayer *local_p=ePlayer::PlayerConfig(i);
if (local_p)
{
if ( se_VisibleSpectatorsSupported() && bool(local_p->netPlayer) )
{
local_p->netPlayer->spectating_ = spectate || local_p->spectate;
local_p->netPlayer->RequestSync();
}
else
local_p->netPlayer = NULL;
}
}
}
void ePlayerNetID::CompleteRebuild()
{
ClearAll();
Update();
}
static int se_ColorDistance( int a[3], int b[3] )
{
int distance = 0;
for( int i = 2; i >= 0; --i )
{
int diff = a[i] - b[i];
distance += diff * diff;
//diff = diff < 0 ? -diff : diff;
//if ( diff > distance )
//{
// distance = diff;
//}
}
return distance;
}
//This seems more random. Stolen from the old randomize color, but no comparing. Also another bonus, generates multi colored cycle / tails with the limit increase to 32.
static void se_RandomizeColor(ePlayer * l)
{
int currentRGB[3];
int newRGB[3];
static tReproducibleRandomizer randomizer;
for( int i = 2; i >= 0; --i )
{
currentRGB[i] = l->rgb[i];
newRGB[i] = randomizer.Get(32);
}
for( int i = 2; i >= 0; --i )
{
l->rgb[i] = newRGB[i];
}
}
//This didnt seem to be too random, more like picking a unique color no one else currently has.
static void se_UniqueColor( ePlayer * l, ePlayerNetID * p )
{
int currentRGB[3];
int newRGB[3];
int nullRGB[3]= {0,0,0};
static tReproducibleRandomizer randomizer;
for( int i = 2; i >= 0; --i )
{
currentRGB[i] = l->rgb[i];
newRGB[i] = randomizer.Get(15);
}
int currentMinDiff = se_ColorDistance( currentRGB, nullRGB )/2;
int newMinDiff = se_ColorDistance( newRGB, nullRGB )/2;
// check the minimal distance of the new random color with all players
for ( int i = se_PlayerNetIDs.Len()-1; i >= 0; --i )
{
ePlayerNetID * other = se_PlayerNetIDs(i);
if ( other != p )
{
int color[3] = { other->r, other->g, other->b };
int currentDiff = se_ColorDistance( currentRGB, color );
int newDiff = se_ColorDistance( newRGB, color );
if ( currentDiff < currentMinDiff )
{
currentMinDiff = currentDiff;
}
if ( newDiff < newMinDiff )
{
newMinDiff = newDiff;
}
}
}
// update current color
if ( currentMinDiff < newMinDiff )
{
for( int i = 2; i >= 0; --i )
{
l->rgb[i] = newRGB[i];
}
}
}
//Gather all the rgb colors and put them in a nice list.
static void se_listPlayerColors()
{
tColoredString listColors;
for ( int i = 0; i <= se_PlayerNetIDs.Len()-1; i++ )
{
ePlayerNetID * otherPlayers = se_PlayerNetIDs(i);
listColors << (i+1) << ": " << otherPlayers->GetColoredName() << "0xRESETT (" << otherPlayers->r << ", " << otherPlayers->g << ", " << otherPlayers->b << ")\n";
con << listColors;
listColors = "";
}
}
static nSettingItem<int> se_pingCharityServerConf("PING_CHARITY_SERVER",sn_pingCharityServer );
static nVersionFeature se_pingCharityServerControlled( 14 );
static int se_pingCharityMax = 500, se_pingCharityMin = 0;
static tSettingItem<int> se_pingCharityMaxConf( "PING_CHARITY_MAX", se_pingCharityMax );
static tSettingItem<int> se_pingCharityMinConf( "PING_CHARITY_MIN", se_pingCharityMin );
static bool se_ForceSpectate( REAL & time, REAL minTime, char const * message, char const * & cantPlayMessage, int & experienceNeeded )
{
if ( time < 0 )
{
time = 0;
}
if ( time >= minTime )
{
return false;
}
else
{
// store message. The player should be presented with a single
// message telling him the easyest way to gain the required experience;
// if 10 minutes of total play time are needed and 5 minutes of online play time,
// we tell the player 10 more minutes of online play are required.
int needed = int( minTime - time + 2 );
if ( needed > experienceNeeded )
{
experienceNeeded = needed;
}
cantPlayMessage = message;
return true;
}
}
// sorted storage for pre-join shuffle commands
typedef std::multimap< int, tJUST_CONTROLLED_PTR< ePlayerNetID > >
ePrejoinShuffleMap;
typedef std::pair< int, tJUST_CONTROLLED_PTR< ePlayerNetID > >
ePrejoinPair;
static ePrejoinShuffleMap se_prejoinShuffles;
// Update the netPlayer_id list
void ePlayerNetID::Update()
{
#ifdef KRAWALL_SERVER
// update access level
UpdateAccessLevelRequiredToPlay();
// remove players with insufficient access rights
tAccessLevel required = AccessLevelRequiredToPlay();
for( int i=se_PlayerNetIDs.Len()-1; i >= 0; --i )
{
ePlayerNetID* player = se_PlayerNetIDs(i);
if ( player->GetAccessLevel() > required && player->IsHuman() )
{
player->SetTeamWish(0);
}
}
#endif
#ifdef DEDICATED
if (sr_glOut)
#endif
{
// the last update time
static nTimeRolling lastTime = tSysTimeFloat();
bool playing = false; // set to true if someone is playing
bool teamPlay = false; // set to true if someone is playing in a team
char const * cantPlayMessage = NULL;
int experienceNeeded = 0;
for(int i=0; i<MAX_PLAYERS; ++i )
{
bool in_game=ePlayer::PlayerIsInGame(i);
ePlayer *local_p=ePlayer::PlayerConfig(i);
tASSERT(local_p);
tCONTROLLED_PTR(ePlayerNetID) &p=local_p->netPlayer;
if (!p && in_game && ( !local_p->spectate || se_VisibleSpectatorsSupported() ) ) // insert new player
{
// reset last time so idle time in the menus does not count as play time
lastTime = tSysTimeFloat();
p=tNEW(ePlayerNetID) (i);
//p->FindDefaultTeam();
p->SetDefaultTeam();
p->RequestSync();
}
if (bool(p) && (!in_game || ( local_p->spectate && !se_VisibleSpectatorsSupported() ) ) && // remove player
p->Owner() == ::sn_myNetID )
{
p->RemoveFromGame();
if (p->object)
p->object->player = NULL;
p->object = NULL;
p = NULL;
}
if (bool(p) && in_game) // update
{
p->favoriteNumberOfPlayersPerTeam=ePlayer::PlayerConfig(i)->favoriteNumberOfPlayersPerTeam;
p->nameTeamAfterMe=ePlayer::PlayerConfig(i)->nameTeamAfterMe;
//Does the player want color randomization?
switch(ePlayer::PlayerConfig(i)->colorRandomization)
{
case COLORRANDOMIZATIONOFF:
break;
case COLORRANDOMIZATIONRANDOM:
se_RandomizeColor(local_p);
break;
case COLORRANDOMIZATIONUNIQUE:
se_UniqueColor(local_p,p);
break;
default:
//Number not in the range of 0-2? Oh well, no color randomization for you.
break;
}
p->r=ePlayer::PlayerConfig(i)->rgb[0];
p->g=ePlayer::PlayerConfig(i)->rgb[1];
p->b=ePlayer::PlayerConfig(i)->rgb[2];
sg_ClampPingCharity();
p->pingCharity=::pingCharity;
p->SetTeamname(local_p->Teamname());
// update spectator status
bool spectate = local_p->spectate;
// force to spectator mode if the player lacks experience
if ( !spectate )
{
se_ForceSpectate( se_playTimeTotal, se_minPlayTimeTotal, "$play_time_total_lacking", cantPlayMessage, experienceNeeded );
se_ForceSpectate( se_playTimeOnline, se_minPlayTimeOnline, "$play_time_online_lacking", cantPlayMessage, experienceNeeded );
se_ForceSpectate( se_playTimeTeam, se_minPlayTimeTeam, "$play_time_team_lacking", cantPlayMessage, experienceNeeded );
if ( cantPlayMessage )
{
spectate = true;
// print message to console (but don't spam)
static nTimeRolling lastTime = -100;
nTimeRolling now = tSysTimeFloat();
if ( now - lastTime > 30 )
{
lastTime = now;
con << tOutput( cantPlayMessage, experienceNeeded );
}
}
}
if ( p->spectating_ != spectate )
p->RequestSync();
p->spectating_ = spectate;
// set playing flags
if ( !spectate )
{
playing = true;
}
if ( p->CurrentTeam() && p->CurrentTeam()->NumHumanPlayers() > 1 )
{
teamPlay = true;
}
// update stealth status
if ( p->stealth_ != local_p->stealth )
p->RequestSync();
p->stealth_ = local_p->stealth;
// update name
tString newName( ePlayer::PlayerConfig(i)->Name() );
if ( ::sn_GetNetState() != nCLIENT || newName != p->nameFromClient_ )
{
p->RequestSync();
}
p->SetName( local_p->Name() );
}
}
// account for play time
nTimeRolling now = tSysTimeFloat();
REAL time = (now - lastTime)/60.0f;
lastTime = now;
if ( playing )
{
// all activity gets logged here
se_playTimeTotal += time;
if ( sn_GetNetState() == nCLIENT )
{
// all online activity counts here
se_playTimeOnline += time;
if ( teamPlay )
{
// all online team play counts here
se_playTimeTeam += time;
}
}
}
}
int i;
// update the ping charity, but
// don't do so on the client if the server controls the ping charity completely
if ( sn_GetNetState() == nSERVER || !se_pingCharityServerControlled.Supported(0) )
{
int old_c=sn_pingCharityServer;
sg_ClampPingCharity();
sn_pingCharityServer=::pingCharity;
#ifndef DEDICATED
if (sn_GetNetState()==nCLIENT)
#endif
sn_pingCharityServer+=100000;
// set configurable maximum
if ( se_pingCharityServerControlled.Supported() )
{
sn_pingCharityServer = se_pingCharityMax;
}
for(i=se_PlayerNetIDs.Len()-1; i>=0; i--)
{
ePlayerNetID *pni=se_PlayerNetIDs(i);
pni->UpdateName();
int new_ps=pni->pingCharity;
new_ps+=int(pni->ping*500);
// only take ping charity into account for non-spectators
if ( sn_GetNetState() != nSERVER || pni->currentTeam || pni->nextTeam )
if (new_ps < sn_pingCharityServer)
sn_pingCharityServer=new_ps;
}
if (sn_pingCharityServer<0)
sn_pingCharityServer=0;
// set configurable minimum
if ( se_pingCharityServerControlled.Supported() )
{
if ( sn_pingCharityServer < se_pingCharityMin )
sn_pingCharityServer = se_pingCharityMin;
}
if (old_c!=sn_pingCharityServer)
{
tOutput o;
o.SetTemplateParameter(1, old_c);
o.SetTemplateParameter(2, sn_pingCharityServer);
o << "$player_pingcharity_changed";
con << o;
// trigger transmission to the clients
if (sn_GetNetState()==nSERVER)
se_pingCharityServerConf.nConfItemBase::CheckChange(true);
}
}
// update team assignment
bool assigned = true;
while ( assigned && sn_GetNetState() != nCLIENT )
{
assigned = false;
int players = se_PlayerNetIDs.Len();
// start with the players that came in earlier
for( i=0; i<players; ++i )
{
ePlayerNetID* player = se_PlayerNetIDs(i);
// only assign new team if it is possible
if ( player->NextTeam() != player->CurrentTeam() && player->TeamChangeAllowed() &&
( !player->NextTeam() || player->NextTeam()->PlayerMayJoin( player ) )
)
{
player->UpdateTeam();
if ( player->NextTeam() == player->CurrentTeam() )
assigned = true;
}
}
// assign players that are not currently on a team, but want to, to any team. Start with the late comers here.
if ( !assigned )
{
for( i=players-1; i>=0; --i )
{
ePlayerNetID* player = se_PlayerNetIDs(i);
// if the player is not currently on a team, but wants to join a specific team, let it join any, but keep the wish stored
if ( player->NextTeam() && !player->CurrentTeam() && player->TeamChangeAllowed() )
{
tJUST_CONTROLLED_PTR< eTeam > wish = player->NextTeam();
bool assignBack = se_assignTeamAutomatically;
se_assignTeamAutomatically = true;
//player->FindDefaultTeam();
player->SetDefaultTeam();
se_assignTeamAutomatically = assignBack;
player->SetTeamForce( wish );
if ( player->CurrentTeam() )
{
assigned = true;
break;
}
}
}
}
}
if ( sn_GetNetState() != nCLIENT )
{
for(i=se_PlayerNetIDs.Len()-1; i>=0; i--)
{
ePlayerNetID* player = se_PlayerNetIDs(i);
// announce unfullfilled wishes
if ( player->NextTeam() != player->CurrentTeam() && player->NextTeam() )
{
// if the player can't change teams or their wish team emptied, delete the team wish
if(!player->TeamChangeAllowed() || player->NextTeam()->NumPlayers() == 0)
{
player->SetTeam( player->CurrentTeam() );
continue;
}
tOutput message( "$player_joins_team_wish",
player->GetName(),
player->NextTeam()->Name() );
sn_ConsoleOut( message );
// if team change is futile because team play is disabled,
// delete the team change wish
if ( eTeam::maxPlayers <= 1 )
player->SetTeam( player->CurrentTeam() );
}
}
}
// update the teams as well
for (i=eTeam::teams.Len()-1; i>=0; --i)
{
eTeam::teams(i)->UpdateProperties();
}
// execute all prejoin shuffles
for( ePrejoinShuffleMap::iterator i = se_prejoinShuffles.begin(); i!= se_prejoinShuffles.end(); ++i )
{
ePlayerNetID * player = (*i).second;
if( player && player->IsActive() )
{
eTeam * team = player->CurrentTeam();
if( team )
{
int wish = (*i).first;
// sanity check
if( wish < 0 )
{
wish = 0;
}
if( wish >= team->NumPlayers() )
{
wish = team->NumPlayers()-1;
}
// delegate shuffling work
team->Shuffle( player->TeamListID(), wish );
}
}
}
se_prejoinShuffles.clear();
// get rid of deleted netobjects
nNetObject::ClearAllDeleted();
}
// wait at most this long for any player to leave chat state...
static REAL se_playerWaitMax = 10.0f;
static tSettingItem< REAL > se_playerWaitMaxConf( "PLAYER_CHAT_WAIT_MAX", se_playerWaitMax );
// and no more than this much measured relative to his non-chatting time.
static REAL se_playerWaitFraction = .05f;
static tSettingItem< REAL > se_playerWaitFractionConf( "PLAYER_CHAT_WAIT_FRACTION", se_playerWaitFraction );
// flag to only account one player for the chat break
static bool se_playerWaitSingle = false;
static tSettingItem< bool > se_playerWaitSingleConf( "PLAYER_CHAT_WAIT_SINGLE", se_playerWaitSingle );
// flag to only let the team leader pause the timer
static bool se_playerWaitTeamleader = true;
static tSettingItem< bool > se_playerWaitTeamleaderConf( "PLAYER_CHAT_WAIT_TEAMLEADER", se_playerWaitTeamleader );
// wait for players to leave chat state
bool ePlayerNetID::WaitToLeaveChat()
{
static bool lastReturn = false;
static double lastTime = 0;
static ePlayerNetID * lastPlayer = 0; // the last player that caused a pause. Use only for comparison, the pointer may be bad. Don't dereference!
double time = tSysTimeFloat();
REAL dt = time - lastTime;
bool ret = false;
if ( !lastReturn )
{
// account for non-break pause: give players additional pause time
for ( int i = se_PlayerNetIDs.Len()-1; i>=0; --i )
{
ePlayerNetID* player = se_PlayerNetIDs(i);
if ( dt > 1.0 || !player->chatting_ )
{
player->wait_ += se_playerWaitFraction * dt;
if ( player->wait_ > se_playerWaitMax )
{
player->wait_ = se_playerWaitMax;
}
}
}
if ( dt > 1.0 )
lastPlayer = 0;
dt = 0;
}
// the chatting player with the most wait seconds left
ePlayerNetID * maxPlayer = 0;
REAL maxWait = .2;
// iterate over chatting players
for ( int i = se_PlayerNetIDs.Len()-1; i>=0; --i )
{
ePlayerNetID* player = se_PlayerNetIDs(i);
if ( player->CurrentTeam() && !player->IsSilenced() && player->chatting_ && ( !se_playerWaitTeamleader || player->CurrentTeam()->OldestHumanPlayer() == player ) )
{
// account for waiting time if everyone is to get his time reduced
if ( !se_playerWaitSingle )
{
player->wait_ -= dt;
// hold back
if ( player->wait_ > 0 )
{
ret = true;
}
else
{
player->wait_ = 0;
}
}
// determine player we'll wait for longest
if ( ( maxPlayer != lastPlayer || NULL == maxPlayer ) && ( player->wait_ > maxWait || player == lastPlayer ) && player->wait_ > 0 )
{
maxWait = player->wait_;
maxPlayer = player;
}
}
}
// account for waiting time if only one player should get his waiting time reduced
if ( se_playerWaitSingle && maxPlayer )
{
maxPlayer->wait_ -= dt;
// hold back
if ( maxPlayer->wait_ < 0 )
{
maxPlayer->wait_ = 0;
}
}
static double lastPrint = -2;
// print information: who are we waiting for?
if ( maxPlayer && maxPlayer != lastPlayer && tSysTimeFloat() - lastPrint > 1 )
{
sn_ConsoleOut( tOutput( "$gamestate_chat_wait", maxPlayer->GetName(), int(10*maxPlayer->wait_)*.1f ) );
lastPlayer = maxPlayer;
}
if ( lastPlayer == maxPlayer )
{
lastPrint = tSysTimeFloat();
}
// store values for future reference
lastReturn = ret;
lastTime = time;
return ret;
}
// time in chat mode before a player is no longer spawned
static REAL se_chatterRemoveTime = 180.0;
static tSettingItem< REAL > se_chatterRemoveTimeConf( "CHATTER_REMOVE_TIME", se_chatterRemoveTime );
// time without keypresses before a player is no longer spawned
static REAL se_idleRemoveTime = 0;
static tSettingItem< REAL > se_idleRemoveTimeConf( "IDLE_REMOVE_TIME", se_idleRemoveTime );
// time without keypresses before a player is kicked
static REAL se_idleKickTime = 0;
static tSettingItem< REAL > se_idleKickTimeConf( "IDLE_KICK_TIME", se_idleKickTime );
// access level where users on level or above are exempt from idle_kick_time
static REAL se_idleKickExempt = 0;
static tSettingItem< REAL > se_idleKickExemptConf( "IDLE_KICK_EXEMPT", se_idleKickExempt );
//removes chatbots and idling players from the game
void ePlayerNetID::RemoveChatbots()
{
// nothing to be done on the clients
if ( nCLIENT == sn_GetNetState() )
return;
#ifdef KRAWALL_SERVER
// update access level
UpdateAccessLevelRequiredToPlay();
#endif
// determine the length of the last round
static double lastTime = 0;
double currentTime = tSysTimeFloat();
REAL roundTime = currentTime - lastTime;
lastTime = currentTime;
// go through all players that don't have a team assigned currently, and assign one
for ( int i = se_PlayerNetIDs.Len()-1; i>=0; --i )
{
ePlayerNetID *p = se_PlayerNetIDs(i);
if ( p && p->IsHuman() )
{
// time allowed to be idle
REAL idleTime = p->IsChatting() ? se_chatterRemoveTime : se_idleRemoveTime;
// determine whether the player should have a team
bool shouldHaveTeam = idleTime <= 0 || p->LastActivity() - roundTime < idleTime;
shouldHaveTeam &= !p->IsSpectating();
tColoredString name;
name << *p << tColoredString::ColorString(1,.5,.5);
// see to it that the player has or has not a team.
if ( shouldHaveTeam )
{
if ( !p->CurrentTeam() )
{
//p->FindDefaultTeam();
p->SetDefaultTeam();
}
}
else
{
if ( p->CurrentTeam() )
{
p->SetTeam( NULL );
p->UpdateTeam();
}
}
// kick idle players (Removes player from list, this must be the last operation of the loop)
if ( se_idleKickTime > 0 && se_idleKickTime < p->LastActivity() - roundTime && se_autokickImmunity < p->GetAccessLevel() && p->GetAccessLevel() > se_idleKickExempt)
{
sn_KickUser( p->Owner(), tOutput( "$network_kill_idle" ) );
// if many players get kicked with one client, the array may have changed
if ( i >= se_PlayerNetIDs.Len() )
i = se_PlayerNetIDs.Len()-1;
}
}
}
// kick unworthy spectators (in case MAX_CLIENTS has changed)
se_kickUnworthySpare = -1;
se_KickUnworthy();
}
void ePlayerNetID::ThrowOutDisconnected()
{
int i;
// find all disconnected players
for(i=se_PlayerNetIDs.Len()-1; i>=0; i--)
{
ePlayerNetID *pni=se_PlayerNetIDs(i);
if (pni->disconnected)
{
// remove it from the list of players (so it won't be deleted twice...)
se_PlayerNetIDs.Remove(pni, pni->listID);
}
}
se_PlayerReferences.ReleaseAll();
}
void ePlayerNetID::GetScoreFromDisconnectedCopy()
{
int i;
// find a copy
for(i=se_PlayerNetIDs.Len()-1; i>=0; i--)
{
ePlayerNetID *pni=se_PlayerNetIDs(i);
if (pni->disconnected && pni->GetUserName() == GetUserName() && pni->Owner() == 0)
{
#ifdef DEBUG
con << GetName() << " reconnected.\n";
#endif
pni->RequestSync();
RequestSync();
score = pni->score;
ControlObject(pni->Object());
// object->ePlayer = this;
pni->object = NULL;
if (bool(object))
chatting_ = true;
pni->disconnected = false;
se_PlayerNetIDs.Remove(pni, pni->listID);
se_PlayerReferences.Remove( pni ); // really delete it without a message
}
}
}
static bool ass=true;
void se_AutoShowScores()
{
if (ass)
show_scores=true;
}
void se_UserShowScores(bool show)
{
show_scores=show;
}
void se_SetShowScoresAuto(bool a)
{
ass=a;
}
static void scores()
{
ePlayerNetID::DisplayScores();
se_alreadyDisplayedScores = false;
}
static rPerFrameTask pf(&scores);
// static bool force_small_cons(){
// return show_scores;
// }
// static rSmallConsoleCallback sc(&force_small_cons);
//static void cd(){
// show_scores = false;
//}
//static rCenterDisplayCallback c_d(&cd);
static uActionGlobal score("SCORE");
static bool sf(REAL x)
{
if (x>0) show_scores = !show_scores;
return true;
}
static uActionGlobalFunc saf(&score,&sf);
tOutput& operator << (tOutput& o, const ePlayerNetID& p)
{
tColoredString x;
x << p;
o << x;
return o;
}
tCallbackString *eCallbackGreeting::anchor = NULL;
ePlayerNetID* eCallbackGreeting::greeted = NULL;
tString eCallbackGreeting::Greet(ePlayerNetID* player)
{
greeted = player;
return Exec(anchor);
}
eCallbackGreeting::eCallbackGreeting(STRINGRETFUNC* f)
:tCallbackString(anchor, f)
{
}
void ePlayerNetID::GreetHighscores(tString &s)
{
s << eCallbackGreeting::Greet(this);
// tOutput o;
// gHighscoresBase::Greet(this,o);
// s << o;
}
// *******************
// * chatting_ *
// *******************
void ePlayerNetID::SetChatting ( ChatFlags flag, bool chatting )
{
/* z-man can't remember why this exception was made; probably
just do disable the chat indicator while you play in local menus.
if ( sn_GetNetState() == nSTANDALONE && flag == ChatFlags_Menu )
{
chatting = false;
}
*/
if ( chatting )
{
chatFlags_ |= flag;
if ( !chatting_ )
this->RequestSync();
chatting_ = true;
}
else
{
chatFlags_ &= ~flag;
if ( 0 == chatFlags_ )
{
if ( chatting_ )
this->RequestSync();
chatting_ = false;
}
}
}
// *******************
// * team management *
// *******************
bool ePlayerNetID::TeamChangeAllowed( bool informPlayer ) const
{
if (!( allowTeamChange_ || se_allowTeamChanges ))
{
if ( informPlayer )
{
sn_ConsoleOut(tOutput("$player_teamchanges_disallowed"), Owner());
}
return false;
}
if (IsSuspended())
{
if ( informPlayer )
{
sn_ConsoleOut(tOutput("$player_teamchanges_suspended", RoundsSuspended()), Owner());
}
return false;
}
#ifdef KRAWALL_SERVER
// only allow players with enough access level to enter the game, everyone is free to leave, though
if (!( GetAccessLevel() <= AccessLevelRequiredToPlay() || CurrentTeam() ))
{
if ( informPlayer )
{
sn_ConsoleOut(tOutput("$player_teamchanges_accesslevel",
tCurrentAccessLevel::GetName( GetAccessLevel() ),
tCurrentAccessLevel::GetName( AccessLevelRequiredToPlay() ) ),
Owner());
}
return false;
}
#endif
return true;
}
// put a new player into a default team
void ePlayerNetID::SetDefaultTeam( )
{
// only the server should do this, the client does not have the full information on how to do do it right.
if ( sn_GetNetState() == nCLIENT || !se_assignTeamAutomatically || spectating_ || !TeamChangeAllowed() )
return;
/*static bool recursion = false;
if ( recursion )
{
return;
}
if ( !IsHuman() )
{
SetTeam( NULL );
return;
}
recursion = true;*/
eTeam * defaultTeam = FindDefaultTeam();
if (defaultTeam)
SetTeamWish(defaultTeam);
if ( eTeam::NewTeamAllowed() )
CreateNewTeamWish();
}
// put a new player into a default team
eTeam * ePlayerNetID::FindDefaultTeam( )
{
// if ( !IsHuman() )
// {
// SetTeam( NULL );
// return;
// }
// find the team with the least number of players on it
eTeam *min = NULL;
for ( int i=eTeam::teams.Len()-1; i>=0; --i )
{
eTeam *t = eTeam::teams( i );
if ( t->IsHuman() && !t->IsLocked() && ( !min || min->NumHumanPlayers() > t->NumHumanPlayers() ) )
min = t;
}
if ( min &&
eTeam::teams.Len() >= eTeam::minTeams &&
min->PlayerMayJoin( this ) &&
( !eTeam::NewTeamAllowed() || ( min->NumHumanPlayers() > 0 && min->NumHumanPlayers() < favoriteNumberOfPlayersPerTeam ) )
)
/*SetTeamWish( min ); // join the team
else if ( eTeam::NewTeamAllowed() )
CreateNewTeamWish(); // create a new team
// yes, if all teams are full and no team creation is allowed, the player stays without team and will not be spawned.
recursion = false;*/
{
// return the team
return min;
}
// return NULL to indicate no team was found => "create a new team" (?)
return NULL;
}
// register me in the given team (callable on the server)
void ePlayerNetID::SetTeam( eTeam* newTeam )
{
// check if the team change is legal
tASSERT ( !newTeam || nCLIENT != sn_GetNetState() );
SetTeamForce( newTeam );
if (newTeam && ( !newTeam->PlayerMayJoin( this ) || IsSpectating() ) )
{
tOutput message;
message.SetTemplateParameter( 1, GetName() );
if ( newTeam )
message.SetTemplateParameter(2, newTeam->Name() );
else
message.SetTemplateParameter(2, "NULL");
message << "$player_nojoin_team";
sn_ConsoleOut( message, Owner() );
// return;
}
}
// set teamname to be used for my own team
void ePlayerNetID::SetTeamname(const char* newTeamname)
{
teamname = newTeamname;
if (bool(currentTeam) && currentTeam->OldestHumanPlayer() &&
currentTeam->OldestHumanPlayer()->ID()==ID())
{
currentTeam->UpdateAppearance();
}
}
// register me in the given team (callable on the server)
void ePlayerNetID::SetTeamForce( eTeam* newTeam )
{
// check if the team change is legal
//tASSERT ( !newTeam || nCLIENT != sn_GetNetState() );
#ifdef DEBUG
std::cout << "DEBUG: Player:" << this->GetName() << " SetTeamForce:" << ((newTeam)?(const char*)newTeam->Name():"NULL") << "\n";
#endif
nextTeam = newTeam;
}
// register me in the given team (callable on the server)
void ePlayerNetID::UpdateTeam()
{
// check if work is needed
if ( nextTeam == currentTeam )
{
return;
}
if ( nCLIENT != sn_GetNetState() && bool( nextTeam ) && !nextTeam->PlayerMayJoin( this ) )
{
tOutput message;
message.SetTemplateParameter(1, GetName() );
if ( nextTeam )
message.SetTemplateParameter(2, nextTeam->Name() );
else
message.SetTemplateParameter(2, "NULL");
message << "$player_nojoin_team";
sn_ConsoleOut( message, Owner() );
return;
}
UpdateTeamForce();
}
void ePlayerNetID::UpdateTeamForce()
{
// check if work is needed
if ( nextTeam == currentTeam )
{
return;
}
eTeam *oldTeam = currentTeam;
if ( nextTeam )
{
if( nCLIENT != sn_GetNetState() && !oldTeam && teamListID >= 0 )
{
// clear current team list ID, it was just a shuffle wish
// but store the shuffle wish first
se_prejoinShuffles.insert( ePrejoinPair( teamListID, this ) );
teamListID = -1;
}
nextTeam->AddPlayer ( this );
}
else if ( oldTeam )
{
oldTeam->RemovePlayer( this );
}
if ( nCLIENT != sn_GetNetState() && GetRefcount() > 0 )
{
RequestSync();
}
}
// teams this player is invited to
ePlayerNetID::eTeamSet const & ePlayerNetID::GetInvitations() const
{
return invitations_;
}
// sends a team change notification message to everyone's console
static void se_TeamChangeMessage( ePlayerNetID const & player )
{
if ( player.NextTeam() )
{
// send notification
tOutput message;
tString playerName = tColoredString::RemoveColors(player.GetName());
tString teamName = tColoredString::RemoveColors(player.NextTeam()->Name());
message.SetTemplateParameter(1, playerName );
if ( playerName != teamName )
{
message.SetTemplateParameter(2, teamName );
message << "$player_joins_team";
}
else
{
message << "$player_joins_team_solo";
}
sn_ConsoleOut( message );
}
}
// create a new team and join it (on the server)
void ePlayerNetID::CreateNewTeam()
{
// check if the team change is legal
tASSERT ( nCLIENT != sn_GetNetState() );
if(!TeamChangeAllowed( true ))
{
return;
}
if ( !eTeam::NewTeamAllowed() ||
( bool( currentTeam ) && ( currentTeam->NumHumanPlayers() == 1 ) ) ||
IsSpectating() )
{
tOutput message;
message.SetTemplateParameter(1, GetName() );
message << "$player_nocreate_team";
sn_ConsoleOut( message, Owner() );
if ( !currentTeam )
{
bool assignBack = se_assignTeamAutomatically;
se_assignTeamAutomatically = true;
//FindDefaultTeam();
SetDefaultTeam();
se_assignTeamAutomatically = assignBack;
}
return;
}
// create the new team and join it
tJUST_CONTROLLED_PTR< eTeam > newTeam = tNEW( eTeam );
nextTeam = newTeam;
nextTeam->AddScore( score );
// directly if possible
if ( !currentTeam )
{
UpdateTeam();
}
else
{
nextTeam->UpdateAppearance();
se_TeamChangeMessage( *this );
}
}
const unsigned short TEAMCHANGE = 0;
const unsigned short NEW_TEAM = 1;
// express the wish to be part of the given team (always callable)
void ePlayerNetID::SetTeamWish(eTeam* newTeam)
{
if (NextTeam()==newTeam)
return;
if ( nCLIENT == sn_GetNetState() && Owner() == sn_myNetID )
{
nMessage* m = NewControlMessage();
(*m) << TEAMCHANGE;
(*m) << newTeam;
m->BroadCast();
// update local client data, should be ok (dangerous?, why?)
SetTeamForce( newTeam );
}
else
{
SetTeam( newTeam );
// directly join if possible to keep counts up to date
if (!currentTeam)
UpdateTeam();
}
}
// express the wish to create a new team and join it
void ePlayerNetID::CreateNewTeamWish()
{
if ( nCLIENT == sn_GetNetState() )
{
nMessage* m = NewControlMessage();
(*m) << NEW_TEAM;
m->BroadCast();
}
else
CreateNewTeam();
}
// receive the team control wish
void ePlayerNetID::ReceiveControlNet(nMessage &m)
{
short messageType;
m >> messageType;
switch (messageType)
{
case NEW_TEAM:
{
CreateNewTeam();
break;
}
case TEAMCHANGE:
{
eTeam *newTeam;
m >> newTeam;
if(!TeamChangeAllowed( true ))
{
break;
}
// annihilate team if it no longer is in the game
if ( bool(newTeam) && newTeam->TeamID() < 0 )
newTeam = 0;
// NULL team probably means that the change target does not
// exist any more. Create a new team instead.
if ( !newTeam )
{
if ( currentTeam )
sn_ConsoleOut( tOutput( "$player_joins_team_noex", tColoredString::RemoveColors(GetName()) ), Owner() );
break;
}
// check if the resulting message is obnoxious
bool redundant = ( nextTeam == newTeam );
bool obnoxious = ( nextTeam != currentTeam || redundant );
SetTeam( newTeam );
// announce the change
if ( bool(nextTeam) && !redundant )
{
se_TeamChangeMessage( *this );
// count it as spam if it is obnoxious
if ( obnoxious )
GetChatSpam().CheckSpam( 4.0, Owner(), tOutput("$spam_teamchage") );
}
break;
}
default:
{
tASSERT(0);
}
}
}
void ePlayerNetID::Color( REAL&a_r, REAL&a_g, REAL&a_b ) const
{
if ( ( static_cast<bool>(currentTeam) ) && ( currentTeam->IsHuman() ) )
{
REAL w = 5;
REAL r_w = 2;
REAL g_w = 1;
REAL b_w = 2;
int r = this->r;
int g = this->g;
int b = this->b;
// don't tolerate color overflow in a real team
if ( currentTeam->NumPlayers() > 1 )
{
if ( r > 15 )
r = 15;
if ( g > 15 )
g = 15;
if ( b > 15 )
b = 15;
}
a_r=(r_w*r + w*currentTeam->R())/( 15.0 * ( w + r_w ) );
a_g=(g_w*g + w*currentTeam->G())/( 15.0 * ( w + g_w ) );
a_b=(b_w*b + w*currentTeam->B())/( 15.0 * ( w + b_w ) );
}
else
{
a_r = r/15.0;
a_g = g/15.0;
a_b = b/15.0;
}
}
void ePlayerNetID::TrailColor( REAL&a_r, REAL&a_g, REAL&a_b ) const
{
Color( a_r, a_g, a_b );
/*
if ( ( static_cast<bool>(currentTeam) ) && ( currentTeam->IsHuman() ) )
{
int w = 6;
a_r=(2*r + w*currentTeam->R())/( 15.0 * ( w + 2 ) );
a_g=(2*g + w*currentTeam->G())/( 15.0 * ( w + 2 ) );
_b=(2*b + w*currentTeam->B())/( 15.0 * ( w + 2 ) );
}
else
{
a_r = r/15.0;
a_g = g/15.0;
a_b = b/15.0;
}
*/
}
/*
void ePlayerNetID::AddRef()
{
nNetObject::AddRef();
}
void ePlayerNetID::Release()
{
nNetObject::Release();
}
*/
static void se_PlayerMessageConf(std::istream &s)
{
if ( se_NeedsServer( "PLAYER_MESSAGE", s ) )
{
return;
}
int receiver = se_ReadUser( s );
tColoredString msg;
s >> msg;
if ( receiver <= 0 || s.good() )
{
con << tOutput("$player_message_usage");
return;
}
msg << '\n';
sn_ConsoleOut(msg, 0);
sn_ConsoleOut(msg, receiver);
}
static tConfItemFunc se_PlayerMessage_c("PLAYER_MESSAGE", &se_PlayerMessageConf);
static tAccessLevelSetter se_messConfLevel( se_PlayerMessage_c, tAccessLevel_Moderator );
static void CenterPlayerMessage_conf(std::istream &s)
{
if ( se_NeedsServer( "CENTER_PLAYER_MESSAGE", s ) )
{
return;
}
int receiver = se_ReadUser( s );
tColoredString msg;
s >> msg;
if ( receiver <= 0 || s.good() )
{
con << tOutput("Usage: CENTER_PLAYER_MESSAGE <user ID or name> \"<Message>\"\n");
return;
}
// display it
con << tOutput(msg) << tOutput("\n");
sn_CenterMessage(msg, receiver);
}
static tConfItemFunc CenterPlayerMessage_c("CENTER_PLAYER_MESSAGE",&CenterPlayerMessage_conf);
static tAccessLevelSetter sn_CenterPlayerConfLevel( CenterPlayerMessage_c, tAccessLevel_Moderator );
static tString se_defaultKickReason("");
static tConfItemLine se_defaultKickReasonConf( "DEFAULT_KICK_REASON", se_defaultKickReason );
static void se_KickConf(std::istream &s)
{
if ( se_NeedsServer( "KICK", s ) )
{
return;
}
// get user ID
int num = se_ReadUser( s );
tString reason = se_defaultKickReason;
if ( !s.eof() )
reason.ReadLine(s);
// and kick.
if ( num > 0 && !s.good() )
{
// output to console so we can detect
con << "ADMIN command KICK issued for "<< num << " " << reason << "\n";
sn_KickUser( num , reason.Len() > 1 ? static_cast< char const *>( reason ) : "$network_kill_kick" );
}
else
{
con << tOutput("$kick_usage");
return;
}
}
static tConfItemFunc se_kickConf("KICK",&se_KickConf);
static tAccessLevelSetter se_kickConfLevel( se_kickConf, tAccessLevel_Moderator );
static void se_BootConf(std::istream &s)
{
if ( se_NeedsServer( "BOOT", s ) )
{
return;
}
// get user ID
int num = se_ReadUser( s );
tString reason = se_defaultKickReason;
if ( !s.eof() )
reason.ReadLine(s);
// and kick.
if ( num > 0 && !s.good() )
{
// output to console so we can detect
con << "ADMIN command BOOT issued for "<< num << " " << reason << "\n";
sn_DisconnectUser( num , reason.Len() > 1 ? static_cast< char const *>( reason ) : "$network_kill_kick" );
}
else
{
con << tOutput("$boot_usage");
return;
}
}
static tConfItemFunc se_bootConf("BOOT",& se_BootConf);
static tAccessLevelSetter se_bootConfLevel( se_bootConf, tAccessLevel_Moderator );
static tString se_defaultKickToServer("");
static int se_defaultKickToPort = 4534;
static tString se_defaultKickToReason("");
static tSettingItem< tString > se_defaultKickToServerConf( "DEFAULT_KICK_TO_SERVER", se_defaultKickToServer );
static tSettingItem< int > se_defaultKickToPortConf( "DEFAULT_KICK_TO_PORT", se_defaultKickToPort );
static tConfItemLine se_defaultKickToReasonConf( "DEFAULT_KICK_TO_REASON", se_defaultKickToReason );
static void se_MoveToConf(std::istream &s, REAL severity, const char * command )
{
if ( se_NeedsServer( "KICK/MOVE_TO", s ) )
{
return;
}
// get user ID
int num = se_ReadUser( s );
// read redirection target
tString server = se_defaultKickToServer;
if ( !s.eof() )
{
s >> server;
}
int pos, port = se_defaultKickToPort;
if ( ( pos = server.StrPos( ":" ) ) != -1 )
{
port = atoi( server.SubStr( pos + 1 ) );
server = server.SubStr( 0, pos );
}
nServerInfoRedirect redirect( server, port );
tString reason = se_defaultKickToReason;
if ( !s.eof() )
reason.ReadLine(s);
// and kick.
if ( num > 0 && !s.good() )
{
sn_KickUser( num , reason.Len() > 1 ? static_cast< char const *>( reason ) : "$network_kill_kick", severity, &redirect );
}
else
{
con << tOutput( "$kickmove_usage", command );
return;
}
}
static void se_KickToConf(std::istream &s )
{
se_MoveToConf( s, 1, "KICK_TO" );
}
static tConfItemFunc se_kickToConf("KICK_TO",&se_KickToConf);
static tAccessLevelSetter se_kickToConfLevel( se_kickToConf, tAccessLevel_Moderator );
static void se_MoveToConf(std::istream &s )
{
se_MoveToConf( s, 0, "MOVE_TO" );
}
static tConfItemFunc se_moveToConf("MOVE_TO",&se_MoveToConf);
static tAccessLevelSetter se_moveConfLevel( se_moveToConf, tAccessLevel_Moderator );
static void se_BanConf(std::istream &s)
{
if ( se_NeedsServer( "BAN", s ) )
{
return;
}
// get user ID
int num = se_ReadUser( s );
if ( num == 0 && !s.good() )
{
con << tOutput( "$ban_usage" );
return;
}
// read time to ban
REAL banTime = 60;
s >> banTime;
std::ws(s);
tString reason;
reason.ReadLine(s);
// output to console so we can detect
con << "ADMIN command BAN issued for "<< num << " " << banTime << " " << reason << "\n";
// and ban.
if ( num > 0 )
{
nMachine::GetMachine( num ).Ban( banTime * 60, reason );
sn_DisconnectUser( num , reason.Len() > 1 ? static_cast< char const *>( reason ) : "$network_kill_kick" );
}
}
static tConfItemFunc se_banConf("BAN",&se_BanConf);
static tAccessLevelSetter se_banConfLevel( se_banConf, tAccessLevel_Moderator );
ePlayerNetID * ePlayerNetID::ReadPlayer( std::istream & s )
{
// read name of player to be returned
tString name;
s >> name;
/* Removed by ed so players are not selected by id number, just names, So players with a number for a name do not confuse things
int num = name.toInt();
if ( num > 0 )
{
// look for a player from that client
for ( int i = se_PlayerNetIDs.Len()-1; i>=0; --i )
{
ePlayerNetID* p = se_PlayerNetIDs(i);
// check whether it's p who should be returned
if ( p->Owner() == num )
{
return p;
}
}
}
*/
return ePlayerNetID::FindPlayerByName( name );
}
static bool se_enableAdminKillMessage = true;
static tSettingItem< bool > se_enableAdminKillMessageConf( "ADMIN_KILL_MESSAGE", se_enableAdminKillMessage );
static eLadderLogWriter se_playerKilledWriter("PLAYER_KILLED", true);
static ePlayerNetID * ReadPlayer( std::istream & s )
{
return ePlayerNetID::ReadPlayer( s );
}
static void Kill_conf(std::istream &s)
{
if ( se_NeedsServer( "KILL", s, false ) )
{
return;
}
ePlayerNetID * p = ReadPlayer( s );
if ( p && p->Object() && p->Object()->Alive() )
{
if (se_enableAdminKillMessage)
{
sn_ConsoleOut( tOutput( "$player_admin_kill", p->GetColoredName() ) );
}
se_playerKilledWriter << p->GetUserName() << nMachine::GetMachine(p->Owner()).GetIP() << p->Object()->Position().x << p->Object()->Position().y << p->Object()->Direction().x << p->Object()->Direction().y;
se_playerKilledWriter.write();
p->Object()->Kill();
}
}
static tConfItemFunc kill_conf("KILL",&Kill_conf);
static tAccessLevelSetter se_killConfLevel( kill_conf, tAccessLevel_Moderator );
static void Kill_ID_conf(std::istream &s)
{
if ( se_NeedsServer( "KILL_ID", s, false ) )
{
return;
}
int owner_id = 0;
s >> owner_id;
ePlayerNetID *p = ePlayerNetID::FindPlayerById(owner_id);
if (p)
{
if (p->Object() && p->Object()->Alive())
{
if (se_enableAdminKillMessage)
{
sn_ConsoleOut( tOutput( "$player_admin_kill", p->GetColoredName() ) );
}
se_playerKilledWriter << p->GetUserName() << nMachine::GetMachine(p->Owner()).GetIP() << p->Object()->Position().x << p->Object()->Position().y << p->Object()->Direction().x << p->Object()->Direction().y;
se_playerKilledWriter.write();
p->Object()->Kill();
}
}
}
static tConfItemFunc kill_id_conf("KILL_ID",&Kill_conf);
static tAccessLevelSetter se_killIDConfLevel( kill_id_conf, tAccessLevel_Moderator );
static void Slap_conf(std::istream &s)
{
if ( se_NeedsServer( "SLAP", s, false ) )
{
return;
}
ePlayerNetID * victim = ReadPlayer( s );
if ( victim )
{
int points = 1;
s >> points;
if ( points == 0)
{
// oh well :)
sn_ConsoleOut( tOutput("$player_admin_slap_free", victim->GetColoredName() ) );
}
else
{
tOutput win;
tOutput lose;
win << "$player_admin_slap_win";
lose << "$player_admin_slap_lose";
victim->AddScore( -points, win, lose );
}
}
}
static tConfItemFunc slap_conf("SLAP", &Slap_conf);
static void Points_conf(std::istream &s)
{
if ( se_NeedsServer( "POINTS", s, false ) )
{
return;
}
ePlayerNetID * victim = ReadPlayer( s );
if ( victim )
{
int points = 1;
s >> points;
if ( points == 0)
{
// oh well :)
sn_ConsoleOut( tOutput("$player_admin_slap_free", victim->GetColoredName() ) );
}
else
{
tOutput win;
tOutput lose;
win << "$player_admin_slap_win";
lose << "$player_admin_slap_lose";
victim->AddScore( points, win, lose );
}
}
}
static tConfItemFunc pointsconf("POINTS", &Points_conf);
static void GivePoints_conf(std::istream &s)
{
if ( se_NeedsServer( "GIVE_POINTS", s, false ) )
{
return;
}
ePlayerNetID * victim = ReadPlayer( s );
if ( victim )
{
int points = 1;
s >> points;
if ( points == 0)
{
// oh well :)
sn_ConsoleOut( tOutput("$player_admin_slap_free", victim->GetColoredName() ) );
}
else
{
tOutput win;
//tOutput lose;
win << "$player_admin_slap_win";
//lose << "$player_admin_slap_lose";
victim->AddScore( points, win, "" );
}
}
}
static tConfItemFunc givepoint_conf("GIVE_POINTS", &GivePoints_conf);
static void TakePoints_conf(std::istream &s)
{
if ( se_NeedsServer( "TAKE_POINTS", s, false ) )
{
return;
}
ePlayerNetID * victim = ReadPlayer( s );
if ( victim )
{
int points = 1;
s >> points;
if ( points == 0)
{
// oh well :)
sn_ConsoleOut( tOutput("$player_admin_slap_free", victim->GetColoredName() ) );
}
else
{
//tOutput win;
tOutput lose;
//win << "$player_admin_slap_win";
lose << "$player_admin_slap_lose";
victim->AddScore( -points, "", lose );
}
}
}
static tConfItemFunc takepoint_conf("TAKE_POINTS", &TakePoints_conf);
static int se_suspendDefault = 5;
static tSettingItem< int > se_suspendDefaultConf( "SUSPEND_DEFAULT_ROUNDS", se_suspendDefault );
static void Suspend_conf_base(std::istream &s, int rounds )
{
if ( se_NeedsServer( "SUSPEND", s, false ) )
{
return;
}
tString player;
s >> player;
s >> rounds;
tString reason;
std::ws(s);
if ( s.good() )
{
reason.ReadLine(s);
}
ePlayerNetID *p = ePlayerNetID::FindPlayerByName(player);
if (p)
{
if (reason.Filter() != "")
p->Suspend( rounds, reason );
else
p->Suspend( rounds );
}
}
static void Suspend_conf(std::istream &s )
{
Suspend_conf_base( s, se_suspendDefault );
}
static void UnSuspend_conf(std::istream &s )
{
Suspend_conf_base( s, 0 );
}
static tConfItemFunc suspend_conf("SUSPEND",&Suspend_conf);
static tConfItemFunc Unsuspend_conf("UNSUSPEND",&UnSuspend_conf);
static tAccessLevelSetter se_suspendConfLevel( suspend_conf, tAccessLevel_Moderator );
static tAccessLevelSetter se_unsuspendConfLevel( Unsuspend_conf, tAccessLevel_Moderator );
static void Suspend_All_Base(int rounds)
{
if ( sn_GetNetState() == nCLIENT )
{
return;
}
for (int i = 0; i < se_PlayerNetIDs.Len(); i++)
{
ePlayerNetID *p = se_PlayerNetIDs[i];
if (p)
{
p->Suspend(rounds);
}
}
}
static void SuspendAll_conf(std::istream &s )
{
tString params, roundsStr;
int rounds = se_suspendDefault;
s >> roundsStr;
if ((roundsStr.Filter() != "") && (roundsStr.IsNumeric()))
rounds = atoi(roundsStr);
Suspend_All_Base(rounds);
}
static void UnSuspendAll_conf(std::istream &s )
{
Suspend_All_Base(0);
}
static tConfItemFunc suspendall_conf("SUSPEND_ALL",&SuspendAll_conf);
static tConfItemFunc Unsuspendall_conf("UNSUSPEND_ALL",&UnSuspendAll_conf);
static tAccessLevelSetter se_suspendallConfLevel( suspendall_conf, tAccessLevel_Moderator );
static tAccessLevelSetter se_unsuspendallConfLevel( Unsuspendall_conf, tAccessLevel_Moderator );
static void SuspendList_conf(std::istream &s)
{
sn_ConsoleOut("List of currently suspended players:\n", 0 );
if (se_PlayerNetIDs.Len()>0)
{
for(int i = 0; i < se_PlayerNetIDs.Len(); i++)
{
ePlayerNetID *p = se_PlayerNetIDs[i];
if (p)
{
// let's ensure this person is actually suspended
if (p->IsSuspended())
{
tColoredString send;
send << tColoredString::ColorString( 1,1,.5 );
send << "( ";
send << p->GetColoredName();
send << tColoredString::ColorString( 1,1,.5 );
send << " | " << p->RoundsSuspended() << " rounds | ";
// making sure if there really was a reason for suspension.
if (p->ReasonSuspended().Filter() != "")
send << p->ReasonSuspended();
// if not, then let's tell them that
else
send << "UNKNOWN_REASON";
send << " )\n";
sn_ConsoleOut( send, 0 );
}
}
}
}
}
static tConfItemFunc suspendlist_conf("SUSPEND_LIST", &SuspendList_conf);
static tAccessLevelSetter se_suspendlistConfLevel( suspendlist_conf, tAccessLevel_Moderator );
static void Silence_conf(std::istream &s)
{
if ( se_NeedsServer( "SILENCE", s ) )
{
return;
}
ePlayerNetID * p = ReadPlayer( s );
if ( p && !p->IsSilenced() )
{
sn_ConsoleOut( tOutput( "$player_silenced", p->GetColoredName() ) );
p->SetSilenced( true );
}
}
static tConfItemFunc silence_conf("SILENCE",&Silence_conf);
static tAccessLevelSetter se_silenceConfLevel( silence_conf, tAccessLevel_Moderator );
static void SilenceAll_conf(std::istream &s)
{
if ( se_NeedsServer( "SILENCE_ALL", s ) )
{
return;
}
if (se_PlayerNetIDs.Len()>0)
{
int max = se_PlayerNetIDs.Len();
for(int i=0; i<max; i++)
{
ePlayerNetID *p=se_PlayerNetIDs(i);
if ( p && !p->IsSilenced() )
{
p->SetSilenced( true );
}
}
sn_ConsoleOut( tOutput( "$player_silenced_all") );
}
}
static tConfItemFunc silenceall_conf("SILENCE_ALL",&SilenceAll_conf);
static tAccessLevelSetter se_silenceallConfLevel( silenceall_conf, tAccessLevel_Moderator );
static void Voice_conf(std::istream &s)
{
if ( se_NeedsServer( "VOICE", s ) || se_NeedsServer( "UNSILENCE", s ))
{
return;
}
ePlayerNetID * p = ReadPlayer( s );
if ( p && p->IsSilenced() )
{
sn_ConsoleOut( tOutput( "$player_voiced", p->GetColoredName() ) );
p->SetSilenced( false );
}
}
static tConfItemFunc voice_conf("VOICE",&Voice_conf);
static tAccessLevelSetter se_voiceConfLevel( voice_conf, tAccessLevel_Moderator );
static tConfItemFunc unsilence_conf("UNSILENCE",&Voice_conf);
static tAccessLevelSetter se_unsilenceConfLevel( unsilence_conf, tAccessLevel_Moderator );
static void VoiceAll(std::istream &s)
{
if ( se_NeedsServer( "VOICE_ALL", s ) || se_NeedsServer( "UNSILENCE_ALL", s ))
{
return;
}
if (se_PlayerNetIDs.Len()>0)
{
int max = se_PlayerNetIDs.Len();
for(int i=0; i<max; i++)
{
ePlayerNetID *p=se_PlayerNetIDs(i);
if ( p && p->IsSilenced() )
{
p->SetSilenced( false );
}
}
sn_ConsoleOut( tOutput( "$player_voiced_all") );
}
}
static tConfItemFunc voiceall_conf("VOICE_ALL",&VoiceAll);
static tAccessLevelSetter se_voiceallConfLevel( voiceall_conf, tAccessLevel_Moderator );
static tConfItemFunc unsilenceall_conf("UNSILENCE_ALL",&VoiceAll);
static tAccessLevelSetter se_unsilenceallConfLevel( unsilenceall_conf, tAccessLevel_Moderator );
static tString sg_url;
static tSettingItem< tString > sg_urlConf( "URL", sg_url );
static tString sg_options("Nothing special.");
#ifdef DEDICATED
static tConfItemLine sg_optionsConf( "SERVER_OPTIONS", sg_options );
#endif
class gServerInfoAdmin: public nServerInfoAdmin
{
public:
gServerInfoAdmin() {}
private:
virtual tString GetUsers() const
{
tString ret;
for ( int i = se_PlayerNetIDs.Len()-1; i>=0; --i )
{
ePlayerNetID* p = se_PlayerNetIDs(i);
if ( p->IsHuman() )
{
ret << p->GetName() << "\n";
}
}
return ret;
}
virtual tString GetGlobalIDs() const
{
tString ret;
#ifdef KRAWALL_SERVER
int count = 0;
for ( int i = se_PlayerNetIDs.Len()-1; i>=0; --i )
{
ePlayerNetID* p = se_PlayerNetIDs(i);
if ( p->IsHuman() )
{
if( p->IsAuthenticated() && !se_Hide(p, tAccessLevel_Default) )
{
for(; count > 0; --count)
{
ret << "\n";
}
ret << p->GetFilteredAuthenticatedName();
}
++count;
}
}
#endif
return ret;
}
virtual tString GetOptions() const
{
se_CutString( sg_options, 240 );
return sg_options;
}
virtual tString GetUrl() const
{
se_CutString( sg_url, 75 );
return sg_url;
}
};
static gServerInfoAdmin sg_serverAdmin;
static eLadderLogWriter se_playerEnteredGridWriter("PLAYER_ENTERED_GRID", true);
static eLadderLogWriter se_playerEnteredSpectatorWriter("PLAYER_ENTERED_SPECTATOR", true);
static eLadderLogWriter se_playerAIEnteredWriter("PLAYER_AI_ENTERED", true);
static eLadderLogWriter se_playerRenamedWriter("PLAYER_RENAMED", true);
class eNameMessenger
{
public:
eNameMessenger( ePlayerNetID & player )
: player_( player )
, oldScreenName_( player.GetName() )
, oldLogName_( player.GetLogName() )
, adminRename_( !player.IsAllowedToRename() )
{
// store old name for password re-request and name change message
oldPrintName_ << player_ << tColoredString::ColorString(.5,1,.5);
}
~eNameMessenger()
{
if ( sn_GetNetState() == nCLIENT )
{
return;
}
tString logName = player_.GetLogName();
tString const & screenName = player_.GetName();
// messages for the users
tColoredString printName;
printName << player_ << tColoredString::ColorString(.5,1,.5);
tOutput mess;
mess.SetTemplateParameter(1, printName);
mess.SetTemplateParameter(2, oldPrintName_);
// is the player new?
if ( oldLogName_.Len() <= 1 && logName.Len() > 0 )
{
if ( player_.IsHuman() )
{
player_.Greet();
// print spectating join message (regular join messages are handled by eTeam)
if ( ( player_.IsSpectating() || player_.IsSuspended() || !se_assignTeamAutomatically ) && ( se_assignTeamAutomatically || se_specSpam ) )
{
se_playerEnteredSpectatorWriter << logName << nMachine::GetMachine(player_.Owner()).GetIP() << screenName;
se_playerEnteredSpectatorWriter.write();
player_.LogActivity(ACTIVITY_ENTERED_SPECTATOR);
mess << "$player_entered_spectator";
sn_ConsoleOut(mess);
}
else
{
se_playerEnteredGridWriter << logName << nMachine::GetMachine(player_.Owner()).GetIP() << screenName;
se_playerEnteredGridWriter.write();
player_.LogActivity(ACTIVITY_ENTERED_GRID);
}
tColoredString colouredName;
colouredName << player_.GetColoredName();
se_playerColoredNameWriter << player_.GetUserName() << colouredName;
se_playerColoredNameWriter.write();
}
else
{
se_playerAIEnteredWriter << logName << screenName;
se_playerAIEnteredWriter.write();
tColoredString colouredName;
colouredName << player_.GetColoredName();
se_playerColoredNameWriter << player_.GetUserName() << colouredName;
se_playerColoredNameWriter.write();
}
}
else if ( logName != oldLogName_ || screenName != oldScreenName_ )
{
se_playerRenamedWriter << oldLogName_ << logName << nMachine::GetMachine(player_.Owner()).GetIP();
#ifdef KRAWALL_SERVER
se_playerRenamedWriter << (player_.IsAuthenticated()?1:0);
#else
se_playerRenamedWriter << (player_.HasLoggedIn()?1:0);
#endif
se_playerRenamedWriter << screenName;
se_playerRenamedWriter.write();
//! Race Hack
// clearing out hacked variable for proper use with username
if (player_.HasLoggedIn())
player_.SetAuthenticatedName(tString(""));
if ( oldScreenName_ != screenName )
{
eVoter *voter = eVoter::GetPersistentVoter( player_.Owner() );
if ( voter )
{
voter->PlayerChanged();
}
if ( adminRename_ )
{
// if our player isn't able to rename, he didn't do it alone, did he ? :)
mess << "$player_got_renamed";
}
else
{
mess << "$player_renamed";
}
sn_ConsoleOut(mess);
tColoredString colouredName;
colouredName << player_.GetColoredName();
se_playerColoredNameWriter << player_.GetUserName() << colouredName;
se_playerColoredNameWriter.write();
}
}
}
ePlayerNetID & player_;
tString oldScreenName_, oldLogName_;
tColoredString oldPrintName_;
bool adminRename_;
};
// ******************************************************************************************
// *
// * UpdateName
// *
// ******************************************************************************************
//!
//!
// ******************************************************************************************
void ePlayerNetID::UpdateName( void )
{
// don't do a thing if we're not fully synced
if ( this->ID() == 0 && nameFromClient_.Len() <= 1 && sn_GetNetState() == nSERVER )
return;
// monitor name changes
eNameMessenger messenger( *this );
// apply client change, stripping excess spaces
if ( sn_GetNetState() == nSTANDALONE
|| ( Owner() == 0 && sn_GetNetState() != nCLIENT )
|| (
IsHuman()
&& ( sn_GetNetState() == nCLIENT || !messenger.adminRename_ )
&& ( sn_GetNetState() != nCLIENT || Owner() == sn_myNetID )
)
)
{
// apply name filters only on remote players
if ( Owner() != 0 )
se_OptionalNameFilters( nameFromClient_, Owner() );
// nothing wrong ? proceed to renaming
nameFromAdmin_ = nameFromServer_ = nameFromClient_;
}
else if ( sn_GetNetState() == nCLIENT )
{
// If we are in client mode, just follow our leader the server :)
nameFromAdmin_ = nameFromClient_ = nameFromServer_;
}
else
{
// revert name
nameFromClient_ = nameFromServer_ = nameFromAdmin_;
}
// remove colors from name
tString newName = tColoredString::RemoveColors( nameFromServer_ );
tString newUserName = se_UnauthenticatedUserName( newName );
// test if it is already taken, find an alternative name if so.
if ( sn_GetNetState() != nCLIENT && se_IsNameTaken( newUserName, this ) )
{
// Remove possilble trailing digit.
if ( newName.Len() > 2 && isdigit(newName(newName.Len()-2)) )
{
newName = newName.SubStr( 0, newName.Len()-2 );
}
// append numbers until the name is free
for ( int i = 2; i < se_PlayerNetIDs.Len(); ++i )
{
tString testName(newName);
testName << i;
// cut the beginning if the name is too long
if ( testName.Len() > 17 )
testName = testName.SubStr( testName.Len() - 17 );
newUserName = se_UnauthenticatedUserName( testName );
if ( !se_IsNameTaken( newUserName, this ) )
{
newName = testName;
break;
}
}
// rudely overwrite name from client
nameFromAdmin_ = nameFromServer_ = newName;
}
// set the colored name to the name from the client, set trailing color to white
coloredName_.Clear();
REAL r,g,b;
Color(r,g,b);
coloredName_ << tColoredString::ColorString(r,g,b) << nameFromServer_;
if ( name_ != newName || lastAccessLevel != GetAccessLevel() )
{
// copy it to the name, removing colors of course
name_ = newName;
// remove spaces and possibly other nasties for the user name
userName_ = se_UnauthenticatedUserName( name_ );
if (sn_GetNetState()!=nCLIENT)
{
// sync the new name
RequestSync();
}
}
// store access level for next update
lastAccessLevel = GetAccessLevel();
#ifdef KRAWALL_SERVER
// take the user name to be the authenticated name
if ( IsAuthenticated() )
{
userName_ = GetFilteredAuthenticatedName();
if ( se_legacyLogNames )
{
userName_ = tString( "0:" ) + userName_;
}
}
else
{
rawAuthenticatedName_ = "";
authenticatedname = "";//! Race hack
}
#endif
}
// ******************************************************************************************
// *
// * AllowRename
// *
// ******************************************************************************************
//!
//! @param allow let the player rename or not ?
//!
// ******************************************************************************************
void ePlayerNetID::AllowRename( bool allow )
{
// simple eh ? :-)
renameAllowed_ = allow;
}
// Now we're here, set commands for it
static void AllowRename( std::istream & s , bool allow , bool announce )
{
if ( se_NeedsServer( "(DIS)ALLOW_RENAME_PLAYER", s ) )
{
return;
}
ePlayerNetID * p;
p = ReadPlayer( s );
if ( p )
{
// announce it?
if ( announce && allow )
{
sn_ConsoleOut( tOutput("$player_allowed_rename", p->GetColoredName() ) );
}
else if ( announce && !allow )
{
sn_ConsoleOut( tOutput("$player_disallowed_rename", p->GetColoredName() ) );
}
p->AllowRename ( allow );
}
}
static void AllowRename( std::istream & s )
{
if ( se_NeedsServer( "ALLOW_RENAME_PLAYER", s ) )
{
return;
}
AllowRename( s , true, true );
}
static tConfItemFunc AllowRename_conf("ALLOW_RENAME_PLAYER", &AllowRename);
static tAccessLevelSetter AllowRename_confLevel( AllowRename_conf, tAccessLevel_Moderator );
static void DisAllowRename( std::istream & s )
{
if ( se_NeedsServer( "DISALLOW_RENAME_PLAYER", s ) )
{
return;
}
AllowRename( s , false, true );
}
static tConfItemFunc DisAllowRename_conf("DISALLOW_RENAME_PLAYER", &DisAllowRename);
static tAccessLevelSetter DisAllowRename_confLevel( DisAllowRename_conf, tAccessLevel_Moderator );
// ******************************************************************************************
// *
// * IsAllowedToRename
// *
// ******************************************************************************************
//!
//!
// ******************************************************************************************
bool ePlayerNetID::HasRenameCapability ( ePlayerNetID const * victim, ePlayerNetID const * admin )
{
return Rename_conf.GetRequiredLevel() <= admin->GetAccessLevel();
}
// ******************************************************************************************
// *
// * IsAllowedToRename
// *
// ******************************************************************************************
//!
//!
// ******************************************************************************************
bool ePlayerNetID::IsAllowedToRename ( void )
{
if ( !IsHuman() || ( nameFromServer_ == nameFromClient_ && nameFromServer_ == nameFromAdmin_ ) || nameFromServer_.Len() <= 1 || sn_GetNetState() == nCLIENT )
{
// Don't complain about people who either are bots, doesn't change name, or are entering the grid
return true;
}
if ( nameFromServer_ != nameFromAdmin_ )
{
// We are going to rename this player, so, no need to tell him he's trying to rename from his old name to his old name :-P
// Just return false so the server thinks the player can't be renamed in any other way than admin-rename.
return false;
}
// didn't we disallow this player to rename via a command ?
if ( !this->renameAllowed_ )
{
tOutput message( "$player_rename_rejected_admin", nameFromServer_, nameFromClient_ );
se_SecretConsoleOut( message, this, &ePlayerNetID::HasRenameCapability, this );
con << message;
return false;
}
// don't let the player rename if s/he is silenced.
if ( this->IsSilenced() )
{
tOutput message("$player_rename_silenced");
sn_ConsoleOut( message, Owner() );
return false;
}
// disallow name changes if there was a kick vote recently
eVoter *voter = eVoter::GetVoter( Owner() );
if ( !( !bool(voter) || voter->AllowNameChange() || nameFromServer_.Len() <= 1 ) && nameFromServer_ != nameFromClient_ )
{
// inform victim to avoid complaints
tOutput message( "$player_rename_rejected_votekick", nameFromServer_, nameFromClient_ );
sn_ConsoleOut( message, Owner() );
con << message;
return false;
}
// Nothing to complain about ? fine, he can rename
return true;
}
// filters illegal player characters
class ePlayerCharacterFilter
{
public:
ePlayerCharacterFilter()
{
int i;
filter[0]=0;
// map all unknown characters to underscores
for (i=255; i>0; --i)
{
filter[i] = '_';
}
// leave ASCII characters as they are
for (i=126; i>32; --i)
{
filter[i] = i;
}
// but convert uppercase characters to lowercase
for (i='Z'; i>='A'; --i)
{
filter[i] = i + ('a' - 'A');
}
//! map umlauts and stuff to their base characters
SetMap(0xc0,0xc5,'a');
SetMap(0xd1,0xd6,'o');
SetMap(0xd9,0xdD,'u');
SetMap(0xdf,'s');
SetMap(0xe0,0xe5,'a');
SetMap(0xe8,0xeb,'e');
SetMap(0xec,0xef,'i');
SetMap(0xf0,0xf6,'o');
SetMap(0xf9,0xfc,'u');
// ok, some of those are a bit questionable, but still better than _...
SetMap(161,'!');
SetMap(162,'c');
SetMap(163,'l');
SetMap(165,'y');
SetMap(166,'|');
SetMap(167,'s');
SetMap(168,'"');
SetMap(169,'c');
SetMap(170,'a');
SetMap(171,'"');
SetMap(172,'!');
SetMap(174,'r');
SetMap(176,'o');
SetMap(177,'+');
SetMap(178,'2');
SetMap(179,'3');
SetMap(182,'p');
SetMap(183,'.');
SetMap(185,'1');
SetMap(187,'"');
SetMap(198,'a');
SetMap(199,'c');
SetMap(208,'d');
SetMap(209,'n');
SetMap(215,'x');
SetMap(216,'o');
SetMap(221,'y');
SetMap(222,'p');
SetMap(231,'c');
SetMap(241,'n');
SetMap(247,'/');
SetMap(248,'o');
SetMap(253,'y');
SetMap(254,'p');
SetMap(255,'y');
//map 0 to o because they look similar
SetMap('0','o');
// TODO: make this data driven.
}
char Filter( unsigned char in )
{
return filter[ static_cast< unsigned int >( in )];
}
private:
void SetMap( int in1, int in2, unsigned char out)
{
tASSERT( in2 <= 0xff );
tASSERT( 0 <= in1 );
tASSERT( in1 < in2 );
for( int i = in2; i >= in1; --i )
filter[ i ] = out;
}
void SetMap( unsigned char in, unsigned char out)
{
filter[ static_cast< unsigned int >( in ) ] = out;
}
char filter[256];
};
static bool se_IsUnderscore( char c )
{
return c == '_';
}
// ******************************************************************************************
// *
// * FilterName
// *
// ******************************************************************************************
//!
//! @param in input name
//! @param out output name cleared to be usable as a username
//!
// ******************************************************************************************
void ePlayerNetID::FilterName( tString const & in, tString & out )
{
int i;
static ePlayerCharacterFilter filter;
out = tColoredString::RemoveColors( in );
// filter out illegal characters
for ( i = out.Len()-1; i>=0; --i )
{
char & c = out[i];
c = filter.Filter( c );
}
// strip leading and trailing unknown characters
se_StripMatchingEnds( out, se_IsUnderscore, se_IsUnderscore );
}
// ******************************************************************************************
// *
// * FilterName
// *
// ******************************************************************************************
//!
//! @param in input name
//! @return output name cleared to be usable as a username
//!
// ******************************************************************************************
tString ePlayerNetID::FilterName( tString const & in )
{
tString out;
FilterName( in, out );
return out;
}
// ******************************************************************************************
// *
// * SetName
// *
// ******************************************************************************************
//!
//! @param name this player's name without colors. to set
//! @return A reference to this to allow chaining
//!
// ******************************************************************************************
ePlayerNetID & ePlayerNetID::SetName( tString const & name )
{
this->nameFromClient_ = name;
this->nameFromClient_.NetFilter();
// replace empty name
if ( !IsLegalPlayerName( nameFromClient_ ) )
{
nameFromClient_ = "Player ";
nameFromClient_ << Owner();
}
if ( sn_GetNetState() != nCLIENT )
nameFromServer_ = nameFromClient_;
UpdateName();
return *this;
}
// ******************************************************************************************
// *
// * SetName
// *
// ******************************************************************************************
//!
//! @param name this player's name without colors. to set
//! @return A reference to this to allow chaining
//!
// ******************************************************************************************
ePlayerNetID & ePlayerNetID::SetName( char const * name )
{
SetName( tString( name ) );
return *this;
}
// ******************************************************************************************
// *
// * ForceName
// *
// ******************************************************************************************
//!
//! @param name this player's name
//!
// ******************************************************************************************
ePlayerNetID & ePlayerNetID::ForceName( tString const & name )
{
// This just sets nameFromAdmin_ waiting for the server to look at it next round (this->UpdateName())
// Also forbid the player from renameing then, because it would be useless :-P
if ( sn_GetNetState() != nCLIENT )
{
tColoredString oldName;
tColoredString newName;
oldName << this->GetColoredName() << tColoredString::ColorString( -1, -1, -1 );
this->nameFromAdmin_ = name;
this->nameFromAdmin_.NetFilter();
// remove all colors from name
tString colorlessName = tColoredString::RemoveColors(this->nameFromAdmin_, false);
// check if the colorless name's length is longer than the limited length
if (colorlessName.Len() > 16)
{
se_CutString( this->nameFromAdmin_, 16 );
}
// crappiest line ever :-/
newName << tColoredString::ColorString( r/15.0, g/15.0, b/15.0 ) << this->nameFromAdmin_ << tColoredString::ColorString( -1, -1, -1 );
sn_ConsoleOut(tOutput("$player_will_be_renamed", newName, oldName));
AllowRename ( false );
}
return *this;
}
// Set an admin command for it
void ForceName ( std::istream & s )
{
ePlayerNetID * p = NULL;
tString playername, newname;
s >> playername;
p = ePlayerNetID::FindPlayerByName(playername);
if (p)
{
s >> newname;
if (newname.Filter() != "")
p->ForceName ( newname );
}
}
// the tConfItemFunc is defined in ePlayer.h
// ******************************************************************************************
// *
// * GetFilteredAuthenticatedName
// *
// ******************************************************************************************
//!
//! @return The filtered authentication name, or "" if no authentication is supported or the player is not authenticated
//!
// ******************************************************************************************
tString ePlayerNetID::GetFilteredAuthenticatedName( void ) const
{
#ifdef KRAWALL_SERVER
return tString( se_EscapeName( GetRawAuthenticatedName() ).c_str() );
#else
return tString( se_EscapeName( GetAuthenticatedName() ).c_str() );
#endif
}
class eEnemiesWhitelist
{
public:
eEnemiesWhitelist() :usernames_whitelist_(), ip_addresses_whitelist_() {}
// Returns true if the two players can be enemies.
//
// Assumes both "a" and "b" are from the same IP address.
bool CanBeEnemies( const ePlayerNetID * a, const ePlayerNetID * b ) const
{
bool enemies = HasEntry( ip_addresses_whitelist_, a->GetMachine().GetIP() );
#ifdef KRAWALL_SERVER
enemies |= a->IsAuthenticated() && HasEntry( usernames_whitelist_, a->GetLogName() );
enemies |= b->IsAuthenticated() && HasEntry( usernames_whitelist_, b->GetLogName() );
#endif
return enemies;
}
void AddUsernames( std::istream & s )
{
Parse( usernames_whitelist_, s );
}
void AddIPAddresses( std::istream & s )
{
Parse( ip_addresses_whitelist_, s );
}
protected:
typedef std::set< tString > StringSet;
void Parse( StringSet & whitelist, std::istream & s )
{
int entries_count = 0;
while ( s.good() )
{
tString name;
s >> name;
if ( name.Len() > 1 )
{
std::pair< StringSet::iterator, bool > ret = whitelist.insert( name );
if ( ret.second ) entries_count++;
}
}
con << tOutput( "$whitelist_enemies_success", entries_count ) << '\n';
}
bool HasEntry( const StringSet & whitelist, const tString & value ) const
{
return whitelist.find( value ) != whitelist.end();
}
StringSet usernames_whitelist_;
StringSet ip_addresses_whitelist_;
};
static eEnemiesWhitelist se_enemiesWhitelist;
#ifdef KRAWALL_SERVER
void se_WhiteListEnemiesUsername( std::istream & s )
{
se_enemiesWhitelist.AddUsernames( s );
}
static tConfItemFunc se_whiteListEnemiesUsernameConfItemFunc( "WHITELIST_ENEMIES_USERNAME", se_WhiteListEnemiesUsername );
#endif
void se_WhiteListEnemiesIP( std::istream & s )
{
se_enemiesWhitelist.AddIPAddresses( s );
}
static tConfItemFunc se_whiteListEnemiesIPConfItemFunc( "WHITELIST_ENEMIES_IP", se_WhiteListEnemiesIP );
// allow enemies from the same IP?
static bool se_allowEnemiesSameIP = false;
static tSettingItem< bool > se_allowEnemiesSameIPConf( "ALLOW_ENEMIES_SAME_IP", se_allowEnemiesSameIP );
// allow enemies from the same client?
static bool se_allowEnemiesSameClient = false;
static tSettingItem< bool > se_allowEnemiesSameClientConf( "ALLOW_ENEMIES_SAME_CLIENT", se_allowEnemiesSameClient );
// *******************************************************************************
// *
// * Enemies
// *
// *******************************************************************************
//!
//! @param a first player to compare
//! @param b second player to compare
//! @return true if a should be able to score against b or vice versa
//!
// *******************************************************************************
bool ePlayerNetID::Enemies( ePlayerNetID const * a, ePlayerNetID const * b )
{
// the client does not need a true answer
if ( sn_GetNetState() == nCLIENT )
return true;
// no scoring if one of them does not exist
if ( !a || !b )
return false;
// no scoring for two players from the same IP
if ( !se_allowEnemiesSameIP && a->Owner() != 0 && a->GetMachine() == b->GetMachine() && !se_enemiesWhitelist.CanBeEnemies( a, b ) )
return false;
// no scoring for two players from the same client
if ( !se_allowEnemiesSameClient && a->Owner() != 0 && a->Owner() == b->Owner() )
return false;
// no objections
return true;
}
// *******************************************************************************
// *
// * RegisterWithMachine
// *
// *******************************************************************************
//!
//!
// *******************************************************************************
void ePlayerNetID::RegisterWithMachine( void )
{
if ( !registeredMachine_ )
{
// store machine (it won't get deleted while this object exists; the player count prevents that)
registeredMachine_ = &this->nNetObject::DoGetMachine();
registeredMachine_->AddPlayer();
}
}
// *******************************************************************************
// *
// * UnregisterWithMachine
// *
// *******************************************************************************
//!
//!
// *******************************************************************************
void ePlayerNetID::UnregisterWithMachine( void )
{
if ( registeredMachine_ )
{
// store suspension count
eVoter *voter = eVoter::GetPersistentVoter( Owner() );
if ( voter )
{
voter->suspended_ = suspended_;
voter->silenced_ = silenced_;
}
registeredMachine_->RemovePlayer();
registeredMachine_ = 0;
}
}
// *******************************************************************************
// *
// * DoGetMachine
// *
// *******************************************************************************
//!
//! @return the machine this object belongs to
//!
// *******************************************************************************
nMachine & ePlayerNetID::DoGetMachine( void ) const
{
// return machine I'm registered at, otherwise whatever the base class thinks
if ( registeredMachine_ )
return *registeredMachine_;
else
return nNetObject::DoGetMachine();
}
// *******************************************************************************
// *
// * LastActivity
// *
// *******************************************************************************
//!
//! @return
//!
// *******************************************************************************
REAL ePlayerNetID::LastActivity( void ) const
{
return tSysTimeFloat() - lastActivity_;
}
// *******************************************************************************
// *
// * ResetScoreDifferences
// *
// *******************************************************************************
//!
//!
// *******************************************************************************
void ePlayerNetID::ResetScoreDifferences( void )
{
for ( int i = se_PlayerNetIDs.Len()-1; i>=0; --i )
{
ePlayerNetID* p = se_PlayerNetIDs(i);
if ( bool(p->Object()) && p->IsHuman() )
p->lastScore_ = p->score;
}
eTeam::ResetScoreDifferences();
}
// *******************************************************************************
// *
// * Suspend
// *
// *******************************************************************************
//!
//! @param rounds number of rounds to suspend
//!
// *******************************************************************************
void ePlayerNetID::Suspend( int rounds, tString reason )
{
if ( rounds < 0 )
{
rounds = 0;
}
if ( RoundsSuspended() == rounds )
{
return;
}
roundsSuspended_ = rounds;
if ( roundsSuspended_ == 0 )
{
sn_ConsoleOut( tOutput( "$player_no_longer_suspended", GetColoredName() ) );
FindDefaultTeam();
suspended_ = false;
suspendReason_ = "";
}
else
{
sn_ConsoleOut( tOutput( "$player_suspended", GetColoredName(), roundsSuspended_ ) );
SetTeam( NULL );
if ( Object() && Object()->Alive() )
Object()->Kill();
suspended_ = true;
suspendReason_= reason;
}
}
// *******************************************************************************
// *
// * LogScoreDifferences
// *
// *******************************************************************************
//!
//!
// *******************************************************************************
void ePlayerNetID::LogScoreDifferences( void )
{
for ( int i = se_PlayerNetIDs.Len()-1; i>=0; --i )
{
ePlayerNetID* p = se_PlayerNetIDs(i);
p->LogScoreDifference();
}
eTeam::LogScoreDifferences();
}
static eLadderLogWriter se_matchScoreWriter("MATCH_SCORE", true);
void ePlayerNetID::LogMatchScores( void )
{
for ( int i = se_PlayerNetIDs.Len()-1; i>=0; --i )
{
ePlayerNetID* p = se_PlayerNetIDs(i);
if (p->IsHuman())
{
se_matchScoreWriter << p->score << p->GetUserName();
if ( p->currentTeam )
se_matchScoreWriter << FilterName( p->currentTeam->Name() );
se_matchScoreWriter.write();
}
}
eTeam::LogMatchScores();
}
void ePlayerNetID::UpdateSuspensions()
{
for ( int i = se_PlayerNetIDs.Len()-1; i>=0; --i )
{
ePlayerNetID* p = se_PlayerNetIDs[i];
// update suspension count
if (p->IsSuspended())
{
if ( p->CurrentTeam() && !p->NextTeam() )
{
p->UpdateTeam();
}
else
{
p->Suspend( p->RoundsSuspended() - 1 );
}
}
}
}
void ePlayerNetID::UpdateShuffleSpamTesters()
{
if( sn_GetNetState() != nSERVER )
{
return;
}
for ( int i = se_PlayerNetIDs.Len()-1; i>=0; --i )
{
ePlayerNetID *p = se_PlayerNetIDs( i );
p->GetShuffleSpam().Reset();
}
}
// *******************************************************************************
// *
// * AnalyzeTiming
// *
// *******************************************************************************
//!
//!
// *******************************************************************************
void ePlayerNetID::AnalyzeTiming( REAL timing )
{
// just delegate safely
if( GetRefcount() > 0 )
{
tJUST_CONTROLLED_PTR< ePlayerNetID > keep( this );
uncannyTimingDetector_.Analyze( timing, this );
}
}
eUncannyTimingDetector::eUncannyTimingSettings::~eUncannyTimingSettings()
{
#ifdef DEBUG_X
#ifdef DEDICATED
con << "Best ratio achieved for " << timescale*1000 << "ms stat: " << bestRatio << "\n";
#endif
#endif
}
REAL eUncannyTimingDetector::eUncannyTimingAnalysis::Analyze( REAL timing, eUncannyTimingSettings const & settings )
{
if( timing < settings.timescale )
{
REAL increment = 1.0/turnsSoFar;
if( turnsSoFar < settings.averageOverEvents )
{
turnsSoFar++;
}
// don't rate failed timings too much. The user may not even have
// attempted to time something.
if( timing < 0 )
{
increment /= 4;
}
// event falls into the buckets
if( 2*timing < settings.timescale && timing > 0 )
{
// event falls into the 'good' bucket, count it
accurateRatio += increment;
}
// let ratio decay
accurateRatio /= 1+increment;
}
REAL ratio = accurateRatio/(1-accurateRatio);
// keep stats
if (ratio > settings.bestRatio)
{
settings.bestRatio = ratio;
}
REAL ret = (ratio-settings.goodHumanRatio)/(settings.maxGoodRatio-settings.goodHumanRatio);
if( ret < 0 )
{
ret = 0;
}
return ret;
}
eUncannyTimingDetector::eUncannyTimingAnalysis::eUncannyTimingAnalysis()
: accurateRatio( .3 ), turnsSoFar(10)
{}
/* stats; ladle 37:
prematch:
[0] Best ratio achieved for 125ms stat: 0.653367, 591turns.
[0] Best ratio achieved for 62.5ms stat: 1.07667, 124turns.
[0] Best ratio achieved for 31.25ms stat: 0.464286, 43turns.
up to zealous assertion failure:
[0] Best ratio achieved for 125ms stat: 1.45674
[0] Best ratio achieved for 62.5ms stat: 1.08824
[0] Best ratio achieved for 31.25ms stat: 0.942842
proper, after assertions had been removed:
[0] Best ratio achieved for 125ms stat: 1.71929, 4686turns.
[0] Best ratio achieved for 62.5ms stat: 1.08824, 713turns.
[0] Best ratio achieved for 31.25ms stat: 0.952494, 163turns.
z-man, trying really hard:
[0] Best ratio achieved for 125ms stat: 4.71739
[0] Best ratio achieved for 62.5ms stat: 0.945886
[0] Best ratio achieved for 31.25ms stat: 0.444307
tst prematch, only counting enemy grinds:
[0] Best ratio achieved for 125ms stat: 6.04985
[0] Best ratio achieved for 62.5ms stat: 1.80428
[0] Best ratio achieved for 31.25ms stat: 0.819629
all grinds:
[0] Best ratio achieved for 125ms stat: 2.09805
[0] Best ratio achieved for 62.5ms stat: 2.32939
[0] Best ratio achieved for 31.25ms stat: 1
tst proper, enemies only:
[0] Best ratio achieved for 125ms stat: 5.60549
[0] Best ratio achieved for 62.5ms stat: 1.01227
[0] Best ratio achieved for 31.25ms stat: 0.681035
all grinds:
[0] Best ratio achieved for 125ms stat: 1.72932
[0] Best ratio achieved for 62.5ms stat: 1.68816
[0] Best ratio achieved for 31.25ms stat: 0.750099
ladle41, hamar and partner team actions included:
[0] Best ratio achieved for 125ms stat: 23.7208
[0] Best ratio achieved for 62.5ms stat: 2.01171
[0] Best ratio achieved for 31.25ms stat: 0.90623
*/
static eUncannyTimingDetector::eUncannyTimingSettings
se_uncannyTimingSettingsFast(1/32.0, 1, 1.5),
se_uncannyTimingSettingsMedium(1/16.0, 2, 4);
// se_uncannyTimingSettingsSlow(1/8.0, 7, 15);
static REAL se_Max( REAL a, REAL b )
{
return a > b ? a : b;
}
eUncannyTimingDetector::eUncannyTimingDetector()
: dangerLevel( DangerLevel_Low )
{
}
// opportunity to tune timebot detection sensitivity
static REAL se_timebotSensitivity = 1.0;
static tSettingItem< REAL > se_timebotSensitivityConf( "TIMEBOT_SENSITIVITY", se_timebotSensitivity );
// different ways to react to timebot detection
enum eTimebotAction
{
eTimebotAction_Nothing = 0, // do nothing
eTimebotAction_Log = 1, // log it
eTimebotAction_NotifyModerator = 2, // notify moderators that happen to be online
eTimebotAction_NotifyEveryone = 3, // notify all players
eTimebotAction_Kick = 4 // kick the player
};
tCONFIG_ENUM( eTimebotAction );
static eTimebotAction se_timebotActionMedium = eTimebotAction_Log;
static eTimebotAction se_timebotActionHigh = eTimebotAction_Log;
static eTimebotAction se_timebotActionMax = eTimebotAction_Log;
static tSettingItem< eTimebotAction > se_timebotActionMediumConf( "TIMEBOT_ACTION_MEDIUM", se_timebotActionMedium );
static tSettingItem< eTimebotAction > se_timebotActionHighConf( "TIMEBOT_ACTION_HIGH", se_timebotActionHigh );
static tSettingItem< eTimebotAction > se_timebotActionMaxConf( "TIMEBOT_ACTION_MAX", se_timebotActionMax );
// severity of kick (for autobans)
static REAL se_timebotKickSeverity = 0.5;
static tSettingItem< REAL > se_timebotKickSeverityConf( "TIMEBOT_KICK_SEVERITY", se_timebotKickSeverity );
static void se_TimebotAction( eTimebotAction action, ePlayerNetID * player, char const * message )
{
if (action == eTimebotAction_Nothing)
{
return;
}
// look up message
tOutput m (message, player->GetName());
switch (action)
{
case eTimebotAction_Kick:
if( player->Owner() > 0 )
{
sn_KickUser( player->Owner(), m, se_timebotKickSeverity );
}
// no break on purpose.
case eTimebotAction_NotifyEveryone:
sn_ConsoleOut( m );
break;
case eTimebotAction_NotifyModerator:
#ifdef DEDICATED
se_SecretConsoleOut( m, player, &se_cannotSeeConsole );
break;
#endif
case eTimebotAction_Log:
con << m;
break;
case eTimebotAction_Nothing:
break;
}
}
//! analzye a timing event
void eUncannyTimingDetector::Analyze( REAL timing, ePlayerNetID * player )
{
// ignore this system on the client itself
if( sn_GetNetState() != nSERVER || se_timebotSensitivity <= 0 )
{
return;
}
// apply sensitivity
timing /= se_timebotSensitivity;
REAL maxUncanny = fast.Analyze( timing, se_uncannyTimingSettingsFast );
maxUncanny = se_Max( maxUncanny, medium.Analyze( timing, se_uncannyTimingSettingsMedium ) );
// maxUncanny = se_Max( maxUncanny, slow.Analyze( timing, se_uncannyTimingSettingsSlow ) );
switch( dangerLevel )
{
case DangerLevel_Low:
if( maxUncanny > .25 )
{
dangerLevel =DangerLevel_Medium;
se_TimebotAction( se_timebotActionMedium, player, "$timebot_action_medium" );
}
break;
case DangerLevel_Medium:
if( maxUncanny > .5 )
{
dangerLevel = DangerLevel_High;
se_TimebotAction( se_timebotActionHigh, player, "$timebot_action_high" );
}
else if( maxUncanny <= 0.01 )
{
dangerLevel = DangerLevel_Low;
}
break;
case DangerLevel_High:
if( maxUncanny > 1 )
{
dangerLevel = DangerLevel_Max;
se_TimebotAction( se_timebotActionMax, player, "$timebot_action_max" );
}
else if( maxUncanny < .25 )
{
dangerLevel = DangerLevel_Medium;
}
break;
case DangerLevel_Max:
if( maxUncanny < .75 )
{
dangerLevel = DangerLevel_High;
}
}
}
// *******************************************************************************
// *
// * LogScoreDifference
// *
// *******************************************************************************
//!
//!
// *******************************************************************************
static eLadderLogWriter se_roundScoreWriter("ROUND_SCORE", true);
void ePlayerNetID::LogScoreDifference( void )
{
if ( lastScore_ > IMPOSSIBLY_LOW_SCORE && IsHuman() )
{
int scoreDifference = (currentTeam?score - lastScore_:0);
//lastScore_ = IMPOSSIBLY_LOW_SCORE;
se_roundScoreWriter << scoreDifference << GetUserName();
if ( currentTeam )
se_roundScoreWriter << FilterName( currentTeam->Name() );
se_roundScoreWriter.write();
}
}
static void se_allowTeamChangesPlayer(bool allow, std::istream &s)
{
if ( se_NeedsServer( "(DIS)ALLOW_TEAM_CHANGE_PLAYER", s, false ) )
{
return;
}
ePlayerNetID * p = ReadPlayer( s );
if ( p )
{
sn_ConsoleOut( tOutput( (allow ? "$player_allowed_teamchange" : "$player_disallowed_teamchange"), p->GetName() ) );
p->SetTeamChangeAllowed( allow );
}
}
static void se_allowTeamChangesPlayer(std::istream &s)
{
se_allowTeamChangesPlayer(true, s);
}
static void se_disallowTeamChangesPlayer(std::istream &s)
{
se_allowTeamChangesPlayer(false, s);
}
static tConfItemFunc se_allowTeamChangesPlayerConf("ALLOW_TEAM_CHANGE_PLAYER", &se_allowTeamChangesPlayer);
static tConfItemFunc se_disallowTeamChangesPlayerConf("DISALLOW_TEAM_CHANGE_PLAYER", &se_disallowTeamChangesPlayer);
static tAccessLevelSetter se_atcConfLevel( se_allowTeamChangesPlayerConf, tAccessLevel_TeamLeader );
static tAccessLevelSetter se_dtcConfLevel( se_disallowTeamChangesPlayerConf, tAccessLevel_TeamLeader );
static void sg_AddScorePlayer(std::istream &s)
{
tString params;
params.ReadLine( s, true );
// parse the line to get the param : Teamname Points Message
int pos = 0; //
tString PlayerStr = tString("");
PlayerStr = params.ExtractNonBlankSubString(pos);
ePlayerNetID *pPlayer = 0;
pPlayer = ePlayerNetID::FindPlayerByName(PlayerStr, NULL);
if (!pPlayer) return;
tString ScoreStr = tString("");
ScoreStr = params.ExtractNonBlankSubString(pos);
int pScore = atoi(ScoreStr);
tString pMessage = params.SubStr(pos+1);
if(pMessage.Len()<=1)
{
pPlayer->AddScore(pScore,pMessage,pMessage,false);
}
else
{
pMessage << "\n";
pPlayer->AddScore(pScore,pMessage,pMessage);
}
}
static tConfItemFunc sg_AddScorePlayer_conf("ADD_SCORE_PLAYER",&sg_AddScorePlayer);
static void sg_SetPlayerTeam(std::istream &s)
{
tString params;
params.ReadLine( s, true );
// parse the line to get the param : Teamname Points Message
int pos = 0; //
tString PlayerStr = tString("");
PlayerStr = params.ExtractNonBlankSubString(pos);
ePlayerNetID *pPlayer = 0;
pPlayer = ePlayerNetID::FindPlayerByName(PlayerStr, NULL);
if (!pPlayer) return;
tString TeamStr = tString("");
TeamStr = params.ExtractNonBlankSubString(pos);
eTeam *pTeam=NULL;
for (int i = eTeam::teams.Len() - 1; i>=0; --i)
{
tString teamName = eTeam::teams(i)->Name();
if (TeamStr==ePlayerNetID::FilterName(teamName))
{
pTeam = eTeam::teams(i);
break;
}
}
if (!pTeam) return;
// Force player to a team
pPlayer->SetTeamForce(pTeam);
}
static tConfItemFunc sg_SetPlayerTeam_conf("SET_PLAYER_TEAM",&sg_SetPlayerTeam);
// * =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
// * Substitute feature
// * =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
static bool se_substituteAutomatically = false;
static tSettingItem< bool > se_substituteAutomaticallyConf( "AUTO_SUBSTITUTION", se_substituteAutomatically );
static tAccessLevelSetter se_substituteAutomaticallyConfLevel( se_substituteAutomaticallyConf, tAccessLevel_Owner );
// * SetSubstitute
// * Goal: check whether this substitute is valid and store it
// * Params: a pointer to a player
// * Return: true is substitute is valid and has been set, false otherwise
bool ePlayerNetID::SetSubstitute(ePlayerNetID *p)
{
// first, this player must be a active human playing for a team ...
if (!IsActive()||!IsHuman()||!CurrentTeam()) // Substitution failed !
{
substitute = NULL;
return false;
}
// substitute must be human spectator and must be invited first.
if (p && p->IsHuman() && p->CurrentTeam() == NULL && CurrentTeam()->IsInvited(p))
{
substitute = p;
return true;
}
substitute = NULL;
return false;
}
// * ApplySubstitution
// * Goal: check whether the substitute is still valid (since it has been stored) and performs substitution
// * Return: true is substitute is valid and has been performed, false otherwise
bool ePlayerNetID::ApplySubstitution()
{
// first, this player must be a active human playing for a team ...
if (!IsActive()||!IsHuman()||!CurrentTeam()) // Substitution failed !
{
substitute = NULL;
return false;
}
// substitute must join the team while this player leave. substitute must take this player's position too. Let's keep these data first.
tJUST_CONTROLLED_PTR< eTeam > team( CurrentTeam() );
int IDWish = TeamListID();
// try to find a substitute for any leaving player if auto substitution is on and no substitute is defined
if (se_substituteAutomatically && !substitute && !NextTeam())
{
for ( int i = se_PlayerNetIDs.Len()-1; i>=0; --i )
{
ePlayerNetID *p = se_PlayerNetIDs( i );
if (p != this && p->IsHuman() && p->CurrentTeam() == NULL && currentTeam->IsInvited(p))
substitute = p;
}
}
// substitute must be invited first
if (substitute && substitute->IsHuman() && substitute->CurrentTeam() == NULL && currentTeam->IsInvited(substitute))
{
// remove this player
SetTeamForce(NULL);
UpdateTeamForce();
team->Invite(this);
// add substitute
substitute->SetTeamForce(team);
substitute->UpdateTeamForce();
if (substitute->CurrentTeam()!=team) // Substitution failed ! Try to add leaving player again ...
{
SetTeamForce(team);
UpdateTeamForce();
CurrentTeam()->Shuffle( TeamListID(), IDWish );
substitute = NULL;
return false;
}
substitute->CurrentTeam()->Shuffle( substitute->TeamListID(), IDWish );
substitute = NULL;
return true;
}
substitute = NULL;
return false;
}
// * ClearSubstitutes
// * Goal: reset all players'substitutes
void ePlayerNetID::ClearSubstitutes()
{
for ( int i = se_PlayerNetIDs.Len()-1; i>=0; --i )
{
ePlayerNetID *p = se_PlayerNetIDs( i );
p->SetSubstitute(NULL);
}
}
// * ApplySubstitutions
// * Goal: performs all pending substitutions (and reset substitutes)
void ePlayerNetID::ApplySubstitutions()
{
for ( int i = se_PlayerNetIDs.Len()-1; i>=0; --i )
{
ePlayerNetID *p = se_PlayerNetIDs( i );
if (p->ApplySubstitution())
{
ePlayerNetID *p_in = se_PlayerNetIDs( i );
// inform players about substitution
tOutput out( tOutput("$substitute_player_request",p->GetLogName(), p->GetLogName(), p_in->GetLogName()) );
sn_ConsoleOut( out, p->Owner() );
sn_ConsoleOut( out, p_in->Owner() );
con << out;
}
else p->SetSubstitute(NULL);
}
}
#ifdef KRAWALL_SERVER
// substitute: swap 2 players within a team
static void se_ChatSubstitute( ePlayerNetID * p, std::istream & s )
{
// substitute. Allow to swap 2 players within a team. The second player might be spectator.
// syntax:
// /substitute <player_out> <player_in>: replace player_out by player_in
if ( p->GetAccessLevel() > se_substituteAccessLevel )
{
sn_ConsoleOut(tOutput("$access_level_substitute_denied", tCurrentAccessLevel::GetName(se_substituteAccessLevel), tCurrentAccessLevel::GetName(p->GetAccessLevel())), p->Owner());
return;
}
tString n_out, n_in;
s >> n_out;
s >> n_in;
ePlayerNetID * p_out = ePlayerNetID::FindPlayerByName( n_out );
ePlayerNetID * p_in = ePlayerNetID::FindPlayerByName( n_in );
if (p_out && p_in && p_out->SetSubstitute(p_in))
{
// inform players about substitution
tOutput out( tOutput("$substitute_player_request",p->GetLogName(), p_out->GetLogName(), p_in->GetLogName()) );
sn_ConsoleOut( out, p_out->Owner() );
sn_ConsoleOut( out, p_in->Owner() );
con << out;
return;
}
tOutput out( tOutput("$substitute_message_usage") );
sn_ConsoleOut( out, p->Owner() );
con << out;
}
#endif
static void se_FillServerSettings()
{
nServerInfo::SettingsDigest & digest = *nCallbackFillServerInfo::ToFill();
digest.minPlayTimeTotal_ = int(se_minPlayTimeTotal);
digest.minPlayTimeOnline_ = int(se_minPlayTimeOnline);
digest.minPlayTimeTeam_ = int(se_minPlayTimeTeam);
digest.SetFlag( nServerInfo::SettingsDigest::Flags_AuthenticationRequired,
#ifdef KRAWALL_SERVER
se_accessLevelRequiredToPlay < tAccessLevel_Program ||
se_playAccessLevel < tAccessLevel_Program
#else
false
#endif
);
}
static nCallbackFillServerInfo se_fillServerSettings(se_FillServerSettings);
static void sg_KillChatters(std::istream &s)
{
if (se_PlayerNetIDs.Len() > 0)
{
for(int i = 0; i < se_PlayerNetIDs.Len(); i++)
{
ePlayerNetID *p = se_PlayerNetIDs[i];
if (p && p->IsChatting())
{
if (p->Object() && p->Object()->Alive())
p->Object()->Kill();
}
}
sn_ConsoleOut( tOutput( "$player_chatter_die") );
}
}
static tConfItemFunc sg_KillChatters_conf("CHATTERS_KILL", &sg_KillChatters);
static tAccessLevelSetter sg_KillChatters_conflevel( sg_KillChatters_conf, tAccessLevel_Moderator );
static void sg_SilenceChatters(std::istream &s)
{
if (se_PlayerNetIDs.Len() > 0)
{
for(int i = 0; i < se_PlayerNetIDs.Len(); i++)
{
ePlayerNetID *p = se_PlayerNetIDs[i];
if (p && p->IsChatting())
{
p->SetSilenced(true);
}
}
sn_ConsoleOut( tOutput( "$player_chatter_silence") );
}
}
static tConfItemFunc sg_SilenceChatters_conf("CHATTERS_SILENCE", &sg_SilenceChatters);
static tAccessLevelSetter sg_SilenceChatters_conflevel( sg_SilenceChatters_conf, tAccessLevel_Moderator );
static void SuspendChatter_conf_base(std::istream &s, int rounds )
{
if ( se_NeedsServer( "CHATTERS_SUSPEND", s, false ) )
{
return;
}
if ( rounds > 0 )
{
s >> rounds;
}
if (se_PlayerNetIDs.Len() > 0)
{
for(int i = 0; i < se_PlayerNetIDs.Len(); i++)
{
ePlayerNetID *p = se_PlayerNetIDs[i];
if (p && p->IsChatting())
{
p->Suspend(rounds);
}
}
sn_ConsoleOut( tOutput( "$player_chatter_suspend_success", rounds) );
}
}
static void SuspendChatters_conf(std::istream &s )
{
SuspendChatter_conf_base( s, se_suspendDefault );
}
static tConfItemFunc sg_SuspendChatters_conf("CHATTERS_SUSPEND", &SuspendChatters_conf);
static tAccessLevelSetter sg_SuspendChatters_conflevel( sg_SuspendChatters_conf, tAccessLevel_Moderator );
static void sg_ListChatters(std::istream &s)
{
ePlayerNetID * receiver=0;
tColoredString send;
if (se_PlayerNetIDs.Len() > 0)
{
for(int i = 0; i < se_PlayerNetIDs.Len(); i++)
{
ePlayerNetID *p = se_PlayerNetIDs[i];
if (p && p->IsChatting())
{
send << p->GetColoredName() << tColoredString::ColorString( 1,1,.5 ) << ", ";
}
}
send << "\n";
sn_ConsoleOut( send, receiver->Owner() );
}
}
static tConfItemFunc sg_ListChatters_conf("CHATTERS_LIST", &sg_ListChatters);
static tAccessLevelSetter sg_ListChatters_confLevel( sg_ListChatters_conf, tAccessLevel_Moderator );
|