summaryrefslogtreecommitdiff
path: root/indra/newview/llviewermessage.cpp
blob: f907ac698e335a19555cc81c631c8da227fc9b67 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
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
/** 
 * @file llviewermessage.cpp
 * @brief Dumping ground for viewer-side message system callbacks.
 *
 * Copyright (c) 2002-$CurrentYear$, Linden Research, Inc.
 * $License$
 */

#include "llviewerprecompiledheaders.h"

#include "llviewermessage.h"

#include <deque>
#include <stdio.h>
#include <string.h>

#include "audioengine.h" 
#include "audiosettings.h"
#include "indra_constants.h"
#include "lscript_byteformat.h"
#include "mean_collision_data.h"
#include "llfloaterbump.h"
#include "llassetstorage.h"
#include "llcachename.h"
#include "llchat.h"
#include "lldbstrings.h"
#include "lleconomy.h"
#include "llfilepicker.h"
#include "llfloaterimport.h"
#include "llfocusmgr.h"
#include "llfollowcamparams.h"
#include "llinstantmessage.h"
#include "llquantize.h"
#include "llregionflags.h"
#include "llregionhandle.h"
#include "llsdserialize.h"
#include "llstring.h"
#include "llteleportflags.h"
#include "lltracker.h"
#include "lltransactionflags.h"
#include "llwindow.h"			// shell_open()
#include "llxfermanager.h"
#include "message.h"
#include "sound_ids.h"
#include "lltimer.h"
#include "llmd5.h"

#include "llagent.h"
#include "llcallingcard.h"
#include "llconsole.h"
#include "llviewercontrol.h"
#include "lldrawpool.h"
#include "llfirstuse.h"
#include "llfloateractivespeakers.h"
#include "llfloaterbuycurrency.h"
#include "llfloaterbuyland.h"
#include "llfloaterchat.h"
#include "llfloatergroupinfo.h"
#include "llfloaterimagepreview.h"
#include "llfloaterland.h"
#include "llfloaterregioninfo.h"
#include "llfloaterlandholdings.h"
#include "llfloatermap.h"
#include "llfloatermute.h"
#include "llfloaterpostcard.h"
#include "llfloaterpreference.h"
#include "llfloaterreleasemsg.h"
#include "llfollowcam.h"
#include "llgroupnotify.h"
#include "llhudeffect.h"
#include "llhudeffecttrail.h"
#include "llhudmanager.h"
#include "llimpanel.h"
#include "llinventorymodel.h"
#include "llinventoryview.h"
#include "llmenugl.h"
#include "llmutelist.h"
#include "llnetmap.h"
#include "llnotify.h"
#include "llpanelgrouplandmoney.h"
#include "llselectmgr.h"
#include "llstartup.h"
#include "llsky.h"
#include "llstatenums.h"
#include "llstatusbar.h"
#include "llimview.h"
#include "lltool.h"
#include "lltoolbar.h"
#include "lltoolmgr.h"
#include "llui.h"			// for make_ui_sound
#include "lluploaddialog.h"
#include "llviewercamera.h"
#include "llviewergenericmessage.h"
#include "llviewerinventory.h"
#include "llviewermenu.h"
#include "llviewerobject.h"
#include "llviewerobjectlist.h"
#include "llviewerparcelmgr.h"
#include "llviewerpartsource.h"
#include "llviewerregion.h"
#include "llviewerstats.h"
#include "llviewertexteditor.h"
#include "llviewerthrottle.h"
#include "llviewerwindow.h"
#include "llvlmanager.h"
#include "llvoavatar.h"
#include "llvotextbubble.h"
#include "llweb.h"
#include "llworld.h"
#include "pipeline.h"
#include "viewer.h"
#include "llfloaterworldmap.h"

#include <boost/tokenizer.hpp>

#if LL_WINDOWS // For Windows specific error handler
#include "llwindebug.h"	// For the invalid message handler
#endif

//
// Constants
//
const F32 BIRD_AUDIBLE_RADIUS = 32.0f;
const F32 SIT_DISTANCE_FROM_TARGET = 0.25f;
static const F32 LOGOUT_REPLY_TIME = 3.f;	// Wait this long after LogoutReply before quitting.
extern BOOL gDebugClicks;

extern void bad_network_handler();

// function prototypes
void open_offer(const std::vector<LLUUID>& items, const std::string& from_name);
void friendship_offer_callback(S32 option, void* user_data);
bool check_offer_throttle(const std::string& from_name, bool check_only);

//inventory offer throttle globals
LLFrameTimer gThrottleTimer;
const U32 OFFER_THROTTLE_MAX_COUNT=5; //number of items per time period
const F32 OFFER_THROTTLE_TIME=10.f; //time period in seconds

//script permissions
const LLString SCRIPT_QUESTIONS[SCRIPT_PERMISSION_EOF] = 
	{ 
		"ScriptTakeMoney",
		"ActOnControlInputs",
		"RemapControlInputs",
		"AnimateYourAvatar",
		"AttachToYourAvatar",
		"ReleaseOwnership",
		"LinkAndDelink",
		"AddAndRemoveJoints",
		"ChangePermissions",
		"TrackYourCamera",
		"ControlYourCamera"
	};

struct LLFriendshipOffer
{
	LLUUID mFromID;
	LLUUID mTransactionID;
	BOOL mOnline;
	LLHost mHost;
};

//const char BUSY_AUTO_RESPONSE[] =	"The Resident you messaged is in 'busy mode' which means they have "
//									"requested not to be disturbed. Your message will still be shown in their IM "
//									"panel for later viewing.";

//
// Functions
//

void give_money(const LLUUID& uuid, LLViewerRegion* region, S32 amount, BOOL is_group,
				S32 trx_type, const LLString& desc)
{
	if(0 == amount) return;
	amount = abs(amount);
	llinfos << "give_money(" << uuid << "," << amount << ")"<< llendl;
	if(can_afford_transaction(amount))
	{
//		gStatusBar->debitBalance(amount);
		LLMessageSystem* msg = gMessageSystem;
		msg->newMessageFast(_PREHASH_MoneyTransferRequest);
		msg->nextBlockFast(_PREHASH_AgentData);
		msg->addUUIDFast(_PREHASH_AgentID, agent_get_id());
		msg->addUUIDFast(_PREHASH_SessionID, agent_get_session_id());
		msg->nextBlockFast(_PREHASH_MoneyData);
		msg->addUUIDFast(_PREHASH_SourceID, gAgent.getID() );
		msg->addUUIDFast(_PREHASH_DestID, uuid);
		msg->addU8Fast(_PREHASH_Flags, pack_transaction_flags(FALSE, is_group));
		msg->addS32Fast(_PREHASH_Amount, amount);
		msg->addU8Fast(_PREHASH_AggregatePermNextOwner, (U8)LLAggregatePermissions::AP_EMPTY);
		msg->addU8Fast(_PREHASH_AggregatePermInventory, (U8)LLAggregatePermissions::AP_EMPTY);
		msg->addS32Fast(_PREHASH_TransactionType, trx_type );
		msg->addStringFast(_PREHASH_Description, desc.c_str());
		msg->sendReliable(region->getHost());
	}
	else
	{
		LLFloaterBuyCurrency::buyCurrency("Giving", amount);
	}
}

void send_complete_agent_movement(const LLHost& sim_host)
{
	LLMessageSystem* msg = gMessageSystem;
	msg->newMessageFast(_PREHASH_CompleteAgentMovement);
	msg->nextBlockFast(_PREHASH_AgentData);
	msg->addUUIDFast(_PREHASH_AgentID, gAgent.getID());
	msg->addUUIDFast(_PREHASH_SessionID, gAgent.getSessionID());
	msg->addU32Fast(_PREHASH_CircuitCode, msg->mOurCircuitCode);
	msg->sendReliable(sim_host);
}

void process_logout_reply(LLMessageSystem* msg, void**)
{
	// The server has told us it's ok to quit.
	llinfos << "process_logout_reply" << llendl;

	LLUUID agent_id;
	msg->getUUID("AgentData", "AgentID", agent_id);
	LLUUID session_id;
	msg->getUUID("AgentData", "SessionID", session_id);
	if((agent_id != agent_get_id()) || (session_id != agent_get_session_id()))
	{
		llwarns << "Bogus Logout Reply" << llendl;
	}

	LLInventoryModel::update_map_t parents;
	S32 count = msg->getNumberOfBlocksFast( _PREHASH_InventoryData );
	for(S32 i = 0; i < count; ++i)
	{
		LLUUID item_id;
		msg->getUUIDFast(_PREHASH_InventoryData, _PREHASH_ItemID, item_id, i);

		if( (1 == count) && item_id.isNull() )
		{
			// Detect dummy item.  Indicates an empty list.
			break;
		}

		// We do not need to track the asset ids, just account for an
		// updated inventory version.
		llinfos << "process_logout_reply itemID=" << item_id << llendl;
		LLInventoryItem* item = gInventory.getItem( item_id );
		if( item )
		{
			parents[item->getParentUUID()] = 0;
			gInventory.addChangedMask(LLInventoryObserver::INTERNAL, item_id);
		}
		else
		{
			llinfos << "process_logout_reply item not found: " << item_id << llendl;
		}
	}
	if(!parents.empty())
	{
		gInventory.accountForUpdate(parents);
		gInventory.notifyObservers();
	}
	app_force_quit(NULL);
}

void process_layer_data(LLMessageSystem *mesgsys, void **user_data)
{
	LLViewerRegion *regionp = gWorldp->getRegion(mesgsys->getSender());

	if (!regionp || gNoRender)
	{
		return;
	}


	S32 size;
	S8 type;

	mesgsys->getS8Fast(_PREHASH_LayerID, _PREHASH_Type, type);
	size = mesgsys->getSizeFast(_PREHASH_LayerData, _PREHASH_Data);
	if (0 == size)
	{
		llwarns << "Layer data has zero size." << llendl;
		return;
	}
	if (size < 0)
	{
		// getSizeFast() is probably trying to tell us about an error
		llwarns << "getSizeFast() returned negative result: "
			<< size
			<< llendl;
		return;
	}
	U8 *datap = new U8[size];
	mesgsys->getBinaryDataFast(_PREHASH_LayerData, _PREHASH_Data, datap, size);
	LLVLData *vl_datap = new LLVLData(regionp, type, datap, size);
	if (mesgsys->getReceiveCompressedSize())
	{
		gVLManager.addLayerData(vl_datap, mesgsys->getReceiveCompressedSize());
	}
	else
	{
		gVLManager.addLayerData(vl_datap, mesgsys->getReceiveSize());
	}
}

S32 exported_object_count = 0;
S32 exported_image_count = 0;
S32 current_object_count = 0;
S32 current_image_count = 0;

extern LLNotifyBox *gExporterNotify;
extern LLUUID gExporterRequestID;
extern LLString gExportDirectory;

extern LLUploadDialog *gExportDialog;

LLString gExportedFile;

std::map<LLUUID, LLString> gImageChecksums;

void export_complete()
{
		LLUploadDialog::modalUploadFinished();
		gExporterRequestID.setNull();
		gExportDirectory = "";

		FILE* fXML = LLFile::fopen(gExportedFile.c_str(), "rb");		/* Flawfinder: ignore */
		fseek(fXML, 0, SEEK_END);
		long length = ftell(fXML);
		fseek(fXML, 0, SEEK_SET);
		U8 *buffer = new U8[length + 1];
		size_t nread = fread(buffer, 1, length, fXML);
		if (nread < (size_t) length)
		{
			llwarns << "Short read" << llendl;
		}
		buffer[nread] = '\0';
		fclose(fXML);

		char *pos = (char *)buffer;
		while ((pos = strstr(pos+1, "<sl:image ")) != 0)
		{
			char *pos_check = strstr(pos, "checksum=\"");

			if (pos_check)
			{
				char *pos_uuid = strstr(pos_check, "\">");

				if (pos_uuid)
				{
					char image_uuid_str[UUID_STR_SIZE];		/* Flawfinder: ignore */
					memcpy(image_uuid_str, pos_uuid+2, UUID_STR_SIZE-1);		/* Flawfinder: ignore */
					image_uuid_str[UUID_STR_SIZE-1] = 0;
					
					LLUUID image_uuid(image_uuid_str);

					llinfos << "Found UUID: " << image_uuid << llendl;

					std::map<LLUUID, LLString>::iterator itor = gImageChecksums.find(image_uuid);
					if (itor != gImageChecksums.end())
					{
						llinfos << "Replacing with checksum: " << itor->second << llendl;
						if (itor->second.c_str() != NULL)
							{
								memcpy(&pos_check[10], itor->second.c_str(), 32);		/* Flawfinder: ignore */
							}
					}
				}
			}
		}

		FILE* fXMLOut = LLFile::fopen(gExportedFile.c_str(), "wb");		/* Flawfinder: ignore */
		if (fwrite(buffer, 1, length, fXMLOut) != length)
		{
			llwarns << "Short write" << llendl;
		}
		fclose(fXMLOut);

		delete [] buffer;
}


void exported_item_complete(const LLTSCode status, void *user_data)
{
	//LLString *filename = (LLString *)user_data;

	if (status < LLTS_OK)
	{
		llinfos << "Export failed!" << llendl;
	}
	else
	{
		++current_object_count;
		if (current_image_count == exported_image_count && current_object_count == exported_object_count)
		{
			llinfos << "*** Export complete ***" << llendl;

			export_complete();
		}
		else
		{
			gExportDialog->setMessage(llformat("Exported %d/%d object files, %d/%d textures.", current_object_count, exported_object_count, current_image_count, exported_image_count));
		}
	}
}

struct exported_image_info
{
	LLUUID image_id;
	LLString filename;
	U32 image_num;
};

void exported_j2c_complete(const LLTSCode status, void *user_data)
{
	exported_image_info *info = (exported_image_info *)user_data;
	LLUUID image_id = info->image_id;
	U32 image_num = info->image_num;
	LLString filename = info->filename;
	delete info;

	if (status < LLTS_OK)
	{
		llinfos << "Image download failed!" << llendl;
	}
	else
	{
		FILE* fIn = LLFile::fopen(filename.c_str(), "rb");		/* Flawfinder: ignore */
		if (fIn) 
		{
			LLPointer<LLImageJ2C> ImageUtility = new LLImageJ2C;
			LLPointer<LLImageTGA> TargaUtility = new LLImageTGA;

			fseek(fIn, 0, SEEK_END);
			S32 length = ftell(fIn);
			fseek(fIn, 0, SEEK_SET);
			U8 *buffer = ImageUtility->allocateData(length);
			if (fread(buffer, 1, length, fIn) != length)
			{
				llwarns << "Short read" << llendl;
			}
			fclose(fIn);
			LLFile::remove(filename.c_str());

			// Convert to TGA
			LLPointer<LLImageRaw> image = new LLImageRaw();

			ImageUtility->updateData();
			ImageUtility->decode(image, 100000.0f);
			
			TargaUtility->encode(image);
			U8 *data = TargaUtility->getData();
			S32 data_size = TargaUtility->getDataSize();

			char *file_path = new char[filename.size()+1];
			strcpy(file_path, filename.c_str());		/* Flawfinder: ignore */
			char *end = strrchr(file_path, gDirUtilp->getDirDelimiter()[0]);
			end[0] = 0;
			LLString output_file = llformat("%s/image-%03d.tga", file_path, image_num);//filename;
			delete [] file_path;
			//S32 name_len = output_file.length();
			//strcpy(&output_file[name_len-3], "tga");
			FILE* fOut = LLFile::fopen(output_file.c_str(), "wb");		/* Flawfinder: ignore */
			char md5_hash_string[33];		/* Flawfinder: ignore */
			strcpy(md5_hash_string, "00000000000000000000000000000000");		/* Flawfinder: ignore */
			if (fOut)
			{
				if (fwrite(data, 1, data_size, fOut) != data_size)
				{
					llwarns << "Short write" << llendl;
				}
				fseek(fOut, 0, SEEK_SET);
				fclose(fOut);
				fOut = LLFile::fopen(output_file.c_str(), "rb");		/* Flawfinder: ignore */
				LLMD5 my_md5_hash(fOut);
				my_md5_hash.hex_digest(md5_hash_string);
			}

			gImageChecksums.insert(std::pair<LLUUID, LLString>(image_id, md5_hash_string));
		}
	}

	++current_image_count;
	if (current_image_count == exported_image_count && current_object_count == exported_object_count)
	{
		llinfos << "*** Export textures complete ***" << llendl;
			export_complete();
	}
	else
	{
		gExportDialog->setMessage(llformat("Exported %d/%d object files, %d/%d textures.", current_object_count, exported_object_count, current_image_count, exported_image_count));
	}
}

void process_derez_ack(LLMessageSystem*, void**)
{
	if(gViewerWindow) gViewerWindow->getWindow()->decBusyCount();
}

void process_places_reply(LLMessageSystem* msg, void** data)
{
	LLUUID query_id;

	msg->getUUID("AgentData", "QueryID", query_id);
	if (query_id.isNull())
	{
		LLFloaterLandHoldings::processPlacesReply(msg, data);
	}
	else if(gAgent.isInGroup(query_id))
	{
		LLPanelGroupLandMoney::processPlacesReply(msg, data);
	}
	else
	{
		llwarns << "Got invalid PlacesReply message" << llendl;
	}
}

void send_sound_trigger(const LLUUID& sound_id, F32 gain)
{
	if (sound_id.isNull())
	{
		// zero guids don't get sent (no sound)
		return;
	}

	LLMessageSystem* msg = gMessageSystem;
	msg->newMessageFast(_PREHASH_SoundTrigger);
	msg->nextBlockFast(_PREHASH_SoundData);
	msg->addUUIDFast(_PREHASH_SoundID, sound_id);
	// Client untrusted, ids set on sim
	msg->addUUIDFast(_PREHASH_OwnerID, LLUUID::null );
	msg->addUUIDFast(_PREHASH_ObjectID, LLUUID::null );
	msg->addUUIDFast(_PREHASH_ParentID, LLUUID::null );

	msg->addU64Fast(_PREHASH_Handle, gAgent.getRegion()->getHandle());

	LLVector3 position = gAgent.getPositionAgent();
	msg->addVector3Fast(_PREHASH_Position, position);
	msg->addF32Fast(_PREHASH_Gain, gain);

	gAgent.sendMessage();
}

struct LLJoinGroupData
{
	LLUUID mGroupID;
	LLUUID mTransactionID;
	std::string mName;
	std::string mMessage;
	S32 mFee;
};

void join_group_callback(S32 option, void* user_data)
{
	LLJoinGroupData* data = (LLJoinGroupData*)user_data;
	BOOL delete_context_data = TRUE;
	bool accept_invite = false;

	if (option == 2 && data && !data->mGroupID.isNull())
	{
		LLFloaterGroupInfo::showFromUUID(data->mGroupID);
		LLString::format_map_t args;
		args["[MESSAGE]"] = data->mMessage;
		LLNotifyBox::showXml("JoinGroup", args, &join_group_callback, data);
		return;
	}
	if(option == 0 && data && !data->mGroupID.isNull())
	{
		// check for promotion or demotion.
		S32 max_groups = MAX_AGENT_GROUPS;
		if(gAgent.isInGroup(data->mGroupID)) ++max_groups;

		if(gAgent.mGroups.count() < max_groups)
		{
			accept_invite = true;
		}
		else
		{
			delete_context_data = FALSE;
			LLString::format_map_t args;
			args["[NAME]"] = data->mName;
			args["[INVITE]"] = data->mMessage;
			LLAlertDialog::showXml("JoinedTooManyGroupsMember", args, join_group_callback, (void*)data);
		}
	}

	if (accept_invite)
	{
		// If there is a fee to join this group, make
		// sure the user is sure they want to join.
		if (data->mFee > 0)
		{
			delete_context_data = FALSE;
			LLString::format_map_t args;
			args["[COST]"] = llformat("%d", data->mFee);
			// Set the fee to 0, so that we don't keep
			// asking about a fee.
			data->mFee = 0;
			gViewerWindow->alertXml("JoinGroupCanAfford",
									args,
									join_group_callback,
									(void*)data);
		}
		else
		{
			send_improved_im(data->mGroupID,
							"name",
							"message",
							IM_ONLINE,
							IM_GROUP_INVITATION_ACCEPT,
							data->mTransactionID);
		}
	}
	else if (data)
	{
		send_improved_im(data->mGroupID,
						"name",
						"message",
						IM_ONLINE,
						IM_GROUP_INVITATION_DECLINE,
						data->mTransactionID);
	}

	if(delete_context_data)
	{
		delete data;
		data = NULL;
	}
}


//-----------------------------------------------------------------------------
// Instant Message
//-----------------------------------------------------------------------------
class LLOpenAgentOffer : public LLInventoryFetchObserver
{
public:
	LLOpenAgentOffer(const std::string& from_name) : mFromName(from_name) {}
	/*virtual*/ void done()
	{
		open_offer(mComplete, mFromName);
		gInventory.removeObserver(this);
		delete this;
	}
private:
	std::string mFromName;
};

//unlike the FetchObserver for AgentOffer, we only make one 
//instance of the AddedObserver for TaskOffers
//and it never dies.  We do this because we don't know the UUID of 
//task offers until they are accepted, so we don't wouldn't 
//know what to watch for, so instead we just watch for all additions. -Gigs
class LLOpenTaskOffer : public LLInventoryAddedObserver
{
protected:
	/*virtual*/ void done()
	{
		open_offer(mAdded, "");
		mAdded.clear();
	}
 };

//one global instance to bind them
LLOpenTaskOffer* gNewInventoryObserver=NULL;

void start_new_inventory_observer()
{
	if (!gNewInventoryObserver) //task offer observer 
	{
		// Observer is deleted by gInventory
		gNewInventoryObserver = new LLOpenTaskOffer;
		gInventory.addObserver(gNewInventoryObserver);
	}
}

class LLDiscardAgentOffer : public LLInventoryFetchComboObserver
{
public:
	LLDiscardAgentOffer(const LLUUID& folder_id, const LLUUID& object_id) :
		mFolderID(folder_id),
		mObjectID(object_id) {}
	virtual ~LLDiscardAgentOffer() {}
	virtual void done()
	{
		lldebugs << "LLDiscardAgentOffer::done()" << llendl;
		LLUUID trash_id;
		trash_id = gInventory.findCategoryUUIDForType(LLAssetType::AT_TRASH);
		bool notify = false;
		if(trash_id.notNull() && mObjectID.notNull())
		{
			LLInventoryModel::update_list_t update;
			LLInventoryModel::LLCategoryUpdate old_folder(mFolderID, -1);
			update.push_back(old_folder);
			LLInventoryModel::LLCategoryUpdate new_folder(trash_id, 1);
			update.push_back(new_folder);
			gInventory.accountForUpdate(update);
			gInventory.moveObject(mObjectID, trash_id);
			LLInventoryObject* obj = gInventory.getObject(mObjectID);
			if(obj)
			{
				// no need to restamp since this is already a freshly
				// stamped item.
				obj->updateParentOnServer(FALSE);
				notify = true;
			}
		}
		else
		{
			llwarns << "DiscardAgentOffer unable to find: "
					<< (trash_id.isNull() ? "trash " : "")
					<< (mObjectID.isNull() ? "object" : "") << llendl;
		}
		gInventory.removeObserver(this);
		if(notify)
		{
			gInventory.notifyObservers();
		}
		delete this;
	}
protected:
	LLUUID mFolderID;
	LLUUID mObjectID;
};


//Returns TRUE if we are OK, FALSE if we are throttled
//Set check_only true if you want to know the throttle status 
//without registering a hit -Gigs
bool check_offer_throttle(const std::string& from_name, bool check_only)
{
	static U32 throttle_count;
	static bool throttle_logged;
	LLChat chat;
	LLString log_message;

	if (!gSavedSettings.getBOOL("ShowNewInventory"))
		return false;

	if (check_only)
	{
		return gThrottleTimer.hasExpired();
	}
	
	if(gThrottleTimer.checkExpirationAndReset(OFFER_THROTTLE_TIME))
	{
		//llinfos << "Throttle Expired" << llendl;
		throttle_count=1;
		throttle_logged=false;
		return true;
	}
	else //has not expired
	{
		//llinfos << "Throttle Not Expired, Count: " << throttle_count << llendl;
		// When downloading the initial inventory we get a lot of new items
		// coming in and can't tell that from spam.  JC
		if (LLStartUp::getStartupState() >= STATE_STARTED
			&& throttle_count >= OFFER_THROTTLE_MAX_COUNT)
		{
			if (!throttle_logged)
			{
				// Use the name of the last item giver, who is probably the person
				// spamming you. JC
				std::ostringstream message;
				message << gSecondLife;
				if (!from_name.empty())
				{
					message << ": Items coming in too fast from " << from_name;
				}
				else
				{
					message << ": Items coming in too fast";
				}
				message << ", automatic preview disabled for "
					<< OFFER_THROTTLE_TIME << " seconds.";
				chat.mText = message.str();
				//this is kinda important, so actually put it on screen
				LLFloaterChat::addChat(chat, FALSE, FALSE);
				throttle_logged=true;
			}
			return false;
		}
		else
		{
			throttle_count++;
			return true;
		}
	}
}
 
void open_offer(const std::vector<LLUUID>& items, const std::string& from_name)
{
	std::vector<LLUUID>::const_iterator it = items.begin();
	std::vector<LLUUID>::const_iterator end = items.end();
	LLUUID trash_id(gInventory.findCategoryUUIDForType(LLAssetType::AT_TRASH));
	LLInventoryItem* item;
	for(; it != end; ++it)
	{
		item = gInventory.getItem(*it);
		if(!item)
		{
			llwarns << "Unable to show inventory item: " << *it << llendl;
			continue;
		}
		if(gInventory.isObjectDescendentOf(*it, trash_id))
		{
			continue;
		}
		//if we are throttled, don't display them - Gigs
		if (check_offer_throttle(from_name, false))
		{
			// I'm not sure this is a good idea.  JC
			bool show_keep_discard = item->getPermissions().getCreator() != gAgent.getID();
			//bool show_keep_discard = true;
			switch(item->getType())
			{
			case LLAssetType::AT_NOTECARD:
				open_notecard((LLViewerInventoryItem*)item, LLString("Note: ") + item->getName(), LLUUID::null, show_keep_discard, LLUUID::null, FALSE);
				break;
			case LLAssetType::AT_LANDMARK:
				open_landmark((LLViewerInventoryItem*)item, LLString("Landmark: ") + item->getName(), show_keep_discard, LLUUID::null, FALSE);
				break;
			case LLAssetType::AT_TEXTURE:
				open_texture(*it, LLString("Texture: ") + item->getName(), show_keep_discard, LLUUID::null, FALSE);
				break;
			default:
				break;
			}
		}
		//highlight item, if it's not in the trash or lost+found
		
		// Don't auto-open the inventory floater
		LLInventoryView* view = LLInventoryView::getActiveInventory();
		if(!view)
		{
			return;
		}

		//Trash Check
		LLUUID trash_id;
		trash_id = gInventory.findCategoryUUIDForType(LLAssetType::AT_TRASH);
		if(gInventory.isObjectDescendentOf(item->getUUID(), trash_id))
		{
			return;
		}
		LLUUID lost_and_found_id = gInventory.findCategoryUUIDForType(LLAssetType::AT_LOST_AND_FOUND);
		//BOOL inventory_has_focus = gFocusMgr.childHasKeyboardFocus(view);
		BOOL user_is_away = gAwayTimer.getStarted();

		// don't select lost and found items if the user is active
		if (gInventory.isObjectDescendentOf(item->getUUID(), lost_and_found_id)
			&& !user_is_away)
		{
			return;
		}

		//Not sure about this check.  Could make it easy to miss incoming items. -Gigs
		//don't dick with highlight while the user is working
		//if(inventory_has_focus && !user_is_away)
		//	break;
		//llinfos << "Highlighting" << item->getUUID()  << llendl;
		//highlight item

		LLUICtrl* focus_ctrl = gFocusMgr.getKeyboardFocus();
		LLFocusMgr::FocusLostCallback callback;
		callback = gFocusMgr.getFocusCallback();
		view->getPanel()->setSelection(item->getUUID(), TAKE_FOCUS_NO);
		gFocusMgr.setKeyboardFocus(focus_ctrl, callback);
	}
}

void inventory_offer_mute_callback(const LLUUID& blocked_id,
								   const char* first_name,
								   const char* last_name,
								   BOOL is_group,
								   void* user_data)
{
	LLString from_name;
	LLMute::EType type;

	if (is_group)
	{
		type = LLMute::GROUP;
		from_name = first_name;
	}
	else
	{
		type = LLMute::AGENT;
		from_name += first_name;
		from_name += " ";
		from_name += last_name;
	}

	LLMute mute(blocked_id, from_name, type);
	if (gMuteListp->add(mute))
	{
		gFloaterMute->show();
		gFloaterMute->selectMute(blocked_id);
	}

	// purge the offer queue of any previously queued inventory offers from the same source.
	LLView::child_list_t notification_queue(*(gNotifyBoxView->getChildList()));
	for(LLView::child_list_iter_t iter = notification_queue.begin();
		iter != notification_queue.end();
		iter++)
	{
		LLNotifyBox* notification = (LLNotifyBox*)*iter;
		// scan for other inventory offers (i.e. ignore other types of notifications).
		// we can tell by looking for the associated callback they were created with.
		if(notification->getNotifyCallback() == inventory_offer_callback)
		{
			// found one.
			// safe to downcast user data because we know it's associated with offer callback.
			LLOfferInfo* offer_data = (LLOfferInfo*)notification->getUserData();
			if(offer_data == user_data)
			{
				continue; // don't remove the msg triggering us. it will be dequeued normally.
			}
			if(offer_data->mFromID == blocked_id) 
			{
				gNotifyBoxView->removeChild(notification);
			}
		}
	}
}

void inventory_offer_callback(S32 button, void* user_data)
 {
	LLChat chat;
	LLString log_message;

	LLOfferInfo* info = (LLOfferInfo*)user_data;
	if(!info) return;

	// For muting, we need to add the mute, then decline the offer.
	// This must be done here because:
	// * callback may be called immediately,
	// * adding the mute sends a message,
	// * we can't build two messages at once.  JC
	if (2 == button)
	{
		gCacheName->get(info->mFromID, info->mFromGroup, inventory_offer_mute_callback, user_data);
	}

	LLMessageSystem* msg = gMessageSystem;
	msg->newMessageFast(_PREHASH_ImprovedInstantMessage);
	msg->nextBlockFast(_PREHASH_AgentData);
	msg->addUUIDFast(_PREHASH_AgentID, gAgent.getID());
	msg->addUUIDFast(_PREHASH_SessionID, gAgent.getSessionID());
	msg->nextBlockFast(_PREHASH_MessageBlock);
	msg->addBOOLFast(_PREHASH_FromGroup, FALSE);
	msg->addUUIDFast(_PREHASH_ToAgentID, info->mFromID);
	msg->addU8Fast(_PREHASH_Offline, IM_ONLINE);
	msg->addUUIDFast(_PREHASH_ID, info->mTransactionID);
	msg->addU32Fast(_PREHASH_Timestamp, NO_TIMESTAMP); // no timestamp necessary
	std::string name;
	gAgent.buildFullname(name);
	msg->addStringFast(_PREHASH_FromAgentName, name);
	msg->addStringFast(_PREHASH_Message, ""); 
	msg->addU32Fast(_PREHASH_ParentEstateID, 0);
	msg->addUUIDFast(_PREHASH_RegionID, LLUUID::null);
	msg->addVector3Fast(_PREHASH_Position, gAgent.getPositionAgent());
	LLInventoryObserver* opener = NULL;
	LLViewerInventoryCategory* catp = NULL;
	catp = (LLViewerInventoryCategory*)gInventory.getCategory(info->mObjectID);
	LLViewerInventoryItem* itemp = NULL;
	if(!catp)
	{
		itemp = (LLViewerInventoryItem*)gInventory.getItem(info->mObjectID);
	}

	// XUI:translate
	LLString from_string; // Used in the pop-up.
	LLString chatHistory_string;  // Used in chat history.
	if (info->mFromObject == TRUE)
	{
		if (info->mFromGroup)
		{
			char group_name[MAX_STRING];		/* Flawfinder: ignore */
			if (gCacheName->getGroupName(info->mFromID, group_name))
			{
				from_string = LLString("An object named '") + info->mFromName + "' owned by the group '" + group_name + "'";
				chatHistory_string = info->mFromName + " owned by the group '" + group_name + "'";
			}
			else
			{
				from_string = LLString("An object named '") + info->mFromName + "' owned by an unknown group";
				chatHistory_string = info->mFromName + " owned by an unknown group";
			}
		}
		else
		{
			char first_name[MAX_STRING];		/* Flawfinder: ignore */
			char last_name[MAX_STRING];		/* Flawfinder: ignore */
			if (gCacheName->getName(info->mFromID, first_name, last_name))
			{
				from_string = LLString("An object named '") + info->mFromName + "' owned by " + first_name + " " + last_name;
				chatHistory_string = info->mFromName + " owned by " + first_name + " " + last_name;
			}
			else
			{
				from_string = LLString("An object named '") + info->mFromName + "' owned by an unknown user";
				chatHistory_string = info->mFromName + " owned by an unknown user";
			}
		}
	}
	else
	{
		from_string = chatHistory_string = info->mFromName;
	}
	
	bool busy=FALSE;
	
	switch(button)
	{
	case IOR_ACCEPT:
		// ACCEPT. The math for the dialog works, because the accept
		// for inventory_offered, task_inventory_offer or
		// group_notice_inventory is 1 greater than the offer integer value.
		// Generates IM_INVENTORY_ACCEPTED, IM_TASK_INVENTORY_ACCEPTED, 
		// or IM_GROUP_NOTICE_INVENTORY_ACCEPTED
		msg->addU8Fast(_PREHASH_Dialog, (U8)(info->mIM + 1));
		msg->addBinaryDataFast(_PREHASH_BinaryBucket, &(info->mFolderID.mData),
					 sizeof(info->mFolderID.mData));
		// send the message
		msg->sendReliable(info->mHost);

		//don't spam them if they are getting flooded
		if (check_offer_throttle(info->mFromName, true))
		{
			log_message = chatHistory_string + " gave you " + info->mDesc + ".";
 			chat.mText = log_message;
 			LLFloaterChat::addChatHistory(chat);
		}

		// we will want to open this item when it comes back.
		lldebugs << "Initializing an opener for tid: " << info->mTransactionID
				 << llendl;
		switch (info->mIM)
		{
		case IM_INVENTORY_OFFERED:
		{
			// This is an offer from an agent. In this case, the back
			// end has already copied the items into your inventory,
			// so we can fetch it out of our inventory.
			LLInventoryFetchObserver::item_ref_t items;
			items.push_back(info->mObjectID);
			LLOpenAgentOffer* open_agent_offer = new LLOpenAgentOffer(from_string);
			open_agent_offer->fetchItems(items);
			if(catp || (itemp && itemp->isComplete()))
			{
				open_agent_offer->done();
			}
			else
			{
				opener = open_agent_offer;
			}
		}
			break;
		case IM_TASK_INVENTORY_OFFERED:
		case IM_GROUP_NOTICE:
		case IM_GROUP_NOTICE_REQUESTED:
		{
			// This is an offer from a task or group.
			// We don't use a new instance of an opener
			// We instead use the singular observer gOpenTaskOffer
			// Since it already exists, we don't need to actually do anything
		}
		break;
		default:
			llwarns << "inventory_offer_callback: unknown offer type" << llendl;
			break;
		}	// end switch (info->mIM)
		break;

	case IOR_BUSY:
		//Busy falls through to decline.  Says to make busy message.
		busy=TRUE;
	case IOR_MUTE:
		// MUTE falls through to decline
	case IOR_DECLINE:
		// DECLINE. The math for the dialog works, because the decline
		// for inventory_offered, task_inventory_offer or
		// group_notice_inventory is 2 greater than the offer integer value.
		// Generates IM_INVENTORY_DECLINED, IM_TASK_INVENTORY_DECLINED,
		// or IM_GROUP_NOTICE_INVENTORY_DECLINED
	default:
		// close button probably
		msg->addU8Fast(_PREHASH_Dialog, (U8)(info->mIM + 2));
		msg->addBinaryDataFast(_PREHASH_BinaryBucket, EMPTY_BINARY_BUCKET, EMPTY_BINARY_BUCKET_SIZE);
		// send the message
		msg->sendReliable(info->mHost);

		log_message = "You decline " + info->mDesc + " from " + info->mFromName + ".";
		chat.mText = log_message;
		if( gMuteListp->isMuted(info->mFromID ) && ! gMuteListp->isLinden(info->mFromName) )  // muting for SL-42269
		{
			chat.mMuted = TRUE;
		}
		LLFloaterChat::addChatHistory(chat);

		// If it's from an agent, we have to fetch the item to throw
		// it away. If it's from a task or group, just denying the 
		// request will suffice to discard the item.
		if(IM_INVENTORY_OFFERED == info->mIM)
		{
			LLInventoryFetchComboObserver::folder_ref_t folders;
			LLInventoryFetchComboObserver::item_ref_t items;
			items.push_back(info->mObjectID);
			LLDiscardAgentOffer* discard_agent_offer;
			discard_agent_offer = new LLDiscardAgentOffer(info->mFolderID, info->mObjectID);
			discard_agent_offer->fetch(folders, items);
			if(catp || (itemp && itemp->isComplete()))
			{
				discard_agent_offer->done();
			}
			else
			{
				opener = discard_agent_offer;
			}
			
		}
		if (busy || (!info->mFromGroup && !info->mFromObject))
		{
			busy_message(msg,info->mFromID);
		}
		break;
	}

	if(opener)
	{
		gInventory.addObserver(opener);
	}

	delete info;
	info = NULL;

	// Allow these to stack up, but once you deal with one, reset the
	// position.
	gFloaterView->resetStartingFloaterPosition();
}


void inventory_offer_handler(LLOfferInfo* info, BOOL from_task)
{
	//Until throttling is implmented, busy mode should reject inventory instead of silently
	//accepting it.  SEE SL-39554
	if (gAgent.getBusy())
	{
		inventory_offer_callback(IOR_BUSY, info);
		return;
	}
	
	//If muted, don't even go through the messaging stuff.  Just curtail the offer here.
	if (gMuteListp->isMuted(info->mFromID, info->mFromName))
	{
		inventory_offer_callback(IOR_MUTE, info);
		return;
	}

	// Avoid the Accept/Discard dialog if the user so desires. JC
	if (gSavedSettings.getBOOL("AutoAcceptNewInventory")
		&& (info->mType == LLAssetType::AT_NOTECARD
			|| info->mType == LLAssetType::AT_LANDMARK
			|| info->mType == LLAssetType::AT_TEXTURE))
	{
		// For certain types, just accept the items into the inventory,
		// and possibly open them on receipt depending upon "ShowNewInventory".
		inventory_offer_callback(IOR_ACCEPT, info);
		return;
	}

	LLString::format_map_t args;
	args["[OBJECTNAME]"] = info->mDesc;
	args["[OBJECTTYPE]"] = LLAssetType::lookupHumanReadable(info->mType);

	// Name cache callbacks don't store userdata, so can't save
	// off the LLOfferInfo.  Argh.  JC
	BOOL name_found = FALSE;
	char first_name[MAX_STRING];		/* Flawfinder: ignore */
	char last_name[MAX_STRING];		/* Flawfinder: ignore */
	if (info->mFromGroup)
	{
		if (gCacheName->getGroupName(info->mFromID, first_name))
		{
			args["[FIRST]"] = first_name;
			args["[LAST]"] = "";
			name_found = TRUE;
		}
	}
	else
	{
		if (gCacheName->getName(info->mFromID, first_name, last_name))
		{
			args["[FIRST]"] = first_name;
			args["[LAST]"] = last_name;
			name_found = TRUE;
		}
	}
	if (from_task)
	{
		args["[OBJECTFROMNAME]"] = info->mFromName;
		LLNotifyBox::showXml(name_found ? "ObjectGiveItem" : "ObjectGiveItemUnknownUser",
							args, &inventory_offer_callback, (void*)info);
	}
	else
	{
		// XUI:translate -> [FIRST] [LAST]
		args["[NAME]"] = info->mFromName;
		LLNotifyBox::showXml("UserGiveItem", args,
							&inventory_offer_callback, (void*)info);
	}
}


void group_vote_callback(S32 option, void *userdata)
{
	LLUUID *group_id = (LLUUID *)userdata;
	if (!group_id) return;

	switch(option)
	{
	case 0:
		// Vote Now
		// Open up the voting tab
		LLFloaterGroupInfo::showFromUUID(*group_id, "voting_tab");
		break;
	default:
		// Vote Later or
		// close button
		break;
	}
	delete group_id;
	group_id = NULL;
}

struct LLLureInfo
{
	LLLureInfo(const LLUUID& from, const LLUUID& lure_id, BOOL godlike) :
		mFromID(from),
		mLureID(lure_id),
		mGodlike(godlike)
	{}

	LLUUID mFromID;
	LLUUID mLureID;
	BOOL mGodlike;
};

void lure_callback(S32 option, void* user_data)
{
	LLLureInfo* info = (LLLureInfo*)user_data;
	if(!info) return;
	switch(option)
	{
	case 0:
		{
			// accept
			send_simple_im(info->mFromID,
						   "",
						   IM_LURE_ACCEPTED,
						   info->mLureID);
			gAgent.teleportViaLure(info->mLureID, info->mGodlike);
		}
		break;
	case 1:
	default:
		// decline
		send_simple_im(info->mFromID,
					   "",
					   IM_LURE_DECLINED,
					   info->mLureID);
		break;
	}
	delete info;
	info = NULL;
}

void goto_url_callback(S32 option, void* user_data)
{
	char* url = (char*)user_data;
	if(1 == option)
	{
		LLWeb::loadURL(url);
	}
	delete[] url;
}

void process_improved_im(LLMessageSystem *msg, void **user_data)
{
	if (gNoRender)
	{
		return;
	}
	LLUUID from_id;
	BOOL from_group;
	LLUUID to_id;
	U8 offline;
	U8 d = 0;
	LLUUID session_id;
	U32 t;
	char name[DB_FULL_NAME_BUF_SIZE];		/* Flawfinder: ignore */
	char message[DB_IM_MSG_BUF_SIZE];		/* Flawfinder: ignore */
	U32 parent_estate_id = 0;
	LLUUID region_id;
	LLVector3 position;
	char buffer[DB_IM_MSG_BUF_SIZE * 2];		/* Flawfinder: ignore */
	U8 binary_bucket[MTUBYTES];
	S32 binary_bucket_size;
	LLChat chat;

	//XUI:translate - need to fix the full name to first/last
	msg->getUUIDFast(_PREHASH_AgentData, _PREHASH_AgentID, from_id);
	msg->getBOOLFast(_PREHASH_MessageBlock, _PREHASH_FromGroup, from_group);
	msg->getUUIDFast(_PREHASH_MessageBlock, _PREHASH_ToAgentID, to_id);
	msg->getU8Fast(  _PREHASH_MessageBlock, _PREHASH_Offline, offline);
	msg->getU8Fast(  _PREHASH_MessageBlock, _PREHASH_Dialog, d);
	msg->getUUIDFast(_PREHASH_MessageBlock, _PREHASH_ID, session_id);
	msg->getU32Fast( _PREHASH_MessageBlock, _PREHASH_Timestamp, t);
	//msg->getData("MessageBlock", "Count",		&count);
	msg->getStringFast(_PREHASH_MessageBlock, _PREHASH_FromAgentName, DB_FULL_NAME_BUF_SIZE, name);
	msg->getStringFast(_PREHASH_MessageBlock, _PREHASH_Message,		DB_IM_MSG_BUF_SIZE, message);
	msg->getU32Fast(_PREHASH_MessageBlock, _PREHASH_ParentEstateID, parent_estate_id);
	msg->getUUIDFast(_PREHASH_MessageBlock, _PREHASH_RegionID, region_id);
	msg->getVector3Fast(_PREHASH_MessageBlock, _PREHASH_Position, position);
	msg->getBinaryDataFast(  _PREHASH_MessageBlock, _PREHASH_BinaryBucket, binary_bucket, 0, 0, MTUBYTES);
	binary_bucket_size = msg->getSizeFast(_PREHASH_MessageBlock, _PREHASH_BinaryBucket);
	EInstantMessage dialog = (EInstantMessage)d;
	time_t timestamp = (time_t)t;

	BOOL is_busy = gAgent.getBusy();
	BOOL is_muted = gMuteListp->isMuted(from_id, name, LLMute::flagTextChat);
	BOOL is_linden = gMuteListp->isLinden(name);
	BOOL is_owned_by_me = FALSE;
	
	chat.mMuted = is_muted && !is_linden;
	chat.mFromID = from_id;
	chat.mFromName = name;

	LLViewerObject *source = gObjectList.findObject(session_id); //Session ID is probably the wrong thing.
	if (source)
	{
		is_owned_by_me = source->permYouOwner();
	}

	char separator_string[3]=": ";		/* Flawfinder: ignore */
	int message_offset=0;

		//Handle IRC styled /me messages.
	if (!strncmp(message, "/me ", 4) || !strncmp(message, "/me'", 4))
	{
		strcpy(separator_string,"");		/* Flawfinder: ignore */
		message_offset=3;
	}

	LLString::format_map_t args;
	switch(dialog)
	{
	case IM_CONSOLE_AND_CHAT_HISTORY:
		// These are used for system messages, hence don't need the name,
		// as it is always "Second Life".
	  	// XUI:translate
		args["[MESSAGE]"] = message;

		// Note: don't put the message in the IM history, even though was sent
		// via the IM mechanism.
		LLNotifyBox::showXml("SystemMessageTip",args);
		break;

	case IM_NOTHING_SPECIAL: 
		// Don't show dialog, just do IM
		if (!gAgent.isGodlike()
				&& gAgent.getRegion()->isPrelude() 
				&& to_id.isNull() )
		{
			// do nothing -- don't distract newbies in
			// Prelude with global IMs
		}
		else if (offline == IM_ONLINE && !is_linden && is_busy && strcmp(name, SYSTEM_FROM))
		{
			// return a standard "busy" message, but only do it to online IM 
			// (i.e. not other auto responses and not store-and-forward IM)
			if (!gIMMgr->hasSession(session_id))
			{
				// if there is not a panel for this conversation (i.e. it is a new IM conversation
				// initiated by the other party) then...
				std::string my_name;
				gAgent.buildFullname(my_name);
				LLString response = gSavedPerAccountSettings.getText("BusyModeResponse");
				pack_instant_message(
					gMessageSystem,
					gAgent.getID(),
					FALSE,
					gAgent.getSessionID(),
					from_id,
					my_name.c_str(),
					response.c_str(),
					IM_ONLINE,
					IM_BUSY_AUTO_RESPONSE,
					session_id);
				gAgent.sendReliableMessage();
			}

			// now store incoming IM in chat history

			snprintf(buffer, sizeof(buffer), "%s%s%s", name, separator_string, (message+message_offset));		/* Flawfinder: ignore */
	
			llinfos << "process_improved_im: session_id( " << session_id << " ), from_id( " << from_id << " )" << llendl;

			// add to IM panel, but do not bother the user
			gIMMgr->addMessage(
				session_id,
				from_id,
				name,
				buffer,
				NULL,
				dialog,
				parent_estate_id,
				region_id,
				position);

			// pretend this is chat generated by self, so it does not show up on screen
			snprintf(buffer, sizeof(buffer), "IM: %s%s%s", name, separator_string, (message+message_offset));		/* Flawfinder: ignore */
			chat.mText = buffer;
			LLFloaterChat::addChat( chat, TRUE, TRUE );
		}
		else if (from_id.isNull())
		{
			// Messages from "Second Life" don't go to IM history
			snprintf(buffer, sizeof(buffer), "%s: %s", name, message);		/* Flawfinder: ignore */
			chat.mText = buffer;
			LLFloaterChat::addChat(chat, FALSE, FALSE);
		}
		else if (to_id.isNull())
		{
			// Message to everyone from GOD
			args["[NAME]"] = name;
			args["[MESSAGE]"] = message;
			LLNotifyBox::showXml("GodMessage", args);

			// Treat like a system message and put in chat history.
			// Claim to be from a local agent so it doesn't go into
			// console.
			snprintf(buffer, sizeof(buffer), "%s%s%s", name, separator_string, (message+message_offset));		/* Flawfinder: ignore */
			chat.mText = buffer;
			BOOL local_agent = TRUE;
			LLFloaterChat::addChat(chat, FALSE, local_agent);
		}
		else
		{
			// standard message, not from system
			char saved[MAX_STRING];		/* Flawfinder: ignore */
			saved[0] = '\0';
			if(offline == IM_OFFLINE)
			{
				char time_buf[TIME_STR_LENGTH];		/* Flawfinder: ignore */
				snprintf(saved, MAX_STRING, "(Saved %s) ",		/* Flawfinder: ignore */
						formatted_time(timestamp, time_buf));
			}
			snprintf(buffer, sizeof(buffer), "%s%s%s%s", name, separator_string, saved,(message+message_offset));		/* Flawfinder: ignore */

			llinfos << "process_improved_im: session_id( " << session_id << " ), from_id( " << from_id << " )" << llendl;

			if (!is_muted || is_linden)
			{
				gIMMgr->addMessage(
					session_id,
					from_id,
					name,
					buffer,
					NULL,
					dialog,
					parent_estate_id,
					region_id,
					position);
				snprintf(buffer, sizeof(buffer), "IM: %s%s%s%s", name, separator_string, saved, (message+message_offset));		/* Flawfinder: ignore */

				chat.mText = buffer;
				BOOL local_agent = FALSE;
				LLFloaterChat::addChat( chat, TRUE, local_agent );
			}
			else
			{
				// muted user, so don't start an IM session, just record line in chat
				// history.  Pretend the chat is from a local agent,
				// so it will go into the history but not be shown on screen.
				chat.mText = buffer;
				BOOL local_agent = TRUE;
				LLFloaterChat::addChat( chat, TRUE, local_agent );
			}
		}
		break;

	case IM_TYPING_START:
		{
			LLPointer<LLIMInfo> im_info = new LLIMInfo(gMessageSystem);
			gIMMgr->processIMTypingStart(im_info);
		}
		break;

	case IM_TYPING_STOP:
		{
			LLPointer<LLIMInfo> im_info = new LLIMInfo(gMessageSystem);
			gIMMgr->processIMTypingStop(im_info);
		}
		break;

	case IM_MESSAGEBOX:
		{
			// This is a block, modeless dialog.
			//XUI:translate
			args["[MESSAGE]"] = message;
			LLNotifyBox::showXml("SystemMessage", args);
		}
		break;
	case IM_GROUP_NOTICE:
	case IM_GROUP_NOTICE_REQUESTED:
		{
			llinfos << "Received IM_GROUP_NOTICE message." << llendl;
			// Read the binary bucket for more information.
			struct notice_bucket_header_t
			{
				U8 has_inventory;
				U8 asset_type;
				LLUUID group_id;
			};
			struct notice_bucket_full_t
			{
				struct notice_bucket_header_t header;
				U8 item_name[DB_INV_ITEM_NAME_BUF_SIZE];
			}* notice_bin_bucket;

			// Make sure the binary bucket is big enough to hold the header 
			// and a null terminated item name.
			if ( (binary_bucket_size < (S32)((sizeof(notice_bucket_header_t) + sizeof(U8))))
				|| (binary_bucket[binary_bucket_size - 1] != '\0') )
			{
				llwarns << "Malformed group notice binary bucket" << llendl;
				break;
			}

			notice_bin_bucket = (struct notice_bucket_full_t*) &binary_bucket[0];
			U8 has_inventory = notice_bin_bucket->header.has_inventory;
			U8 asset_type = notice_bin_bucket->header.asset_type;
			LLUUID group_id = notice_bin_bucket->header.group_id;
			const char* item_name = (const char*) notice_bin_bucket->item_name;

			// If there is inventory, give the user the inventory offer.
			LLOfferInfo* info = NULL;
			if (has_inventory)
			{
				info = new LLOfferInfo;
				info->mIM = IM_GROUP_NOTICE;
				info->mFromID = from_id;
				info->mFromGroup = from_group;
				info->mTransactionID = session_id;
				info->mType = (LLAssetType::EType) asset_type;
				info->mFolderID = gInventory.findCategoryUUIDForType(info->mType);
				std::string from_name;

				from_name += "A group member named ";
				from_name += name;

				info->mFromName = from_name;
				info->mDesc = item_name;
				info->mHost = msg->getSender();
			}
			
			std::string str(message);

			// Tokenize the string.
			// TODO: Support escaped tokens ("||" -> "|")
			typedef boost::tokenizer<boost::char_separator<char> > tokenizer;
			boost::char_separator<char> sep("|","",boost::keep_empty_tokens);
			tokenizer tokens(str, sep);
			tokenizer::iterator iter = tokens.begin();

			LLString subj(*iter++);
			LLString mes(*iter++);

			if (IM_GROUP_NOTICE == dialog)
			{
				subj += "\n";
				mes = "\n\n" + mes;
				LLGroupNotifyBox::show(subj.c_str(),mes.c_str(),name,group_id,t,has_inventory,item_name,info);
			}
			else if (IM_GROUP_NOTICE_REQUESTED == dialog)
			{
				LLFloaterGroupInfo::showNotice(subj.c_str(),mes.c_str(),group_id,has_inventory,item_name,info);
			}
		}
		break;
	case IM_GROUP_INVITATION:
		{
			//if (!is_linden && (is_busy || is_muted))
			if ((is_busy || is_muted))
			{
				LLMessageSystem *msg = gMessageSystem;
				join_group_callback(1, NULL);
				busy_message(msg,from_id);
			}
			else
			{
				llinfos << "Received IM_GROUP_INVITATION message." << llendl;
				// Read the binary bucket for more information.
				struct invite_bucket_t
				{
					S32 membership_fee;
					LLUUID role_id;
				}* invite_bucket;

				// Make sure the binary bucket is the correct size.
				if (binary_bucket_size != sizeof(invite_bucket_t))
				{
					llwarns << "Malformed group invite binary bucket" << llendl;
					break;
				}

				invite_bucket = (struct invite_bucket_t*) &binary_bucket[0];
				S32 membership_fee = ntohl(invite_bucket->membership_fee);

				LLJoinGroupData* userdata = new LLJoinGroupData;
				userdata->mTransactionID = session_id;
				userdata->mGroupID = from_id;
				userdata->mName.assign(name);
				userdata->mMessage.assign(message);
				userdata->mFee = membership_fee;

				LLString::format_map_t args;
				args["[MESSAGE]"] = message;
				LLNotifyBox::showXml("JoinGroup", args,
									 &join_group_callback,
									 (void*)userdata);
			}
		}
		break;

	case IM_INVENTORY_OFFERED:
	case IM_TASK_INVENTORY_OFFERED:
		// Someone has offered us some inventory.
		{
			LLOfferInfo* info = new LLOfferInfo;

			if (IM_INVENTORY_OFFERED == dialog)
			{
				struct offer_agent_bucket_t
				{
					S8		asset_type;
					LLUUID	object_id;
				}* bucketp;

				if (sizeof(offer_agent_bucket_t) != binary_bucket_size)
				{
					llwarns << "Malformed inventory offer from agent" << llendl;
					break;
				}
				bucketp = (struct offer_agent_bucket_t*) &binary_bucket[0];
				info->mType = (LLAssetType::EType) bucketp->asset_type;
				info->mObjectID = bucketp->object_id;
			}
			else
			{
				if (sizeof(S8) != binary_bucket_size)
				{
					llwarns << "Malformed inventory offer from object" << llendl;
					break;
				}
				info->mType = (LLAssetType::EType) binary_bucket[0];
				info->mObjectID = LLUUID::null;
			}

			info->mIM = dialog;
			info->mFromID = from_id;
			info->mFromGroup = from_group;
			info->mTransactionID = session_id;
			info->mFolderID = gInventory.findCategoryUUIDForType(info->mType);

			if (dialog == IM_TASK_INVENTORY_OFFERED)
			{
				info->mFromObject = TRUE;
			}
			else
			{
				info->mFromObject = FALSE;
			}
			info->mFromName = name;
			info->mDesc = message;
			info->mHost = msg->getSender();
			//if (((is_busy && !is_owned_by_me) || is_muted))
			if ( is_muted )
			{
				// Same as closing window
				inventory_offer_callback(-1, info);
			}
			else
			{
				inventory_offer_handler(info, dialog == IM_TASK_INVENTORY_OFFERED);
			}
		}
		break;

	case IM_INVENTORY_ACCEPTED:
	{
		args["[NAME]"] = name;
		LLNotifyBox::showXml("InventoryAccepted", args);
		break;
	}
	case IM_INVENTORY_DECLINED:
	{
		args["[NAME]"] = name;
		LLNotifyBox::showXml("InventoryDeclined", args);
		break;
	}
	case IM_GROUP_VOTE:
	{
		LLUUID *userdata = new LLUUID(session_id);
		args["[NAME]"] = name;
		args["[MESSAGE]"] = message;
		LLNotifyBox::showXml("GroupVote", args,
							 &group_vote_callback, userdata);
	}
	break;

	case IM_GROUP_ELECTION_DEPRECATED:
	{
		llwarns << "Received IM: IM_GROUP_ELECTION_DEPRECATED" << llendl;
	}
	break;
	
	case IM_SESSION_SEND:
	{
		if (!is_linden && is_busy)
		{
			return;
		}

		// Only show messages if we have a session open (which
		// should happen after you get an "invitation"
		if ( !gIMMgr->hasSession(session_id) )
		{
			return;
		}

		// standard message, not from system
		char saved[MAX_STRING];		/* Flawfinder: ignore */
		saved[0] = '\0';
		if(offline == IM_OFFLINE)
		{
			char time_buf[TIME_STR_LENGTH];		/* Flawfinder: ignore */
			snprintf(saved,		/* Flawfinder: ignore */
					 MAX_STRING, 
					 "(Saved %s) ", 
					 formatted_time(timestamp, time_buf));
		}
		snprintf(buffer, sizeof(buffer), "%s%s%s%s", name, separator_string, saved, (message+message_offset));		/* Flawfinder: ignore */
		BOOL is_this_agent = FALSE;
		if(from_id == gAgentID)
		{
			is_this_agent = TRUE;
		}
		gIMMgr->addMessage(
			session_id,
			from_id,
			name,
			buffer,
			(char*)binary_bucket,
			IM_SESSION_INVITE,
			parent_estate_id,
			region_id,
			position);

		snprintf(buffer, sizeof(buffer), "IM: %s%s%s%s", name, separator_string, saved, (message+message_offset));		/* Flawfinder: ignore */
		chat.mText = buffer;
		LLFloaterChat::addChat(chat, TRUE, is_this_agent);
	}
	break;

	case IM_FROM_TASK:
		if (is_busy && !is_owned_by_me)
		{
			return;
		}
		snprintf(buffer, sizeof(buffer), "%s%s%s", name, separator_string, (message+message_offset));		/* Flawfinder: ignore */
		// Note: lie to LLFloaterChat::addChat(), pretending that this is NOT an IM, because
		// IMs from objcts don't open IM sessions.
		chat.mText = buffer;
		chat.mSourceType = CHAT_SOURCE_OBJECT;
		LLFloaterChat::addChat(chat, FALSE, FALSE);
		break;
	case IM_FROM_TASK_AS_ALERT:
		if (is_busy && !is_owned_by_me)
		{
			return;
		}
		{
			// Construct a viewer alert for this message.
			args["[NAME]"] = name;
			args["[MESSAGE]"] = message;
			LLNotifyBox::showXml("ObjectMessage", args);
		}
		break;
	case IM_BUSY_AUTO_RESPONSE:
		// fix for JIRA issue VWR-20 submitted 13-JAN-2007 - Paul Churchill
		if (is_muted)
		{
			lldebugs << "Ignoring busy response from " << from_id << llendl;
			return;
		}
		else
		{
			// original code resumes
			gIMMgr->addMessage(session_id, from_id, name, message);
		}
		break;
		
	case IM_LURE_USER:
		{
			if (is_muted)
			{ 
				return;
			}
			else if (is_busy) 
			{
				busy_message(msg,from_id);
			}
			else
			{
				// XUI:translate -> [FIRST] [LAST]
				LLLureInfo* info = new LLLureInfo(from_id, session_id, FALSE);
				args["[NAME]"] = name;
				args["[MESSAGE]"] = message;
				LLNotifyBox::showXml("OfferTeleport", args,
									 lure_callback, (void*)info);
			}
		}
		break;

	case IM_GODLIKE_LURE_USER:
		{
			LLLureInfo* info = new LLLureInfo(from_id, session_id, TRUE);
			// do not show a message box, because you're about to be
			// teleported.
			lure_callback(0, (void *)info);
		}
		break;

	case IM_GOTO_URL:
		{
			if (binary_bucket_size <= 0)
			{
				llwarns << "bad binary_bucket_size: "
					<< binary_bucket_size
					<< " - aborting function." << llendl;
				return;
			}

			char* url = new char[binary_bucket_size];
			if (url == NULL)
			{
				llerrs << "Memory Allocation failed" << llendl;
				return;
			}

			strncpy(url, (char*)binary_bucket, binary_bucket_size-1);		/* Flawfinder: ignore */
			url[binary_bucket_size-1] = '\0';
			args["[MESSAGE]"] = message;
			args["[URL]"] = url;
			LLNotifyBox::showXml("GotoURL", args,
								 goto_url_callback, (void*)url);
		}
		break;

	case IM_FRIENDSHIP_OFFERED:
		{
			LLFriendshipOffer* offer = new LLFriendshipOffer;
			offer->mFromID = from_id;
			offer->mTransactionID = session_id;
			offer->mOnline = (offline == IM_ONLINE);
			offer->mHost = msg->getSender();

			if (is_busy)
			{
				busy_message(msg, from_id);
				friendship_offer_callback(1, (void*)offer);
			}
			else if (is_muted)
			{
				friendship_offer_callback(1, (void*)offer);
			}
			else
			{
				args["[NAME]"] = name;
				LLNotifyBox::showXml("OfferFriendship", args,
					&friendship_offer_callback, (void*)offer);
			}
		}
		break;

	case IM_FRIENDSHIP_ACCEPTED:
		{
			// In the case of an offline IM, the formFriendship() may be extraneous
			// as the database should already include the relationship.  But it
			// doesn't hurt for dupes.
			LLAvatarTracker::formFriendship(from_id);
			
			std::vector<std::string> strings;
			strings.push_back(from_id.asString());
			send_generic_message("requestonlinenotification", strings);
			
			args["[NAME]"] = name;
			LLNotifyBox::showXml("FriendshipAccepted", args);
		}
		break;

	case IM_FRIENDSHIP_DECLINED:
		args["[NAME]"] = name;
		LLNotifyBox::showXml("FriendshipDeclined", args);
		break;

	default:
		llwarns << "Instant message calling for unknown dialog "
				<< (S32)dialog << llendl;
		break;
	}

	LLWindow* viewer_window = gViewerWindow->getWindow();
	if (viewer_window && viewer_window->getMinimized())
	{
		viewer_window->flashIcon(5.f);
	}
}

void busy_message (LLMessageSystem* msg, LLUUID from_id) 
{
	if (gAgent.getBusy())
	{
		LLString response = gSavedPerAccountSettings.getText("BusyModeResponse");
		pack_instant_message(
			gMessageSystem,
			gAgent.getID(),
			FALSE,
			gAgent.getSessionID(),
			from_id,
			SYSTEM_FROM,
			response.c_str(),
			IM_ONLINE,
			IM_CONSOLE_AND_CHAT_HISTORY);
		gAgent.sendReliableMessage();
	}
}

void friendship_offer_callback(S32 option, void* user_data)
{
	LLFriendshipOffer* offer = (LLFriendshipOffer*)user_data;
	if(!offer) return;
	LLUUID fid;
	LLMessageSystem* msg = gMessageSystem;
	switch(option)
	{
	case 0:
		// accept
		LLAvatarTracker::formFriendship(offer->mFromID);

		fid = gInventory.findCategoryUUIDForType(LLAssetType::AT_CALLINGCARD);

		// This will also trigger an onlinenotification if the user is online
		msg->newMessageFast(_PREHASH_AcceptFriendship);
		msg->nextBlockFast(_PREHASH_AgentData);
		msg->addUUIDFast(_PREHASH_AgentID, gAgent.getID());
		msg->addUUIDFast(_PREHASH_SessionID, gAgent.getSessionID());
		msg->nextBlockFast(_PREHASH_TransactionBlock);
		msg->addUUIDFast(_PREHASH_TransactionID, offer->mTransactionID);
		msg->nextBlockFast(_PREHASH_FolderData);
		msg->addUUIDFast(_PREHASH_FolderID, fid);
		msg->sendReliable(offer->mHost);
		break;
	case 1:
		// decline
		msg->newMessageFast(_PREHASH_DeclineFriendship);
		msg->nextBlockFast(_PREHASH_AgentData);
		msg->addUUIDFast(_PREHASH_AgentID, gAgent.getID());
		msg->addUUIDFast(_PREHASH_SessionID, gAgent.getSessionID());
		msg->nextBlockFast(_PREHASH_TransactionBlock);
		msg->addUUIDFast(_PREHASH_TransactionID, offer->mTransactionID);
		msg->sendReliable(offer->mHost);
		break;
	default:
		// close button probably, possibly timed out
		break;
	}

	delete offer;
	offer = NULL;
}

struct LLCallingCardOfferData
{
	LLUUID mTransactionID;
	LLUUID mSourceID;
	LLHost mHost;
};

void callingcard_offer_callback(S32 option, void* user_data)
{
	LLCallingCardOfferData* offerdata = (LLCallingCardOfferData*)user_data;
	if(!offerdata) return;
	LLUUID fid;
	LLUUID from_id;
	LLMessageSystem* msg = gMessageSystem;
	switch(option)
	{
	case 0:
		// accept
		msg->newMessageFast(_PREHASH_AcceptCallingCard);
		msg->nextBlockFast(_PREHASH_AgentData);
		msg->addUUIDFast(_PREHASH_AgentID, gAgent.getID());
		msg->addUUIDFast(_PREHASH_SessionID, gAgent.getSessionID());
		msg->nextBlockFast(_PREHASH_TransactionBlock);
		msg->addUUIDFast(_PREHASH_TransactionID, offerdata->mTransactionID);
		fid = gInventory.findCategoryUUIDForType(LLAssetType::AT_CALLINGCARD);
		msg->nextBlockFast(_PREHASH_FolderData);
		msg->addUUIDFast(_PREHASH_FolderID, fid);
		msg->sendReliable(offerdata->mHost);
		break;
	case 1:
		// decline		
		msg->newMessageFast(_PREHASH_DeclineCallingCard);
		msg->nextBlockFast(_PREHASH_AgentData);
		msg->addUUIDFast(_PREHASH_AgentID, gAgent.getID());
		msg->addUUIDFast(_PREHASH_SessionID, gAgent.getSessionID());
		msg->nextBlockFast(_PREHASH_TransactionBlock);
		msg->addUUIDFast(_PREHASH_TransactionID, offerdata->mTransactionID);
		msg->sendReliable(offerdata->mHost);
		busy_message(msg, offerdata->mSourceID);
		break;
	default:
		// close button probably, possibly timed out
		break;
	}

	delete offerdata;
	offerdata = NULL;
}

void process_offer_callingcard(LLMessageSystem* msg, void**)
{
	// someone has offered to form a friendship
	lldebugs << "callingcard offer" << llendl;

	LLUUID source_id;
	msg->getUUIDFast(_PREHASH_AgentData, _PREHASH_AgentID, source_id);
	LLUUID tid;
	msg->getUUIDFast(_PREHASH_AgentBlock, _PREHASH_TransactionID, tid);

	LLCallingCardOfferData* offerdata = new LLCallingCardOfferData;
	offerdata->mTransactionID = tid;
	offerdata->mSourceID = source_id;
	offerdata->mHost = msg->getSender();

	LLViewerObject* source = gObjectList.findObject(source_id);
	LLString::format_map_t args;
	std::string source_name;
	if(source && source->isAvatar())
	{
		LLNameValue* nvfirst = source->getNVPair("FirstName");
		LLNameValue* nvlast  = source->getNVPair("LastName");
		if (nvfirst && nvlast)
		{
			args["[FIRST]"] = nvfirst->getString();
			args["[LAST]"] = nvlast->getString();
			source_name = std::string(nvfirst->getString()) + " " + nvlast->getString();
		}
	}

	if(!source_name.empty())
	{
		if (gAgent.getBusy() 
			|| gMuteListp->isMuted(source_id, source_name, LLMute::flagTextChat))
		{
			// automatically decline offer
			callingcard_offer_callback(1, (void*)offerdata);
			offerdata = NULL; // pointer was freed by callback
		}
		else
		{
			LLNotifyBox::showXml("OfferCallingCard", args,
					     &callingcard_offer_callback, (void*)offerdata);
			offerdata = NULL; // pointer ownership transferred
		}
	}
	else
	{
		llwarns << "Calling card offer from an unknown source." << llendl;
	}

	delete offerdata; // !=NULL if we didn't give ownership away
	offerdata = NULL;
}

void process_accept_callingcard(LLMessageSystem* msg, void**)
{
	LLNotifyBox::showXml("CallingCardAccepted");
}

void process_decline_callingcard(LLMessageSystem* msg, void**)
{
	LLNotifyBox::showXml("CallingCardDeclined");
}


void process_chat_from_simulator(LLMessageSystem *msg, void **user_data)
{
	LLChat		chat;
	char		mesg[DB_CHAT_MSG_BUF_SIZE];		/* Flawfinder: ignore */
	char		from_name[DB_FULL_NAME_BUF_SIZE];		/* Flawfinder: ignore */
	U8			source_temp;
	U8			type_temp;
	U8			audible_temp;
	LLColor4	color(1.0f, 1.0f, 1.0f, 1.0f);
	LLUUID		from_id;
	LLUUID		owner_id;
	BOOL		is_owned_by_me = FALSE;
	LLViewerObject*	chatter;

	msg->getString("ChatData", "FromName", DB_FULL_NAME_BUF_SIZE, from_name);
	chat.mFromName = from_name;
	
	msg->getUUID("ChatData", "SourceID", from_id);
	chat.mFromID = from_id;
	
	// Object owner for objects
	msg->getUUID("ChatData", "OwnerID", owner_id);
	
	msg->getU8Fast(_PREHASH_ChatData, _PREHASH_SourceType, source_temp);
	chat.mSourceType = (EChatSourceType)source_temp;

	msg->getU8("ChatData", "ChatType", type_temp);
	chat.mChatType = (EChatType)type_temp;

	msg->getU8Fast(_PREHASH_ChatData, _PREHASH_Audible, audible_temp);
	chat.mAudible = (EChatAudible)audible_temp;
	
	chat.mTime = LLFrameTimer::getElapsedSeconds();
	
	BOOL is_self = (from_id == gAgent.getID());
	BOOL is_busy = gAgent.getBusy();

	// Apparently you can receive chat before app is fully initialized, hence
	// gMuteListp can be null. JC
	BOOL is_muted = FALSE;
	BOOL is_linden = FALSE;
	if (gMuteListp)
	{
		is_muted = gMuteListp->isMuted(from_id, from_name, LLMute::flagTextChat)
				   || gMuteListp->isMuted(owner_id, LLMute::flagTextChat);
		is_linden = chat.mSourceType != CHAT_SOURCE_OBJECT && gMuteListp->isLinden(from_name);
	}

	BOOL is_audible = (CHAT_AUDIBLE_FULLY == chat.mAudible);
	chatter = gObjectList.findObject(from_id);
	if (chatter)
	{
		chat.mPosAgent = chatter->getPositionAgent();
		
		// Make swirly things only for talking objects. (not script debug messages, though)
		if (chat.mSourceType == CHAT_SOURCE_OBJECT 
			&& chat.mChatType != CHAT_TYPE_DEBUG_MSG)
		{
			LLPointer<LLViewerPartSourceChat> psc = new LLViewerPartSourceChat(chatter->getPositionAgent());
			psc->setSourceObject(chatter);
			psc->setColor(color);
			//We set the particles to be owned by the object's owner, 
			//just in case they should be muted by the mute list
			psc->setOwnerUUID(owner_id);
			gWorldPointer->mPartSim.addPartSource(psc);
		}

		// record last audible utterance
		if (is_audible
			&& (is_linden || (!is_muted && !is_busy)))
		{
			if (chat.mChatType != CHAT_TYPE_START 
				&& chat.mChatType != CHAT_TYPE_STOP)
			{
				gAgent.heardChat(chat.mFromID);
			}
		}

		is_owned_by_me = chatter->permYouOwner();
	}

	if (is_audible)
	{
		BOOL visible_in_chat_bubble = FALSE;
		std::string verb;

		color.setVec(1,1,1,1);
		msg->getStringFast(_PREHASH_ChatData, _PREHASH_Message, DB_CHAT_MSG_BUF_SIZE, mesg);

		BOOL ircstyle = FALSE;

		// Look for IRC-style emotes here so chatbubbles work
		if (!strncmp(mesg, "/me ", 4) || !strncmp(mesg, "/me'", 4))
		{
			chat.mText = from_name;
			chat.mText += (mesg + 3);
			ircstyle = TRUE;
		}
		else
		{
			chat.mText = mesg;
		}

		// Look for the start of typing so we can put "..." in the bubbles.
		if (CHAT_TYPE_START == chat.mChatType)
		{
			gLocalSpeakerMgr->setSpeakerTyping(from_id, TRUE);

			// Might not have the avatar constructed yet, eg on login.
			if (chatter && chatter->isAvatar())
			{
				((LLVOAvatar*)chatter)->startTyping();
			}
			return;
		}
		else if (CHAT_TYPE_STOP == chat.mChatType)
		{
			gLocalSpeakerMgr->setSpeakerTyping(from_id, FALSE);

			// Might not have the avatar constructed yet, eg on login.
			if (chatter && chatter->isAvatar())
			{
				((LLVOAvatar*)chatter)->stopTyping();
			}
			return;
		}

		// We have a real utterance now, so can stop showing "..." and proceed.
		if (chatter && chatter->isAvatar())
		{
			gLocalSpeakerMgr->setSpeakerTyping(from_id, FALSE);
			((LLVOAvatar*)chatter)->stopTyping();

			if (!is_muted && !is_busy)
			{
				visible_in_chat_bubble = gSavedSettings.getBOOL("UseChatBubbles");
				((LLVOAvatar*)chatter)->addChat(chat);
			}
		}

		// Look for IRC-style emotes
		if (ircstyle)
		{
			// Do nothing, ircstyle is fixed above for chat bubbles
		}
		else
		{
			switch(chat.mChatType)
			{
			case CHAT_TYPE_WHISPER:
				if (is_self)
				{
					verb = " whisper: ";
				}
				else
				{
					verb = " whispers: ";
				}
				break;
			case CHAT_TYPE_DEBUG_MSG:
			case CHAT_TYPE_OWNER:
			case CHAT_TYPE_NORMAL:
				verb = ": ";
				break;
			case CHAT_TYPE_SHOUT:
				if (is_self)
				{
					verb = " shout: ";
				}
				else
				{
					verb = " shouts: ";
				}
				break;
			case CHAT_TYPE_START:
			case CHAT_TYPE_STOP:
				llwarns << "Got chat type start/stop in main chat processing." << llendl;
				break;
			default:
				llwarns << "Unknown type " << chat.mChatType << " in chat!" << llendl;
				verb = " say, ";
				break;
			}

			if (is_self)
			{
				chat.mText = "You";
			}
			else
			{
				chat.mText = from_name;
			}
			chat.mText += verb;
			chat.mText += mesg;
		}
		
		if (chatter)
		{
			chat.mPosAgent = chatter->getPositionAgent();
		}

		// truth table:
		// LINDEN	BUSY	MUTED	OWNED_BY_YOU	TASK		DISPLAY		STORE IN HISTORY
		// F		F		F		F				*			Yes			Yes
		// F		F		F		T				*			Yes			Yes
		// F		F		T		F				*			No			No
		// F		F		T		T				*			No			No
		// F		T		F		F				*			No			Yes
		// F		T		F		T				*			Yes			Yes
		// F		T		T		F				*			No			No
		// F		T		T		T				*			No			No
		// T		*		*		*				F			Yes			Yes

		chat.mMuted = is_muted && !is_linden;
		
		
		if (!visible_in_chat_bubble 
			&& (is_linden || !is_busy || is_owned_by_me))
		{
			// show on screen and add to history
			LLFloaterChat::addChat(chat, FALSE, FALSE);
		}
		else
		{
			// just add to chat history
			LLFloaterChat::addChatHistory(chat);
		}
	}
}


// Simulator we're on is informing the viewer that the agent
// is starting to teleport (perhaps to another sim, perhaps to the 
// same sim). If we initiated the teleport process by sending some kind 
// of TeleportRequest, then this info is redundant, but if the sim 
// initiated the teleport (via a script call, being killed, etc.) 
// then this info is news to us.
void process_teleport_start(LLMessageSystem *msg, void**)
{
	U32 teleport_flags = 0x0;
	msg->getU32("Info", "TeleportFlags", teleport_flags);

	if (teleport_flags & TELEPORT_FLAGS_DISABLE_CANCEL)
	{
		gViewerWindow->setProgressCancelButtonVisible(FALSE, "");
	}
	else
	{
		gViewerWindow->setProgressCancelButtonVisible(TRUE, "Cancel");
	}

	// Freeze the UI and show progress bar
	// Note: could add data here to differentiate between normal teleport and death.

	if( gAgent.getTeleportState() == LLAgent::TELEPORT_NONE )
	{
		gTeleportDisplay = TRUE;
		gAgent.setTeleportState( LLAgent::TELEPORT_START );
		make_ui_sound("UISndTeleportOut");
		
		// Don't call LLFirstUse::useTeleport here because this could be
		// due to being killed, which would send you home, not to a Telehub
	}
}

void process_teleport_progress(LLMessageSystem* msg, void**)
{
	LLUUID agent_id;
	msg->getUUID("AgentData", "AgentID", agent_id);
	if((gAgent.getID() != agent_id)
	   || (gAgent.getTeleportState() == LLAgent::TELEPORT_NONE))
	{
		llwarns << "Unexpected teleport progress message." << llendl;
		return;
	}
	U32 teleport_flags = 0x0;
	msg->getU32("Info", "TeleportFlags", teleport_flags);
	if (teleport_flags & TELEPORT_FLAGS_DISABLE_CANCEL)
	{
		gViewerWindow->setProgressCancelButtonVisible(FALSE, "");
	}
	else
	{
		gViewerWindow->setProgressCancelButtonVisible(TRUE, "Cancel");
	}
	char buffer[MAX_STRING];		/* Flawfinder: ignore */
	msg->getString("Info", "Message", MAX_STRING, buffer);
	lldebugs << "teleport progress: " << buffer << llendl;

	//Sorta hacky...default to using simulator raw messages
	//if we don't find the coresponding mapping in our progress mappings
	LLString message = buffer;

	if (LLAgent::sTeleportProgressMessages.find(buffer) != 
		LLAgent::sTeleportProgressMessages.end() )
	{
		message = LLAgent::sTeleportProgressMessages[buffer];
	}

	gAgent.setTeleportMessage(LLAgent::sTeleportProgressMessages[message]);
}

class LLFetchInWelcomeArea : public LLInventoryFetchDescendentsObserver
{
public:
	LLFetchInWelcomeArea() {}
	virtual void done()
	{
		LLIsType is_landmark(LLAssetType::AT_LANDMARK);
		LLIsType is_card(LLAssetType::AT_CALLINGCARD);

		LLInventoryModel::cat_array_t	card_cats;
		LLInventoryModel::item_array_t	card_items;
		LLInventoryModel::cat_array_t	land_cats;
		LLInventoryModel::item_array_t	land_items;

		folder_ref_t::iterator it = mCompleteFolders.begin();
		folder_ref_t::iterator end = mCompleteFolders.end();
		for(; it != end; ++it)
		{
			gInventory.collectDescendentsIf(
				(*it),
				land_cats,
				land_items,
				LLInventoryModel::EXCLUDE_TRASH,
				is_landmark);
			gInventory.collectDescendentsIf(
				(*it),
				card_cats,
				card_items,
				LLInventoryModel::EXCLUDE_TRASH,
				is_card);
		}
		LLString::format_map_t args;
		if ( land_items.count() > 0 )
		{	// Show notification that they can now teleport to landmarks.  Use a random landmark from the inventory
			S32 random_land = ll_rand( land_items.count() - 1 );
			args["[NAME]"] = land_items[random_land]->getName();
			LLNotifyBox::showXml("TeleportToLandmark",args);
		}
		if ( card_items.count() > 0 )
		{	// Show notification that they can now contact people.  Use a random calling card from the inventory
			S32 random_card = ll_rand( card_items.count() - 1 );
			args["[NAME]"] = card_items[random_card]->getName();
			LLNotifyBox::showXml("TeleportToPerson",args);
		}

		gInventory.removeObserver(this);
		delete this;
	}
};



class LLPostTeleportNotifiers : public LLEventTimer 
{
public:
	LLPostTeleportNotifiers();
	virtual ~LLPostTeleportNotifiers();

	//function to be called at the supplied frequency
	virtual BOOL tick();
};

LLPostTeleportNotifiers::LLPostTeleportNotifiers() : LLEventTimer( 2.0 )
{
};

LLPostTeleportNotifiers::~LLPostTeleportNotifiers()
{
}

BOOL LLPostTeleportNotifiers::tick()
{
	BOOL all_done = FALSE;
	if ( gAgent.getTeleportState() == LLAgent::TELEPORT_NONE )
	{
		// get callingcards and landmarks available to the user arriving.
		LLInventoryFetchDescendentsObserver::folder_ref_t folders;
		LLUUID folder_id;
		folder_id = gInventory.findCategoryUUIDForType(LLAssetType::AT_CALLINGCARD);
		if(folder_id.notNull()) 
			folders.push_back(folder_id);
		folder_id = gInventory.findCategoryUUIDForType(LLAssetType::AT_LANDMARK);
		if(folder_id.notNull()) 
			folders.push_back(folder_id);
		if(!folders.empty())
		{
			LLFetchInWelcomeArea* fetcher = new LLFetchInWelcomeArea;
			fetcher->fetchDescendents(folders);
			if(fetcher->isEverythingComplete())
			{
				fetcher->done();
			}
			else
			{
				gInventory.addObserver(fetcher);
			}
		}
		all_done = TRUE;
	}

	return all_done;
}



// Teleport notification from the simulator
// We're going to pretend to be a new agent
void process_teleport_finish(LLMessageSystem* msg, void**)
{
	//llinfos << "Got teleport location message" << llendl;
	LLUUID agent_id;
	msg->getUUIDFast(_PREHASH_Info, _PREHASH_AgentID, agent_id);
	if (agent_id != gAgent.getID())
	{
		llwarns << "Got teleport notification for wrong agent!" << llendl;
		return;
	}

	// Do teleport effect for where you're leaving
	// VEFFECT: TeleportStart
	LLHUDEffectSpiral *effectp = (LLHUDEffectSpiral *)gHUDManager->createViewerEffect(LLHUDObject::LL_HUD_EFFECT_POINT, TRUE);
	effectp->setPositionGlobal(gAgent.getPositionGlobal());
	effectp->setColor(LLColor4U(gAgent.getEffectColor()));
	gHUDManager->sendEffects();

	U32 location_id;
	U32 sim_ip;
	U16 sim_port;
	LLVector3 pos, look_at;
	U64 region_handle;
	msg->getU32Fast(_PREHASH_Info, _PREHASH_LocationID, location_id);
	msg->getIPAddrFast(_PREHASH_Info, _PREHASH_SimIP, sim_ip);
	msg->getIPPortFast(_PREHASH_Info, _PREHASH_SimPort, sim_port);
	//msg->getVector3Fast(_PREHASH_Info, _PREHASH_Position, pos);
	//msg->getVector3Fast(_PREHASH_Info, _PREHASH_LookAt, look_at);
	msg->getU64Fast(_PREHASH_Info, _PREHASH_RegionHandle, region_handle);
	U32 teleport_flags;
	msg->getU32Fast(_PREHASH_Info, _PREHASH_TeleportFlags, teleport_flags);
	
	
	char seedCap[STD_STRING_BUF_SIZE];		/* Flawfinder: ignore */
	msg->getStringFast(_PREHASH_Info, _PREHASH_SeedCapability,
		STD_STRING_BUF_SIZE, seedCap);

	// update home location if we are teleporting out of prelude - specific to teleporting to welcome area 
	if((teleport_flags & TELEPORT_FLAGS_SET_HOME_TO_TARGET)
	   && (!gAgent.isGodlike()))
	{
		gAgent.setHomePosRegion(region_handle, pos);

		// Create a timer that will send notices when teleporting is all finished.  Since this is 
		// based on the LLEventTimer class, it will be managed by that class and not orphaned or leaked.
		new LLPostTeleportNotifiers();
	}

	LLHost sim_host(sim_ip, sim_port);

	// Viewer trusts the simulator.
	gMessageSystem->enableCircuit(sim_host, TRUE);
	LLViewerRegion* regionp =  gWorldp->addRegion(region_handle, sim_host);

/*
	// send camera update to new region
	gAgent.updateCamera();

	// likewise make sure the camera is behind the avatar
	gAgent.resetView(TRUE);
	LLVector3 shift_vector = regionp->getPosRegionFromGlobal(gAgent.getRegion()->getOriginGlobal());
	gAgent.setRegion(regionp);
	gObjectList.shiftObjects(shift_vector);

	if (gAgent.getAvatarObject())
	{
		gAgent.getAvatarObject()->clearChatText();
		gAgent.slamLookAt(look_at);
	}
	gAgent.setPositionAgent(pos);
	gAssetStorage->setUpstream(sim);
	gCacheName->setUpstream(sim);
*/

	// now, use the circuit info to tell simulator about us!
	llinfos << "process_teleport_finish() Enabling "
			<< sim_host << " with code " << msg->mOurCircuitCode << llendl;
	msg->newMessageFast(_PREHASH_UseCircuitCode);
	msg->nextBlockFast(_PREHASH_CircuitCode);
	msg->addU32Fast(_PREHASH_Code, msg->getOurCircuitCode());
	msg->addUUIDFast(_PREHASH_SessionID, gAgent.getSessionID());
	msg->addUUIDFast(_PREHASH_ID, gAgent.getID());
	msg->sendReliable(sim_host);

	send_complete_agent_movement(sim_host);
	gAgent.setTeleportState( LLAgent::TELEPORT_MOVING );
	gAgent.setTeleportMessage(LLAgent::sTeleportProgressMessages["contacting"]);

	regionp->setSeedCapability(std::string(seedCap));

	// Don't send camera updates to the new region until we're
	// actually there...


	// Now do teleport effect for where you're going.
	// VEFFECT: TeleportEnd
	effectp = (LLHUDEffectSpiral *)gHUDManager->createViewerEffect(LLHUDObject::LL_HUD_EFFECT_POINT, TRUE);
	effectp->setPositionGlobal(gAgent.getPositionGlobal());

	effectp->setColor(LLColor4U(gAgent.getEffectColor()));
	gHUDManager->sendEffects();

//	gTeleportDisplay = TRUE;
//	gTeleportDisplayTimer.reset();
//	gViewerWindow->setShowProgress(TRUE);

	// This could be first use of teleport, so test for that
	LLFirstUse::useTeleport();
}

// stuff we have to do every time we get an AvatarInitComplete from a sim
/*
void process_avatar_init_complete(LLMessageSystem* msg, void**)
{
	LLVector3 agent_pos;
	msg->getVector3Fast(_PREHASH_AvatarData, _PREHASH_Position, agent_pos);
	agent_movement_complete(msg->getSender(), agent_pos);
}
*/

void process_agent_movement_complete(LLMessageSystem* msg, void**)
{
	gAgentMovementCompleted = TRUE;

	LLUUID agent_id;
	msg->getUUIDFast(_PREHASH_AgentData, _PREHASH_AgentID, agent_id);
	LLUUID session_id;
	msg->getUUIDFast(_PREHASH_AgentData, _PREHASH_SessionID, session_id);
	if((gAgent.getID() != agent_id) || (gAgent.getSessionID() != session_id))
	{
		llwarns << "Incorrect id in process_agent_movement_complete()"
				<< llendl;
		return;
	}

	llinfos << "process_agent_movement_complete()" << llendl;

	// *TODO: check timestamp to make sure the movement compleation
	// makes sense.
	LLVector3 agent_pos;
	msg->getVector3Fast(_PREHASH_Data, _PREHASH_Position, agent_pos);
	LLVector3 look_at;
	msg->getVector3Fast(_PREHASH_Data, _PREHASH_LookAt, look_at);
	U64 region_handle;
	msg->getU64Fast(_PREHASH_Data, _PREHASH_RegionHandle, region_handle);
	
	char version_channel_char[MAX_STRING];
	msg->getString("SimData", "ChannelVersion", MAX_STRING, version_channel_char);

	LLVOAvatar* avatarp = gAgent.getAvatarObject();
	if (!avatarp)
	{
		// Could happen if you were immediately god-teleported away on login,
		// maybe other cases.  Continue, but warn.  JC
		llwarns << "agent_movement_complete() with NULL avatarp." << llendl;
	}

	F32 x, y;
	from_region_handle(region_handle, &x, &y);
	LLViewerRegion* regionp = gWorldp->getRegionFromHandle(region_handle);
	if (!regionp)
	{
		if (gAgent.getRegion())
		{
			llwarns << "current region " << gAgent.getRegion()->getOriginGlobal() << llendl;
		}

		llwarns << "Agent being sent to invalid home region: " 
			<< x << ":" << y 
			<< " current pos " << gAgent.getPositionGlobal()
			<< llendl;
		do_disconnect("You were sent to an invalid region.");
		return;

	}

	llinfos << "Changing home region to " << x << ":" << y << llendl;

	// set our upstream host the new simulator and shuffle things as
	// appropriate.
	LLVector3 shift_vector = regionp->getPosRegionFromGlobal(
		gAgent.getRegion()->getOriginGlobal());
	gAgent.setRegion(regionp);
	gObjectList.shiftObjects(shift_vector);
	gAssetStorage->setUpstream(msg->getSender());
	gCacheName->setUpstream(msg->getSender());
	gViewerThrottle.sendToSim();
	gViewerWindow->sendShapeToSim();

	bool is_teleport = false;

	if( gAgent.getTeleportState() == LLAgent::TELEPORT_MOVING )
	{
		// Force the camera back onto the agent, don't animate. JC
		gAgent.setFocusOnAvatar(TRUE, FALSE);
		gAgent.slamLookAt(look_at);
		gAgent.updateCamera();

		gAgent.setTeleportState( LLAgent::TELEPORT_START_ARRIVAL );

		// set the appearance on teleport since the new sim does not
		// know what you look like.
		gAgent.sendAgentSetAppearance();

		if (avatarp)
		{
			avatarp->setPositionAgent(agent_pos);
			avatarp->clearChat();
			avatarp->slamPosition();
		}

		is_teleport = true;
	}
	else
	{
		gAgent.setTeleportState( LLAgent::TELEPORT_NONE );
	}

	if ( LLTracker::isTracking(NULL) )
	{
		// Check distance to beacon, if < 5m, remove beacon
		LLVector3d beacon_pos = LLTracker::getTrackedPositionGlobal();
		LLVector3 beacon_dir(agent_pos.mV[VX] - (F32)fmod(beacon_pos.mdV[VX], 256.0), agent_pos.mV[VY] - (F32)fmod(beacon_pos.mdV[VY], 256.0), 0);
		if (beacon_dir.magVecSquared() < 25.f)
		{
			LLTracker::stopTracking(NULL);
		}
		else if ( is_teleport )
		{
			//look at the beacon
			LLVector3 global_agent_pos = agent_pos;
			global_agent_pos[0] += x;
			global_agent_pos[1] += y;
			look_at = (LLVector3)beacon_pos - global_agent_pos;
			look_at.normVec();
			gAgent.slamLookAt(look_at);
		}
	}

	// TODO: Put back a check for flying status! DK 12/19/05
	// Sim tells us whether the new position is off the ground
	/*
	if (teleport_flags & TELEPORT_FLAGS_IS_FLYING)
	{
		gAgent.setFlying(TRUE);
	}
	else
	{
		gAgent.setFlying(FALSE);
	}
	*/

	send_agent_update(TRUE, TRUE);

	if (gAgent.getRegion()->getBlockFly())
	{
		gAgent.setFlying(gAgent.canFly());
	}

	// force simulator to recognize busy state
	if (gAgent.getBusy())
	{
		gAgent.setBusy();
	}
	else
	{
		gAgent.clearBusy();
	}

	if (avatarp)
	{
		avatarp->mFootPlane.clearVec();
	}
	
	// reset always run status
	msg->newMessageFast(_PREHASH_SetAlwaysRun);
	msg->nextBlockFast(_PREHASH_AgentData);
	msg->addUUIDFast(_PREHASH_AgentID, gAgent.getID());
	msg->addUUIDFast(_PREHASH_SessionID, gAgent.getSessionID());
	msg->addBOOLFast(_PREHASH_AlwaysRun, gAgent.getAlwaysRun());
	gAgent.sendReliableMessage();

	
	LLString version_channel = LLString(version_channel_char);

	if (gLastVersionChannel != version_channel)
	{
		//show release message if not on initial login
		if (!gLastVersionChannel.empty())
		{ 
			gLastVersionChannel = version_channel;
			LLFloaterReleaseMsg::show();
		}
		else {
			gLastVersionChannel = version_channel;
		}
	}
	
}

void process_crossed_region(LLMessageSystem* msg, void**)
{
	LLUUID agent_id;
	msg->getUUIDFast(_PREHASH_AgentData, _PREHASH_AgentID, agent_id);
	LLUUID session_id;
	msg->getUUIDFast(_PREHASH_AgentData, _PREHASH_SessionID, session_id);
	if((gAgent.getID() != agent_id) || (gAgent.getSessionID() != session_id))
	{
		llwarns << "Incorrect id in process_crossed_region()"
				<< llendl;
		return;
	}
	llinfos << "process_crossed_region()" << llendl;

	U32 sim_ip;
	msg->getIPAddrFast(_PREHASH_RegionData, _PREHASH_SimIP, sim_ip);
	U16 sim_port;
	msg->getIPPortFast(_PREHASH_RegionData, _PREHASH_SimPort, sim_port);
	LLHost sim_host(sim_ip, sim_port);
	U64 region_handle;
	msg->getU64Fast(_PREHASH_RegionData, _PREHASH_RegionHandle, region_handle);
	
	char seedCap[STD_STRING_BUF_SIZE];		/* Flawfinder: ignore */
	msg->getStringFast(_PREHASH_RegionData, _PREHASH_SeedCapability, STD_STRING_BUF_SIZE, seedCap);

	send_complete_agent_movement(sim_host);

	LLViewerRegion* regionp = gWorldp->addRegion(region_handle, sim_host);
	regionp->setSeedCapability(std::string(seedCap));
}



// Sends avatar and camera information to simulator.
// Sent roughly once per frame, or 20 times per second, whichever is less often

const F32 THRESHOLD_HEAD_ROT_QDOT = 0.9997f;	// ~= 2.5 degrees -- if its less than this we need to update head_rot
const F32 MAX_HEAD_ROT_QDOT = 0.99999f;			// ~= 0.5 degrees -- if its greater than this then no need to update head_rot
												// between these values we delay the updates (but no more than one second)


void send_agent_update(BOOL force_send, BOOL send_reliable)
{
	if (gAgent.getTeleportState() != LLAgent::TELEPORT_NONE)
	{
		// We don't care if they want to send an agent update, they're not allowed to until the simulator
		// that's the target is ready to receive them (after avatar_init_complete is received)
		return;
	}

	// We have already requested to log out.  Don't send agent updates.
	if(gLogoutRequestSent)
	{
		return;
	}

	const F32 TRANSLATE_THRESHOLD = 0.01f;

	// NOTA BENE: This is (intentionally?) using the small angle sine approximation to test for rotation
	//			  Plus, there is an extra 0.5 in the mix since the perpendicular between last_camera_at and getAtAxis() bisects cam_rot_change
	//			  Thus, we're actually testing against 0.2 degrees
	const F32 ROTATION_THRESHOLD = 0.1f * 2.f*F_PI/360.f;			//  Rotation thresh 0.2 deg, see note above

	const U8 DUP_MSGS = 1;				//  HACK!  number of times to repeat data on motionless agent

	//  Store data on last sent update so that if no changes, no send
	static LLVector3 last_camera_pos_agent, 
					 last_camera_at, 
					 last_camera_left,
					 last_camera_up;
	
	static LLVector3 cam_center_chg,
					 cam_rot_chg;

	static LLQuaternion last_head_rot;
	static U32 last_control_flags = 0;
	static U8 last_render_state;
	static U8 duplicate_count = 0;
	static F32 head_rot_chg = 1.0;
	static U8 last_flags;

	LLMessageSystem	*msg = gMessageSystem;
	LLVector3		camera_pos_agent;				// local to avatar's region
	U8				render_state;

	LLQuaternion body_rotation = gAgent.getFrameAgent().getQuaternion();
	LLQuaternion head_rotation = gAgent.getHeadRotation();

	camera_pos_agent = gAgent.getCameraPositionAgent();

	render_state = gAgent.getRenderState();

	U32		control_flag_change = 0;
	U8		flag_change = 0;

	cam_center_chg = last_camera_pos_agent - camera_pos_agent;
	cam_rot_chg = last_camera_at - gCamera->getAtAxis();

	// If a modifier key is held down, turn off
	// LBUTTON and ML_LBUTTON so that using the camera (alt-key) doesn't
	// trigger a control event.
	U32 control_flags = gAgent.getControlFlags();
	MASK	key_mask = gKeyboard->currentMask(TRUE);
	if (key_mask & MASK_ALT || key_mask & MASK_CONTROL)
	{
		control_flags &= ~(	AGENT_CONTROL_LBUTTON_DOWN |
							AGENT_CONTROL_ML_LBUTTON_DOWN );
		control_flags |= 	AGENT_CONTROL_LBUTTON_UP |
							AGENT_CONTROL_ML_LBUTTON_UP ;
	}

	control_flag_change = last_control_flags ^ control_flags;

	U8 flags = AU_FLAGS_NONE;
	if (gAgent.isGroupTitleHidden())
	{
		flags |= AU_FLAGS_HIDETITLE;
	}

	flag_change = last_flags ^ flags;

	head_rot_chg = dot(last_head_rot, head_rotation);

	if (force_send || 
		(cam_center_chg.magVec() > TRANSLATE_THRESHOLD) || 
		(head_rot_chg < THRESHOLD_HEAD_ROT_QDOT) ||	
		(last_render_state != render_state) ||
		(cam_rot_chg.magVec() > ROTATION_THRESHOLD) ||
		control_flag_change != 0 ||
		flag_change != 0)  
	{
/*
		if (head_rot_chg < THRESHOLD_HEAD_ROT_QDOT)
		{
			//llinfos << "head rot " << head_rotation << llendl;
			llinfos << "head_rot_chg = " << head_rot_chg << llendl;
		}
		if (cam_rot_chg.magVec() > ROTATION_THRESHOLD) 
		{
			llinfos << "cam rot " <<  cam_rot_chg.magVec() << llendl;
		}
		if (cam_center_chg.magVec() > TRANSLATE_THRESHOLD)
		{
			llinfos << "cam center " << cam_center_chg.magVec() << llendl;
		}
//		if (drag_delta_chg.magVec() > TRANSLATE_THRESHOLD)
//		{
//			llinfos << "drag delta " << drag_delta_chg.magVec() << llendl;
//		}
		if (control_flag_change)
		{
			llinfos << "dcf = " << control_flag_change << llendl;
		}
*/

		duplicate_count = 0;
	}
	else
	{
		duplicate_count++;

		if (head_rot_chg < MAX_HEAD_ROT_QDOT  &&  duplicate_count < AGENT_UPDATES_PER_SECOND)
		{
			// The head_rotation is sent for updating things like attached guns.
			// We only trigger a new update when head_rotation deviates beyond
			// some threshold from the last update, however this can break fine
			// adjustments when trying to aim an attached gun, so what we do here
			// (where we would normally skip sending an update when nothing has changed)
			// is gradually reduce the threshold to allow a better update to 
			// eventually get sent... should update to within 0.5 degrees in less 
			// than a second.
			if (head_rot_chg < THRESHOLD_HEAD_ROT_QDOT + (MAX_HEAD_ROT_QDOT - THRESHOLD_HEAD_ROT_QDOT) * duplicate_count / AGENT_UPDATES_PER_SECOND)
			{
				duplicate_count = 0;
			}
			else
			{
				return;
			}
		}
		else
		{
			return;
		}
	}

	if (duplicate_count < DUP_MSGS && !gDisconnected)
	{
		// Build the message
		msg->newMessageFast(_PREHASH_AgentUpdate);
		msg->nextBlockFast(_PREHASH_AgentData);
		msg->addUUIDFast(_PREHASH_AgentID, gAgent.getID());
		msg->addUUIDFast(_PREHASH_SessionID, gAgent.getSessionID());
		msg->addQuatFast(_PREHASH_BodyRotation, body_rotation);
		msg->addQuatFast(_PREHASH_HeadRotation, head_rotation);
		msg->addU8Fast(_PREHASH_State, render_state);
		msg->addU8Fast(_PREHASH_Flags, flags);

//		if (camera_pos_agent.mV[VY] > 255.f)
//		{
//			llinfos << "Sending camera center " << camera_pos_agent << llendl;
//		}
		
		msg->addVector3Fast(_PREHASH_CameraCenter, camera_pos_agent);
		msg->addVector3Fast(_PREHASH_CameraAtAxis, gCamera->getAtAxis());
		msg->addVector3Fast(_PREHASH_CameraLeftAxis, gCamera->getLeftAxis());
		msg->addVector3Fast(_PREHASH_CameraUpAxis, gCamera->getUpAxis());
		msg->addF32Fast(_PREHASH_Far, gAgent.mDrawDistance);
		
		msg->addU32Fast(_PREHASH_ControlFlags, control_flags);

		if (gDebugClicks)
		{
			if (control_flags & AGENT_CONTROL_LBUTTON_DOWN)
			{
				llinfos << "AgentUpdate left button down" << llendl;
			}

			if (control_flags & AGENT_CONTROL_LBUTTON_UP)
			{
				llinfos << "AgentUpdate left button up" << llendl;
			}
		}

		gAgent.enableControlFlagReset();

		if (!send_reliable)
		{
			gAgent.sendMessage();
		}
		else
		{
			gAgent.sendReliableMessage();
		}

		//llinfos << "agent " << avatar_pos_agent << " cam " << camera_pos_agent << llendl;

		// Copy the old data 
		last_head_rot = head_rotation;
		last_render_state = render_state;
		last_camera_pos_agent = camera_pos_agent;
		last_camera_at = gCamera->getAtAxis();
		last_camera_left = gCamera->getLeftAxis();
		last_camera_up = gCamera->getUpAxis();
		last_control_flags = control_flags;
		last_flags = flags;
	}
}



// *TODO: Remove this dependency, or figure out a better way to handle
// this hack.
extern U32 gObjectBits;

void process_object_update(LLMessageSystem *mesgsys, void **user_data)
{	
	LLMemType mt(LLMemType::MTYPE_OBJECT);
	// Update the data counters
	if (mesgsys->getReceiveCompressedSize())
	{
		gObjectBits += mesgsys->getReceiveCompressedSize() * 8;
	}
	else
	{
		gObjectBits += mesgsys->getReceiveSize() * 8;
	}

	// Update the object...
	gObjectList.processObjectUpdate(mesgsys, user_data, OUT_FULL);
	stop_glerror();
}

void process_compressed_object_update(LLMessageSystem *mesgsys, void **user_data)
{
	LLMemType mt(LLMemType::MTYPE_OBJECT);
	// Update the data counters
	if (mesgsys->getReceiveCompressedSize())
	{
		gObjectBits += mesgsys->getReceiveCompressedSize() * 8;
	}
	else
	{
		gObjectBits += mesgsys->getReceiveSize() * 8;
	}

	// Update the object...
	gObjectList.processCompressedObjectUpdate(mesgsys, user_data, OUT_FULL_COMPRESSED);
	stop_glerror();
}

void process_cached_object_update(LLMessageSystem *mesgsys, void **user_data)
{
	LLMemType mt(LLMemType::MTYPE_OBJECT);
	// Update the data counters
	if (mesgsys->getReceiveCompressedSize())
	{
		gObjectBits += mesgsys->getReceiveCompressedSize() * 8;
	}
	else
	{
		gObjectBits += mesgsys->getReceiveSize() * 8;
	}

	// Update the object...
	gObjectList.processCachedObjectUpdate(mesgsys, user_data, OUT_FULL_CACHED);
	stop_glerror();
}


void process_terse_object_update_improved(LLMessageSystem *mesgsys, void **user_data)
{
	LLMemType mt(LLMemType::MTYPE_OBJECT);
	if (mesgsys->getReceiveCompressedSize())
	{
		gObjectBits += mesgsys->getReceiveCompressedSize() * 8;
	}
	else
	{
		gObjectBits += mesgsys->getReceiveSize() * 8;
	}

	gObjectList.processCompressedObjectUpdate(mesgsys, user_data, OUT_TERSE_IMPROVED);
}



void process_kill_object(LLMessageSystem *mesgsys, void **user_data)
{
	LLFastTimer t(LLFastTimer::FTM_PROCESS_OBJECTS);

	LLUUID		id;
	U32			local_id;
	S32			i;
	S32			num_objects;

	num_objects = mesgsys->getNumberOfBlocksFast(_PREHASH_ObjectData);

	for (i = 0; i < num_objects; i++)
	{
		mesgsys->getU32Fast(_PREHASH_ObjectData, _PREHASH_ID, local_id, i);

		LLViewerObjectList::getUUIDFromLocal(id,
											local_id,
											gMessageSystem->getSenderIP(),
											gMessageSystem->getSenderPort());
		if (id == LLUUID::null)
		{
			//llinfos << "Unknown kill for local " << local_id << llendl;
			gObjectList.mNumUnknownKills++;
			continue;
		}
		else
		{
			//llinfos << "Kill message for local " << local_id << llendl;
		}

		gSelectMgr->removeObjectFromSelections(id);

		// ...don't kill the avatar
		if (!(id == gAgentID))
		{
			LLViewerObject *objectp = gObjectList.findObject(id);
			if (objectp)
			{
				// Display green bubble on kill
				if ( gShowObjectUpdates )
				{
					LLViewerObject* newobject;
					newobject = gObjectList.createObjectViewer(LL_PCODE_LEGACY_TEXT_BUBBLE, objectp->getRegion());

					LLVOTextBubble* bubble = (LLVOTextBubble*) newobject;

					bubble->mColor.setVec(0.f, 1.f, 0.f, 1.f);
					bubble->setScale( 2.0f * bubble->getScale() );
					bubble->setPositionGlobal(objectp->getPositionGlobal());
					gPipeline.addObject(bubble);
				}

				// Do the kill
				gObjectList.killObject(objectp);
			}
			else
			{
				llwarns << "Object in UUID lookup, but not on object list in kill!" << llendl;
				gObjectList.mNumUnknownKills++;
			}
		}
	}
}

void process_time_synch(LLMessageSystem *mesgsys, void **user_data)
{
	LLVector3 sun_direction;
	LLVector3 sun_ang_velocity;
	F32 phase;
	U64	space_time_usec;

	// "SimulatorViewerTimeMessage"
	mesgsys->getU64Fast(_PREHASH_TimeInfo, _PREHASH_UsecSinceStart, space_time_usec);
	mesgsys->getU32Fast(_PREHASH_TimeInfo, _PREHASH_SecPerDay, gSecondsPerDay);
	mesgsys->getU32Fast(_PREHASH_TimeInfo, _PREHASH_SecPerYear, gSecondsPerYear);

	// This should eventually be moved to an "UpdateHeavenlyBodies" message
	mesgsys->getF32Fast(_PREHASH_TimeInfo, _PREHASH_SunPhase, phase);
	mesgsys->getVector3Fast(_PREHASH_TimeInfo, _PREHASH_SunDirection, sun_direction);
	mesgsys->getVector3Fast(_PREHASH_TimeInfo, _PREHASH_SunAngVelocity, sun_ang_velocity);

	gWorldp->setSpaceTimeUSec(space_time_usec);

	//lldebugs << "time_synch() - " << sun_direction << ", " << sun_ang_velocity
	//		 << ", " << phase << llendl;

	gSky.setSunPhase(phase);
	gSky.setSunTargetDirection(sun_direction, sun_ang_velocity);
	if (!gNoRender && !(gSavedSettings.getBOOL("SkyOverrideSimSunPosition") || gSky.getOverrideSun()))
	{
		gSky.setSunDirection(sun_direction, sun_ang_velocity);
	}
}

void process_sound_trigger(LLMessageSystem *msg, void **)
{
	if (!gAudiop) return;
	if (!gParcelMgr) return;
	if (!gMuteListp) return;

	U64		region_handle = 0;
	F32		gain = 0;
	LLUUID	sound_id;
	LLUUID	owner_id;
	LLUUID	object_id;
	LLUUID	parent_id;
	LLVector3	pos_local;

	msg->getUUIDFast(_PREHASH_SoundData, _PREHASH_SoundID, sound_id);
	msg->getUUIDFast(_PREHASH_SoundData, _PREHASH_OwnerID, owner_id);
	msg->getUUIDFast(_PREHASH_SoundData, _PREHASH_ObjectID, object_id);
	msg->getUUIDFast(_PREHASH_SoundData, _PREHASH_ParentID, parent_id);
	msg->getU64Fast(_PREHASH_SoundData, _PREHASH_Handle, region_handle);
	msg->getVector3Fast(_PREHASH_SoundData, _PREHASH_Position, pos_local);
	msg->getF32Fast(_PREHASH_SoundData, _PREHASH_Gain, gain);

	// adjust sound location to true global coords
	LLVector3d	pos_global = from_region_handle(region_handle);
	pos_global.mdV[VX] += pos_local.mV[VX];
	pos_global.mdV[VY] += pos_local.mV[VY];
	pos_global.mdV[VZ] += pos_local.mV[VZ];

	// Don't play a trigger sound if you can't hear it due
	// to parcel "local audio only" settings.
	if (!gParcelMgr->canHearSound(pos_global)) return;

	// Don't play sounds triggered by someone you muted.
	if (gMuteListp->isMuted(owner_id, LLMute::flagObjectSounds)) return;
	
	// Don't play sounds from an object you muted
	if (gMuteListp->isMuted(object_id)) return;

	// Don't play sounds from an object whose parent you muted
	if (parent_id.notNull()
		&& gMuteListp->isMuted(parent_id))
	{
		return;
	}

	F32 volume = gain * gSavedSettings.getF32("AudioLevelSFX");
	gAudiop->triggerSound(sound_id, owner_id, volume, pos_global);
}

void process_preload_sound(LLMessageSystem *msg, void **user_data)
{
	if (!gAudiop)
	{
		return;
	}

	LLUUID sound_id;
	LLUUID object_id;
	LLUUID owner_id;

	msg->getUUIDFast(_PREHASH_DataBlock, _PREHASH_SoundID, sound_id);
	msg->getUUIDFast(_PREHASH_DataBlock, _PREHASH_ObjectID, object_id);
	msg->getUUIDFast(_PREHASH_DataBlock, _PREHASH_OwnerID, owner_id);

	LLViewerObject *objectp = gObjectList.findObject(object_id);
	if (!objectp) return;

	if (gMuteListp->isMuted(object_id)) return;
	if (gMuteListp->isMuted(owner_id, LLMute::flagObjectSounds)) return;
	
	LLAudioSource *sourcep = objectp->getAudioSource(owner_id);
	if (!sourcep) return;
	
	LLAudioData *datap = gAudiop->getAudioData(sound_id);

	// Note that I don't actually do any loading of the
	// audio data into a buffer at this point, as it won't actually
	// help us out.

	// Add audioData starts a transfer internally.
	sourcep->addAudioData(datap, FALSE);
}

void process_attached_sound(LLMessageSystem *msg, void **user_data)
{
	F32 gain = 0;
	LLUUID sound_id;
	LLUUID object_id;
	LLUUID owner_id;
	U8 flags;

	msg->getUUIDFast(_PREHASH_DataBlock, _PREHASH_SoundID, sound_id);
	msg->getUUIDFast(_PREHASH_DataBlock, _PREHASH_ObjectID, object_id);
	msg->getUUIDFast(_PREHASH_DataBlock, _PREHASH_OwnerID, owner_id);
	msg->getF32Fast(_PREHASH_DataBlock, _PREHASH_Gain, gain);
	msg->getU8Fast(_PREHASH_DataBlock, _PREHASH_Flags, flags);

	LLViewerObject *objectp = gObjectList.findObject(object_id);
	if (!objectp)
	{
		// we don't know about this object, just bail
		return;
	}
	
	if (gMuteListp->isMuted(object_id)) return;
	
	if (gMuteListp->isMuted(owner_id, LLMute::flagObjectSounds)) return;

	objectp->setAttachedSound(sound_id, owner_id, gain, flags);
}


void process_attached_sound_gain_change(LLMessageSystem *mesgsys, void **user_data)
{
	F32 gain = 0;
	LLUUID object_guid;
	LLViewerObject *objectp = NULL;

	mesgsys->getUUIDFast(_PREHASH_DataBlock, _PREHASH_ObjectID, object_guid);

	if (!((objectp = gObjectList.findObject(object_guid))))
	{
		// we don't know about this object, just bail
		return;
	}

 	mesgsys->getF32Fast(_PREHASH_DataBlock, _PREHASH_Gain, gain);

	objectp->adjustAudioGain(gain);
}

/* Unused July 2006
void process_attached_sound_cutoff_radius(LLMessageSystem *mesgsys, void **user_data)
{
	F32 radius = 0;
	LLUUID object_guid;
	LLViewerObject *objectp = NULL;

	mesgsys->getUUIDFast(_PREHASH_DataBlock, _PREHASH_ObjectID, object_guid);

	if (!((objectp = gObjectList.findObject(object_guid))))
	{
		// we don't know about this object, just bail
		return;
	}

	mesgsys->getF32Fast(_PREHASH_DataBlock, _PREHASH_Radius, radius);

	if (gAudiop)
	{
//		gAudiop->attachToObject(sound_guid, object_guid, gain, priority, flags);
	}
}
*/

void process_health_message(LLMessageSystem *mesgsys, void **user_data)
{
	F32 health;

	mesgsys->getF32Fast(_PREHASH_HealthData, _PREHASH_Health, health);

	if (gStatusBar)
	{
		gStatusBar->setHealth((S32)health);
	}
}


void process_sim_stats(LLMessageSystem *msg, void **user_data)
{	
	S32 count = msg->getNumberOfBlocks("Stat");
	for (S32 i = 0; i < count; ++i)
	{
		U32 stat_id;
		F32 stat_value;
		msg->getU32("Stat", "StatID", stat_id, i);
		msg->getF32("Stat", "StatValue", stat_value, i);
		switch (stat_id)
		{
		case LL_SIM_STAT_TIME_DILATION:
			gViewerStats->mSimTimeDilation.addValue(stat_value);
			break;
		case LL_SIM_STAT_FPS:
			gViewerStats->mSimFPS.addValue(stat_value);
			break;
		case LL_SIM_STAT_PHYSFPS:
			gViewerStats->mSimPhysicsFPS.addValue(stat_value);
			break;
		case LL_SIM_STAT_AGENTUPS:
			gViewerStats->mSimAgentUPS.addValue(stat_value);
			break;
		case LL_SIM_STAT_FRAMEMS:
			gViewerStats->mSimFrameMsec.addValue(stat_value);
			break;
		case LL_SIM_STAT_NETMS:
			gViewerStats->mSimNetMsec.addValue(stat_value);
			break;
		case LL_SIM_STAT_SIMOTHERMS:
			gViewerStats->mSimSimOtherMsec.addValue(stat_value);
			break;
		case LL_SIM_STAT_SIMPHYSICSMS:
			gViewerStats->mSimSimPhysicsMsec.addValue(stat_value);
			break;
		case LL_SIM_STAT_AGENTMS:
			gViewerStats->mSimAgentMsec.addValue(stat_value);
			break;
		case LL_SIM_STAT_IMAGESMS:
			gViewerStats->mSimImagesMsec.addValue(stat_value);
			break;
		case LL_SIM_STAT_SCRIPTMS:
			gViewerStats->mSimScriptMsec.addValue(stat_value);
			break;
		case LL_SIM_STAT_NUMTASKS:
			gViewerStats->mSimObjects.addValue(stat_value);
			break;
		case LL_SIM_STAT_NUMTASKSACTIVE:
			gViewerStats->mSimActiveObjects.addValue(stat_value);
			break;
		case LL_SIM_STAT_NUMAGENTMAIN:
			gViewerStats->mSimMainAgents.addValue(stat_value);
			break;
		case LL_SIM_STAT_NUMAGENTCHILD:
			gViewerStats->mSimChildAgents.addValue(stat_value);
			break;
		case LL_SIM_STAT_NUMSCRIPTSACTIVE:
			gViewerStats->mSimActiveScripts.addValue(stat_value);
			break;
		case LL_SIM_STAT_LSLIPS:
			gViewerStats->mSimLSLIPS.addValue(stat_value);
			break;
		case LL_SIM_STAT_INPPS:
			gViewerStats->mSimInPPS.addValue(stat_value);
			break;
		case LL_SIM_STAT_OUTPPS:
			gViewerStats->mSimOutPPS.addValue(stat_value);
			break;
		case LL_SIM_STAT_PENDING_DOWNLOADS:
			gViewerStats->mSimPendingDownloads.addValue(stat_value);
			break;
		case LL_SIM_STAT_PENDING_UPLOADS:
			gViewerStats->mSimPendingUploads.addValue(stat_value);
			break;
		case LL_SIM_STAT_PENDING_LOCAL_UPLOADS:
			gViewerStats->mSimPendingLocalUploads.addValue(stat_value);
			break;
		case LL_SIM_STAT_TOTAL_UNACKED_BYTES:
			gViewerStats->mSimTotalUnackedBytes.addValue(stat_value / 1024.f);
			break;
		default:
			llwarns << "Unknown stat id" << stat_id << llendl;
		}
	}

	/*
	msg->getF32Fast(_PREHASH_Statistics, _PREHASH_PhysicsTimeDilation, time_dilation);
	gViewerStats->mSimTDStat.addValue(time_dilation);

	// Process information
	//	{	CpuUsage			F32				}
	//	{	SimMemTotal			F32				}
	//	{	SimMemRSS			F32				}
	//	{	ProcessUptime		F32				}
	F32 cpu_usage;
	F32 sim_mem_total;
	F32 sim_mem_rss;
	F32 process_uptime;
	msg->getF32Fast(_PREHASH_Statistics, _PREHASH_CpuUsage, cpu_usage);
	msg->getF32Fast(_PREHASH_Statistics, _PREHASH_SimMemTotal, sim_mem_total);
	msg->getF32Fast(_PREHASH_Statistics, _PREHASH_SimMemRSS, sim_mem_rss);
	msg->getF32Fast(_PREHASH_Statistics, _PREHASH_ProcessUptime, process_uptime);
	gViewerStats->mSimCPUUsageStat.addValue(cpu_usage);
	gViewerStats->mSimMemTotalStat.addValue(sim_mem_total);
	gViewerStats->mSimMemRSSStat.addValue(sim_mem_rss);
	*/

	//
	// Various hacks that aren't statistics, but are being handled here.
	//
	U32 max_tasks_per_region;
	U32 region_flags;
	msg->getU32("Region", "ObjectCapacity", max_tasks_per_region);
	msg->getU32("Region", "RegionFlags", region_flags);

	LLViewerRegion* regionp = gAgent.getRegion();
	if (regionp)
	{
		BOOL was_flying = gAgent.getFlying();
		regionp->setRegionFlags(region_flags);
		regionp->setMaxTasks(max_tasks_per_region);
		// HACK: This makes agents drop from the sky if the region is 
		// set to no fly while people are still in the sim.
		if (was_flying && regionp->getBlockFly())
		{
			gAgent.setFlying(gAgent.canFly());
		}
	}
}


// This info is requested by the simulator when the agent first logs in
// or when it moves into a simulator in which it did not already have
// a child agent.
/*
void process_avatar_info_request(LLMessageSystem *mesgsys, void **user_data)
{
	llinfos << "process_avatar_info_request()" << llendl;

	// Send the avatar appearance (parameters and texture entry UUIDs)
	gAgent.sendAgentSetAppearance();
	send_agent_update(TRUE, TRUE);
}*/


void process_avatar_animation(LLMessageSystem *mesgsys, void **user_data)
{
	LLUUID	animation_id;
	LLUUID	uuid;
	S32		anim_sequence_id;
	LLVOAvatar *avatarp;
	
	mesgsys->getUUIDFast(_PREHASH_Sender, _PREHASH_ID, uuid);

	//clear animation flags
	avatarp = (LLVOAvatar *)gObjectList.findObject(uuid);

	if (!avatarp)
	{
		// no agent by this ID...error?
		llwarns << "Received animation state for unknown avatar" << uuid << llendl;
		return;
	}

	S32 num_blocks = mesgsys->getNumberOfBlocksFast(_PREHASH_AnimationList);
	S32 num_source_blocks = mesgsys->getNumberOfBlocksFast(_PREHASH_AnimationSourceList);

	avatarp->mSignaledAnimations.clear();
	
	if (avatarp->mIsSelf)
	{
		LLUUID object_id;

		for( S32 i = 0; i < num_blocks; i++ )
		{
			mesgsys->getUUIDFast(_PREHASH_AnimationList, _PREHASH_AnimID, animation_id, i);
			mesgsys->getS32Fast(_PREHASH_AnimationList, _PREHASH_AnimSequenceID, anim_sequence_id, i);

			//llinfos << "Anim sequence ID: " << anim_sequence_id << llendl;

			avatarp->mSignaledAnimations[animation_id] = anim_sequence_id;

			if (i < num_source_blocks)
			{
				mesgsys->getUUIDFast(_PREHASH_AnimationSourceList, _PREHASH_ObjectID, object_id, i);
			
				LLViewerObject* object = gObjectList.findObject(object_id);
				if (object)
				{
					object->mFlags |= FLAGS_ANIM_SOURCE;

					BOOL anim_found = FALSE;
					LLVOAvatar::AnimSourceIterator anim_it = avatarp->mAnimationSources.find(object_id);
					for (;anim_it != avatarp->mAnimationSources.end(); ++anim_it)
					{
						if (anim_it->second == animation_id)
						{
							anim_found = TRUE;
							break;
						}
					}

					if (!anim_found)
					{
						avatarp->mAnimationSources.insert(LLVOAvatar::AnimationSourceMap::value_type(object_id, animation_id));
					}
				}
			}
		}
	}
	else
	{
		for( S32 i = 0; i < num_blocks; i++ )
		{
			mesgsys->getUUIDFast(_PREHASH_AnimationList, _PREHASH_AnimID, animation_id, i);
			mesgsys->getS32Fast(_PREHASH_AnimationList, _PREHASH_AnimSequenceID, anim_sequence_id, i);
			avatarp->mSignaledAnimations[animation_id] = anim_sequence_id;
		}
	}

	if (num_blocks)
	{
		avatarp->processAnimationStateChanges();
	}
}

void process_avatar_appearance(LLMessageSystem *mesgsys, void **user_data)
{
	LLUUID uuid;
	mesgsys->getUUIDFast(_PREHASH_Sender, _PREHASH_ID, uuid);

	LLVOAvatar* avatarp = (LLVOAvatar *)gObjectList.findObject(uuid);
	if( avatarp )
	{
		avatarp->processAvatarAppearance( mesgsys );
	}
	else
	{
		llwarns << "avatar_appearance sent for unknown avatar " << uuid << llendl;
	}
}

void process_camera_constraint(LLMessageSystem *mesgsys, void **user_data)
{
	LLVector4 cameraCollidePlane;
	mesgsys->getVector4Fast(_PREHASH_CameraCollidePlane, _PREHASH_Plane, cameraCollidePlane);

	gAgent.setCameraCollidePlane(cameraCollidePlane);
}

void near_sit_object(BOOL success, void *data)
{
	if (success)
	{
		// Send message to sit on object
		gMessageSystem->newMessageFast(_PREHASH_AgentSit);
		gMessageSystem->nextBlockFast(_PREHASH_AgentData);
		gMessageSystem->addUUIDFast(_PREHASH_AgentID, gAgent.getID());
		gMessageSystem->addUUIDFast(_PREHASH_SessionID, gAgent.getSessionID());
		gAgent.sendReliableMessage();
	}
}

void process_avatar_sit_response(LLMessageSystem *mesgsys, void **user_data)
{
	LLVector3 sitPosition;
	LLQuaternion sitRotation;
	LLUUID sitObjectID;
	BOOL use_autopilot;
	mesgsys->getUUIDFast(_PREHASH_SitObject, _PREHASH_ID, sitObjectID);
	mesgsys->getBOOLFast(_PREHASH_SitTransform, _PREHASH_AutoPilot, use_autopilot);
	mesgsys->getVector3Fast(_PREHASH_SitTransform, _PREHASH_SitPosition, sitPosition);
	mesgsys->getQuatFast(_PREHASH_SitTransform, _PREHASH_SitRotation, sitRotation);
	LLVector3 camera_eye;
	mesgsys->getVector3Fast(_PREHASH_SitTransform, _PREHASH_CameraEyeOffset, camera_eye);
	LLVector3 camera_at;
	mesgsys->getVector3Fast(_PREHASH_SitTransform, _PREHASH_CameraAtOffset, camera_at);
	BOOL force_mouselook;
	mesgsys->getBOOLFast(_PREHASH_SitTransform, _PREHASH_ForceMouselook, force_mouselook);

	LLVOAvatar* avatar = gAgent.getAvatarObject();

	if (avatar && dist_vec_squared(camera_eye, camera_at) > 0.0001f)
	{
		gAgent.setSitCamera(sitObjectID, camera_eye, camera_at);
	}
	
	gAgent.mForceMouselook = force_mouselook;

	LLViewerObject* object = gObjectList.findObject(sitObjectID);
	if (object)
	{
		LLVector3 sit_spot = object->getPositionAgent() + (sitPosition * object->getRotation());
		if (!use_autopilot || (avatar && avatar->mIsSitting && avatar->getRoot() == object->getRoot()))
		{
			//we're already sitting on this object, so don't autopilot
		}
		else
		{
			gAgent.startAutoPilotGlobal(gAgent.getPosGlobalFromAgent(sit_spot), "Sit", &sitRotation, near_sit_object, NULL, 0.5f);
		}
	}
	else
	{
		llwarns << "Received sit approval for unknown object " << sitObjectID << llendl;
	}
}

void process_clear_follow_cam_properties(LLMessageSystem *mesgsys, void **user_data)
{
	LLUUID		source_id;

	mesgsys->getUUIDFast(_PREHASH_ObjectData, _PREHASH_ObjectID, source_id);

	LLFollowCamMgr::removeFollowCamParams(source_id);
}

void process_set_follow_cam_properties(LLMessageSystem *mesgsys, void **user_data)
{
	S32			type;
	F32			value;
	bool		settingPosition = false;
	bool		settingFocus	= false;
	bool		settingFocusOffset = false;
	LLVector3	position;
	LLVector3	focus;
	LLVector3	focus_offset;

	LLUUID		source_id;

	mesgsys->getUUIDFast(_PREHASH_ObjectData, _PREHASH_ObjectID, source_id);

	LLViewerObject* objectp = gObjectList.findObject(source_id);
	if (objectp)
	{
		objectp->mFlags |= FLAGS_CAMERA_SOURCE;
	}

	S32 num_objects = mesgsys->getNumberOfBlocks("CameraProperty");
	for (S32 block_index = 0; block_index < num_objects; block_index++)
	{
		mesgsys->getS32("CameraProperty", "Type", type, block_index);
		mesgsys->getF32("CameraProperty", "Value", value, block_index);
		switch(type)
		{
		case FOLLOWCAM_PITCH:
			LLFollowCamMgr::setPitch(source_id, value);
			break;
		case FOLLOWCAM_FOCUS_OFFSET_X:
			focus_offset.mV[VX] = value;
			settingFocusOffset = true;
			break;
		case FOLLOWCAM_FOCUS_OFFSET_Y:
			focus_offset.mV[VY] = value;
			settingFocusOffset = true;
			break;
		case FOLLOWCAM_FOCUS_OFFSET_Z:
			focus_offset.mV[VZ] = value;
			settingFocusOffset = true;
			break;
		case FOLLOWCAM_POSITION_LAG:
			LLFollowCamMgr::setPositionLag(source_id, value);
			break;
		case FOLLOWCAM_FOCUS_LAG:
			LLFollowCamMgr::setFocusLag(source_id, value);
			break;
		case FOLLOWCAM_DISTANCE:
			LLFollowCamMgr::setDistance(source_id, value);
			break;
		case FOLLOWCAM_BEHINDNESS_ANGLE:
			LLFollowCamMgr::setBehindnessAngle(source_id, value);
			break;
		case FOLLOWCAM_BEHINDNESS_LAG:
			LLFollowCamMgr::setBehindnessLag(source_id, value);
			break;
		case FOLLOWCAM_POSITION_THRESHOLD:
			LLFollowCamMgr::setPositionThreshold(source_id, value);
			break;
		case FOLLOWCAM_FOCUS_THRESHOLD:
			LLFollowCamMgr::setFocusThreshold(source_id, value);
			break;
		case FOLLOWCAM_ACTIVE:
			//if 1, set using followcam,. 
			LLFollowCamMgr::setCameraActive(source_id, value != 0.f);
			break;
		case FOLLOWCAM_POSITION_X:
			settingPosition = true;
			position.mV[ 0 ] = value;
			break;
		case FOLLOWCAM_POSITION_Y:
			settingPosition = true;
			position.mV[ 1 ] = value;
			break;
		case FOLLOWCAM_POSITION_Z:
			settingPosition = true;
			position.mV[ 2 ] = value;
			break;
		case FOLLOWCAM_FOCUS_X:
			settingFocus = true;
			focus.mV[ 0 ] = value;
			break;
		case FOLLOWCAM_FOCUS_Y:
			settingFocus = true;
			focus.mV[ 1 ] = value;
			break;
		case FOLLOWCAM_FOCUS_Z:
			settingFocus = true;
			focus.mV[ 2 ] = value;
			break;
		case FOLLOWCAM_POSITION_LOCKED:
			LLFollowCamMgr::setPositionLocked(source_id, value != 0.f);
			break;
		case FOLLOWCAM_FOCUS_LOCKED:
			LLFollowCamMgr::setFocusLocked(source_id, value != 0.f);
			break;

		default:
			break;
		}
	}

	if ( settingPosition )
	{
		LLFollowCamMgr::setPosition(source_id, position);
	}
	if ( settingFocus )
	{
		LLFollowCamMgr::setFocus(source_id, focus);
	}
	if ( settingFocusOffset )
	{
		LLFollowCamMgr::setFocusOffset(source_id, focus_offset);
	}
}
//end Ventrella 


// Culled from newsim lltask.cpp
void process_name_value(LLMessageSystem *mesgsys, void **user_data)
{
	char	temp_str[NAME_VALUE_BUF_SIZE];		/* Flawfinder: ignore */
	LLUUID	id;
	S32		i, num_blocks;

	mesgsys->getUUIDFast(_PREHASH_TaskData, _PREHASH_ID, id);

	LLViewerObject* object = gObjectList.findObject(id);

	if (object)
	{
		num_blocks = mesgsys->getNumberOfBlocksFast(_PREHASH_NameValueData);
		for (i = 0; i < num_blocks; i++)
		{
			mesgsys->getStringFast(_PREHASH_NameValueData, _PREHASH_NVPair, NAME_VALUE_BUF_SIZE, temp_str, i);
			llinfos << "Added to object Name Value: " << temp_str << llendl;
			object->addNVPair(temp_str);
		}
	}
	else
	{
		llinfos << "Can't find object " << id << " to add name value pair" << llendl;
	}
}

void process_remove_name_value(LLMessageSystem *mesgsys, void **user_data)
{
	char	temp_str[NAME_VALUE_BUF_SIZE];		/* Flawfinder: ignore */
	LLUUID	id;
	S32		i, num_blocks;

	mesgsys->getUUIDFast(_PREHASH_TaskData, _PREHASH_ID, id);

	LLViewerObject* object = gObjectList.findObject(id);

	if (object)
	{
		num_blocks = mesgsys->getNumberOfBlocksFast(_PREHASH_NameValueData);
		for (i = 0; i < num_blocks; i++)
		{
			mesgsys->getStringFast(_PREHASH_NameValueData, _PREHASH_NVPair, NAME_VALUE_BUF_SIZE, temp_str, i);
			llinfos << "Removed from object Name Value: " << temp_str << llendl;
			object->removeNVPair(temp_str);
		}
	}
	else
	{
		llinfos << "Can't find object " << id << " to remove name value pair" << llendl;
	}
}

void process_kick_user(LLMessageSystem *msg, void** /*user_data*/)
{
	char message[2048];		/* Flawfinder: ignore */
	message[0] = '\0';

	msg->getStringFast(_PREHASH_UserInfo, _PREHASH_Reason, 2048, message);

	do_disconnect(message);
}


/*
void process_user_list_reply(LLMessageSystem *msg, void **user_data)
{
	LLUserList::processUserListReply(msg, user_data);
	return;
	char	firstname[MAX_STRING+1];
	char	lastname[MAX_STRING+1];
	U8		status;
	S32		user_count;

	user_count = msg->getNumberOfBlocks("UserBlock");

	for (S32 i = 0; i < user_count; i++)
	{
		msg->getData("UserBlock", i, "FirstName", firstname);
		msg->getData("UserBlock", i, "LastName", lastname);
		msg->getData("UserBlock", i, "Status", &status);

		if (status & 0x01)
		{
			dialog_friends_add_friend(buffer, TRUE);
		}
		else
		{
			dialog_friends_add_friend(buffer, FALSE);
		}
	}

	dialog_friends_done_adding();
}
*/

// this is not handled in processUpdateMessage
/*
void process_time_dilation(LLMessageSystem *msg, void **user_data)
{
	// get the time_dilation
	U16 foo;
	msg->getData("TimeDilation", "TimeDilation", &foo);
	F32 time_dilation = ((F32) foo) / 65535.f;

	// get the pointer to the right region
	U32 ip = msg->getSenderIP();
	U32 port = msg->getSenderPort();
	LLViewerRegion *regionp = gWorldp->getRegion(ip, port);
	if (regionp)
	{
		regionp->setTimeDilation(time_dilation);
	}
}
*/



void process_money_balance_reply( LLMessageSystem* msg, void** )
{
	S32 balance = 0;
	S32 credit = 0;
	S32 committed = 0;
	char desc[STD_STRING_BUF_SIZE] = "";		/* Flawfinder: ignore */

	msg->getS32("MoneyData", "MoneyBalance", balance);
	msg->getS32("MoneyData", "SquareMetersCredit", credit);
	msg->getS32("MoneyData", "SquareMetersCommitted", committed);
	msg->getStringFast(_PREHASH_MoneyData, _PREHASH_Description,	STD_STRING_BUF_SIZE,	desc);
	llinfos << "L$, credit, committed: " << balance << " " << credit << " "
			<< committed << llendl;

	if (gStatusBar)
	{
		S32 old_balance = gStatusBar->getBalance();

		// This is an update, not the first transmission of balance
		if (old_balance != 0)
		{
			// this is actually an update
			if (balance > old_balance)
			{
				LLFirstUse::useBalanceIncrease(balance - old_balance);
			}
			else if (balance < old_balance)
			{
				LLFirstUse::useBalanceDecrease(balance - old_balance);
			}
		}

		gStatusBar->setBalance(balance);
		gStatusBar->setLandCredit(credit);
		gStatusBar->setLandCommitted(committed);
	}

	LLUUID tid;
	msg->getUUID("MoneyData", "TransactionID", tid);
	static std::deque<LLUUID> recent;
	if(desc[0] && gSavedSettings.getBOOL("NotifyMoneyChange")
	   && (std::find(recent.rbegin(), recent.rend(), tid) == recent.rend()))
	{
		// Make the user confirm the transaction, since they might
		// have missed something during an event.
		// XUI:translate
		LLString::format_map_t args;
		args["[MESSAGE]"] = desc;
		LLNotifyBox::showXml("SystemMessage", args);

		// Once the 'recent' container gets large enough, chop some
		// off the beginning.
		const U32 MAX_LOOKBACK = 30;
		const S32 POP_FRONT_SIZE = 12;
		if(recent.size() > MAX_LOOKBACK)
		{
			lldebugs << "Removing oldest transaction records" << llendl;
			recent.erase(recent.begin(), recent.begin() + POP_FRONT_SIZE);
		}
		//lldebugs << "Pushing back transaction " << tid << llendl;
		recent.push_back(tid);
	}
}

void process_agent_alert_message(LLMessageSystem* msgsystem, void** user_data)
{
	char buffer[MAX_STRING];		/* Flawfinder: ignore */
	msgsystem->getStringFast(_PREHASH_AlertData, _PREHASH_Message, MAX_STRING, buffer);
	BOOL modal = FALSE;
	msgsystem->getBOOL("AlertData", "Modal", modal);
	process_alert_core(buffer, modal);
}

void process_alert_message(LLMessageSystem *msgsystem, void **user_data)
{
	char buffer[MAX_STRING];		/* Flawfinder: ignore */
	msgsystem->getStringFast(_PREHASH_AlertData, _PREHASH_Message, MAX_STRING, buffer);
	BOOL modal = FALSE;
	process_alert_core(buffer, modal);
}

void process_alert_core(const char* buffer, BOOL modal)
{
	// make sure the cursor is back to the usual default since the
	// alert is probably due to some kind of error.
	gViewerWindow->getWindow()->resetBusyCount();

	// HACK -- handle callbacks for specific alerts 
	if( !strcmp( buffer, "You died and have been teleported to your home location" ) )
	{
		gViewerStats->incStat(LLViewerStats::ST_KILLED_COUNT);
	}
	else if( !strcmp( buffer, "Home position set." ) )
	{
		// save the home location image to disk
		LLString snap_filename = gDirUtilp->getLindenUserDir();
		snap_filename += gDirUtilp->getDirDelimiter();
		snap_filename += SCREEN_HOME_FILENAME;
		gViewerWindow->saveSnapshot(snap_filename, gViewerWindow->getWindowWidth(), gViewerWindow->getWindowHeight(), FALSE, FALSE);
	}

	// Translate system messages here.
	const char ALERT_PREFIX[] = "ALERT: ";
	const size_t ALERT_PREFIX_LEN = sizeof(ALERT_PREFIX) - 1;
	if (!strncmp(buffer, ALERT_PREFIX, ALERT_PREFIX_LEN))
	{
		// Allow the server to spawn a named alert so that server alerts can be
		// translated out of English. JC
		std::string alert_name(buffer + ALERT_PREFIX_LEN);
		LLAlertDialog::showXml(alert_name);
	}
	else if (buffer[0] == '/')
	{
		// System message is important, show in upper-right box not tip
		LLString text(buffer+1);
		LLString::format_map_t args;
		if (text.substr(0,17) == "RESTART_X_MINUTES")
		{
			S32 mins = 0;
			LLString::convertToS32(text.substr(18), mins);
			args["[MINUTES]"] = llformat("%d",mins);
			LLNotifyBox::showXml("RegionRestartMinutes", args);
		}
		else if (text.substr(0,17) == "RESTART_X_SECONDS")
		{
			S32 secs = 0;
			LLString::convertToS32(text.substr(18), secs);
			args["[SECONDS]"] = llformat("%d",secs);
			LLNotifyBox::showXml("RegionRestartSeconds", args);
		}
		else
		{
			//XUI:translate
			args["[MESSAGE]"] = text;
			LLNotifyBox::showXml("SystemMessage", args);
		}
	}
	else if (modal)
	{
		//XUI:translate
		LLString::format_map_t args;
		args["[ERROR_MESSAGE]"] = buffer;
		gViewerWindow->alertXml("ErrorMessage", args);
	}
	else
	{
		//XUI:translate
		LLString::format_map_t args;
		args["[MESSAGE]"] = buffer;
		LLNotifyBox::showXml("SystemMessageTip", args);
	}
}

LLLinkedList<LLMeanCollisionData>	gMeanCollisionList;
time_t								gLastDisplayedTime = 0;

void handle_show_mean_events(void *)
{
	if (gNoRender)
	{
		return;
	}

	LLFloaterBump::show(NULL);
}

void mean_name_callback(const LLUUID &id, const char *first, const char *last, BOOL always_false, void* data)
{
	if (gNoRender)
	{
		return;
	}

	while(gMeanCollisionList.getLength() > 20)
	{
		gMeanCollisionList.getLastData();
		gMeanCollisionList.deleteCurrentData();
	}

	LLMeanCollisionData *mcd;
	for (mcd = gMeanCollisionList.getFirstData(); mcd; mcd = gMeanCollisionList.getNextData())
	{
		if (mcd->mPerp == id)
		{
			strncpy(mcd->mFirstName, first, DB_FIRST_NAME_BUF_SIZE -1);		/* Flawfinder: ignore */
			mcd->mFirstName[DB_FIRST_NAME_BUF_SIZE -1] = '\0';
			strncpy(mcd->mLastName, last, DB_LAST_NAME_BUF_SIZE -1);		/* Flawfinder: ignore */
			mcd->mLastName[DB_LAST_NAME_BUF_SIZE -1] = '\0';
		}
	}
}

void process_mean_collision_alert_message(LLMessageSystem *msgsystem, void **user_data)
{
	if (gAgent.inPrelude())
	{
		// JC: In prelude, bumping is OK.  This dialog is rather confusing to 
		// newbies, so we don't show it.  Drop the packet on the floor.
		return;
	}

	// make sure the cursor is back to the usual default since the
	// alert is probably due to some kind of error.
	gViewerWindow->getWindow()->resetBusyCount();

	LLUUID perp;
	U32	   time;
	U8	   u8type;
	EMeanCollisionType	   type;
	F32    mag;

	S32 i, num = msgsystem->getNumberOfBlocks(_PREHASH_MeanCollision);

	for (i = 0; i < num; i++)
	{
		msgsystem->getUUIDFast(_PREHASH_MeanCollision, _PREHASH_Perp, perp);
		msgsystem->getU32Fast(_PREHASH_MeanCollision, _PREHASH_Time, time);
		msgsystem->getF32Fast(_PREHASH_MeanCollision, _PREHASH_Mag, mag);
		msgsystem->getU8Fast(_PREHASH_MeanCollision, _PREHASH_Type, u8type);

		type = (EMeanCollisionType)u8type;

		LLMeanCollisionData *mcd;

		BOOL b_found = FALSE;

		for (mcd = gMeanCollisionList.getFirstData(); mcd; mcd = gMeanCollisionList.getNextData())
		{
			if ((mcd->mPerp == perp) && (mcd->mType == type))
			{
				mcd->mTime = time;
				mcd->mMag = mag;
				b_found = TRUE;
				break;
			}
		}

		if (!b_found)
		{
			LLMeanCollisionData *mcd = new LLMeanCollisionData(gAgentID, perp, time, type, mag);
			gMeanCollisionList.addData(mcd);
			const BOOL is_group = FALSE;
			gCacheName->get(perp, is_group, mean_name_callback);
		}
	}
}

void process_frozen_message(LLMessageSystem *msgsystem, void **user_data)
{
	// make sure the cursor is back to the usual default since the
	// alert is probably due to some kind of error.
	gViewerWindow->getWindow()->resetBusyCount();
	BOOL b_frozen;
	
	msgsystem->getBOOL("FrozenData", "Data", b_frozen);

	// TODO: make being frozen change view
	if (b_frozen)
	{
	}
	else
	{
	}
}

// do some extra stuff once we get our economy data
void process_economy_data(LLMessageSystem *msg, void** /*user_data*/)
{
	LLGlobalEconomy::processEconomyData(msg, (void**)gGlobalEconomy);

	S32 upload_cost = gGlobalEconomy->getPriceUpload();
	LLFloaterImagePreview::setUploadAmount(upload_cost);

	gMenuHolder->childSetLabelArg("Upload Image", "[COST]", llformat("%d", upload_cost));
	gMenuHolder->childSetLabelArg("Upload Sound", "[COST]", llformat("%d", upload_cost));
	gMenuHolder->childSetLabelArg("Upload Animation", "[COST]", llformat("%d", upload_cost));
	gMenuHolder->childSetLabelArg("Bulk Upload", "[COST]", llformat("%d", upload_cost));
}

class LLScriptQuestionCBData
{
public:
	LLScriptQuestionCBData(const LLUUID &taskid, const LLUUID &itemid, const LLHost &sender, S32 questions, const char *object_name, const char *owner_name)
		: mTaskID(taskid), mItemID(itemid), mSender(sender), mQuestions(questions), mObjectName(object_name), mOwnerName(owner_name)
	{
	}

	LLUUID mTaskID;
	LLUUID mItemID;
	LLHost mSender;
	S32	   mQuestions;
	LLString mObjectName;
	LLString mOwnerName;
};

void notify_cautioned_script_question(LLScriptQuestionCBData* cbdata, S32 orig_questions, BOOL granted)
{
	// only continue if at least some permissions were requested
	if (orig_questions)
	{
		// check to see if the person we are asking

		// "'[OBJECTNAME]', an object owned by '[OWNERNAME]', 
		// located in [REGIONNAME] at [REGIONPOS], 
		// has been <granted|denied> permission to: [PERMISSIONS]."

		LLUIString notice(LLNotifyBox::getTemplateMessage(granted ? "ScriptQuestionCautionChatGranted" : "ScriptQuestionCautionChatDenied"));

		// always include the object name and owner name 
		notice.setArg("[OBJECTNAME]", cbdata->mObjectName);
		notice.setArg("[OWNERNAME]", cbdata->mOwnerName);

		// try to lookup viewerobject that corresponds to the object that
		// requested permissions (here, taskid->requesting object id)
		BOOL foundpos = FALSE;
		LLViewerObject* viewobj = gObjectList.findObject(cbdata->mTaskID);
		if (viewobj)
		{
			// found the viewerobject, get it's position in its region
			LLVector3 objpos(viewobj->getPosition());
			
			// try to lookup the name of the region the object is in
			LLViewerRegion* viewregion = viewobj->getRegion();
			if (viewregion)
			{
				// got the region, so include the region and 3d coordinates of the object
				notice.setArg("[REGIONNAME]", viewregion->getName());				
				LLString formatpos = llformat("%.1f, %.1f,%.1f", objpos[VX], objpos[VY], objpos[VZ]);
				notice.setArg("[REGIONPOS]", formatpos);

				foundpos = TRUE;
			}
		}

		if (!foundpos)
		{
			// unable to determine location of the object
			notice.setArg("[REGIONNAME]", "(unknown region)");
			notice.setArg("[REGIONPOS]", "(unknown position)");
		}

		// check each permission that was requested, and list each 
		// permission that has been flagged as a caution permission
		BOOL caution = FALSE;
		S32 count = 0;
		LLString perms;
		for (S32 i = 0; i < SCRIPT_PERMISSION_EOF; i++)
		{
			if ((orig_questions & LSCRIPTRunTimePermissionBits[i]) && LLNotifyBox::getTemplateIsCaution(SCRIPT_QUESTIONS[i]))
			{
				count++;
				caution = TRUE;

				// add a comma before the permission description if it is not the first permission
				// added to the list or the last permission to check
				if ((count > 1) && (i < SCRIPT_PERMISSION_EOF))
				{
					perms.append(", ");
				}

				perms.append(LLNotifyBox::getTemplateMessage(SCRIPT_QUESTIONS[i]));
			}
		}

		notice.setArg("[PERMISSIONS]", perms);

		// log a chat message as long as at least one requested permission
		// is a caution permission
		if (caution)
		{
			LLChat chat(notice.getString());
			LLFloaterChat::addChat(chat, FALSE, FALSE);
		}
	}
}

void script_question_decline_cb(S32 option, void* user_data)
{
	LLMessageSystem *msg = gMessageSystem;
	LLScriptQuestionCBData *cbdata = (LLScriptQuestionCBData *)user_data;
	
	// remember the permissions requested so they can be checked
	// when it comes time to log a chat message
	S32 orig = cbdata->mQuestions;

	// this callback will always decline all permissions requested
	// (any question flags set in the ScriptAnswerYes message
	// will be interpreted as having been granted, so clearing all
	// the bits will deny every permission)
	cbdata->mQuestions = 0;

	// respond with the permissions denial
	msg->newMessageFast(_PREHASH_ScriptAnswerYes);
	msg->nextBlockFast(_PREHASH_AgentData);
	msg->addUUIDFast(_PREHASH_AgentID, gAgent.getID());
	msg->addUUIDFast(_PREHASH_SessionID, gAgent.getSessionID());
	msg->nextBlockFast(_PREHASH_Data);
	msg->addUUIDFast(_PREHASH_TaskID, cbdata->mTaskID);
	msg->addUUIDFast(_PREHASH_ItemID, cbdata->mItemID);
	msg->addS32Fast(_PREHASH_Questions, cbdata->mQuestions);
	msg->sendReliable(cbdata->mSender);

	// log a chat message, if appropriate
	notify_cautioned_script_question(cbdata, orig, FALSE);

	delete cbdata;
}

void script_question_cb(S32 option, void* user_data)
{
	LLMessageSystem *msg = gMessageSystem;
	LLScriptQuestionCBData *cbdata = (LLScriptQuestionCBData *)user_data;
	S32 orig = cbdata->mQuestions;

	// check whether permissions were granted or denied
	BOOL allowed = TRUE;
	// the "yes/accept" button is the first button in the template, making it button 0
	// if any other button was clicked, the permissions were denied
	if (option != 0)
	{
		cbdata->mQuestions = 0;
		allowed = FALSE;
	}	

	// reply with the permissions granted or denied
	msg->newMessageFast(_PREHASH_ScriptAnswerYes);
	msg->nextBlockFast(_PREHASH_AgentData);
	msg->addUUIDFast(_PREHASH_AgentID, gAgent.getID());
	msg->addUUIDFast(_PREHASH_SessionID, gAgent.getSessionID());
	msg->nextBlockFast(_PREHASH_Data);
	msg->addUUIDFast(_PREHASH_TaskID, cbdata->mTaskID);
	msg->addUUIDFast(_PREHASH_ItemID, cbdata->mItemID);
	msg->addS32Fast(_PREHASH_Questions, cbdata->mQuestions);
	msg->sendReliable(cbdata->mSender);

	// only log a chat message if caution prompts are enabled
	if (gSavedSettings.getBOOL("PermissionsCautionEnabled"))
	{
		// log a chat message, if appropriate
		notify_cautioned_script_question(cbdata, orig, allowed);
	}

	delete cbdata;
}

void process_script_question(LLMessageSystem *msg, void **user_data)
{
	// XUI:translate owner name -> [FIRST] [LAST]

	LLHost sender = msg->getSender();

	LLUUID taskid;
	LLUUID itemid;
	S32		questions;
	char object_name[255];		/* Flawfinder: ignore */
	char owner_name[DB_FULL_NAME_BUF_SIZE];		/* Flawfinder: ignore */

	// taskid -> object key of object requesting permissions
	msg->getUUIDFast(_PREHASH_Data, _PREHASH_TaskID, taskid );
	// itemid -> script asset key of script requesting permissions
	msg->getUUIDFast(_PREHASH_Data, _PREHASH_ItemID, itemid );
	msg->getStringFast(_PREHASH_Data, _PREHASH_ObjectName, 255, object_name);
	msg->getStringFast(_PREHASH_Data, _PREHASH_ObjectOwner, DB_FULL_NAME_BUF_SIZE, owner_name);
	msg->getS32Fast(_PREHASH_Data, _PREHASH_Questions, questions );

	// don't display permission requests if this object is muted - JS.
	if (gMuteListp->isMuted(taskid)) return;

	LLString script_question;
	if (questions)
	{
		BOOL caution = FALSE;
		S32 count = 0;
		LLString::format_map_t args;
		args["[OBJECTNAME]"] = object_name;
		args["[NAME]"] = owner_name;

		// check the received permission flags against each permission
		for (S32 i = 0; i < SCRIPT_PERMISSION_EOF; i++)
		{
			if (questions & LSCRIPTRunTimePermissionBits[i])
			{
				count++;
				script_question += "    " + LLNotifyBox::getTemplateMessage(SCRIPT_QUESTIONS[i]) + "\n";

				// check whether permission question should cause special caution dialog
				caution |= LLNotifyBox::getTemplateIsCaution(SCRIPT_QUESTIONS[i]);
			}
		}
		args["[QUESTIONS]"] = script_question;

		LLScriptQuestionCBData *cbdata = new LLScriptQuestionCBData(taskid, itemid, sender, questions, object_name, owner_name);

		// check whether cautions are even enabled or not
		if (gSavedSettings.getBOOL("PermissionsCautionEnabled"))
		{
			if (caution)
			{
				// display the caution permissions prompt
				LLNotifyBox::showXml("ScriptQuestionCaution", args, TRUE, script_question_cb, cbdata);
			}
			else
			{
				// display the permissions request normally
				LLNotifyBox::showXml("ScriptQuestion", args, FALSE, script_question_cb, cbdata);
			}
		}
		else
		{
			// fall back to default behavior if cautions are entirely disabled
			LLNotifyBox::showXml("ScriptQuestion", args, FALSE, script_question_cb, cbdata);
		}

	}
}


void process_derez_container(LLMessageSystem *msg, void**)
{
	llwarns << "call to deprecated process_derez_container" << llendl;
}

void container_inventory_arrived(LLViewerObject* object,
								 InventoryObjectList* inventory,
								 S32 serial_num,
								 void* data)
{
	llinfos << "container_inventory_arrived()" << llendl;
	if( gAgent.cameraMouselook() )
	{
		gAgent.changeCameraToDefault();
	}

	LLInventoryView* view = LLInventoryView::getActiveInventory();

	if (inventory->size() > 2)
	{
		// create a new inventory category to put this in
		LLUUID cat_id;
		cat_id = gInventory.createNewCategory(gAgent.getInventoryRootID(),
											  LLAssetType::AT_NONE,
											  "Acquired Items");

		InventoryObjectList::const_iterator it = inventory->begin();
		InventoryObjectList::const_iterator end = inventory->end();
		for ( ; it != end; ++it)
		{
			if ((*it)->getType() != LLAssetType::AT_CATEGORY &&
				(*it)->getType() != LLAssetType::AT_ROOT_CATEGORY)
			{
				LLInventoryObject* obj = (LLInventoryObject*)(*it);
				LLInventoryItem* item = (LLInventoryItem*)(obj);
				LLUUID item_id;
				item_id.generate();
				S32 creation_date_utc = time_corrected();
				LLPointer<LLViewerInventoryItem> new_item
					= new LLViewerInventoryItem(item_id,
												cat_id,
												item->getPermissions(),
												item->getAssetUUID(),
												item->getType(),
												item->getInventoryType(),
												item->getName(),
												item->getDescription(),
												LLSaleInfo::DEFAULT,
												item->getFlags(),
												creation_date_utc);
				new_item->updateServer(TRUE);
				gInventory.updateItem(new_item);
			}
		}
		gInventory.notifyObservers();
		if(view)
		{
			view->getPanel()->setSelection(cat_id, TAKE_FOCUS_NO);
		}
	}
	else if (inventory->size() == 2)
	{
		// we're going to get one fake root category as well as the
		// one actual object
		InventoryObjectList::iterator it = inventory->begin();

		if ((*it)->getType() == LLAssetType::AT_CATEGORY ||
			(*it)->getType() == LLAssetType::AT_ROOT_CATEGORY)
		{
			++it;
		}

		LLInventoryItem* item = (LLInventoryItem*)((LLInventoryObject*)(*it));
		LLUUID category = gInventory.findCategoryUUIDForType(item->getType());

		LLUUID item_id;
		item_id.generate();
		S32 creation_date_utc = time_corrected();
		LLPointer<LLViewerInventoryItem> new_item
			= new LLViewerInventoryItem(item_id, category,
										item->getPermissions(),
										item->getAssetUUID(),
										item->getType(),
										item->getInventoryType(),
										item->getName(),
										item->getDescription(),
										LLSaleInfo::DEFAULT,
										item->getFlags(),
										creation_date_utc);
		new_item->updateServer(TRUE);
		gInventory.updateItem(new_item);
		gInventory.notifyObservers();
		if(view)
		{
			view->getPanel()->setSelection(item_id, TAKE_FOCUS_NO);
		}
	}

	// we've got the inventory, now delete this object if this was a take
	BOOL delete_object = (BOOL)(intptr_t)data;
	LLViewerRegion *region = gAgent.getRegion();
	if (delete_object && region)
	{
		gMessageSystem->newMessageFast(_PREHASH_ObjectDelete);
		gMessageSystem->nextBlockFast(_PREHASH_AgentData);
		gMessageSystem->addUUIDFast(_PREHASH_AgentID, gAgent.getID());
		gMessageSystem->addUUIDFast(_PREHASH_SessionID, gAgent.getSessionID());
		const U8 NO_FORCE = 0;
		gMessageSystem->addU8Fast(_PREHASH_Force, NO_FORCE);
		gMessageSystem->nextBlockFast(_PREHASH_ObjectData);
		gMessageSystem->addU32Fast(_PREHASH_ObjectLocalID, object->getLocalID());
		gMessageSystem->sendReliable(region->getHost());
	}
}

// method to format the time. Buffer should be at least
// TIME_STR_LENGTH long, and the function returns buffer (for use in
// sprintf and the like)
char* formatted_time(const time_t& the_time, char* buffer)
{
	LLString::copy(buffer, ctime(&the_time), TIME_STR_LENGTH);
	buffer[24] = '\0';
	return buffer;
}


void process_teleport_failed(LLMessageSystem *msg, void**)
{
	char reason[STD_STRING_BUF_SIZE];		/* Flawfinder: ignore */
	msg->getStringFast(_PREHASH_Info, _PREHASH_Reason, STD_STRING_BUF_SIZE, reason);

	LLStringBase<char>::format_map_t args;
	LLString big_reason = LLAgent::sTeleportErrorMessages[reason];
	if ( big_reason.size() > 0 )
	{	// Substitute verbose reason from the local map
		args["[REASON]"] = big_reason;
	}
	else
	{	// Nothing found in the map - use what the server returned
		args["[REASON]"] = reason;
	}

	gViewerWindow->alertXml("CouldNotTeleportReason", args);

	if( gAgent.getTeleportState() != LLAgent::TELEPORT_NONE )
	{
		gAgent.setTeleportState( LLAgent::TELEPORT_NONE );
	}
}

void process_teleport_local(LLMessageSystem *msg,void**)
{
	LLUUID agent_id;
	msg->getUUIDFast(_PREHASH_Info, _PREHASH_AgentID, agent_id);
	if (agent_id != gAgent.getID())
	{
		llwarns << "Got teleport notification for wrong agent!" << llendl;
		return;
	}

	U32 location_id;
	LLVector3 pos, look_at;
	U32 teleport_flags;
	msg->getU32Fast(_PREHASH_Info, _PREHASH_LocationID, location_id);
	msg->getVector3Fast(_PREHASH_Info, _PREHASH_Position, pos);
	msg->getVector3Fast(_PREHASH_Info, _PREHASH_LookAt, look_at);
	msg->getU32Fast(_PREHASH_Info, _PREHASH_TeleportFlags, teleport_flags);

	if( gAgent.getTeleportState() != LLAgent::TELEPORT_NONE )
	{
		gAgent.setTeleportState( LLAgent::TELEPORT_NONE );
	}

	// Sim tells us whether the new position is off the ground
	if (teleport_flags & TELEPORT_FLAGS_IS_FLYING)
	{
		gAgent.setFlying(TRUE);
	}
	else
	{
		gAgent.setFlying(FALSE);
	}

	gAgent.setPositionAgent(pos);
	gAgent.slamLookAt(look_at);

	// likewise make sure the camera is behind the avatar
	gAgent.resetView(TRUE);

	// send camera update to new region
	gAgent.updateCamera();

	send_agent_update(TRUE, TRUE);
}

void send_simple_im(const LLUUID& to_id,
					const char* message,
					EInstantMessage dialog,
					const LLUUID& id)
{
	std::string my_name;
	gAgent.buildFullname(my_name);
	send_improved_im(to_id,
					 my_name.c_str(),
					 message,
					 IM_ONLINE,
					 dialog,
					 id,
					 NO_TIMESTAMP,
					 (U8*)EMPTY_BINARY_BUCKET,
					 EMPTY_BINARY_BUCKET_SIZE);
}

void send_group_notice(const LLUUID& group_id,
					   const char* subject,
					   const char* message,
					   const LLInventoryItem* item)
{
	// Put this notice into an instant message form.
	// This will mean converting the item to a binary bucket,
	// and the subject/message into a single field.
	std::string my_name;
	gAgent.buildFullname(my_name);

	// Combine subject + message into a single string.
	std::ostringstream subject_and_message;
	// TODO: turn all existing |'s into ||'s in subject and message.
	subject_and_message << subject << "|" << message;

	// Create an empty binary bucket.
	U8 bin_bucket[MAX_INVENTORY_BUFFER_SIZE];
	U8* bucket_to_send = bin_bucket;
	bin_bucket[0] = '\0';
	S32 bin_bucket_size = EMPTY_BINARY_BUCKET_SIZE;
	// If there is an item being sent, pack it into the binary bucket.
	if (item)
	{
		LLSD item_def;
		item_def["item_id"] = item->getUUID();
		item_def["owner_id"] = item->getPermissions().getOwner();
		std::ostringstream ostr;
		LLSDSerialize::serialize(item_def, ostr, LLSDSerialize::LLSD_XML);
		bin_bucket_size = ostr.str().copy(
			(char*)bin_bucket, ostr.str().size());
		bin_bucket[bin_bucket_size] = '\0';
	}
	else
	{
		bucket_to_send = (U8*) EMPTY_BINARY_BUCKET;
	}
   

	send_improved_im(
			group_id,
			my_name.c_str(),
			subject_and_message.str().c_str(),
			IM_ONLINE,
			IM_GROUP_NOTICE,
			LLUUID::null,
			NO_TIMESTAMP,
			bucket_to_send,
			bin_bucket_size);
}

void handle_lure_callback(S32 option, const LLString& text, void* userdata)
{
	LLDynamicArray<LLUUID>* invitees = (LLDynamicArray<LLUUID>*)userdata;

	if(0 == option)
	{
		LLMessageSystem* msg = gMessageSystem;
		msg->newMessageFast(_PREHASH_StartLure);
		msg->nextBlockFast(_PREHASH_AgentData);
		msg->addUUIDFast(_PREHASH_AgentID, gAgent.getID());
		msg->addUUIDFast(_PREHASH_SessionID, gAgent.getSessionID());
		msg->nextBlockFast(_PREHASH_Info);
		msg->addU8Fast(_PREHASH_LureType, (U8)0); // sim will fill this in.
		msg->addStringFast(_PREHASH_Message, text.c_str());
		for(LLDynamicArray<LLUUID>::iterator itr = invitees->begin(); itr != invitees->end(); ++itr)
		{
			msg->nextBlockFast(_PREHASH_TargetData);
			msg->addUUIDFast(_PREHASH_TargetID, *itr);
		}
		gAgent.sendReliableMessage();
	}

	delete invitees;
	invitees = NULL;
}

void handle_lure_callback_godlike(S32 option, void* userdata)
{
	handle_lure_callback(option, LLString::null, userdata);
}

void handle_lure(const LLUUID& invitee)
{
	LLDynamicArray<LLUUID> ids;
	ids.push_back(invitee);
	handle_lure(ids);
}

// Prompt for a message to the invited user.
void handle_lure(LLDynamicArray<LLUUID>& ids) 
{
	LLDynamicArray<LLUUID>* userdata = new LLDynamicArray<LLUUID>(ids);

	LLString::format_map_t edit_args;
	edit_args["[REGION]"] = gAgent.getRegion()->getName();
	if (gAgent.isGodlike())
	{
		gViewerWindow->alertXmlEditText("OfferTeleportFromGod", edit_args,
										&handle_lure_callback_godlike, userdata,
										NULL, NULL, edit_args);
	}
	else
	{
		gViewerWindow->alertXmlEditText("OfferTeleport", edit_args,
										NULL, NULL,
										handle_lure_callback, userdata, edit_args);
	}
}


void send_improved_im(const LLUUID& to_id,
							const char* name,
							const char* message,
							U8 offline,
							EInstantMessage dialog,
							const LLUUID& id,
							U32 timestamp, 
							const U8* binary_bucket,
							S32 binary_bucket_size)
{
	pack_instant_message(
		gMessageSystem,
		gAgent.getID(),
		FALSE,
		gAgent.getSessionID(),
		to_id,
		name,
		message,
		offline,
		dialog,
		id,
		0,
		LLUUID::null,
		gAgent.getPositionAgent(),
		timestamp,
		binary_bucket,
		binary_bucket_size);
	gAgent.sendReliableMessage();
}


void send_places_query(const LLUUID& query_id,
					   const LLUUID& trans_id,
					   const char* query_text,
					   U32 query_flags,
					   S32 category,
					   const char* sim_name)
{
	LLMessageSystem* msg = gMessageSystem;

	msg->newMessage("PlacesQuery");
	msg->nextBlock("AgentData");
	msg->addUUID("AgentID", gAgent.getID());
	msg->addUUID("SessionID", gAgent.getSessionID());
	msg->addUUID("QueryID", query_id);
	msg->nextBlock("TransactionData");
	msg->addUUID("TransactionID", trans_id);
	msg->nextBlock("QueryData");
	msg->addString("QueryText", query_text);
	msg->addU32("QueryFlags", query_flags);
	msg->addS8("Category", (S8)category);
	msg->addString("SimName", sim_name);
	gAgent.sendReliableMessage();
}


void process_user_info_reply(LLMessageSystem* msg, void**)
{
	LLUUID agent_id;
	msg->getUUIDFast(_PREHASH_AgentData, _PREHASH_AgentID, agent_id);
	if(agent_id != gAgent.getID())
	{
		llwarns << "process_user_info_reply - "
				<< "wrong agent id." << llendl;
	}
	
	BOOL im_via_email;
	msg->getBOOLFast(_PREHASH_UserData, _PREHASH_IMViaEMail, im_via_email);
	char email[DB_USER_EMAIL_ADDR_BUF_SIZE];		/* Flawfinder: ignore */
	msg->getStringFast(_PREHASH_UserData, _PREHASH_EMail, DB_USER_EMAIL_ADDR_BUF_SIZE,
					   email);
	char dir_visibility[MAX_STRING];			/* Flawfinder: ignore */	
	msg->getString(
		"UserData", "DirectoryVisibility", MAX_STRING, dir_visibility);

	LLFloaterPreference::updateUserInfo(dir_visibility, im_via_email, email);
	LLFloaterPostcard::updateUserInfo(email);
}


//---------------------------------------------------------------------------
// Script Dialog
//---------------------------------------------------------------------------

const S32 SCRIPT_DIALOG_MAX_BUTTONS = 12;
const S32 SCRIPT_DIALOG_BUTTON_STR_SIZE = 24;
const S32 SCRIPT_DIALOG_MAX_MESSAGE_SIZE = 512;
const char* SCRIPT_DIALOG_HEADER = "Script Dialog:\n";

struct ScriptDialogInfo
{
	LLHost mSender;
	LLUUID mObjectID;
	S32 mChatChannel;
	std::vector<LLString> mButtons;
};

void callback_script_dialog(S32 option, void* data)
{
	ScriptDialogInfo* info = (ScriptDialogInfo*)data;
	if (!info) return;

	// Didn't click "Ignore"
	if (0 != option)
	{
		LLMessageSystem* msg = gMessageSystem;
		msg->newMessage("ScriptDialogReply");
		msg->nextBlock("AgentData");
		msg->addUUID("AgentID", gAgent.getID());
		msg->addUUID("SessionID", gAgent.getSessionID());
		msg->nextBlock("Data");
		msg->addUUID("ObjectID", info->mObjectID);
		msg->addS32("ChatChannel", info->mChatChannel);
		msg->addS32("ButtonIndex", option);
		msg->addString("ButtonLabel", info->mButtons[option-1]);
		msg->sendReliable(info->mSender);
	}

	delete info;
}

void process_script_dialog(LLMessageSystem* msg, void**)
{
	S32 i;

	ScriptDialogInfo* info = new ScriptDialogInfo;

	const S32 messageLength = SCRIPT_DIALOG_MAX_MESSAGE_SIZE + sizeof(SCRIPT_DIALOG_HEADER);
	char message[messageLength]; 		/* Flawfinder: ignore */		// Account for size of "Script Dialog:\n"

	char first_name[DB_FIRST_NAME_BUF_SIZE];		/* Flawfinder: ignore */
	char last_name[DB_GROUP_NAME_BUF_SIZE];		/* Flawfinder: ignore */
	char title[DB_INV_ITEM_NAME_BUF_SIZE];		/* Flawfinder: ignore */
	info->mSender = msg->getSender();

	msg->getUUID("Data", "ObjectID", info->mObjectID);
	msg->getString("Data", "FirstName", DB_FIRST_NAME_BUF_SIZE, first_name);
	msg->getString("Data", "LastName", DB_LAST_NAME_BUF_SIZE, last_name);
	msg->getString("Data", "ObjectName", DB_INV_ITEM_NAME_BUF_SIZE, title);
	msg->getString("Data", "Message", SCRIPT_DIALOG_MAX_MESSAGE_SIZE, message);
	msg->getS32("Data", "ChatChannel", info->mChatChannel);

		// unused for now
	LLUUID image_id;
	msg->getUUID("Data", "ImageID", image_id);

	S32 button_count = msg->getNumberOfBlocks("Buttons");
	if (button_count > SCRIPT_DIALOG_MAX_BUTTONS)
	{
		button_count = SCRIPT_DIALOG_MAX_BUTTONS;
	}

	for (i = 0; i < button_count; i++)
	{
		char tdesc[SCRIPT_DIALOG_BUTTON_STR_SIZE+1];		/* Flawfinder: ignore */
		msg->getString("Buttons", "ButtonLabel", SCRIPT_DIALOG_BUTTON_STR_SIZE + 1,  tdesc, i);
		info->mButtons.push_back(LLString(tdesc));
	}

	LLStringBase<char>::format_map_t args;
	args["[TITLE]"] = title;
	args["[MESSAGE]"] = message;
	if (strlen(first_name) > 0)		/* Flawfinder: ignore */
	{
		args["[FIRST]"] = first_name;
		args["[LAST]"] = last_name;
		LLNotifyBox::showXml("ScriptDialog", args,
							 callback_script_dialog, info,
							 info->mButtons,
							 TRUE);
	}
	else
	{
		args["[GROUPNAME]"] = last_name;
		LLNotifyBox::showXml("ScriptDialogGroup", args,
							 callback_script_dialog, info,
							 info->mButtons,
							 TRUE);
	}
}

//---------------------------------------------------------------------------

struct LoadUrlInfo
{
	LLUUID mObjectID;
	LLUUID mOwnerID;
	BOOL mOwnerIsGroup;
	char mObjectName[256];		/* Flawfinder: ignore */
	char mMessage[256];		/* Flawfinder: ignore */
	char mUrl[256];		/* Flawfinder: ignore */
};

std::vector<LoadUrlInfo*> gLoadUrlList;

void callback_load_url(S32 option, void* data)
{
	LoadUrlInfo* infop = (LoadUrlInfo*)data;
	if (!infop) return;

	if (0 == option)
	{
		LLWeb::loadURL(infop->mUrl);  
	}

	delete infop;
	infop = NULL;
}


// We've got the name of the person who owns the object hurling the url.
// Display confirmation dialog.
void callback_load_url_name(const LLUUID& id, const char* first, const char* last, BOOL is_group, void* data)
{
	std::vector<LoadUrlInfo*>::iterator it;
	for (it = gLoadUrlList.begin(); it != gLoadUrlList.end(); )
	{
		LoadUrlInfo* infop = *it;
		if (infop->mOwnerID == id)
		{
			it = gLoadUrlList.erase(it);

			std::string owner_name(first);
			if (is_group)
			{
				owner_name += " (group)";
			}
			else
			{
				owner_name += " ";
				owner_name += last;
			}

			// TODO: Talk to james about using an id instead of a name for this.
			if (gMuteListp->isMuted(LLUUID::null, owner_name))
			{
				delete infop;
				infop = NULL;
				continue;
			}
			LLString::format_map_t args;
			args["[URL]"] = infop->mUrl;
			args["[MESSAGE]"] = infop->mMessage;
			args["[OBJECTNAME]"] = infop->mObjectName;
			args["[NAME]"] = owner_name;
			LLNotifyBox::showXml("LoadWebPage", args, callback_load_url, infop);
		}
		else
		{
			++it;
		}
	}
}

void process_load_url(LLMessageSystem* msg, void**)
{
	LoadUrlInfo* infop = new LoadUrlInfo;

	msg->getString("Data", "ObjectName", 256, infop->mObjectName);
	msg->getUUID(  "Data", "ObjectID", infop->mObjectID);
	msg->getUUID(  "Data", "OwnerID", infop->mOwnerID);
	msg->getBOOL(  "Data", "OwnerIsGroup", infop->mOwnerIsGroup);
	msg->getString("Data", "Message", 256, infop->mMessage);
	msg->getString("Data", "URL", 256, infop->mUrl);

	// URL is safety checked in load_url above

	// Check if object or owner is muted
	if (gMuteListp->isMuted(infop->mObjectID, infop->mObjectName))
	{
		delete infop;
		infop = NULL;
		return;
	}

	// Add to list of pending name lookups
	gLoadUrlList.push_back(infop);

	gCacheName->get(infop->mOwnerID, infop->mOwnerIsGroup, callback_load_url_name);
}


void callback_download_complete(void** data, S32 result, LLExtStat ext_status)
{
	LLString* filepath = (LLString*)data;
	LLString::format_map_t args;
	args["[DOWNLOAD_PATH]"] = *filepath;
	gViewerWindow->alertXml("FinishedRawDownload", args);
	delete filepath;
}


void process_initiate_download(LLMessageSystem* msg, void**)
{
	LLUUID agent_id;
	msg->getUUID("AgentData", "AgentID", agent_id);
	if (agent_id != gAgent.getID())
	{
		llwarns << "Initiate download for wrong agent" << llendl;
		return;
	}

	char sim_filename[MAX_PATH];		/* Flawfinder: ignore */
	char viewer_filename[MAX_PATH];		/* Flawfinder: ignore */
	msg->getString("FileData", "SimFilename", MAX_PATH, sim_filename);
	msg->getString("FileData", "ViewerFilename", MAX_PATH, viewer_filename);

	gXferManager->requestFile(viewer_filename,
		sim_filename,
		LL_PATH_NONE,
		msg->getSender(),
		FALSE,	// don't delete remote
		callback_download_complete,
		(void**)new LLString(viewer_filename));
}


void process_script_teleport_request(LLMessageSystem* msg, void**)
{
	char object_name[256];	/* Flawfinder: ignore */		
	char sim_name[256];		/* Flawfinder: ignore */
	LLVector3 pos;
	LLVector3 look_at;

	msg->getString("Data", "ObjectName", 255, object_name);
	msg->getString(  "Data", "SimName", 255, sim_name);
	msg->getVector3("Data", "SimPosition", pos);
	msg->getVector3("Data", "LookAt", look_at);

	gFloaterWorldMap->trackURL(sim_name, (U32)pos.mV[VX], (U32)pos.mV[VY], (U32)pos.mV[VZ]);
	LLFloaterWorldMap::show(NULL, TRUE);
}

void process_covenant_reply(LLMessageSystem* msg, void**)
{
	LLUUID covenant_id, estate_owner_id;
	char estate_name[MAX_STRING];		/* Flawfinder: ignore */
	U32 covenant_timestamp;
	msg->getUUID("Data", "CovenantID", covenant_id);
	msg->getU32("Data", "CovenantTimestamp", covenant_timestamp);
	msg->getString("Data", "EstateName", MAX_STRING, estate_name);
	msg->getUUID("Data", "EstateOwnerID", estate_owner_id);

	LLPanelEstateCovenant::updateEstateName(estate_name);
	LLPanelLandCovenant::updateEstateName(estate_name);
	LLFloaterBuyLand::updateEstateName(estate_name);

	// standard message, not from system
	char last_modified[MAX_STRING];		/* Flawfinder: ignore */
	last_modified[0] = '\0';
	char time_buf[TIME_STR_LENGTH];		/* Flawfinder: ignore */
	snprintf(last_modified, MAX_STRING, "Last Modified %s",		/* Flawfinder: ignore */
	formatted_time((time_t)covenant_timestamp, time_buf));

	LLPanelEstateCovenant::updateLastModified(last_modified);
	LLPanelLandCovenant::updateLastModified(last_modified);
	LLFloaterBuyLand::updateLastModified(last_modified);

	gCacheName->getName(estate_owner_id, callbackCacheEstateOwnerName);
	
	// load the actual covenant asset data
	const BOOL high_priority = TRUE;
	if (covenant_id.notNull())
	{
		gAssetStorage->getEstateAsset(gAgent.getRegionHost(),
									gAgent.getID(),
									gAgent.getSessionID(),
									covenant_id,
                                    LLAssetType::AT_NOTECARD,
									ET_Covenant,
                                    onCovenantLoadComplete,
									NULL,
									high_priority);
	}
	else
	{
		std::string covenant_text;
		if (estate_owner_id.isNull())
		{
			// mainland
			covenant_text = "There is no Covenant provided for this Estate.";
		}
		else
		{
			covenant_text = "There is no Covenant provided for this Estate. The land on this estate is being sold by the Estate owner, not Linden Lab.  Please contact the Estate Owner for sales details.";
		}
		LLPanelEstateCovenant::updateCovenantText(covenant_text, covenant_id);
		LLPanelLandCovenant::updateCovenantText(covenant_text);
		LLFloaterBuyLand::updateCovenantText(covenant_text, covenant_id);
	}
}

void callbackCacheEstateOwnerName(
		const LLUUID& id,
		const char* first,
		const char* last,
		BOOL is_group,
		void*)
{
	std::string name;
	
	if (id.isNull())
	{
		name = "(none)";
	}
	else
	{
		name = first;
		name += " ";
		name += last;
	}
	LLPanelEstateCovenant::updateEstateOwnerName(name);
	LLPanelLandCovenant::updateEstateOwnerName(name);
	LLFloaterBuyLand::updateEstateOwnerName(name);
}

void onCovenantLoadComplete(LLVFS *vfs,
					const LLUUID& asset_uuid,
					LLAssetType::EType type,
					void* user_data, S32 status, LLExtStat ext_status)
{
	llinfos << "onCovenantLoadComplete()" << llendl;
	std::string covenant_text;
	if(0 == status)
	{
		LLVFile file(vfs, asset_uuid, type, LLVFile::READ);
		
		S32 file_length = file.getSize();
		
		char* buffer = new char[file_length+1];
		if (buffer == NULL)
		{
			llerrs << "Memory Allocation failed" << llendl;
			return;
		}

		file.read((U8*)buffer, file_length);		/* Flawfinder: ignore */
		
		// put a EOS at the end
		buffer[file_length] = 0;
		
		if( (file_length > 19) && !strncmp( buffer, "Linden text version", 19 ) )
		{
			LLViewerTextEditor* editor =
				new LLViewerTextEditor("temp",
						       LLRect(0,0,0,0),
						       file_length+1);
			if( !editor->importBuffer( buffer ) )
			{
				llwarns << "Problem importing estate covenant." << llendl;
				covenant_text = "Problem importing estate covenant.";
			}
			else
			{
				// Version 0 (just text, doesn't include version number)
				covenant_text = editor->getText();
			}
			delete[] buffer;
			delete editor;
		}
		else
		{
			llwarns << "Problem importing estate covenant: Covenant file format error." << llendl;
			covenant_text = "Problem importing estate covenant: Covenant file format error.";
		}
	}
	else
	{
		if( gViewerStats )
		{
			gViewerStats->incStat( LLViewerStats::ST_DOWNLOAD_FAILED );
		}
		
		if( LL_ERR_ASSET_REQUEST_NOT_IN_DATABASE == status ||
		    LL_ERR_FILE_EMPTY == status)
		{
			covenant_text = "Estate covenant notecard is missing from database.";
		}
		else if (LL_ERR_INSUFFICIENT_PERMISSIONS == status)
		{
			covenant_text = "Insufficient permissions to view estate covenant.";
		}
		else
		{
			covenant_text = "Unable to load estate covenant at this time.";
		}
		
		llwarns << "Problem loading notecard: " << status << llendl;
	}
	LLPanelEstateCovenant::updateCovenantText(covenant_text, asset_uuid);
	LLPanelLandCovenant::updateCovenantText(covenant_text);
	LLFloaterBuyLand::updateCovenantText(covenant_text, asset_uuid);
}


void process_feature_disabled_message(LLMessageSystem* msg, void**)
{
	// Handle Blacklisted feature simulator response...
	LLUUID	agentID;
	LLUUID	transactionID;
	char	messageText[MAX_STRING];		/* Flawfinder: ignore */
	msg->getStringFast(_PREHASH_FailureInfo,_PREHASH_ErrorMessage,MAX_STRING,&messageText[0],0);
	msg->getUUIDFast(_PREHASH_FailureInfo,_PREHASH_AgentID,agentID);
	msg->getUUIDFast(_PREHASH_FailureInfo,_PREHASH_TransactionID,transactionID);
	
	llwarns << "Blacklisted Feature Response:" << &messageText[0] << llendl;
}

// ------------------------------------------------------------
// Message system exception callbacks
// ------------------------------------------------------------

void invalid_message_callback(LLMessageSystem* msg,
								   void*,
								   EMessageException exception)
{
	bad_network_handler();
}

// Please do not add more message handlers here. This file is huge.
// Put them in a file related to the functionality you are implementing. JC