aboutsummaryrefslogtreecommitdiffstatshomepage
path: root/linden/indra/newview/rlvhandler.cpp
blob: 2915002b9138e8cde3d96d85f3c8a6fa95cea983 (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
#include "llviewerprecompiledheaders.h"
#include "llagent.h"
#include "lldrawpoolalpha.h"
#include "llfloaterbeacons.h"
#include "llfloaterchat.h"
#include "llfloaterdaycycle.h"
#include "llfloaterenvsettings.h"
#include "llfloatergodtools.h"
#include "llfloaterland.h"
#include "llfloatermap.h"
#include "llfloaterregioninfo.h"
#include "llfloatertools.h"
#include "llfloaterwater.h"
#include "llfloaterwindlight.h"
#include "llfloaterworldmap.h"
#include "llgesturemgr.h"
#include "llinventoryview.h"
#include "llstartup.h"
#include "llviewermenu.h"
#include "llviewermessage.h"
#include "llviewerparcelmgr.h"
#include "llviewerregion.h"
#include "llviewerwindow.h"
#include "llvoavatar.h"
#include "llworld.h"
#include "pipeline.h"

#include "rlvhelper.h"
#include "rlvevent.h"
#include "rlvextensions.h"
#include "rlvhandler.h"

// Only defined in llinventorybridge.cpp
#if RLV_TARGET < RLV_MAKE_TARGET(1, 23, 0)			// Version: 1.22.11
	#include "llinventorybridge.h"
	void confirm_replace_attachment_rez(S32 option, void* user_data);
#endif
// Only defined in llinventorymodel.cpp
extern const char* NEW_CATEGORY_NAME;

// ============================================================================
// Static variable initialization
//

BOOL RlvHandler::m_fEnabled = FALSE;
BOOL RlvHandler::fNoSetEnv = FALSE;
BOOL RlvHandler::fLegacyNaming = FALSE;
BOOL RlvHandler::m_fFetchStarted = FALSE;
BOOL RlvHandler::m_fFetchComplete = FALSE;
RlvMultiStringSearch RlvHandler::m_AttachLookup;

const std::string RlvHandler::cstrSharedRoot = RLV_ROOT_FOLDER;

// Keep these consistent with regular RLV
const std::string RlvHandler::cstrBlockedRecvIM = "*** IM blocked by your viewer";
const std::string RlvHandler::cstrBlockedSendIM = "*** IM blocked by sender's viewer";
const std::string RlvHandler::cstrHidden = "(Hidden)";
const std::string RlvHandler::cstrHiddenParcel = "(Hidden parcel)";
const std::string RlvHandler::cstrHiddenRegion = "(Hidden region)";
const std::string RlvHandler::cstrMsgRecvIM = 
	"The Resident you messaged is prevented from reading your instant messages at the moment, please try again later.";
const std::string RlvHandler::cstrMsgTpLure = 
	"The Resident you invited is prevented from accepting teleport offers. Please try again later.";

const std::string RlvHandler::cstrAnonyms[] =
{
	"A resident", "This resident", "That resident", "An individual", "This individual", "That individual", "A person",
	"This person", "That person", "A stranger", "This stranger", "That stranger", "A human being", "This human being", 
	"That human being", "An agent", "This agent", "That agent", "A soul", "This soul", "That soul", "Somebody", 
	"Some people", "Someone", "Mysterious one", "An unknown being", "Unidentified one", "An unknown person"
};

rlv_handler_t gRlvHandler;

// ============================================================================
// Helper functions
//

// Checked: 2009-07-12 (RLVa-1.0.0h) | Added: RLVa-0.2.0e
inline bool rlvIsWearingItem(const LLInventoryItem* pItem)
{
	return 
		((LLAssetType::AT_OBJECT == pItem->getType()) && (gAgent.getAvatarObject()->isWearingAttachment(pItem->getUUID()))) ||
		((LLAssetType::AT_GESTURE == pItem->getType()) && (gGestureManager.isGestureActive(pItem->getUUID()))) ||
		(gAgent.isWearingItem(pItem->getUUID()));
}

// ============================================================================
// Command specific helper functions
//

// Checked: 2009-08-04 (RLVa-1.0.1d) | Added: RLVa-1.0.1d
static bool rlvParseNotifyOption(const std::string& strOption, S32& nChannel, std::string& strFilter)
{
	boost_tokenizer tokens(strOption, boost::char_separator<char>(";", "", boost::keep_empty_tokens));
	boost_tokenizer::iterator itTok = tokens.begin();

	// Extract and sanity check the first token (required) which is the channel
	if ( (itTok == tokens.end()) || (!LLStringUtil::convertToS32(*itTok, nChannel)) || (!rlvIsValidChannel(nChannel)) )
		return false;

	// Second token (optional) is the filter
	strFilter.clear();
	if (++itTok != tokens.end())
	{
		strFilter = *itTok;
		++itTok;
	}

	return (itTok == tokens.end());
}

// ============================================================================
// Constructor/destructor
//

// Checked: 2009-08-04 (RLVa-1.0.1d) | Modified: RLVa-1.0.1d
RlvHandler::RlvHandler() 
	: m_fCanCancelTp(false), m_idCurObject(LLUUID::null), m_pCurCommand(NULL), m_pGCTimer(NULL), m_pWLSnapshot(NULL), m_pBhvrNotify(NULL)
{
	// Array auto-initialization to 0 is non-standard? (Compiler warning in VC-8.0)
	memset(m_LayersAdd, 0, sizeof(S16) * WT_COUNT);
	memset(m_LayersRem, 0, sizeof(S16) * WT_COUNT);
	memset(m_Behaviours, 0, sizeof(S16) * RLV_BHVR_COUNT);
}

// Checked: 2009-08-04 (RLVa-1.0.1d) | Modified: RLVa-1.0.1d
RlvHandler::~RlvHandler()
{
	//delete m_pGCTimer;	// <- deletes itself
	delete m_pWLSnapshot;	// <- delete on NULL is harmless
	delete m_pBhvrNotify;
}

// ============================================================================
// Attachment related functions 
//

// Checked: 2009-07-12 (RLVa-1.0.0h) | Modified: RLVa-0.2.0d
inline LLViewerJointAttachment* RlvHandler::getAttachPoint(const std::string& strText, bool fExact) const
{
	LLVOAvatar* pAvatar = gAgent.getAvatarObject();
	return (pAvatar) ? get_if_there(pAvatar->mAttachmentPoints, getAttachPointIndex(strText, fExact), (LLViewerJointAttachment*)NULL)
	                 : NULL;
}

// Checked: 2009-07-29 (RLVa-1.0.1b) | Modified: RLVa-1.0.1b
LLViewerJointAttachment* RlvHandler::getAttachPoint(const LLInventoryCategory* pFolder, bool /*fStrict*/) const
{
	if (!pFolder)
		return NULL;

	// RLVa-1.0.1 added support for legacy matching (See http://rlva.catznip.com/blog/2009/07/attachment-point-naming-convention/)
	if (fLegacyNaming)
		return getAttachPointLegacy(pFolder);

	// Otherwise the only valid way to specify an attachment point in a folder name is: ^\.\(\s+attachpt\s+\)
	std::string::size_type idxMatch;
	std::string strAttachPt = rlvGetFirstParenthesisedText(pFolder->getName(), &idxMatch);
	LLStringUtil::trim(strAttachPt);

	return ( (1 == idxMatch) && (RLV_FOLDER_PREFIX_HIDDEN == pFolder->getName().at(0)) ) ? getAttachPoint(strAttachPt, true) : NULL;
}

// Checked: 2009-07-29 (RLVa-1.0.1b) | Modified: RLVa-1.0.1b
LLViewerJointAttachment* RlvHandler::getAttachPoint(const LLInventoryItem* pItem, bool fStrict) const
{
	// Sanity check - if it's not an object then it can't have an attachment point
	if ( (!pItem) || (LLAssetType::AT_OBJECT != pItem->getType()) )
		return NULL;

	// The attachment point should be placed at the end of the item's name, surrounded by parenthesis
	// (if there is no such text then strAttachPt will be an empty string which is fine since it means we'll look at the item's parent)
	std::string strAttachPt = rlvGetLastParenthesisedText(pItem->getName());
	LLStringUtil::trim(strAttachPt);

	// If the item is modify   : we look at the item's name first and only then at the containing folder
	// If the item is no modify: we look at the containing folder's name first and only then at the item itself
	LLViewerJointAttachment* pAttachPt;
	if (pItem->getPermissions().allowModifyBy(gAgent.getID()))
	{
		pAttachPt = (!strAttachPt.empty()) ? getAttachPoint(strAttachPt, true) : NULL;
		if (!pAttachPt)
			pAttachPt = getAttachPoint(gInventory.getCategory(pItem->getParentUUID()), fStrict);
	}
	else
	{
		pAttachPt = getAttachPoint(gInventory.getCategory(pItem->getParentUUID()), fStrict);
		if ( (!pAttachPt) && (!strAttachPt.empty()) )
			pAttachPt = getAttachPoint(strAttachPt, true);
	}
	return pAttachPt;
}

// Checked: 2009-07-12 (RLVa-1.0.0h) | Added: RLVa-0.2.2a
S32 RlvHandler::getAttachPointIndex(const LLViewerJointAttachment* pAttachPt) const
{
	LLVOAvatar* pAvatar = gAgent.getAvatarObject();
	if (pAvatar)
	{
		for (LLVOAvatar::attachment_map_t::const_iterator itAttach = pAvatar->mAttachmentPoints.begin(); 
				itAttach != pAvatar->mAttachmentPoints.end(); ++itAttach)
		{
			if (itAttach->second == pAttachPt)
				return itAttach->first;
		}
	}
	return 0;
}

// Checked: 2009-07-29 (RLVa-1.0.1b) | Added: RLVa-1.0.1b
LLViewerJointAttachment* RlvHandler::getAttachPointLegacy(const LLInventoryCategory* pFolder) const
{
	// Hopefully some day this can just be deprecated (see http://rlva.catznip.com/blog/2009/07/attachment-point-naming-convention/)
	if ( (!pFolder) || (pFolder->getName().empty()) )
		return NULL;

	// Check for a (...) block *somewhere* in the name
	std::string::size_type idxMatch;
	std::string strAttachPt = rlvGetFirstParenthesisedText(pFolder->getName(), &idxMatch);
	if (!strAttachPt.empty())
	{
		// Could be "(attachpt)", ".(attachpt)" or "Folder name (attachpt)"
		if ( (0 != idxMatch) && ((1 != idxMatch) || (RLV_FOLDER_PREFIX_HIDDEN == pFolder->getName().at(0)) ) &&	// No '(' or '.(' start
			 (idxMatch + strAttachPt.length() + 1 != pFolder->getName().length()) )								// or there's extra text
		{
			// It's definitely not one of the first two so assume it's the last form (in which case we need the last paranthesised block)
			strAttachPt = rlvGetLastParenthesisedText(pFolder->getName());
		}
	}
	else
	{
		// There's no paranthesised block, but it could still be "attachpt" or ".attachpt" (just strip away the '.' from the last one)
		strAttachPt = pFolder->getName();
		if (RLV_FOLDER_PREFIX_HIDDEN == strAttachPt[0])
			strAttachPt.erase(0, 1);
	}
	return getAttachPoint(strAttachPt, true);
}

bool RlvHandler::hasLockedHUD() const
{
	LLVOAvatar* pAvatar = gAgent.getAvatarObject();
	if (!pAvatar)
		return false;
	
	LLViewerJointAttachment* pAttachPt;
	for (rlv_detach_map_t::const_iterator itAttachPt = m_Attachments.begin(); itAttachPt != m_Attachments.end(); ++itAttachPt)
	{
		pAttachPt = get_if_there(pAvatar->mAttachmentPoints, (S32)itAttachPt->first, (LLViewerJointAttachment*)NULL);
		if ( (pAttachPt) && (pAttachPt->getIsHUDAttachment()) )
			return true;	// At least one of our locked attachments is a HUD
	}
	return false;			// None of our locked attachments is a HUD
}

bool RlvHandler::isDetachable(const LLInventoryItem* pItem) const
{
	LLVOAvatar* pAvatar = gAgent.getAvatarObject();
	return ( (pItem) && (pAvatar) ) ? isDetachable(pAvatar->getWornAttachment(pItem->getUUID())) : true;
}

// Checked: 2009-08-11 (RLVa-1.0.1h) | Added: RLVa-1.0.1h
bool RlvHandler::isDetachableExcept(S32 idxAttachPt, LLViewerObject *pObj) const
{
	// Loop over every object that marked the specific attachment point undetachable (but ignore pObj and any of its children)
	for (rlv_detach_map_t::const_iterator itAttach = m_Attachments.lower_bound(idxAttachPt), 
		endAttach = m_Attachments.upper_bound(idxAttachPt); itAttach != endAttach; ++itAttach)
	{
		LLViewerObject* pTempObj = gObjectList.findObject(itAttach->second);
		if ( (!pTempObj) || (pTempObj->getRootEdit()->getID() != pObj->getID()) )
			return false;
	}
	return true;
}

// Checked: 2009-05-31 (RLVa-0.2.0e) | Modified: RLVa-0.2.0e
bool RlvHandler::setDetachable(S32 idxAttachPt, const LLUUID& idRlvObj, bool fDetachable)
{
	// Sanity check - make sure it's an object we know about
	rlv_object_map_t::const_iterator itObj = m_Objects.find(idRlvObj);
	if ( (itObj == m_Objects.end()) || (!idxAttachPt) )
		return false;	// If (idxAttachPt) == 0 then: (pObj == NULL) || (pObj->isAttachment() == FALSE)

	if (!fDetachable)
	{
		// Sanity check - make sure it's not already marked undetachable by this object (NOTE: m_Attachments is a *multimap*, not a map)
		for (rlv_detach_map_t::const_iterator itAttach = m_Attachments.lower_bound(idxAttachPt), 
				endAttach = m_Attachments.upper_bound(idxAttachPt); itAttach != endAttach; ++itAttach)
		{
			if (itObj->second.m_UUID == itAttach->second)
				return false;
		}

		m_Attachments.insert(std::pair<S32, LLUUID>(idxAttachPt, itObj->second.m_UUID));
		return true;
	}
	else
	{
		// NOTE: m_Attachments is a *multimap*, not a map
		for (rlv_detach_map_t::iterator itAttach = m_Attachments.lower_bound(idxAttachPt), 
				endAttach = m_Attachments.upper_bound(idxAttachPt); itAttach != endAttach; ++itAttach)
		{
			if (itObj->second.m_UUID == itAttach->second)
			{
				m_Attachments.erase(itAttach);
				return true;
			}
		}
	}
	return false;	// Fall-through for (fDetachable == TRUE) - if the object wasn't undetachable then we consider it a failure
}



#ifdef RLV_EXTENSION_FLAG_NOSTRIP
	// Checked: 2009-05-26 (RLVa-0.2.0d) | Modified: RLVa-0.2.0d
	bool RlvHandler::isStrippable(const LLUUID& idItem) const
	{
		// An item is exempt from @detach or @remoutfit if:
		//   - its name contains "nostrip" (anywhere in the name)
		//   - its parent folder contains "nostrip" (anywhere in the name)
		if (idItem.notNull())
		{
			LLViewerInventoryItem* pItem = gInventory.getItem(idItem);
			if (pItem)
			{
				if (-1 != pItem->getName().find(RLV_FOLDER_FLAG_NOSTRIP))
					return false;

				LLViewerInventoryCategory* pFolder = gInventory.getCategory(pItem->getParentUUID());
				if ( (pFolder) && (-1 != pFolder->getName().find(RLV_FOLDER_FLAG_NOSTRIP)) )
					return false;
			}
		}
		return true;
	}
#endif // RLV_EXTENSION_FLAG_NOSTRIP

// ============================================================================
// Behaviour related functions
//

bool RlvHandler::hasBehaviourExcept(const std::string& strBehaviour, const LLUUID& idObj) const
{
	for (rlv_object_map_t::const_iterator itObj = m_Objects.begin(); itObj != m_Objects.end(); ++itObj)
		if ( (idObj != itObj->second.m_UUID) && (itObj->second.hasBehaviour(strBehaviour)) )
			return true;
	return false;
}

bool RlvHandler::hasBehaviourExcept(ERlvBehaviour eBehaviour, const std::string& strOption, const LLUUID& idObj) const
{
	for (rlv_object_map_t::const_iterator itObj = m_Objects.begin(); itObj != m_Objects.end(); ++itObj)
		if ( (idObj != itObj->second.m_UUID) && (itObj->second.hasBehaviour(eBehaviour, strOption)) )
			return true;
	return false;
}

bool RlvHandler::hasBehaviourExcept(const std::string& strBehaviour, const std::string& strOption, const LLUUID& idObj) const
{
	for (rlv_object_map_t::const_iterator itObj = m_Objects.begin(); itObj != m_Objects.end(); ++itObj)
		if ( (idObj != itObj->second.m_UUID) && (itObj->second.hasBehaviour(strBehaviour, strOption)) )
			return true;
	return false;
}

// ============================================================================
// Command processing functions
//

// Checked: 2009-06-03 (RLVa-0.2.0h)
void RlvHandler::addBehaviourObserver(RlvBehaviourObserver* pBhvrObserver)
{
	std::list<RlvBehaviourObserver*>::iterator itBhvrObserver = std::find(m_BhvrObservers.begin(), m_BhvrObservers.end(), pBhvrObserver);
	if (itBhvrObserver == m_BhvrObservers.end())
		m_BhvrObservers.push_back(pBhvrObserver);
}

// Checked: 2009-06-03 (RLVa-0.2.0h)
void RlvHandler::removeBehaviourObserver(RlvBehaviourObserver* pBhvrObserver)
{
	std::list<RlvBehaviourObserver*>::iterator itBhvrObserver = std::find(m_BhvrObservers.begin(), m_BhvrObservers.end(), pBhvrObserver);
	if (itBhvrObserver != m_BhvrObservers.end())
		m_BhvrObservers.erase(itBhvrObserver);
}

// Checked: 2009-06-03 (RLVa-0.2.0h)
void RlvHandler::notifyBehaviourObservers(const RlvCommand& rlvCmd, bool fInternal)
{
	for (std::list<RlvBehaviourObserver*>::const_iterator itBhvrObserver = m_BhvrObservers.begin();
		itBhvrObserver != m_BhvrObservers.end(); ++itBhvrObserver)
	{
		(*itBhvrObserver)->changed(rlvCmd, fInternal);
	}
}

// Checked:
BOOL RlvHandler::processCommand(const LLUUID& uuid, const std::string& strCmd, bool fFromObj)
{
	#ifdef RLV_DEBUG
		RLV_INFOS << "[" << uuid << "]: " << strCmd << LL_ENDL;
	#endif // RLV_DEBUG

	RlvCommand rlvCmd(strCmd);
	if (!rlvCmd.isValid())
	{
		#ifdef RLV_DEBUG
			RLV_INFOS << "\t-> invalid command: " << strCmd << LL_ENDL;
		#endif // RLV_DEBUG
		return FALSE;
	}
	m_pCurCommand = &rlvCmd; m_idCurObject = uuid;

	BOOL fRet = FALSE;
	switch (rlvCmd.getParamType())
	{
		case RLV_TYPE_ADD:		// Checked: 2009-06-03 (RLVa-0.2.0h) | Modified: RLVa-0.2.0h
			{
				if ( (m_Behaviours[rlvCmd.getBehaviourType()]) && 
					 ( (RLV_BHVR_SETDEBUG == rlvCmd.getBehaviourType()) || (RLV_BHVR_SETENV == rlvCmd.getBehaviourType()) ) )
				{
					// Some restrictions can only be held by one single object to avoid deadlocks
					#ifdef RLV_DEBUG
						RLV_INFOS << "\t- " << rlvCmd.getBehaviour() << " is already set by another object => discarding" << LL_ENDL;
					#endif // RLV_DEBUG
					break;
				}

				rlv_object_map_t::iterator itObj = m_Objects.find(uuid);
				if (itObj != m_Objects.end())
				{
					RlvObject& rlvObj = itObj->second;
					fRet = rlvObj.addCommand(rlvCmd);
				}
				else
				{
					RlvObject rlvObj(uuid);
					fRet = rlvObj.addCommand(rlvCmd);
					m_Objects.insert(std::pair<LLUUID, RlvObject>(uuid, rlvObj));
				}

				#ifdef RLV_DEBUG
					RLV_INFOS << "\t- " << ( (fRet) ? "adding behaviour" : "skipping duplicate") << LL_ENDL;
				#endif // RLV_DEBUG

				if (fRet) {	// If FALSE then this was a duplicate, there's no need to handle those
					if (!m_pGCTimer)
						m_pGCTimer = new RlvGCTimer();
					processAddCommand(uuid, rlvCmd);
					notifyBehaviourObservers(rlvCmd, !fFromObj);
				}
			}
			break;
		case RLV_TYPE_REMOVE:		// Checked:
			{
				rlv_object_map_t::iterator itObj = m_Objects.find(uuid);
				if (itObj != m_Objects.end())
					fRet = itObj->second.removeCommand(rlvCmd);

				#ifdef RLV_DEBUG
					RLV_INFOS << "\t- " << ( (fRet) ? "removing behaviour"
						                            : "skipping remove (unset behaviour or unknown object)") << LL_ENDL;
				#endif // RLV_DEBUG

				if (fRet) {	// Don't handle non-sensical removes
					processRemoveCommand(uuid, rlvCmd);
					notifyBehaviourObservers(rlvCmd, !fFromObj);

					if (0 == itObj->second.m_Commands.size())
					{
						#ifdef RLV_DEBUG
							RLV_INFOS << "\t- command list empty => removing " << uuid << LL_ENDL;
						#endif // RLV_DEBUG
						m_Objects.erase(itObj);
					}
				}
			}
			break;
		case RLV_TYPE_FORCE:		// Checked:
			fRet = processForceCommand(uuid, rlvCmd);
			break;
		case RLV_TYPE_REPLY:		// Checked:
			fRet = processReplyCommand(uuid, rlvCmd);
			break;
		case RLV_TYPE_UNKNOWN:		// Checked:
			{
				if ("clear" == rlvCmd.getBehaviour())
				{
					const std::string& strFilter = rlvCmd.getParam(); std::string strCmdRem;

					rlv_object_map_t::const_iterator itObj = m_Objects.find(uuid);
					if (itObj != m_Objects.end())	// No sense in @clear'ing if we don't have any commands for this object
					{
						const RlvObject& rlvObj = itObj->second; bool fContinue = true;
						for (rlv_command_list_t::const_iterator itCmd = rlvObj.m_Commands.begin(), itCurCmd; 
								((fContinue) && (itCmd != rlvObj.m_Commands.end())); )
						{
							itCurCmd = itCmd++;		// Point itCmd ahead so it won't get invalidated if/when we erase a command

							const RlvCommand& rlvCmdRem = *itCurCmd;
							if ( (strFilter.empty()) || (-1 != rlvCmdRem.asString().find(strFilter)) )
							{
								fContinue = (rlvObj.m_Commands.size() > 1); // rlvObj will become invalid once we remove the last command
								strCmdRem = rlvCmdRem.getBehaviour() + ":" + rlvCmdRem.getOption() + "=y";
								processCommand(uuid, strCmdRem, false);
							}
						}
						fRet = TRUE;
					}
				}
			}
			break;
		#ifdef LL_GNUC
		default:
			break;
		#endif // LL_GNUC
	}

	#ifdef RLV_DEBUG
		RLV_INFOS << "\t--> command " << ((fRet) ? "succeeded" : "failed") << LL_ENDL;
	#endif // RLV_DEBUG

	m_pCurCommand = NULL; m_idCurObject.setNull();
	return fRet;
}

BOOL RlvHandler::processAddCommand(const LLUUID& uuid, const RlvCommand& rlvCmd)
{
	// NOTE: - at this point the command has already been added to the corresponding RlvObject instance
	//       - the object's UUID may or may not exist in gObjectList (see handling of @detach=n)

	ERlvBehaviour eBehaviour = rlvCmd.getBehaviourType();
	const std::string& strOption = rlvCmd.getOption();

	if ( (RLV_BHVR_UNKNOWN != eBehaviour) && (strOption.empty()) )
		m_Behaviours[eBehaviour]++;

	switch (eBehaviour)
	{
		case RLV_BHVR_DETACH:				// @detach[:<option>]=n		- Checked: 2009-08-04 (RLVa-1.0.1d) | Modified: RLVa-1.0.1d
			{
				LLViewerObject* pObj = NULL; S32 idxAttachPt = 0;
				if (strOption.empty())													// @detach=n
				{
					// If the object rezzed before we received @detach=n from it then we can just do our thing here
					// If the object hasn't rezzed yet then we need to wait until RlvHandler::onAttach()
					// If @detach=n were possible for non-attachments another copy/paste would be needed in RlvHandler::onGC()
					if ((pObj = gObjectList.findObject(uuid)) != NULL)
						setDetachable(pObj, uuid, false);
				} 
				else if ((idxAttachPt = getAttachPointIndex(strOption, true)) != 0)		// @detach:<attachpt>=n
				{
					setDetachable(idxAttachPt, uuid, false);

					// (See below)
					LLViewerJointAttachment* pAttachPt = getAttachPoint(strOption, true);
					if (pAttachPt)
						pObj = pAttachPt->getObject();
				}

				// When at least one HUD attachment is locked we want to make sure they're all visible (ie prevent hiding a blindfold HUD)
				// However, since @detach:<attachpt>=n might lock a HUD attachment point that doesn't currently have an object we
				// have to do this here *and* in RlvHandler::onAttach()
				if ( (pObj) && (pObj->isHUDAttachment()) )
					LLPipeline::sShowHUDAttachments = TRUE;
			}
			break;
		case RLV_BHVR_REDIRCHAT:			// @redirchat:<option>=n	- Checked: 2009-07-07 (RLVa-1.0.0d)
		case RLV_BHVR_REDIREMOTE:			// @rediremote:<option>=n	- Checked: 2009-07-07 (RLVa-1.0.0d) | Added: RLVa-0.2.2a
			{
				if (!strOption.empty())
					m_Behaviours[eBehaviour]++;	// @redirchat and @rediremote don't have an optionless version so keep track of it here
				else
					m_Behaviours[eBehaviour]--;	// @redirchat=n and @rediremote=n are undefined, don't keep track of them
			}
			break;
		case RLV_BHVR_SHOWWORLDMAP:			// @showworldmap=n			- Checked: 2009-07-05 (RLVa-1.0.0c)
			{
				// Simulate clicking the Map button [see LLToolBar::onClickMap()]
				if (gFloaterWorldMap->getVisible())
					LLFloaterWorldMap::toggle(NULL);
			}
			break;
		case RLV_BHVR_SHOWMINIMAP:			// @showminimap=n			- Checked: 2009-07-05 (RLVa-1.0.0c)
			{
				// Simulate clicking the Minimap button [see LLToolBar::onClickRadar()]
				if (LLFloaterMap::instanceVisible())
						LLFloaterMap::hideInstance();
			}
			break;
		#ifdef RLV_EXTENSION_STARTLOCATION
		case RLV_BHVR_TPLOC:				// @tploc=n					- Checked: 2009-07-08 (RLVa-1.0.0e) | Added: RLVa-0.2.1d
		case RLV_BHVR_UNSIT:				// @unsit=n					- Checked: 2009-07-08 (RLVa-1.0.0e) | Added: RLVa-0.2.1d
			{
				if (strOption.empty())
					RlvSettings::updateLoginLastLocation();
			}
			break;
		#endif // RLV_EXTENSION_STARTLOCATION
		case RLV_BHVR_EDIT:					// @edit=n					- Checked: 2009-07-04 (RLVa-1.0.0b)
			{
				// Turn off "View / Highlight Transparent"
				LLDrawPoolAlpha::sShowDebugAlpha = FALSE;

				// Close the Beacons floater if it's open
				if (LLFloaterBeacons::instanceVisible())
					LLFloaterBeacons::toggleInstance();

				// Get rid of the build floater if it's open [copy/paste from toggle_build_mode()]
				if (gFloaterTools->getVisible())
				{
					gAgent.resetView(FALSE);
					gFloaterTools->close();
					gViewerWindow->showCursor();
				}
			}
			break;
		case RLV_BHVR_ADDOUTFIT:			// @addoutfit[:<layer>]=n	- Checked: 2009-07-07 (RLVa-1.0.0d)
		case RLV_BHVR_REMOUTFIT:			// @remoutfit[:<layer>]=n	- Checked: 2009-07-07 (RLVa-1.0.0d)
			{
				S16* pLayers = (eBehaviour == RLV_BHVR_ADDOUTFIT) ? m_LayersAdd : m_LayersRem;

				if (strOption.empty())
				{
					for (int idx = 0; idx < WT_COUNT; idx++)
						pLayers[idx]++;
				}
				else
				{
					EWearableType type = LLWearable::typeNameToType(strOption);
					if (WT_INVALID != type)
					{
						pLayers[type]++;
						m_Behaviours[eBehaviour]++;
					}
				}
			}
			break;
		case RLV_BHVR_SHOWINV:				// @showinv=n				- Checked: 2009-07-10 (RLVa-1.0.0g) | Modified: RLVa-1.0.0g
			{
				// Close all open inventory windows
				LLInventoryView::closeAll();
			}
			break;
		case RLV_BHVR_SHOWLOC:				// @showloc=n				- Checked: 2009-07-09 (RLVa-1.0.0f) | Modified: RLVa-1.0.0f
			{
				// If we're the first @showloc=n restriction refresh all object text so we can filter it if necessary
				if (1 == m_Behaviours[RLV_BHVR_SHOWLOC])
					LLHUDText::refreshAllObjectText();

				// Close the "About Land" floater if it's currently visible
				if (LLFloaterLand::instanceVisible())
					LLFloaterLand::hideInstance();

				// Close the "Estate Tools" floater is it's currently visible
				if (LLFloaterRegionInfo::instanceVisible())
					LLFloaterRegionInfo::hideInstance();

				// NOTE: we should close the "God Tools" floater as well, but since calling LLFloaterGodTools::instance() always
				//       creates a new instance of the floater and since it's very unlikely to be open it's just better not to
			}
			break;
		case RLV_BHVR_SHOWNAMES:			// @shownames=n				- Checked: 2009-07-09 (RLVa-1.0.0f) | Modified: RLVa-1.0.0f
			{
				// If we're the first @shownames=n restriction refresh all object text so we can filter it if necessary
				if (1 == m_Behaviours[RLV_BHVR_SHOWNAMES])
					LLHUDText::refreshAllObjectText();

				// Close the "Active Speakers" panel if it's currently visible
				LLFloaterChat::getInstance()->childSetVisible("active_speakers_panel", false);
			}
			break;
		case RLV_BHVR_FLY:					// @fly=n					- Checked: 2009-07-05 (RLVa-1.0.0c)
			{
				// If currently flying, simulate clicking the Fly button [see LLToolBar::onClickFly()]
				if (gAgent.getFlying())
					gAgent.toggleFlying();
			}
			break;
		case RLV_BHVR_SETENV:				// @setenv=n				- Checked: 2009-07-10 (RLVa-1.0.0g) | Modified: RLVa-0.2.0a
			{
				if (!fNoSetEnv)
				{
					// Only close the floaters if their instance exists and they're actually visible
					if ( (LLFloaterEnvSettings::isOpen()) && (LLFloaterEnvSettings::instance()->getVisible()) )
						LLFloaterEnvSettings::instance()->close();
					if ( (LLFloaterWindLight::isOpen()) && (LLFloaterWindLight::instance()->getVisible()) )
						LLFloaterWindLight::instance()->close();
					if ( (LLFloaterWater::isOpen()) && (LLFloaterWater::instance()->getVisible()) )
						LLFloaterWater::instance()->close();
					if ( (LLFloaterDayCycle::isOpen()) && (LLFloaterDayCycle::instance()->getVisible()) )
						LLFloaterDayCycle::instance()->close();

					// Save the current WindLight params so we can restore them on @setenv=y
					if (m_pWLSnapshot)
					{
						RLV_ERRS << "m_pWLSnapshot != NULL" << LL_ENDL; // Safety net in case we set @setenv=n for more than 1 object
						delete m_pWLSnapshot;
					}
					m_pWLSnapshot = RlvWLSnapshot::takeSnapshot();
				}
			}
			break;
		case RLV_BHVR_SHOWHOVERTEXTALL:		// @showhovertextal=n		- Checked: 2009-07-09 (RLVa-1.0.0f) | Modified: RLVa-1.0.0f
		case RLV_BHVR_SHOWHOVERTEXTWORLD:	// @showhovertextworld=n	- Checked: 2009-07-09 (RLVa-1.0.0f) | Modified: RLVa-1.0.0f
		case RLV_BHVR_SHOWHOVERTEXTHUD:		// @showhovertexthud=n		- Checked: 2009-07-09 (RLVa-1.0.0f) | Modified: RLVa-1.0.0f
			{
				// Refresh all hover text (LLHUDText::setStringUTF8() will decide what needs clearing and what doesn't)
				LLHUDText::refreshAllObjectText();
			}
			break;
		case RLV_BHVR_SHOWHOVERTEXT:		// @showhovertext:<uuid>=n	- Checked: 2009-07-09 (RLVa-0.2.2a) | Modified: RLVa-1.0.0f
			{
				LLUUID idException(strOption);
				if (!idException.isNull())	// If there's an option it should be a valid UUID
				{
					addException(eBehaviour, LLUUID(strOption));

					// Clear the object's hover text
					LLViewerObject* pObj = gObjectList.findObject(idException);
					if ( (pObj) && (pObj->mText.notNull()) && (!pObj->mText->getObjectText().empty()) )
						pObj->mText->setStringUTF8("");
				}
			}
			break;
		case RLV_BHVR_NOTIFY:				// @notify:<option>=add		- Checked: 2009-08-04 (RLVa-1.0.1d) | Modified: RLVa-1.0.1d
			{
				S32 nChannel; std::string strFilter;
				if ( (!strOption.empty()) && (rlvParseNotifyOption(strOption, nChannel, strFilter)) )
				{
					if (!m_pBhvrNotify)
						addBehaviourObserver(m_pBhvrNotify = new RlvBehaviourNotifyObserver());
					m_pBhvrNotify->addNotify(uuid, nChannel, strFilter);
				}
			}
			break;
		case RLV_BHVR_RECVCHAT:				// @recvchat:<uuid>=add		- Checked: 2009-07-09 (RLVa-1.0.0f) | Modified: RLVa-1.0.0f
		case RLV_BHVR_RECVEMOTE:			// @recvemote:<uuid>=add	- Checked: 2009-07-09 (RLVa-1.0.0f) | Modified: RLVa-1.0.0f
		case RLV_BHVR_RECVIM:				// @recvim:<uuid>=add		- Checked: 2009-07-09 (RLVa-1.0.0f) | Modified: RLVa-1.0.0f
		case RLV_BHVR_SENDIM:				// @sendim:<uuid>=add		- Checked: 2009-07-09 (RLVa-1.0.0f) | Modified: RLVa-1.0.0f
		case RLV_BHVR_TPLURE:				// @tplure:<uuid>=add		- Checked: 2009-07-09 (RLVa-1.0.0f) | Modified: RLVa-1.0.0f
		case RLV_BHVR_ACCEPTTP:				// @accepttp:<uuid>=add		- Checked: 2009-07-09 (RLVa-1.0.0f) | Modified: RLVa-1.0.0f
			{
				addException(eBehaviour, LLUUID(strOption));
			}
			break;
		default:
			{
				// Give our observers a chance to handle any command we don't
				RlvEvent rlvEvent(uuid, rlvCmd);
				m_Emitter.update(&RlvObserver::onAddCommand, rlvEvent);
			}
			break;
	}
	return TRUE; // Add command success/failure is decided by RlvObject::addCommand()
}

// Checked: 2009-08-05 (RLVa-1.0.1e) | Added: RLVa-1.0.1e
void RlvHandler::processRetainedCommands()
{
	for (rlv_retained_list_t::const_iterator itCmd = m_Retained.begin(); itCmd != m_Retained.end(); ++itCmd)
	{
		const RlvRetainedCommand& cmd = *itCmd;
		processCommand(cmd.idObject, cmd.strCmd, true);
	}
	m_Retained.clear();
}

BOOL RlvHandler::processRemoveCommand(const LLUUID& uuid, const RlvCommand& rlvCmd)
{
	// NOTE: - the RlvObject instance still exists at this point, but the viewer might already have removed it from its object list
	ERlvBehaviour eBehaviour = rlvCmd.getBehaviourType();
	const std::string& strOption = rlvCmd.getOption();

	if ( (RLV_BHVR_UNKNOWN != eBehaviour) && (strOption.empty()) )
		m_Behaviours[eBehaviour]--;

	switch (eBehaviour)
	{
		case RLV_BHVR_DETACH:				// @detach[:<option>]=y		- Checked: 2009-08-04 (RLVa-1.0.1d) | Modified: RLVa-1.0.1d
			{
				S32 idxAttachPt;
				if (strOption.empty())												// @detach=y
				{
					// The object may or may not (if it got detached) still exist so clean up the hard way
					if (m_Objects.find(uuid) != m_Objects.end())
					{
						for (rlv_detach_map_t::const_iterator itAttach = m_Attachments.begin(), endAttach = m_Attachments.end();
							itAttach != endAttach; ++itAttach)
						{
							if (itAttach->second == uuid)
							{
								setDetachable(itAttach->first, uuid, true); // <- invalidates our iterators on return
								break;
							}
						}
					}
				}
				else if ((idxAttachPt = getAttachPointIndex(strOption, true)))		// @detach:<attachpt>=y
				{
					setDetachable(idxAttachPt, uuid, true);
				}
			}
			break;
		case RLV_BHVR_REDIRCHAT:			// @redirchat:<option>=y	- Checked: 2009-07-07 (RLVa-1.0.0d)
		case RLV_BHVR_REDIREMOTE:			// @rediremote:<option>=y	- Checked: 2009-07-07 (RLVa-1.0.0d) | Added: RLVa-0.2.2a
			{
				if (!strOption.empty())
					m_Behaviours[eBehaviour]--;	// @redirchat and @rediremote don't have an optionless version so keep track of it here
				else
					m_Behaviours[eBehaviour]++;	// @redirchat=n and @rediremote=n are undefined, don't keep track of them
			}
			break;
		#ifdef RLV_EXTENSION_STARTLOCATION
		case RLV_BHVR_TPLOC:				// @tploc=y					- Checked: 2009-07-08 (RLVa-1.0.0e) | Added: RLVa-0.2.1d
		case RLV_BHVR_UNSIT:				// @unsit=y					- Checked: 2009-07-08 (RLVa-1.0.0e) | Added: RLVa-0.2.1d
			{
				if (strOption.empty())
					RlvSettings::updateLoginLastLocation();
			}
			break;
		#endif // RLV_EXTENSION_STARTLOCATION
		case RLV_BHVR_ADDOUTFIT:			// @addoutfit[:<layer>]=y	- Checked: 2009-07-07 (RLVa-1.0.0d)
		case RLV_BHVR_REMOUTFIT:			// @remoutfit[:<layer>]=y	- Checked: 2009-07-07 (RLVa-1.0.0d)
			{
				S16* pLayers = (eBehaviour == RLV_BHVR_ADDOUTFIT) ? m_LayersAdd : m_LayersRem;

				if (strOption.empty())
				{
					for (int idx = 0; idx < WT_COUNT; idx++)
						pLayers[idx]--;
				}
				else
				{
					EWearableType type = LLWearable::typeNameToType(strOption);
					if (WT_INVALID != type)
					{
						pLayers[type]--;
						m_Behaviours[eBehaviour]--;
					}
				}
			}
			break;
		case RLV_BHVR_SETENV:				// @setenv=y				- Checked: 2009-07-10 (RLVa-1.0.0g) | Added: RLVa-0.2.0h
			{
				if (!fNoSetEnv)
				{
					// Restore WindLight parameters to what they were before @setenv=n was issued
					RlvWLSnapshot::restoreSnapshot(m_pWLSnapshot);
					delete m_pWLSnapshot;
					m_pWLSnapshot = NULL;
				}
			}
			break;
		case RLV_BHVR_SHOWLOC:				// @showloc=y				- Checked: 2009-07-09 (RLVa-1.0.0f) | Added: RLVa-1.0.0f
		case RLV_BHVR_SHOWNAMES:			// @shownames=y				- Checked: 2009-07-09 (RLVa-1.0.0f) | Added: RLVa-1.0.0f
		case RLV_BHVR_SHOWHOVERTEXTALL:		// @showhovertextal=y		- Checked: 2009-07-09 (RLVa-1.0.0f) | Added: RLVa-1.0.0f
		case RLV_BHVR_SHOWHOVERTEXTWORLD:	// @showhovertextworld=y	- Checked: 2009-07-09 (RLVa-1.0.0f) | Added: RLVa-1.0.0f
		case RLV_BHVR_SHOWHOVERTEXTHUD:		// @showhovertexthud=y		- Checked: 2009-07-09 (RLVa-1.0.0f) | Added: RLVa-1.0.0f
			{
				// If this was the last of any of the five restrictions we should refresh all hover text in case anything needs restoring
				if (!m_Behaviours[eBehaviour])
					LLHUDText::refreshAllObjectText();
			}
			break;
		case RLV_BHVR_SHOWHOVERTEXT:		// @showhovertext:<uuid>=y	- Checked: 2009-07-09 (RLVa-1.0.0f) | Modified: RLVa-1.0.0f
			{
				LLUUID idException(strOption);
				if (!idException.isNull())	// If there's an option it should be a valid UUID
				{
					removeException(eBehaviour, LLUUID(strOption));

					// Restore the object's hover text
					LLViewerObject* pObj = gObjectList.findObject(idException);
					if ( (pObj) && (pObj->mText.notNull()) && (!pObj->mText->getObjectText().empty()) )
						pObj->mText->setStringUTF8(pObj->mText->getObjectText());
				}
			}
			break;
		case RLV_BHVR_NOTIFY:				// @notify:<option>=rem		- Checked: 2009-08-04 (RLVa-1.0.1d) | Modified: RLVa-1.0.1d
			{
				S32 nChannel; std::string strFilter;
				if ( (m_pBhvrNotify) && (!strOption.empty()) && (rlvParseNotifyOption(strOption, nChannel, strFilter)) )
				{
					m_pBhvrNotify->removeNotify(uuid, nChannel, strFilter);

					if (!m_pBhvrNotify->hasNotify())
					{
						removeBehaviourObserver(m_pBhvrNotify);
						delete m_pBhvrNotify;
						m_pBhvrNotify = NULL;
					}
				}
			}
			break;
		case RLV_BHVR_RECVCHAT:				// @recvchat:<uuid>=rem		- Checked: 2009-07-09 (RLVa-1.0.0f) | Modified: RLVa-1.0.0f
		case RLV_BHVR_RECVEMOTE:			// @recvemote:<uui>=red		- Checked: 2009-07-09 (RLVa-1.0.0f) | Modified: RLVa-1.0.0f
		case RLV_BHVR_RECVIM:				// @recvim:<uuid>=rem		- Checked: 2009-07-09 (RLVa-1.0.0f) | Modified: RLVa-1.0.0f
		case RLV_BHVR_SENDIM:				// @sendim:<uuid>=rem		- Checked: 2009-07-09 (RLVa-1.0.0f) | Modified: RLVa-1.0.0f
		case RLV_BHVR_TPLURE:				// @recvim:<uuid>=rem		- Checked: 2009-07-09 (RLVa-1.0.0f) | Modified: RLVa-1.0.0f
		case RLV_BHVR_ACCEPTTP:				// @accepttp:<uuid>=rem		- Checked: 2009-07-09 (RLVa-1.0.0f) | Modified: RLVa-1.0.0f
			{
				removeException(eBehaviour, LLUUID(strOption));
			}
			break;
		default:
			{
				// Give our observers a chance to handle any command we don't
				RlvEvent rlvEvent(uuid, rlvCmd);
				m_Emitter.update(&RlvObserver::onRemoveCommand, rlvEvent);
			}
			break;
	}
	return TRUE; // Remove commands don't fail, doesn't matter what we return here
}

BOOL RlvHandler::processForceCommand(const LLUUID& idObj, const RlvCommand& rlvCmd) const
{
	const std::string& strOption = rlvCmd.getOption();
	BOOL fHandled = TRUE;

	switch (rlvCmd.getBehaviourType())
	{
		case RLV_BHVR_DETACH:		// @detach[:<option>]=force		- Checked:
			onForceDetach(idObj, strOption);
			break;
		case RLV_BHVR_REMOUTFIT:	// @remoutfit:<option>=force	- Checked:
			onForceRemOutfit(idObj, strOption);
			break;
		case RLV_BHVR_UNSIT:		// @unsit=force					- Checked: 2009-06-02 (RLVa-0.2.0g)
			{
				LLVOAvatar* pAvatar = gAgent.getAvatarObject();
				if ( (pAvatar) && (pAvatar->mIsSitting) && (!hasBehaviourExcept(RLV_BHVR_UNSIT, idObj)) )
				{
					// See behaviour notes on why we have to force an agent update here
					gAgent.setControlFlags(AGENT_CONTROL_STAND_UP);
					send_agent_update(TRUE, TRUE);
				}
			}
			break;
		case RLV_BHVR_TPTO:			// @tpto:<option>=force			- Checked: 2009-07-12 (RLVa-1.0.0h) | Modified: RLVa-1.0.0h
			{
				fHandled = FALSE;
				if ( (!strOption.empty()) && (-1 == strOption.find_first_not_of("0123456789/.")) )
				{
					LLVector3d posGlobal;

					typedef boost::tokenizer<boost::char_separator<char> > tokenizer;
					boost::char_separator<char> sep("/", "", boost::keep_empty_tokens);
					tokenizer tokens(strOption, sep); int idx = 0;
					for (tokenizer::iterator itToken = tokens.begin(); itToken != tokens.end(); ++itToken)
					{
						if (idx < 3)
							LLStringUtil::convertToF64(*itToken, posGlobal[idx++]);
					}

					if (idx == 3)
					{
						gAgent.teleportViaLocation(posGlobal);
						fHandled = TRUE;
					}
				} 
			}
			break;
		case RLV_BHVR_SIT:			// @sit:<option>=force			- Checked: 2009-06-02 (RLVa-0.2.0g)
			fHandled = onForceSit(idObj, rlvCmd.getOption());
			break;
		case RLV_BHVR_ADDOUTFIT:	// @addoutfit:<option>=force <- synonym of @attach:<option>=force
		case RLV_BHVR_ATTACH:		// @attach:<option>=force		- Checked:
			onForceWear(rlvCmd.getOption(), true, false);	// Force attach single folder
			break;
		case RLV_BHVR_ATTACHALL:	// @attachall:<option>=force	- Checked:
			onForceWear(rlvCmd.getOption(), true, true);	// Force attach nested folders
			break;
		case RLV_BHVR_DETACHALL:	// @detachall:<option>=force	- Checked:
			onForceWear(rlvCmd.getOption(), false, true);	// Force detach nested folders
			break;
		case RLV_BHVR_ATTACHTHIS:
		case RLV_BHVR_ATTACHALLTHIS:
		case RLV_BHVR_DETACHTHIS:
		case RLV_BHVR_DETACHALLTHIS:
			{
				ERlvBehaviour eBehaviour = rlvCmd.getBehaviourType();
				std::string strReply;
				if (onGetPath(idObj, strOption, strReply))
				{
					LLStringUtil::toLower(strReply);
					onForceWear(strReply, 
						(RLV_BHVR_ATTACHTHIS == eBehaviour) || (RLV_BHVR_ATTACHALLTHIS == eBehaviour), 
						(RLV_BHVR_ATTACHALLTHIS == eBehaviour) || (RLV_BHVR_DETACHALLTHIS == eBehaviour));
				}
			}
			break;
		case RLV_BHVR_DETACHME:		// @detachme=force				- Checked: 2009-06-07 (RLVa-0.2.1c)
			{
				// NOTE: @detachme=force could be seen as a @detach:<attachpt>=force but RLV implements it as a "detach by UUID"
				LLViewerObject* pObj; LLVOAvatar* pAvatar; LLViewerJointAttachment* pAttachPt;
				if ( ((pObj = gObjectList.findObject(idObj)) != NULL) && (pObj->isAttachment()) && 
					 ((pAvatar = gAgent.getAvatarObject()) != NULL) && 
					 ((pAttachPt = pAvatar->getTargetAttachmentPoint(pObj->getRootEdit())) != NULL) )
				{
					handle_detach_from_avatar(pAttachPt);
				}
			}
			break;
		default:
			{
				// Give our observers a chance to handle any command we don't
				RlvEvent rlvEvent(idObj, rlvCmd);
				fHandled = m_Emitter.update(&RlvObserver::onForceCommand, rlvEvent);
			}
			break;
	}
	return fHandled; // If we handled it then it'll still be TRUE; if an observer doesn't handle it'll be FALSE
}

// Checked: 2009-07-12 (RLVa-1.0.0h)
BOOL RlvHandler::processReplyCommand(const LLUUID& uuid, const RlvCommand& rlvCmd) const
{
	const std::string& strOption = rlvCmd.getOption();
	const std::string& strChannel = rlvCmd.getParam();
	std::string strReply;

	BOOL fHandled = TRUE;
	switch (rlvCmd.getBehaviourType())
	{
		case RLV_BHVR_VERSION:			// @version=<channel>				  - Checked: 2009-07-12 (RLVa-1.0.0h)
			strReply = getVersionString();
			break;
		case RLV_BHVR_GETOUTFIT:		// @getoufit[:<layer>]=<channel>	  - Checked: 2009-07-12 (RLVa-1.0.0h) | Modified: RLVa-0.2.0d
			{
				// (Quirk: RLV 1.16.1 will execute @getoutfit=<channel> if <layer> is invalid, so we need to as well)
				EWearableType layerType = LLWearable::typeNameToType(strOption);

				const EWearableType layerTypes[] =
					{ 
						WT_GLOVES, WT_JACKET, WT_PANTS, WT_SHIRT, WT_SHOES, WT_SKIRT, WT_SOCKS, 
						WT_UNDERPANTS, WT_UNDERSHIRT, WT_SKIN, WT_EYES, WT_HAIR, WT_SHAPE
					};

				#ifdef RLV_EXPERIMENTAL_COMPOSITE_FOLDING
					for (int idx = 0, cnt = sizeof(layerTypes) / sizeof(EWearableType); idx < cnt; idx++)
					{
						if ( (WT_INVALID == layerType) || (layerTypes[idx] == layerType) )
						{
							// TODO-RLVa: add support for 'fHideLockedLayers'
							bool fWorn = (gAgent.getWearable(layerTypes[idx])) && 
										 (!isHiddenCompositeItem(gAgent.getWearableItem(layerTypes[idx]), 
																 LLWearable::typeToTypeName(layerTypes[idx])));
							strReply.push_back( (fWorn) ? '1' : '0' );
						}
					}
				#else
					for (int idx = 0, cnt = sizeof(layerTypes) / sizeof(EWearableType); idx < cnt; idx++)
						if ( (WT_INVALID == layerType) || (layerTypes[idx] == layerType) )
						{
							// We never hide body parts, even if they're "locked" and we're hiding locked layers
							// (nor do we hide a layer if the issuing object is the only one that has this layer locked)
							bool fWorn = (gAgent.getWearable(layerTypes[idx])) && 
								( (!RlvSettings::getHideLockedLayers()) || 
								  (LLAssetType::AT_BODYPART == LLWearable::typeToAssetType(layerTypes[idx])) ||
								  ( (isRemovableExcept(layerTypes[idx], uuid)) && 
								    (isStrippable(gAgent.getWearableItem(layerTypes[idx]))) ) );
							strReply.push_back( (fWorn) ? '1' : '0' );
							//strReply.push_back( (gAgent.getWearable(layerTypes[idx])) ? '1' : '0' );
						}
				#endif // RLV_EXPERIMENTAL_COMPOSITE_FOLDING
			}
			break;
		case RLV_BHVR_GETATTACH:		// @getattach[:<layer>]=<channel>	  - Checked: 2009-07-12 (RLVa-1.0.0h) | Modified: RLVa-0.2.0d
			{
				// If we're fetching all worn attachments then the reply should start with 0
				if (strOption.empty())
					strReply.push_back('0');

				LLVOAvatar* pAvatar = gAgent.getAvatarObject(); std::string strAttachName;
				for (LLVOAvatar::attachment_map_t::const_iterator itAttach = pAvatar->mAttachmentPoints.begin(); 
					 itAttach != pAvatar->mAttachmentPoints.end(); ++itAttach)
				{
					LLViewerJointAttachment* pAttachment = itAttach->second;
					if (!pAttachment)
						continue;

					strAttachName = pAttachment->getName(); // Capitalized (see avatar_lad.xml)
					LLStringUtil::toLower(strAttachName);

					#ifdef RLV_EXPERIMENTAL_COMPOSITE_FOLDING
						if ( (strOption.empty()) || (strOption == strAttachName) )
						{
							// TODO-RLVa: add support for 'fHideLockedAttach'
							bool fWorn = (pAttachment->getItemID().notNull()) && 
										 (!isHiddenCompositeItem(pAttachment->getItemID(), strAttachName));
							strReply.push_back( (fWorn) ? '1' : '0' );
						}
					#else
						if ( (strOption.empty()) || (strOption == strAttachName) )
						{
							bool fWorn = (pAttachment->getItemID().notNull()) && 
								( (!RlvSettings::getHideLockedAttach()) || 
								  ( (isDetachable(itAttach->first)) && (isStrippable(pAttachment->getItemID())) ) );
							strReply.push_back( (fWorn) ? '1' : '0' );
							//strReply.push_back( (pAttachment->getItemID().notNull()) ? '1' : '0' );
						}
					#endif // RLV_EXPERIMENTAL_COMPOSITE_FOLDING
				}
			}
			break;
		case RLV_BHVR_GETSTATUS:		// @getstatus[:<option>]=<channel>	  - Checked: 2009-07-12 (RLVa-1.0.0h)
			{
				// NOTE: specification says response should start with '/' but RLV-1.16.1 returns an empty string when no rules are set
				rlv_object_map_t::const_iterator itObj = m_Objects.find(uuid);
				if (itObj != m_Objects.end())
				{
					std::string strObjStatus = itObj->second.getStatusString(strOption);
					if (!strObjStatus.empty())
					{
						strReply.push_back('/');
						strReply += strObjStatus;
					}
				}
			}
			break;
		case RLV_BHVR_GETSTATUSALL:		// @getstatusall[:<option>]=<channel> - Checked: 2009-07-12 (RLVa-1.0.0h)
			{
				// NOTE: specification says response should start with '/' but RLV-1.16.1 returns an empty string when no rules are set
				std::string strObjStatus;
				for (rlv_object_map_t::const_iterator itObj = m_Objects.begin(); itObj != m_Objects.end(); ++itObj)
				{
					strObjStatus = itObj->second.getStatusString(strOption);
					if (!strObjStatus.empty())
					{
						strReply.push_back('/');
						strReply += strObjStatus;
					}
				}
			}
			break;
		case RLV_BHVR_GETINV:			// @getinv[:<path>]=<channel>		  - Checked: 2009-07-28 (RLVa-1.0.1b) | Modified: RLVa-1.0.1b
			{
				LLViewerInventoryCategory* pFolder = getSharedFolder(strOption);
				if (pFolder)
				{
					LLInventoryModel::cat_array_t*  pFolders;
					LLInventoryModel::item_array_t* pItems;
					gInventory.getDirectDescendentsOf(pFolder->getUUID(), pFolders, pItems);

					if (pFolders)
					{
						for (S32 idxFolder = 0, cntFolder = pFolders->count(); idxFolder < cntFolder; idxFolder++)
						{
							const std::string& strFolder = pFolders->get(idxFolder)->getName();
							if ( (!strFolder.empty()) && (RLV_FOLDER_PREFIX_HIDDEN != strFolder[0]) &&
								 (!isFoldedFolder(pFolders->get(idxFolder).get(), true)) )
							{
								if (!strReply.empty())
									strReply.push_back(',');
								strReply += strFolder;
							}
						}
					}
				}
			}
			break;
		case RLV_BHVR_GETINVWORN:		// @getinvworn[:path]=<channel>		  - Checked:
			onGetInvWorn(rlvCmd.getOption(), strReply);
			break;
		case RLV_BHVR_FINDFOLDER:		// @findfolder:<criteria>=<channel>   - Checked: 2009-07-12 (RLVa-1.0.0h)
			{
				// COMPAT-RLV: RLV 1.16.1 returns the first random folder it finds (probably tries to match "" to a folder name?)
				//             (just going to stick with what's there for now... no option => no folder)
				LLInventoryModel::cat_array_t folders;
				if ( (!strOption.empty()) && (findSharedFolders(strOption, folders)) )
				{
					// We need to return an "in depth" result so whoever has the most '/' is our lucky winner
					int maxSlashes = 0, curSlashes; std::string strFolderName;
					for (S32 idxFolder = 0, cntFolder = folders.count(); idxFolder < cntFolder; idxFolder++)
					{
						strFolderName = getSharedPath(folders.get(idxFolder));

						curSlashes = std::count(strFolderName.begin(), strFolderName.end(), '/');
						if (curSlashes > maxSlashes)
						{
							maxSlashes = curSlashes;
							strReply = strFolderName;
						}
					}
				}
			}
			break;
		#ifdef RLV_EXTENSION_CMD_FINDFOLDERS
			case RLV_BHVR_FINDFOLDERS:	// @findfolders:<criteria>=<channel>  - Checked: 2009-07-12 (RLVa-1.0.0h) | Added: RLVa-0.2.0b
				{
					LLInventoryModel::cat_array_t folders;
					if ( (!strOption.empty()) && (findSharedFolders(strOption, folders)) )
					{
						for (S32 idxFolder = 0, cntFolder = folders.count(); idxFolder < cntFolder; idxFolder++)
						{
							if (!strReply.empty())
								strReply.push_back(',');
							strReply += getSharedPath(folders.get(idxFolder));
						}
					}
				}
				break;
		#endif // RLV_EXTENSION_CMD_FINDFOLDERS
		case RLV_BHVR_GETPATH:			// @getpath[:<option>]=<channel>	  - Checked: 2009-07-12 (RLVa-1.0.0h)
			onGetPath(uuid, rlvCmd.getOption(), strReply);
			break;
		case RLV_BHVR_GETSITID:			// @getsitid=<channel>				  - Checked: 2009-07-12 (RLVa-1.0.0h)
			{
				// (Quirk: RLV 1.16.1 returns a NULL uuid if we're not sitting)
				LLVOAvatar* pAvatarObj = gAgent.getAvatarObject(); LLUUID uuid;
				if ( (pAvatarObj) && (pAvatarObj->mIsSitting) )
				{
					// LLVOAvatar inherits from 2 classes so make sure we get the right vfptr
					LLViewerObject* pAvatar = dynamic_cast<LLViewerObject*>(pAvatarObj), *pParent;
					// (If there is a parent, we need to upcast it from LLXform to LLViewerObject to get its UUID)
					if ( (pAvatar) && ((pParent = static_cast<LLViewerObject*>(pAvatar->getRoot())) != pAvatar) )
						uuid = pParent->getID();
				}
				strReply = uuid.asString();
			}
			break;
		default:
			{
				// Give our observers a chance to handle any command we don't
				RlvEvent rlvEvent(uuid, rlvCmd);
				return m_Emitter.update(&RlvObserver::onReplyCommand, rlvEvent);
			}
			break;
	}

	if (fHandled)
		rlvSendChatReply(strChannel, strReply);
	return fHandled;
}

// ============================================================================
// House keeping (see debug notes for test methodology, test script and last run)
//

void RlvHandler::initLookupTables()
{
	static bool fInitialized = false;
	if (!fInitialized)
	{
		// Initialize the attachment name lookup table
		LLVOAvatar* pAvatar = gAgent.getAvatarObject();
		if (pAvatar)
		{
			std::string strAttachPtName;
			for (LLVOAvatar::attachment_map_t::const_iterator itAttach = pAvatar->mAttachmentPoints.begin(); 
					 itAttach != pAvatar->mAttachmentPoints.end(); ++itAttach)
			{
				LLViewerJointAttachment* pAttachPt = itAttach->second;
				if (pAttachPt)
				{
					strAttachPtName = pAttachPt->getName();
					LLStringUtil::toLower(strAttachPtName);
					m_AttachLookup.addKeyword(strAttachPtName, itAttach->first);
				}
			}
			fInitialized = true;
		}
	}
}

// Checked: 2009-08-11 (RLVa-1.0.1h) | Modified: RLVa-1.0.1h
void RlvHandler::onAttach(LLViewerJointAttachment* pAttachPt, bool fFullyLoaded)
{
	// Sanity check - LLVOAvatar::attachObject() should call us *after* calling LLViewerJointAttachment::addObject()
	LLViewerObject* pObj = pAttachPt->getObject();
	S32 idxAttachPt = getAttachPointIndex(pObj);	 // getAttachPointIndex() has a NULL pointer check so this is safe
	if ( (!pObj) || (!idxAttachPt) )
	{
		RLV_ERRS << "pAttachPt->getObject() == NULL" << LL_ENDL;
		return;
	}

	// Check if this attachment point has a pending "reattach-on-detach"
	rlv_reattach_map_t::iterator itReattach = m_AttachPending.find(idxAttachPt);
	if (itReattach != m_AttachPending.end())
	{
		if (itReattach->second == pAttachPt->getItemID())
		{
			RLV_INFOS << "Reattached " << pAttachPt->getItemID().asString() << " to " << idxAttachPt << LL_ENDL;
			m_AttachPending.erase(itReattach);
		}
	}
	else if ( (fFullyLoaded) && (!isDetachableExcept(idxAttachPt, pObj)) )
	{
		// We're fully loaded with no pending reattach on this attach point but it's "undetachable" -> force detach the new attachment

		// Assertion: the only way the attachment point could be locked at this point is if some object locked it with @detach:attachpt=n
		//   - previous attachments on this attachment point might have issued @detach=n but those were all cleaned up at detach
		//   - the new attachment might have issued @detach=n but that won't actually lock down the attachment point until further down
		// NOTE 1: "some object" may no longer exist if it was not an attachment and the GC hasn't cleaned it up yet (informative)
		// NOTE 2: "some object" may refer to the new attachment - ie @detach:spine=n from object on spine (problematic, causes reattach)
		//           -> solved by using isDetachableExcept(idxAttachPt, pObj) instead of isDetachable(idxAttachPt)

		m_DetachPending.insert(std::pair<S32, LLUUID>(idxAttachPt, pObj->getID()));
		rlvForceDetach(pAttachPt);
	}

	// Check if we already have an RlvObject instance for this object (rezzed prim attached from in-world, or an attachment that rezzed in)
	rlv_object_map_t::iterator itObj = m_Objects.find(pObj->getID());
	if (itObj != m_Objects.end())
	{
		// If it's an attachment we processed commands for but that only just rezzed in we need to mark it as existing in gObjectList
		if (!itObj->second.m_fLookup)
			itObj->second.m_fLookup = true;

		// In both cases we should check for "@detach=n" and actually lock down the attachment point it got attached to
		if (itObj->second.hasBehaviour(RLV_BHVR_DETACH))
		{
			// (Copy/paste from processAddCommand)
			setDetachable(pObj, pObj->getID(), false);

			if (pObj->isHUDAttachment())
				LLPipeline::sShowHUDAttachments = TRUE;	// Prevents hiding of locked HUD attachments
		}
	}

	// Fetch the inventory item if we don't currently have it since we might need it for reattach-on-detach
	const LLUUID& idItem = pAttachPt->getItemID();
	LLViewerInventoryItem* pItem = ( (idItem.notNull()) && (gInventory.isInventoryUsable()) ) ? gInventory.getItem(idItem) : NULL;
	if ( (STATE_STARTED == LLStartUp::getStartupState()) && (pItem != NULL) )
	{
		RlvCurrentlyWorn f;
		f.fetchItem(idItem);
	}

	// If what we're wearing is located under the shared root then append the attachment point name (if needed)
	LLViewerInventoryCategory* pRlvRoot = getSharedRoot();
	if ( (STATE_STARTED == LLStartUp::getStartupState()) && (pRlvRoot) && (pItem) && (pItem->isComplete()) &&
		 (gInventory.isObjectDescendentOf(idItem, pRlvRoot->getUUID())) )
	{
		std::string strAttachPt = pAttachPt->getName();
		LLStringUtil::toLower(strAttachPt);

		// If we can modify the item then it should contain the attach point name itself, otherwise its parent should
		if (pItem->getPermissions().allowModifyBy(gAgent.getID()))
		{
			if (!getAttachPoint(pItem, true))
			{
				// It doesn't specify an attach point and we can rename it [see LLItemBridge::renameItem()]
				std::string strName = pItem->getName();
				LLStringUtil::truncate(strName, DB_INV_ITEM_NAME_STR_LEN - strAttachPt.length() - 3);

				strName += " (" + strAttachPt + ")";

				pItem->rename(strName);
				pItem->updateServer(FALSE);
				gInventory.updateItem(pItem);
				//gInventory.notifyObservers(); <- done further down in LLVOAvatar::attachObject()
			}
		}
		else
		{
			// Folder can't be the shared root, or be its direct descendant (= nested at least 2 levels deep)
			LLViewerInventoryCategory* pFolder = gInventory.getCategory(pItem->getParentUUID());
			if ( (pFolder) && 
				 (pFolder->getUUID() != pRlvRoot->getUUID()) && (pFolder->getParentUUID() != pRlvRoot->getUUID()) && 
				 (!getAttachPoint(pFolder, true)) )
			{
				// It's no mod and its parent folder doesn't contain an attach point
				LLInventoryModel::cat_array_t*  pFolders;
				LLInventoryModel::item_array_t* pItems;
				gInventory.getDirectDescendentsOf(pFolder->getUUID(), pFolders, pItems);

				if (pItems)
				{
					int cntObjects = 0;
					for (S32 idxItem = 0, cntItem = pItems->size(); idxItem < cntItem; idxItem++)
					{
						if (LLAssetType::AT_OBJECT == pItems->get(idxItem)->getType())
							cntObjects++;
					}

					// Only rename if there's exactly 1 object/attachment inside of it [see LLFolderBridge::renameItem()]
					if ( (1 == cntObjects) && (NEW_CATEGORY_NAME == pFolder->getName()) )
					{
						std::string strName = ".(" + strAttachPt + ")";

						pFolder->rename(strName);
						pFolder->updateServer(FALSE);
						gInventory.updateCategory(pFolder);
						//gInventory.notifyObservers(); <- done further down in LLVOAvatar::attachObject()
					}
				}
			}
		}
	}
}

// Checked: 2009-05-31 (RLVa-0.2.0e) | Modified: RLVa-0.2.0e
void RlvHandler::onDetach(LLViewerJointAttachment* pAttachPt)
{
	LLViewerObject* pObj = pAttachPt->getObject();
	if (!pObj)
	{
		// LLVOAvatar::detachObject() should call us *before* calling LLViewerJointAttachment::removeObject()
		RLV_ERRS << "pAttachPt->getObject() == NULL" << LL_ENDL;
		return;
	}
	S32 idxAttachPt = getAttachPointIndex(pObj);
	if (0 == idxAttachPt)
	{
		// If we ended up here then the user "Drop"'ed this attachment (which we can't recover from)
		return;
	}

	#ifdef RLV_DEBUG
		// TODO-RLV: when we're exiting (for whatever reason) app state won't always reflect it but 
		//           gAgent.getAvatarObject()->mAttachmentPoints will be NULL so anywhere we use
		//			 "get_if_there" will call through a NULL pointer. One case is "idling out" -> test the rest
		//LLViewerJointAttachment* pDbgAttachmentPt = 
		//	get_if_there(gAgent.getAvatarObject()->mAttachmentPoints, (S32)idxAttachPt, (LLViewerJointAttachment*)NULL);
		//RLV_INFOS << "Clean up for '" << pDbgAttachmentPt->getName() << "'" << LL_ENDL;
	#endif // RLV_DEBUG

	// If the attachment was locked then we should reattach it (unless we're already trying to reattach to this attachment point)
	// (unless we forcefully detached it else in which case we do not want to reattach it)
	rlv_reattach_map_t::iterator itDetach = m_DetachPending.find(idxAttachPt);
	if (itDetach != m_DetachPending.end())
	{
		// RLVa-TODO: we should really be comparing item UUIDs but is it even possible to end up here and not have them match?
		m_DetachPending.erase(itDetach);
	}
	else if ( (!isDetachable(idxAttachPt)) && (m_AttachPending.find(idxAttachPt) == m_AttachPending.end()) )
	{
		// In an ideal world we would simply set up an LLInventoryObserver but there's no specific "asset updated" changed flag *sighs*
		// NOTE: attachments *always* know their "inventory item UUID" so we don't have to worry about fetched vs unfetched inventory
		m_AttachPending.insert(std::pair<S32, LLUUID>(idxAttachPt, pAttachPt->getItemID()));
	}

	// We can't - easily - clean up child prims that never issued @detach=n but the GC will get those eventually
	rlv_detach_map_t::iterator itAttach = m_Attachments.find(idxAttachPt);
	while ( (itAttach != m_Attachments.upper_bound(idxAttachPt)) && (itAttach != m_Attachments.end()) )
	{
		LLViewerObject* pTempObj = gObjectList.findObject(itAttach->second);
		if ( (pTempObj) && (pTempObj->getRootEdit()->getID() == pObj->getID()) )
		{
			// Iterator points to the object (or to a child prim) so issue a clear on behalf of the object (there's the 
			// possibility of going into an eternal loop, but that's ok since it indicates a bug in @clear that needs fixing)
			processCommand(itAttach->second, "clear", true);

			itAttach = m_Attachments.find(idxAttachPt); // @clear will invalidate all iterators so we have to start anew
		}
		else
		{
			itAttach++;
		}
	}

	// Clean up in case there was never a @detach=n (only works for the root prim - see above)
	rlv_object_map_t::iterator itObj = m_Objects.find(pObj->getID());
	if (itObj != m_Objects.end())
		processCommand(itObj->second.m_UUID, "clear", true);
}

// Checked: 2009-07-30 (RLVa-1.0.1c) | Modified: RLVa-1.0.1c
bool RlvHandler::onGC()
{
	// We can't issue @clear on an object while we're in the loop below since that would invalidate our iterator
	// (and starting over would mean that some objects might get their "lookup misses" counter updated more than once per GC run)
	std::list<LLUUID> ExpiredObjects;

	for (rlv_object_map_t::iterator itObj = m_Objects.begin(); itObj != m_Objects.end(); ++itObj)
	{
		LLViewerObject* pObj = gObjectList.findObject(itObj->second.m_UUID);
		if (!pObj)
		{
			// If the RlvObject once existed in the gObjectList and now doesn't then expire it right now
			// If the RlvObject never existed in the gObjectList and still doesn't then increase its "lookup misses" counter
			// but if that reaches 20 (we run every 30 seconds so that's about 10 minutes) then we'll expire it too
			if ( (itObj->second.m_fLookup) || (++itObj->second.m_nLookupMisses > 20) )
				ExpiredObjects.push_back(itObj->first);
		}
		else
		{
			// Check if this is an RlvObject instance who's object never existed in gObjectList before (rezzed prim in-world)
			// (it could also be an attachment that only just rezzed in but RlvHandler::onAttach() should be handling those)
			if ( (!itObj->second.m_fLookup) && (!pObj->isAttachment()) )
				itObj->second.m_fLookup = true;
		}
	}

	for (std::list<LLUUID>::const_iterator itExpired = ExpiredObjects.begin(); itExpired != ExpiredObjects.end(); ++itExpired)
	{
		#ifdef RLV_DEBUG
			RLV_INFOS << "Garbage collecting " << *itExpired << LL_ENDL;
		#endif // RLV_DEBUG

		processCommand(*itExpired, "clear", true);
	}

	return (0 != m_Objects.size());	// GC will kill itself if it has nothing to do
}

// Checked: 2009-08-08 (RLVa-1.0.1g) | Modified: RLVa-1.0.1g
void RlvHandler::onSavedAssetIntoInventory(const LLUUID& idItem)
{
	for (rlv_reattach_map_t::iterator itAttach = m_AttachPending.begin(); itAttach != m_AttachPending.end(); ++itAttach)
	{
		if (idItem == itAttach->second)
		{
			RLV_INFOS << "Reattaching " << idItem.asString() << " to " << itAttach->first << LL_ENDL;

			#if RLV_TARGET < RLV_MAKE_TARGET(1, 23, 0)			// Version: 1.22.11
				LLAttachmentRezAction* rez_action = new LLAttachmentRezAction;
				rez_action->mItemID = itAttach->second;
				rez_action->mAttachPt = itAttach->first;

				confirm_replace_attachment_rez(0/*YES*/, (void*)rez_action); // (Will call delete on rez_action)
			#else												// Version: 1.23.4
				LLSD payload;
				payload["item_id"] = itAttach->second;
				payload["attachment_point"] = itAttach->first;

				LLNotifications::instance().forceResponse(LLNotification::Params("ReplaceAttachment").payload(payload), 0/*YES*/);
			#endif
		}
	}
}

// ============================================================================
// String/chat censoring functions
//

// LL must have included an strlen for UTF8 *somewhere* but I can't seem to find it so this one is home grown
size_t utf8str_strlen(const std::string& utf8)
{
	const char* pUTF8 = utf8.c_str(); size_t length = 0;
	for (int idx = 0, cnt = utf8.length(); idx < cnt ;idx++)
	{
		// We're looking for characters that don't start with 10 as their high bits
		if ((pUTF8[idx] & 0xC0) != 0x80)
			length++;
	}
	return length;
}

// TODO-RLV: works, but more testing won't hurt
std::string utf8str_chtruncate(const std::string& utf8, size_t length)
{
	if (0 == length)
		return std::string();
	if (utf8.length() <= length)
		return utf8;

	const char* pUTF8 = utf8.c_str(); int idx = 0;
	while ( (pUTF8[idx]) && (length > 0) )
	{
		// We're looking for characters that don't start with 10 as their high bits
		if ((pUTF8[idx] & 0xC0) != 0x80)
			length--;
		idx++;
	}

	return utf8.substr(0, idx);
}

// Checked: 2009-07-09 (RLVa-1.0.0f) | Modified: RLVa-1.0.0f
void RlvHandler::filterChat(std::string& strUTF8Text, bool fFilterEmote) const
{
	if (strUTF8Text.empty())
		return;

	if (rlvIsEmote(strUTF8Text))					// Check if it's an emote
	{
		if (fFilterEmote)							// Emote filtering depends on fFilterEmote
		{
			if ( (strUTF8Text.find_first_of("\"()*=^_?~") != -1) || 
				 (strUTF8Text.find(" -") != -1) || (strUTF8Text.find("- ") != -1) || (strUTF8Text.find("''") != -1) )
			{
				strUTF8Text = "...";				// Emote contains illegal character (or character sequence)
			}
			else if (!hasBehaviour("emote"))
			{
				int idx = strUTF8Text.find('.');	// Truncate at 20 characters or at the dot (whichever is shorter)
				strUTF8Text = utf8str_chtruncate(strUTF8Text, ( (idx > 0) && (idx < 20) ) ? idx + 1 : 20);
			}
		}
	} 
	else if (strUTF8Text[0] == '/')					// Not an emote, but starts with a '/'
	{
		if (utf8str_strlen(strUTF8Text) > 7)		// Allow as long if it's 6 characters or less
			strUTF8Text = "...";
	}
	else if ((strUTF8Text.length() < 4) || (strUTF8Text.compare(0, 2, "((")) || (strUTF8Text.compare(strUTF8Text.length() - 2, 2, "))")))
	{
		strUTF8Text = "...";						// Regular chat (not OOC)
	}
}

// Checked: 2009-07-04 (RLVa-1.0.0a) | Modified: RLVa-1.0.0a
void RlvHandler::filterLocation(std::string& strUTF8Text) const
{
	// TODO-RLVa: if either the region or parcel name is a simple word such as "a" or "the" then confusion will ensue?
	//            -> not sure how you would go about preventing this though :|...

	// Filter any mention of the surrounding region names
	LLWorld::region_list_t regions = LLWorld::getInstance()->getRegionList();
	for (LLWorld::region_list_t::const_iterator itRegion = regions.begin(); itRegion != regions.end(); ++itRegion)
		rlvStringReplace(strUTF8Text, (*itRegion)->getName(), rlv_handler_t::cstrHiddenRegion);

	// Filter any mention of the parcel name
	LLViewerParcelMgr* pParcelMgr = LLViewerParcelMgr::getInstance();
	if (pParcelMgr)
		rlvStringReplace(strUTF8Text, pParcelMgr->getAgentParcelName(), rlv_handler_t::cstrHiddenParcel);
}

void RlvHandler::filterNames(std::string& strUTF8Text) const
{
	std::string strFirstName, strLastName, strName;

	// TODO-RLV: make this a bit more efficient (ie people with a large draw distance will have a load of active regions)
	//   -> the cost of multi string matching them all at once seems to be about the same as calling rlvStringReplace 
	//      twice so that would be a tremendous gain (and we'd get first name and word matching for free)
	#if RLV_TARGET < RLV_MAKE_TARGET(1, 23, 0)			// Version: 1.22.11
		for (LLWorld::region_list_t::const_iterator itRegion = LLWorld::getInstance()->getRegionList().begin();
			 itRegion != LLWorld::getInstance()->getRegionList().end(); ++itRegion)
		{
			LLViewerRegion* pRegion = *itRegion;
			
			for (S32 idxAgent = 0, cntAgent = pRegion->mMapAvatars.count(); idxAgent < cntAgent; idxAgent++)
			{
				// LLCacheName::getName() will add the UUID to the lookup queue if we don't know it yet
				if (gCacheName->getName(pRegion->mMapAvatarIDs.get(idxAgent), strFirstName, strLastName))
				{
					strName = strFirstName + " " + strLastName;

					rlvStringReplace(strUTF8Text, strName, getAnonym(strName));
				}
			}
		}
	#else												// Version: trunk
		// TODO-RLV: should restrict this to a certain radius (probably 1-2 sim range?)
		std::vector<LLUUID> idAgents;
		LLWorld::getInstance()->getAvatars(&idAgents, NULL);

		for (int idxAgent = 0, cntAgent = idAgents.size(); idxAgent < cntAgent; idxAgent++)
		{
			// LLCacheName::getName() will add the UUID to the lookup queue if we don't know it yet
			if (gCacheName->getName(idAgents[idxAgent], strFirstName, strLastName))
			{
				strName = strFirstName + " " + strLastName;

				rlvStringReplace(strUTF8Text, strName, getAnonym(strName));
			}
		}
	#endif
}

const std::string& RlvHandler::getAnonym(const std::string& strName) const
{
	const char* pszName = strName.c_str();
	U32 nHash = 0;
	
	// Test with 11,264 SL names showed a 3.33% - 3.82% occurance for each so we *should* get a very even spread
	for (int idx = 0, cnt = strName.length(); idx < cnt; idx++)
		nHash += pszName[idx];

	return cstrAnonyms[nHash % 28];
}

// Checked: 2009-07-07 (RLVa-1.0.0d) | Modified: RLVa-0.2.2a
bool RlvHandler::redirectChatOrEmote(const std::string& strUTF8Text) const
{
	// Sanity check - @redirchat only for chat and @rediremote only for emotes
	bool fIsEmote = rlvIsEmote(strUTF8Text);
	if ( ((!fIsEmote) && (!hasBehaviour(RLV_BHVR_REDIRCHAT))) || ((fIsEmote) && (!hasBehaviour(RLV_BHVR_REDIREMOTE))) )
		return false;

	if (!fIsEmote)
	{
		std::string strText = strUTF8Text;
		filterChat(strText, true);
		if (strText != "...")
			return false;	// @sendchat wouldn't filter it so @redirchat won't redirect it either
	}

	bool fSendChannel = hasBehaviour("sendchannel");
	for (rlv_object_map_t::const_iterator itObj = m_Objects.begin(); itObj != m_Objects.end(); ++itObj)
	{
		for (rlv_command_list_t::const_iterator itCmd = itObj->second.m_Commands.begin(), 
				endCmd = itObj->second.m_Commands.end(); itCmd != endCmd; ++itCmd)
		{
			if ( ( ((!fIsEmote) && (RLV_BHVR_REDIRCHAT == itCmd->getBehaviourType())) ||
				   ((fIsEmote) && (RLV_BHVR_REDIREMOTE == itCmd->getBehaviourType())) ) && 
				 ( (!fSendChannel) || (hasBehaviour("sendchannel", itCmd->getOption())) ) )
			{
				rlvSendChatReply(itCmd->getOption(), strUTF8Text);
			}
		}
	}
	return true;
}

// ============================================================================
// Public service functions (called by the outside world or by extension handlers)
//

BOOL RlvHandler::isAgentNearby(const LLUUID& uuid) const
{
	#if RLV_TARGET < RLV_MAKE_TARGET(1, 23, 0)			// Version: 1.22.11
		for (LLWorld::region_list_t::const_iterator itRegion = LLWorld::getInstance()->getRegionList().begin();
			 itRegion != LLWorld::getInstance()->getRegionList().end(); ++itRegion)
		{
			LLViewerRegion* pRegion = *itRegion;
			
			for (S32 idxAgent = 0, cntAgent = pRegion->mMapAvatars.count(); idxAgent < cntAgent; idxAgent++)
				if (pRegion->mMapAvatarIDs.get(idxAgent) == uuid)
					return TRUE;
		}
	#else												// Version: trunk
		// TODO-RLV: rewrite this to fit trunk, but still need the radius limited to a sane range
		std::vector<LLUUID> idAgents;
		LLWorld::getInstance()->getAvatars(&idAgents, NULL);

		for (int idxAgent = 0, cntAgent = idAgents.size(); idxAgent < cntAgent; idxAgent++)
		{
			if (idAgents[idxAgent] == uuid)
				return TRUE;
		}
	#endif
	return FALSE;
}

// ============================================================================
// General purpose inventory functions
//

// Checked: 2009-07-12 (RLVa-1.0.0h)
class RlvSharedRootFetcher : public LLInventoryFetchDescendentsObserver
{
public:
	RlvSharedRootFetcher() {}

	virtual void done()
	{
		RLV_INFOS << "Shared folders fetch completed" << LL_ENDL;
		RlvHandler::m_fFetchComplete = TRUE;

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

// Checked: 2009-07-12 (RLVa-1.0.0h)
void RlvHandler::fetchSharedInventory()
{
	// Sanity check - don't fetch if we're already fetching, or if we don't have a shared root
	LLViewerInventoryCategory* pRlvRoot = getSharedRoot();
	if ( (m_fFetchStarted) || (!pRlvRoot) )
		return;

	// Grab all the folders under the shared root
	LLInventoryModel::cat_array_t  folders;
	LLInventoryModel::item_array_t items;
	gInventory.collectDescendents(pRlvRoot->getUUID(), folders, items, FALSE);

	/*
	 * Add them to the "to fetch" list
	 */ 
	LLInventoryFetchDescendentsObserver::folder_ref_t fetchFolders;

	fetchFolders.push_back(pRlvRoot->getUUID());
	for (S32 idxFolder = 0, cntFolder = folders.count(); idxFolder < cntFolder; idxFolder++)
		fetchFolders.push_back(folders.get(idxFolder)->getUUID());

	/*
	 * Now fetch them all in one go
	 */
	RlvSharedRootFetcher* fetcher = new RlvSharedRootFetcher;

	RLV_INFOS << "Starting fetch of " << fetchFolders.size() << " shared folders" << LL_ENDL;
	fetcher->fetchDescendents(fetchFolders);

	if (fetcher->isEverythingComplete())
		fetcher->done();
	else
		gInventory.addObserver(fetcher);
}

bool RlvHandler::findSharedFolders(const std::string& strCriteria, LLInventoryModel::cat_array_t& folders) const
{
	// Sanity check - can't do anything without a shared root
	LLViewerInventoryCategory* pRlvRoot = getSharedRoot();
	if (!pRlvRoot)
		return false;

	folders.clear();
	LLInventoryModel::item_array_t items;
	RlvCriteriaCategoryCollector functor(strCriteria);
	gInventory.collectDescendentsIf(pRlvRoot->getUUID(), folders, items, FALSE, functor);

	return (folders.count() != 0);
}

// Checked: 2009-07-12 (RLVa-1.0.0h) | Modified: RLVa-0.2.0e
LLViewerInventoryCategory* RlvHandler::getSharedRoot()
{
	if (gInventory.isInventoryUsable())
	{
		LLInventoryModel::cat_array_t*  pFolders;
		LLInventoryModel::item_array_t* pItems;
		gInventory.getDirectDescendentsOf(gAgent.getInventoryRootID(), pFolders, pItems);
		if (pFolders)
		{
			// NOTE: we might have multiple #RLV folders so we'll just go with the first one we come across
			LLViewerInventoryCategory* pFolder;
			for (S32 idxFolder = 0, cntFolder = pFolders->count(); idxFolder < cntFolder; idxFolder++)
			{
				if ( ((pFolder = pFolders->get(idxFolder)) != NULL) && (RlvHandler::cstrSharedRoot == pFolder->getName()) )
					return pFolder;
			}
		}
	}
	return NULL;
}

// Checked: 2009-07-28 (RLVa-1.0.1a) | Modified: RLVa-1.0.1a
LLViewerInventoryCategory* RlvHandler::getSharedFolder(const LLUUID& idParent, const std::string& strFolderName) const
{
	LLInventoryModel::cat_array_t*  pFolders;
	LLInventoryModel::item_array_t* pItems;
	gInventory.getDirectDescendentsOf(idParent, pFolders, pItems);
	if ( (!pFolders) || (strFolderName.empty()) )
		return NULL;

	// If we can't find an exact match then we'll settle for a "contains" match
	LLViewerInventoryCategory* pPartial = NULL;

	//LLStringUtil::toLower(strFolderName); <- everything was already converted to lower case before

	std::string strName;
	for (S32 idxFolder = 0, cntFolder = pFolders->count(); idxFolder < cntFolder; idxFolder++)
	{
		LLViewerInventoryCategory* pFolder = pFolders->get(idxFolder);

		strName = pFolder->getName();
		if (strName.empty())
			continue;
		LLStringUtil::toLower(strName);

		if (strFolderName == strName)
			return pFolder;		// Found an exact match, no need to keep on going
		else if ( (!pPartial) && (RLV_FOLDER_PREFIX_HIDDEN != strName[0]) && (strName.find(strFolderName) != std::string::npos) )
			pPartial = pFolder;	// Found a partial (non-hidden) match, but we might still find an exact one (first partial match wins)
	}

	return pPartial;
}

// Checked: 2009-07-12 (RLVa-1.0.0h) | Modified: RLVa-0.2.0e
LLViewerInventoryCategory* RlvHandler::getSharedFolder(const std::string& strPath) const
{
	// Sanity check - no shared root => no shared folder
	LLViewerInventoryCategory* pRlvRoot = getSharedRoot(), *pFolder = pRlvRoot;
	if (!pRlvRoot)
		return NULL;

	// Walk the path (starting at the root)
	typedef boost::tokenizer<boost::char_separator<char> > tokenizer;
	boost::char_separator<char> sep("/", "", boost::drop_empty_tokens);
	tokenizer tokens(strPath, sep);
	for (tokenizer::iterator itToken = tokens.begin(); itToken != tokens.end(); ++itToken)
	{
		pFolder = getSharedFolder(pFolder->getUUID(), *itToken);
		if (!pFolder)
			return NULL;	// No such folder
	}

	return pFolder;			// If strPath was empty or just a bunch of //// then: pFolder == pRlvRoot
}

// Checked: 2009-07-12 (RLVa-1.0.0h) | Modified: RLVa-0.2.0g
std::string RlvHandler::getSharedPath(const LLViewerInventoryCategory* pFolder) const
{
	LLViewerInventoryCategory* pRlvRoot = getSharedRoot();
	// Sanity check - no shared root or no folder => no path
	if ( (!pRlvRoot) || (!pFolder) || (pRlvRoot->getUUID() == pFolder->getUUID()) )
		return std::string();

	const LLUUID& idRLV  = pRlvRoot->getUUID();
	const LLUUID& idRoot = gAgent.getInventoryRootID();
	std::string strPath;

	// Walk up the tree until we reach the top
	while (pFolder)
	{
		strPath = "/" + pFolder->getName() + strPath;

		const LLUUID& idParent = pFolder->getParentUUID();
		if (idRLV == idParent)			// Reached the shared root, we're done
			break;
		else if (idRoot == idParent)	// We reached the agent's inventory root (indicative of a logic error elsewhere)
		{
			RLV_ERRS << "Reached agent's inventory root while building path for shared folder" << LL_ENDL;
			return std::string();
		}
		else
			pFolder = gInventory.getCategory(idParent);
	}

	return strPath.erase(0, 1);
}

// ============================================================================
// Composite folders
//

#ifdef RLV_EXPERIMENTAL_COMPOSITES
	// Checked:
	bool RlvHandler::getCompositeInfo(const LLInventoryCategory* pFolder, std::string* pstrName) const
	{
		if (pFolder)
		{
			// Composite folder naming: ^\.?[Folder]
			const std::string& cstrFolder = pFolder->getName();
			int idxStart = cstrFolder.find('['), idxEnd = cstrFolder.find(']', idxStart);
			if ( ((0 == idxStart) || (1 == idxStart)) && (idxEnd - idxStart > 1) )
			{
				if (pstrName)
					pstrName->assign(cstrFolder.substr(idxStart + 1, idxEnd - idxStart - 1));
				return true;
			}
		}
		return false;
	}

	// Checked:
	bool RlvHandler::getCompositeInfo(const LLUUID& idItem, std::string* pstrName, LLViewerInventoryCategory** ppFolder) const
	{
		LLViewerInventoryCategory* pRlvRoot; LLViewerInventoryItem* pItem;

		if ( (idItem.notNull()) && ((pRlvRoot = getSharedRoot()) != NULL) && 
			 (gInventory.isObjectDescendentOf(idItem, pRlvRoot->getUUID())) && ((pItem = gInventory.getItem(idItem)) != NULL) )
		{
			// We know it's an item in a folder under the shared root...
			LLViewerInventoryCategory* pFolder = gInventory.getCategory(pItem->getParentUUID());
			if (getAttachPoint(pFolder, true))
			{
				// ... but it could be named ".(attachpt)" in which case we need its parent
				pFolder = gInventory.getCategory(pFolder->getParentUUID());
			}

			if ( (pFolder) && (getCompositeInfo(pFolder, pstrName)) )
			{
				if (ppFolder)
					*ppFolder = pFolder;
				return true;
			}
		}
		return false;
	}
#endif // RLV_EXPERIMENTAL_COMPOSITES

#ifdef RLV_EXPERIMENTAL_COMPOSITE_FOLDING
	// Checked:
	inline bool RlvHandler::isHiddenCompositeItem(const LLUUID& idItem, const std::string& cstrItemType) const
	{
		// An item that's part of a composite folder will be hidden from @getoutfit and @getattach if:
		//   (1) the composite name specifies either a wearable layer or an attachment point
		//   (2) the specified wearable layer or attachment point is worn and resides in the folder
		//   (3) cstrItemType isn't the specified wearable layer or attach point
		//
		// Example: #RLV/Separates/Shoes/ChiChi Pumps/.[shoes] with items: "Shoe Base", "Shoe (left foot)" and "Shoe (right foot)"
		//   -> as long as "Shoe Base" is worn, @getattach should not reflect "left foot", nor "right foot"
		std::string strComposite; LLViewerInventoryCategory* pFolder;
		EWearableType type; S32 idxAttachPt;
		if ( (getCompositeInfo(idItem, &strComposite, &pFolder)) && (cstrItemType != strComposite) )
		{
			LLUUID idCompositeItem;
			if ((type = LLWearable::typeNameToType(strComposite)) != WT_INVALID)
			{
				idCompositeItem = gAgent.getWearableItem(type);
			}
			else if ((idxAttachPt = getAttachPointIndex(strComposite, true)) != 0)
			{
				LLVOAvatar* pAvatar; LLViewerJointAttachment* pAttachmentPt;
				if ( ((pAvatar = gAgent.getAvatarObject()) != NULL) && 
					 ((pAttachmentPt = get_if_there(pAvatar->mAttachmentPoints, idxAttachPt, (LLViewerJointAttachment*)NULL)) != NULL) )
				{
					idCompositeItem = pAttachmentPt->getItemID();
				}
			}

			if ( (idCompositeItem.notNull()) && (gInventory.isObjectDescendentOf(idCompositeItem, pFolder->getUUID())) )
				return true;
		}
		return false;
	}
#endif // RLV_EXPERIMENTAL_COMPOSITEFOLDING

#ifdef RLV_EXPERIMENTAL_COMPOSITE_LOCKING
	// Checked:
	bool RlvHandler::canTakeOffComposite(const LLInventoryCategory* pFolder) const
	{
		if (!pFolder)		// If there's no folder then there is nothing to take off
			return false;

		LLInventoryModel::cat_array_t  folders;
		LLInventoryModel::item_array_t items;
		RlvWearableItemCollector functor(pFolder->getUUID(), true, false);

		// Grab a list of all the items @detachthis would be detaching/unwearing
		gInventory.collectDescendentsIf(pFolder->getUUID(), folders, items, FALSE, functor);
		if (!items.count())
			return false;	// There are no wearable items in the folder so there is nothing to take off

		LLViewerInventoryItem* pItem;
		for (S32 idxItem = 0, cntItem = items.count(); idxItem < cntItem; idxItem++)
		{
			pItem = items.get(idxItem);

			switch (pItem->getType())
			{
				case LLAssetType::AT_CLOTHING:
					{
						LLWearable* pWearable = gAgent.getWearableFromWearableItem(pItem->getUUID());
						if ( (pWearable) && (!isRemovable(pWearable->getType())) )
							return false;	// If one clothing layer in the composite folder is unremoveable then the entire folder is
					}
					break;
				case LLAssetType::AT_OBJECT:
					{
						LLVOAvatar* pAvatar; LLViewerObject* pObj;
						if ( ((pAvatar = gAgent.getAvatarObject()) != NULL) && 
							 ((pObj = pAvatar->getWornAttachment(pItem->getUUID())) != NULL) && (!isDetachable(pObj)) )
						{
							return false;	// If one attachment in the composite folder is undetachable then the entire folder is
						}
					}
					break;
				#ifdef LL_GNUC
				default:
					break;
				#endif // LL_GNUC
			}
		}
		return true;
	}
#endif // RLV_EXPERIMENTAL_COMPOSITE_LOCKING

// ============================================================================
// Event handlers
//

// Checked: 2009-07-12 (RLVa-1.0.0h) | Modified: RLVa-0.2.0d
void RlvHandler::onForceDetach(const LLUUID& idObj, const std::string& strOption) const
{
	U16 nParam;
	if (strOption.empty())
	{
		// Simulate right-click / Take Off > Detach All
		LLAgent::userRemoveAllAttachments(NULL);
	}
	else if (m_AttachLookup.getExactMatchParam(strOption, nParam))
	{
		// Simulate right-click / Take Off > Detach > ...
		LLVOAvatar* pAvatar; LLViewerJointAttachment* pAttachmentPt;
		if ( ((pAvatar = gAgent.getAvatarObject()) != NULL) &&	// Make sure we're actually wearing something on the attachment point
			 ((pAttachmentPt = get_if_there(pAvatar->mAttachmentPoints, (S32)nParam, (LLViewerJointAttachment*)NULL)) != NULL) &&
			 (isStrippable(pAttachmentPt->getItemID())) )		// ... and that it's not marked as "nostrip"
		{
			#ifdef RLV_EXPERIMENTAL_COMPOSITES
				// If we're stripping something that's part of a composite folder then we should @detachthis instead
				if (isCompositeDescendent(pAttachmentPt->getItemID()))
				{
					std::string strCmd = "detachthis:" + strOption + "=force";
					#ifdef RLV_DEBUG
						RLV_INFOS << "\t- '" << strOption << "' belongs to composite folder: @" << strCmd << LL_ENDL;
					#endif // RLV_DEBUG
					processForceCommand(idObj, RlvCommand(strCmd));
				}
				else
			#endif // RLV_EXPERIMENTAL_COMPOSITES
				{
					handle_detach_from_avatar(pAttachmentPt);
				}
		}
	}
	else
	{
		// Force detach single folder
		onForceWear(strOption, false, false);
	}
}

// Checked: 2009-07-12 (RLVa-1.0.0h) | Modified: RLVa-0.2.0d
void RlvHandler::onForceRemOutfit(const LLUUID& idObj, const std::string& strOption) const
{
	EWearableType typeOption = LLWearable::typeNameToType(strOption), type;
	if ( (WT_INVALID == typeOption) && (!strOption.empty()) )
		return;

	// Before we had an option and optionless branch, but with the addition of composites and nostrip there's less duplication this way
	for (int idxType = 0; idxType < WT_COUNT; idxType++)
	{
		type = (EWearableType)idxType;

		// Only strip clothing (that's currently worn and not marked "nostrip")
		if ( (LLAssetType::AT_CLOTHING != LLWearable::typeToAssetType(type)) ||	
			 (!gAgent.getWearable(type)) || (!isStrippable(gAgent.getWearableItem(type))) )
		{
			continue;
		}

		if ( (typeOption == type) || (strOption.empty()) )
		{
			#ifdef RLV_EXPERIMENTAL_COMPOSITES
				// If we're stripping something that's part of a composite folder then we should @detachthis instead
				if (isCompositeDescendent(gAgent.getWearableItem(type)))
				{
					std::string strCmd = "detachthis:" + LLWearable::typeToTypeName(type) + "=force";
					#ifdef RLV_DEBUG
						RLV_INFOS << "\t- '" << LLWearable::typeToTypeName(type) << "' is composite descendent: @" << strCmd << LL_ENDL;
					#endif // RLV_DEBUG
					processForceCommand(idObj, RlvCommand(strCmd));
				}
				else
			#endif // RLV_EXPERIMENTAL_COMPOSITES
				{
					gAgent.removeWearable(type);
				}
		}
	}
}

// Checked: 2009-07-12 (RLVa-1.0.0h) | Modified: RLVa-0.2.0g
bool RlvHandler::onForceSit(const LLUUID& idObj, const std::string& strOption) const
{
	LLViewerObject* pObject = NULL; LLUUID idTarget(strOption);
	// Sanity checking - we need to know about the object and it should identify a prim/linkset
	if ( (idTarget.isNull()) || ((pObject = gObjectList.findObject(idTarget)) == NULL) || (LL_PCODE_VOLUME != pObject->getPCode()) )
		return false;

	// Don't force sit if:
	//   1) currently sitting and prevented from standing up
	//   2) prevented from sitting
	//   3) @sittp=n restricted (except if @sittp=n was issued by the same prim that's currently force sitting the avie)
	if ( ( (hasBehaviour(RLV_BHVR_UNSIT)) && (gAgent.getAvatarObject()) && (gAgent.getAvatarObject()->mIsSitting) ) || 
		 ( (hasBehaviour(RLV_BHVR_SIT)) ) ||
		 ( (hasBehaviourExcept(RLV_BHVR_SITTP, idObj)) && 
		   (dist_vec_squared(gAgent.getPositionGlobal(), pObject->getPositionGlobal()) > 1.5f * 1.5f) ))
	{
		return false;
	}

	// Copy/paste from handle_sit_or_stand() [see http://wiki.secondlife.com/wiki/AgentRequestSit]
	gMessageSystem->newMessageFast(_PREHASH_AgentRequestSit);
	gMessageSystem->nextBlockFast(_PREHASH_AgentData);
	gMessageSystem->addUUIDFast(_PREHASH_AgentID, gAgent.getID());
	gMessageSystem->addUUIDFast(_PREHASH_SessionID, gAgent.getSessionID());
	gMessageSystem->nextBlockFast(_PREHASH_TargetObject);
	gMessageSystem->addUUIDFast(_PREHASH_TargetID, pObject->mID);
	// Offset: "a rough position in local coordinates for the edge to sit on"
	// (we might not even be looking at the object so I don't think we can supply the offset to an edge)
	gMessageSystem->addVector3Fast(_PREHASH_Offset, LLVector3::zero);
	pObject->getRegion()->sendReliableMessage();

	return true;
}

void RlvHandler::onForceWear(const std::string& strPath, bool fAttach, bool fMatchAll) const
{
	// See LLWearableBridge::wearOnAvatar(): don't wear anything until initial wearables are loaded, can destroy clothing items
	if (!gAgent.areWearablesLoaded()) 
		return;

	LLViewerInventoryCategory* pFolder = getSharedFolder(strPath);
	if (!pFolder)	// Folder not found = nothing to attach
		return;

	LLInventoryModel::cat_array_t  folders;
	LLInventoryModel::item_array_t items;
	RlvWearableItemCollector functor(pFolder->getUUID(), fAttach, fMatchAll);

	// Grab a list of all the items we'll be wearing/attaching
	gInventory.collectDescendentsIf(pFolder->getUUID(), folders, items, FALSE, functor);

	LLViewerInventoryItem* pItem;
	for (S32 idxItem = 0, cntItem = items.count(); idxItem < cntItem; idxItem++)
	{
		pItem = items.get(idxItem);

		switch (pItem->getType())
		{
			case LLAssetType::AT_CLOTHING:
			case LLAssetType::AT_BODYPART:
				{
					LLWearable* pWearable = gAgent.getWearableFromWearableItem(pItem->getUUID());

					#ifdef RLV_EXPERIMENTAL_COMPOSITE_LOCKING
						// If we're already wearing something on this layer then we have to check if it isn't part of a composite
						// folder that has at least one unremovable item (in which case we can't wear or remove this item)
						LLViewerInventoryCategory* pCompositeFolder;
						if ( (!pWearable) || (!getCompositeInfo(pItem->getUUID(), NULL, &pCompositeFolder)) || 
							 (canTakeOffComposite(pFolder)))
						{
					#endif // RLV_EXPERIMENTAL_COMPOSITE_LOCKING
							if (fAttach)
							{
								// Simulate wearing a clothing item from inventory (right click / "Wear")
								// LLWearableBridge::performAction() => LLWearableBridge::wearOnAvatar() => wear_inventory_item_on_avatar()
								wear_inventory_item_on_avatar(pItem);
							}
							else
							{
								if ( (pWearable) && (LLAssetType::AT_CLOTHING == pItem->getType()) )
									gAgent.removeWearable(pWearable->getType());
							}
					#ifdef RLV_EXPERIMENTAL_COMPOSITE_LOCKING
						}
					#endif // RLV_EXPERIMENTAL_COMPOSITE_LOCKING
				}
				break;
			case LLAssetType::AT_OBJECT:
				{
					LLVOAvatar* pAvatar = gAgent.getAvatarObject();
					LLViewerObject* pObj;

					#ifdef RLV_EXPERIMENTAL_COMPOSITE_LOCKING
						// If we're already wearing something on this attach point then we have to check if it isn't part of a composite
						// folder that has at least one unremovable item (in which case we can't attach or detach this item)
						LLViewerInventoryCategory* pCompositeFolder;
						if ( (pAvatar) && 
							 ( ((pObj = pAvatar->getWornAttachment(pItem->getUUID())) == NULL) || 
							   (!getCompositeInfo(pItem->getUUID(), NULL, &pCompositeFolder)) || (canTakeOffComposite(pFolder)) ) )
						{
					#endif // RLV_EXPERIMENTAL_COMPOSITE_LOCKING
							if (fAttach)
							{
								// Simulate wearing an object to a specific attachment point (copy/paste to suppress replacement dialog)
								// LLAttachObject::handleEvent() => rez_attachment()
								LLViewerJointAttachment* pAttachPt = getAttachPoint(pItem, true);
								if ( (pAttachPt) && (isDetachable(pAttachPt->getObject())) )
								{
									#if RLV_TARGET < RLV_MAKE_TARGET(1, 23, 0)			// Version: 1.22.11
										LLAttachmentRezAction* rez_action = new LLAttachmentRezAction;
										rez_action->mItemID = pItem->getUUID();
										rez_action->mAttachPt = getAttachPointIndex(pAttachPt->getName(), true);

										confirm_replace_attachment_rez(0/*YES*/, (void*)rez_action); // (Will call delete on rez_action)
									#else												// Version: 1.23.4
										LLSD payload;
										payload["item_id"] = pItem->getUUID();
										payload["attachment_point"] = getAttachPointIndex(pAttachPt->getName(), true);

										LLNotifications::instance().forceResponse(
											LLNotification::Params("ReplaceAttachment").payload(payload), 0/*YES*/);
									#endif
								}
							}
							else
							{
								if ( (pAvatar) && ((pObj = pAvatar->getWornAttachment(pItem->getUUID())) != NULL) )
								{
									LLViewerJointAttachment* pAttachment = pAvatar->getTargetAttachmentPoint(pObj);
									if (pAttachment)
										handle_detach_from_avatar(pAttachment);
								}
							}
					#ifdef RLV_EXPERIMENTAL_COMPOSITE_LOCKING
						}
					#endif // RLV_EXPERIMENTAL_COMPOSITE_LOCKING
				}
				break;
			#ifdef LL_GNUC
			default:
				break;
			#endif // LL_GNUC
		}
	}
}

// Checked: 2009-07-12 (RLVa-1.0.0h) | Modified: RLVa-0.2.0g
bool RlvHandler::onGetPath(const LLUUID &uuid, const std::string& strOption, std::string& strReply) const
{
	// Sanity check - no need to go through all this trouble if we don't have a shared root
	LLViewerInventoryCategory* pRlvRoot = getSharedRoot();
	if (!pRlvRoot)
		return false;

	LLUUID idItem;

	// <option> can be a clothing layer
	EWearableType layerType = LLWearable::typeNameToType(strOption);
	if (WT_INVALID != layerType)
	{
		idItem = gAgent.getWearableItem(layerType);
	}
	else
	{
		LLViewerJointAttachment* pAttachPt = NULL;

		// ... or it can be empty
		if (strOption.empty())
		{
			// (in which case we act on the object that issued the command)
			LLViewerObject* pObj = gObjectList.findObject(uuid);
			if ( (pObj) && (pObj->isAttachment()) && (gAgent.getAvatarObject()) )
				pAttachPt = gAgent.getAvatarObject()->getTargetAttachmentPoint(pObj);
		}
		else
		{
			// ... or it can specify an attach point
			pAttachPt = getAttachPoint(strOption, true);
		}

		// If we found something, get its inventory item UUID
		if (pAttachPt)
			idItem = pAttachPt->getItemID();
	}

	// If we found something and it's under the shared root, then get its path
	if ( (!idItem.isNull()) && (gInventory.isObjectDescendentOf(idItem, pRlvRoot->getUUID())) )
	{
		LLInventoryItem* pItem = gInventory.getItem(idItem);
		if (pItem)
		{
			// ... unless the containing folder's name specifies an attach point (or nostrip) in which case we need its parent
			LLViewerInventoryCategory* pFolder = gInventory.getCategory(pItem->getParentUUID());
			#ifdef RLV_EXTENSION_FLAG_NOSTRIP
				if ( (getAttachPoint(pFolder, true)) || (pFolder->getName() == ".("RLV_FOLDER_FLAG_NOSTRIP")") )
			#else
				if (getAttachPoint(pFolder, true))
			#endif // RLV_EXTENSION_FLAG_NOSTRIP
					strReply = getSharedPath(pFolder->getParentUUID());
				else
					strReply = getSharedPath(pFolder);
		}
	}
	return !strReply.empty();
}

struct rlv_wear_info { U32 cntWorn, cntTotal, cntChildWorn, cntChildTotal; };

// Checked: 2009-05-30 (RLVa-0.2.0e) | Modified: RLVa-0.2.0e
void RlvHandler::onGetInvWorn(const std::string& strPath, std::string& strReply) const
{
	// Sanity check - getAvatarObject() can't be NULL [see rlvIsWearingItem()] and the folder should exist and not be hidden
	LLViewerInventoryCategory* pFolder = getSharedFolder(strPath);
	if ((!gAgent.getAvatarObject()) || (!pFolder) || (pFolder->getName().empty()) || (RLV_FOLDER_PREFIX_HIDDEN == pFolder->getName()[0]))
		return;

	// Collect everything @attachall would be attaching
	LLInventoryModel::cat_array_t  folders;
	LLInventoryModel::item_array_t items;
	RlvWearableItemCollector functor(pFolder->getUUID(), true, true);
	gInventory.collectDescendentsIf(pFolder->getUUID(), folders, items, FALSE, functor);

	rlv_wear_info wi = {0};

	// Add all the folders to a lookup map 
	std::map<LLUUID, rlv_wear_info> mapFolders;
	mapFolders.insert(std::pair<LLUUID, rlv_wear_info>(pFolder->getUUID(), wi));
	for (S32 idxFolder = 0, cntFolder = folders.count(); idxFolder < cntFolder; idxFolder++)
		mapFolders.insert(std::pair<LLUUID, rlv_wear_info>(folders.get(idxFolder)->getUUID(), wi));

	// Iterate over all the found items
	LLViewerInventoryItem* pItem; std::map<LLUUID, rlv_wear_info>::iterator itFolder;
	for (S32 idxItem = 0, cntItem = items.count(); idxItem < cntItem; idxItem++)
	{
		pItem = items.get(idxItem);

		// The "folded parent" is the folder this item should be considered a direct descendent of (may or may not match actual parent)
		const LLUUID& idParent = functor.getFoldedParent(pItem->getParentUUID());

		// Walk up the tree: sooner or later one of the parents will be a folder in the map
		LLViewerInventoryCategory* pParent = gInventory.getCategory(idParent);
		while ( (itFolder = mapFolders.find(pParent->getUUID())) == mapFolders.end() )
			pParent = gInventory.getCategory(pParent->getParentUUID());

		U32 &cntWorn  = (idParent == pParent->getUUID()) ? itFolder->second.cntWorn : itFolder->second.cntChildWorn, 
			&cntTotal = (idParent == pParent->getUUID()) ? itFolder->second.cntTotal : itFolder->second.cntChildTotal;

		if (rlvIsWearingItem(pItem))
			cntWorn++;
		cntTotal++;
	}

	// Extract the result for the main folder
	itFolder = mapFolders.find(pFolder->getUUID());
	wi.cntWorn = itFolder->second.cntWorn;
	wi.cntTotal = itFolder->second.cntTotal;
	mapFolders.erase(itFolder);

	// Build the result for each child folder
	for (itFolder = mapFolders.begin(); itFolder != mapFolders.end(); ++itFolder)
	{
		rlv_wear_info& wiFolder = itFolder->second;

		wi.cntChildWorn += wiFolder.cntWorn + wiFolder.cntChildWorn;
		wi.cntChildTotal += wiFolder.cntTotal + wiFolder.cntChildTotal;

		strReply += llformat(",%s|%d%d", gInventory.getCategory(itFolder->first)->getName().c_str(),
		 (0 == wiFolder.cntTotal) ? 0 : (0 == wiFolder.cntWorn) ? 1 : (wiFolder.cntWorn != wiFolder.cntTotal) ? 2 : 3,
		 (0 == wiFolder.cntChildTotal) ? 0 : (0 == wiFolder.cntChildWorn) ? 1 : (wiFolder.cntChildWorn != wiFolder.cntChildTotal) ? 2 : 3
		);
	}

	// Now just prepend the root and done
	strReply = llformat("|%d%d", (0 == wi.cntTotal) ? 0 : (0 == wi.cntWorn) ? 1 : (wi.cntWorn != wi.cntTotal) ? 2 : 3,
		(0 == wi.cntChildTotal) ? 0 : (0 == wi.cntChildWorn) ? 1 : (wi.cntChildWorn != wi.cntChildTotal) ? 2: 3) + strReply;
}

// (In case anyone cares: this isn't used in public builds)
bool RlvHandler::getWornInfo(const LLInventoryCategory* pFolder, U8& wiFolder, U8& wiChildren) const
{
	// Sanity check - getAvatarObject() can't be NULL [see rlvIsWearingItem()] and the folder should exist and not be hidden
	if ((!gAgent.getAvatarObject()) || (!pFolder) || (pFolder->getName().empty()) || (RLV_FOLDER_PREFIX_HIDDEN == pFolder->getName()[0]))
		return false;

	LLInventoryModel::cat_array_t  folders;
	LLInventoryModel::item_array_t items;
	RlvWearableItemCollector functor(pFolder->getUUID(), true, true);
	gInventory.collectDescendentsIf(pFolder->getUUID(), folders, items, FALSE, functor);

	LLViewerInventoryItem* pItem;
	U32 cntWorn = 0, cntTotal = 0, cntChildWorn = 0, cntChildTotal = 0;
	for (S32 idxItem = 0, cntItem = items.count(); idxItem < cntItem; idxItem++)
	{
		pItem = items.get(idxItem);

		bool fDirectDescendent = (pFolder->getUUID() == functor.getFoldedParent(pItem->getParentUUID()));
		U32 &refWorn = (fDirectDescendent) ? cntWorn : cntChildWorn, &refTotal = (fDirectDescendent) ? cntTotal : cntChildTotal;

		if (rlvIsWearingItem(pItem))
			refWorn++;
		refTotal++;
	}

	wiFolder = (0 == cntTotal + cntChildTotal) ? 0 : (0 == cntWorn + cntChildWorn) ? 1 : 
		(cntWorn + cntChildWorn != cntTotal + cntChildTotal) ? 2 : 3;
	wiChildren = (0 == cntChildTotal) ? 0 : (0 == cntChildWorn) ? 1 : (cntChildWorn != cntChildTotal) ? 2 : 3;

	return true;
}

// ============================================================================
// Initialization helper functions
//

BOOL RlvHandler::setEnabled(BOOL fEnable)
{
	if (m_fEnabled == fEnable)
		return fEnable;

	if (fEnable)
	{
		if (gSavedSettings.controlExists(RLV_SETTING_NOSETENV))
			fNoSetEnv = gSavedSettings.getBOOL(RLV_SETTING_NOSETENV);
		if (gSavedSettings.controlExists(RLV_SETTING_ENABLELEGACYNAMING))
			fLegacyNaming = gSavedSettings.getBOOL(RLV_SETTING_ENABLELEGACYNAMING);
		if (gSavedSettings.controlExists(RLV_SETTING_SHOWNAMETAGS))
			RlvSettings::fShowNameTags = gSavedSettings.getBOOL(RLV_SETTING_SHOWNAMETAGS);

		RlvCommand::initLookupTable();
		gRlvHandler.addObserver(new RlvExtGetSet());

		if (LLStartUp::getStartupState() >= STATE_CLEANUP)
			fetchSharedInventory();

		m_fEnabled = TRUE;
	}
	else if (canDisable())
	{
		#ifdef RLV_DEBUG
			RLV_INFOS << "Disabling RLV:" << LL_ENDL;
		#endif // RLV_DEBUG

		gRlvHandler.clearState();

		#ifdef RLV_DEBUG
			RLV_INFOS << "\t--> RLV disabled" << LL_ENDL;
		#endif // RLV_DEBUG

		m_fEnabled = FALSE;
	}

	#ifdef RLV_ADVANCED_MENU
		// RELEASE-RLVa: LL defines CLIENT_MENU_NAME but we can't get to it from here so we need to keep those two in sync manually
		LLMenuGL* pClientMenu = NULL;
		if ( (gMenuBarView) && ((pClientMenu = gMenuBarView->getChildMenuByName("Advanced", FALSE)) != NULL) )
		{
			pClientMenu->setItemVisible("RLVa", m_fEnabled);
			pClientMenu->setItemEnabled("RLVa", m_fEnabled);
		}
	#endif // RLV_ADVANCED_MENU

	return m_fEnabled;		// Return enabled/disabled state
}

BOOL RlvHandler::canDisable()
{
	return TRUE;
}

void RlvHandler::clearState()
{
	// TODO-RLVa: should restore all RLV controlled debug variables to their defaults

	// Issue @clear on behalf of every object that has a currently active RLV restriction (even if it's just an exception)
	LLUUID idObj; LLViewerObject* pObj; bool fDetachable;
	while (m_Objects.size())
	{
		idObj = m_Objects.begin()->first; // Need a copy since after @clear the data it points to will no longer exist
		fDetachable = ((pObj = gObjectList.findObject(idObj)) != NULL) ? isDetachable(pObj) : true;

		processCommand(idObj, "clear", false);
		if (!fDetachable)
			processCommand(idObj, "detachme=force", false);
	}

	// Sanity check - these should all be empty after we issue @clear on the last object
	if ( (!m_Objects.empty()) || !(m_Exceptions.empty()) || (!m_Attachments.empty()) )
	{
		RLV_ERRS << "Object, exception or attachment map not empty after clearing state!" << LL_ENDL;
		m_Objects.clear();
		m_Exceptions.clear();
		m_Attachments.clear();
	}

	// These all need manual clearing
	memset(m_LayersAdd, 0, sizeof(S16) * WT_COUNT);
	memset(m_LayersRem, 0, sizeof(S16) * WT_COUNT);
	memset(m_Behaviours, 0, sizeof(S16) * RLV_BHVR_COUNT);
	m_AttachPending.clear();
	m_Emitter.clearObservers(); // <- calls delete on all active observers

	// Clear dynamically allocated memory
	if (m_pGCTimer)
	{
		delete m_pGCTimer;
		m_pGCTimer = NULL;
	}
	if (m_pWLSnapshot)
	{
		delete m_pWLSnapshot;
		m_pWLSnapshot = NULL;
	}
}

// ============================================================================