flotsam /flotsam/Servers/XmlRpcGroupsServer/xmlrpc.php

Language PHP Lines 1755
MD5 Hash 78a280a37b0792fa190ba9b3ff00e762 Estimated Cost $36,766 (why?)
Repository https://bitbucket.org/VirtualReality/flotsam.git View Raw File View Project SPDX
   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
<?php
//	ini_set("display_errors",0);
    /*
      Actual failures that result in mysql or php errors should be returned as:
      
      return array('error' => "Could not successfully run query ($sql) from DB: " . mysql_error(), 'params' => var_export($params, TRUE));
      
      Methods that run without errors, but do not have the intended result should return as:
      
      return array('succeed' => 'false', 'message' => 'No Groups Found', 'params' => var_export($params, TRUE));
      
      or if applicable:
      
      return array('succeed' => 'false', 'message' => 'What went wrong', 'params' => var_export($params, TRUE), 'sql' => $sql);
    */

    include("phpxmlrpclib/xmlrpc.inc");
    include("phpxmlrpclib/xmlrpcs.inc");

    include("config.php");
	

    $groupPowers = array(
        'None' => '0',
        /// <summary>Can send invitations to groups default role</summary>
        'Invite' => '2',
        /// <summary>Can eject members from group</summary>
        'Eject' => '4',
        /// <summary>Can toggle 'Open Enrollment' and change 'Signup fee'</summary>
        'ChangeOptions' => '8',
        /// <summary>Can create new roles</summary>
        'CreateRole' => '16',
        /// <summary>Can delete existing roles</summary>
        'DeleteRole' => '32',
        /// <summary>Can change Role names, titles and descriptions</summary>
        'RoleProperties' => '64',
        /// <summary>Can assign other members to assigners role</summary>
        'AssignMemberLimited' => '128',
        /// <summary>Can assign other members to any role</summary>
        'AssignMember' => '256',
        /// <summary>Can remove members from roles</summary>
        'RemoveMember' => '512',
        /// <summary>Can assign and remove abilities in roles</summary>
        'ChangeActions' => '1024',
        /// <summary>Can change group Charter, Insignia, 'Publish on the web' and which
        /// members are publicly visible in group member listings</summary>
        'ChangeIdentity' => '2048',
        /// <summary>Can buy land or deed land to group</summary>
        'LandDeed' => '4096',
        /// <summary>Can abandon group owned land to Governor Linden on mainland, or Estate owner for
        /// private estates</summary>
        'LandRelease' => '8192',
        /// <summary>Can set land for-sale information on group owned parcels</summary>
        'LandSetSale' => '16384',
        /// <summary>Can subdivide and join parcels</summary>
        'LandDivideJoin' => '32768',
        /// <summary>Can join group chat sessions</summary>
        'JoinChat' => '65536',
        /// <summary>Can toggle "Show in Find Places" and set search category</summary>
        'FindPlaces' => '131072',
        /// <summary>Can change parcel name, description, and 'Publish on web' settings</summary>
        'LandChangeIdentity' => '262144',
        /// <summary>Can set the landing point and teleport routing on group land</summary>
        'SetLandingPoint' => '524288',
        /// <summary>Can change music and media settings</summary>
        'ChangeMedia' => '1048576',
        /// <summary>Can toggle 'Edit Terrain' option in Land settings</summary>
        'LandEdit' => '2097152',
        /// <summary>Can toggle various About Land > Options settings</summary>
        'LandOptions' => '4194304',
        /// <summary>Can always terraform land, even if parcel settings have it turned off</summary>
        'AllowEditLand' => '8388608',
        /// <summary>Can always fly while over group owned land</summary>
        'AllowFly' => '16777216',
        /// <summary>Can always rez objects on group owned land</summary>
        'AllowRez' => '33554432',
        /// <summary>Can always create landmarks for group owned parcels</summary>
        'AllowLandmark' => '67108864',
        /// <summary>Can use voice chat in Group Chat sessions</summary>
        'AllowVoiceChat' => '134217728',
        /// <summary>Can set home location on any group owned parcel</summary>
        'AllowSetHome' => '268435456',
        /// <summary>Can modify public access settings for group owned parcels</summary>
        'LandManageAllowed' => '536870912',
        /// <summary>Can manager parcel ban lists on group owned land</summary>
        'LandManageBanned' => '1073741824',
        /// <summary>Can manage pass list sales information</summary>
        'LandManagePasses' => '2147483648',
        /// <summary>Can eject and freeze other avatars on group owned land</summary>
        'LandEjectAndFreeze' => '4294967296',
        /// <summary>Can return objects set to group</summary>
        'ReturnGroupSet' => '8589934592',
        /// <summary>Can return non-group owned/set objects</summary>
        'ReturnNonGroup' => '17179869184',
        /// <summary>Can landscape using Linden plants</summary>
        'LandGardening' => '34359738368',
        /// <summary>Can deed objects to group</summary>
        'DeedObject' => '68719476736',
        /// <summary>Can moderate group chat sessions</summary>
        'ModerateChat' => '137438953472',
        /// <summary>Can move group owned objects</summary>
        'ObjectManipulate' => '274877906944',
        /// <summary>Can set group owned objects for-sale</summary>
        'ObjectSetForSale' => '549755813888',
        /// <summary>Pay group liabilities and receive group dividends</summary>
        'Accountable' => '1099511627776',
        /// <summary>Can send group notices</summary>
        'SendNotices'    => '4398046511104',
        /// <summary>Can receive group notices</summary>
        'ReceiveNotices' => '8796093022208',
        /// <summary>Can create group proposals</summary>
        'StartProposal' => '17592186044416',
        /// <summary>Can vote on group proposals</summary>
        'VoteOnProposal' => '35184372088832',
        /// <summary>Can return group owned objects</summary>
        'ReturnGroupOwned' => '281474976710656',
        /// <summary>Members are visible to non-owners</summary>
		    'RoleMembersVisible' => '140737488355328'
		);
	
    $uuidZero = "00000000-0000-0000-0000-000000000000";
    
    $groupDBCon = mysql_connect($dbHost,$dbUser,$dbPassword);
    if (!$groupDBCon)
    {
        die('Could not connect: ' . mysql_error());
    }
    mysql_select_db($dbName, $groupDBCon);

    // This is filled in by secure()
    $requestingAgent = $uuidZero;
    
    function test() 
    {
        return array('name' => 'Joe','age' => 27);
    }

    // Use a common signature for all the group functions  ->  struct foo($struct)
    $common_sig = array(array($xmlrpcStruct, $xmlrpcStruct));

    function createGroup($params)
    {
        if( is_array($error = secureRequest($params, TRUE)) )
        {
            return $error;
        }
	
        global $groupEnforceGroupPerms, $requestingAgent, $uuidZero, $groupDBCon;

        $groupID        = $params["GroupID"];
        $name           = $params["Name"];
        $charter        = $params["Charter"];
        $insigniaID     = $params["InsigniaID"];
        $founderID      = $params["FounderID"];
        $membershipFee  = $params["MembershipFee"];
        $openEnrollment = $params["OpenEnrollment"];
        $showInList     = $params["ShowInList"];
        $allowPublish   = $params["AllowPublish"];
        $maturePublish  = $params["MaturePublish"];
        $ownerRoleID    = $params["OwnerRoleID"];
        $everyonePowers = $params["EveryonePowers"];
        $ownersPowers   = $params["OwnersPowers"];
        
        $escapedParams         = array_map("mysql_real_escape_string", $params);
        $escapedGroupID        = $escapedParams["GroupID"];
        $escapedName           = $escapedParams["Name"];
        $escapedCharter        = $escapedParams["Charter"];
        $escapedInsigniaID     = $escapedParams["InsigniaID"];
        $escapedFounderID      = $escapedParams["FounderID"];
        $escapedMembershipFee  = $escapedParams["MembershipFee"];
        $escapedOpenEnrollment = $escapedParams["OpenEnrollment"];
        $escapedShowInList     = $escapedParams["ShowInList"];
        $escapedAllowPublish   = $escapedParams["AllowPublish"];
        $escapedMaturePublish  = $escapedParams["MaturePublish"];
        $escapedOwnerRoleID    = $escapedParams["OwnerRoleID"];

        // Create group
        $sql = "INSERT INTO osgroup
                (GroupID, Name, Charter, InsigniaID, FounderID, MembershipFee, OpenEnrollment, ShowInList, AllowPublish, MaturePublish, OwnerRoleID)
                VALUES
                ('$escapedGroupID', '$escapedName', '$escapedCharter', '$escapedInsigniaID', '$escapedFounderID', $escapedMembershipFee, $escapedOpenEnrollment, $escapedShowInList, $escapedAllowPublish, $escapedMaturePublish, '$escapedOwnerRoleID')";
        
        if (!mysql_query($sql, $groupDBCon))
        {
            return array('error' => "Could not successfully run query ($sql) from DB: " . mysql_error(), 'params' => var_export($params, TRUE));
        }
        
        // Create Everyone Role
        // NOTE: FIXME: This is a temp fix until the libomv enum for group powers is fixed in OpenSim
		
        $result = _addRoleToGroup(array('GroupID' => $groupID, 'RoleID' => $uuidZero, 'Name' => 'Everyone', 'Description' => 'Everyone in the group is in the everyone role.', 'Title' => "Member of $name", 'Powers' => $everyonePowers));
        if( isset($result['error']) )
        {
            return $result;
        }

        // Create Owner Role
        $result = _addRoleToGroup(array('GroupID' => $groupID, 'RoleID' => $ownerRoleID, 'Name' => 'Owners', 'Description' => "Owners of $name", 'Title' => "Owner of $name", 'Powers' => $ownersPowers));
        if( isset($result['error']) )
        {
            return $result;
        }

        // Add founder to group, will automatically place them in the Everyone Role, also places them in specified Owner Role
        $result = _addAgentToGroup(array('AgentID' => $founderID, 'GroupID' => $groupID, 'RoleID' => $ownerRoleID));
        if( isset($result['error']) )
        {
            return $result;
        }
        
        // Select the owner's role for the founder
        $result = _setAgentGroupSelectedRole(array('AgentID' => $founderID, 'RoleID' => $ownerRoleID, 'GroupID' => $groupID));
        if( isset($result['error']) )
        {
            return $result;
        }
        
        // Set the new group as the founder's active group
        $result = _setAgentActiveGroup(array('AgentID' => $founderID, 'GroupID' => $groupID));
        if( isset($result['error']) )
        {
            return $result;
        }
        
        return getGroup(array("GroupID"=>$groupID));
    }
    
	  // Private method, does not include security, to only be called from places that have already verified security
    function _addRoleToGroup($params)
    {
        $everyonePowers = 8796495740928; // This should now be fixed, when libomv was updated...		
	
        global $groupEnforceGroupPerms, $requestingAgent, $uuidZero, $groupDBCon, $groupPowers;
        $groupID = mysql_real_escape_string( $params['GroupID'] );
        $roleID  = mysql_real_escape_string( $params['RoleID'] );
        $name    = mysql_real_escape_string( $params['Name'] );
        $desc    = mysql_real_escape_string( $params['Description'] );
        $title   = mysql_real_escape_string( $params['Title'] );
        $powers  = mysql_real_escape_string( $params['Powers'] );

        if( !isset($powers) || ($powers == 0) || ($powers == '') )
        {
            $powers = $everyonePowers;
        }
        
        $sql = " INSERT INTO osrole (GroupID, RoleID, Name, Description, Title, Powers) VALUES "
              ." ('$groupID', '$roleID', '$name', '$desc', '$title', $powers)";

        if (!mysql_query($sql, $groupDBCon))
        {
            return array('error' => "Could not successfully run query ($sql) from DB: " . mysql_error()
                       , 'method' => 'addRoleToGroup'
                       , 'params' => var_export($params, TRUE));
        }
        
        return array("success" => "true");
    }
	
    function addRoleToGroup($params)
    {
        if( is_array($error = secureRequest($params, TRUE)) )
        {
            return $error;
        }
      
        global $groupEnforceGroupPerms, $requestingAgent, $uuidZero, $groupDBCon, $groupPowers;
        $groupID = $params['GroupID'];
          
        // Verify the requesting agent has permission
        if( is_array($error = checkGroupPermission($groupID, $groupPowers['CreateRole'])) )
        {
            return $error;
        }

        return _addRoleToGroup($params);
    }
    
    function updateGroupRole($params)
    {
        if( is_array($error = secureRequest($params, TRUE)) )
        {
            return $error;
        }
		
        global $groupEnforceGroupPerms, $requestingAgent, $uuidZero, $groupDBCon, $groupPowers;
        $groupID = mysql_real_escape_string( $params['GroupID'] );
        $roleID  = mysql_real_escape_string( $params['RoleID'] );
        $name    = mysql_real_escape_string( $params['Name'] );
        $desc    = mysql_real_escape_string( $params['Description'] );
        $title   = mysql_real_escape_string( $params['Title'] );
        $powers  = mysql_real_escape_string( $params['Powers'] );
        
        // Verify the requesting agent has permission
        if( is_array($error = checkGroupPermission($groupID, $groupPowers['RoleProperties'])) )
        {
            return $error;
        }
		
        $sql = " UPDATE osrole SET RoleID = '$roleID' ";
        if( isset($params['Name']) )
        {
            $sql .= ", Name = '$name'";
        }
        if( isset($params['Description']) )
        {
            $sql .= ", Description = '$desc'";
        }
        if( isset($params['Title']) )
        {
            $sql .= ", Title = '$title'";
        }
        if( isset($params['Powers']) )
        {
            $sql .= ", Powers = $powers";
        }
        
        $sql .= " WHERE GroupID = '$groupID' AND RoleID = '$roleID'";

        if (!mysql_query($sql, $groupDBCon))
        {
            return array('error' => "Could not successfully run query ($sql) from DB: " . mysql_error(), 'params' => var_export($params, TRUE));
        }
        
        return array("success" => "true");
    }
    
    function removeRoleFromGroup($params)
    {
        if( is_array($error = secureRequest($params, TRUE)) )
        {
            return $error;
        }
		
        global $groupEnforceGroupPerms, $requestingAgent, $uuidZero, $groupDBCon, $groupPowers;
        $groupID = mysql_real_escape_string( $params['GroupID'] );
        $roleID  = mysql_real_escape_string( $params['RoleID'] );
        
        if( is_array($error = checkGroupPermission($groupID, $groupPowers['RoleProperties'])) )
        {
            return $error;
        }
		
        /// 1. Remove all members from Role
        /// 2. Set selected Role to uuidZero for anyone that had the role selected
        /// 3. Delete roll
        
        $sql = "DELETE FROM osgrouprolemembership WHERE GroupID = '$groupID' AND RoleID = '$roleID'";
        if (!mysql_query($sql, $groupDBCon))
        {
            return array('error' => "Could not successfully run query ($sql) from DB: " . mysql_error(), 'params' => var_export($params, TRUE));
        }
        
        $sql = "UPDATE osgroupmembership SET SelectedRoleID = '$uuidZero' WHERE GroupID = '$groupID' AND SelectedRoleID = '$roleID'";
        if (!mysql_query($sql, $groupDBCon))
        {
            return array('error' => "Could not successfully run query ($sql) from DB: " . mysql_error(), 'params' => var_export($params, TRUE));
        }
        
        $sql = "DELETE FROM osrole WHERE GroupID = '$groupID' AND RoleID = '$roleID'";
        if (!mysql_query($sql, $groupDBCon))
        {
            return array('error' => "Could not successfully run query ($sql) from DB: " . mysql_error(), 'params' => var_export($params, TRUE));
        }
        
        return array("success" => "true");
    }
    
    function getGroup($params)
    {
        if( is_array($error = secureRequest($params, FALSE)) )
        {
          return $error;
        }
		
        return _getGroup($params);
    }
		
    function _getGroup($params)
    {
        global $groupEnforceGroupPerms, $requestingAgent, $uuidZero, $groupDBCon;
        $sql = " SELECT osgroup.GroupID, osgroup.Name, Charter, InsigniaID, FounderID, MembershipFee, OpenEnrollment, ShowInList, AllowPublish, MaturePublish, OwnerRoleID"
              ." , count(osrole.RoleID) as GroupRolesCount, count(osgroupmembership.AgentID) as GroupMembershipCount "
              ." FROM osgroup "
              ." LEFT JOIN osrole ON (osgroup.GroupID = osrole.GroupID)"
              ." LEFT JOIN osgroupmembership ON (osgroup.GroupID = osgroupmembership.GroupID)"
              ." WHERE ";

        if( isset($params['GroupID']) )
        {
            $sql .= "osgroup.GroupID = '" . mysql_real_escape_string($params['GroupID']). "'";
        } 
        else if( isset($params['Name']) ) 
        {
            $sql .= "osgroup.Name = '" . mysql_real_escape_string($params['Name']) . "'";
        } 
        else 
        {
            return array("error" => "Must specify GroupID or Name");
        }
        
        $sql .= " GROUP BY osgroup.GroupID, osgroup.name, charter, insigniaID, founderID, membershipFee, openEnrollment, showInList, allowPublish, maturePublish, ownerRoleID";
        
        $result = mysql_query($sql, $groupDBCon);
        
        if (!$result) 
        {
            return array('error' => "Could not successfully run query ($sql) from DB: " . mysql_error(), 'params' => var_export($params, TRUE));
        }

        if (mysql_num_rows($result) == 0) 
        {
            return array('succeed' => 'false', 'error' => 'Group Not Found', 'params' => var_export($params, TRUE), 'sql' => $sql);
        }
        
        return mysql_fetch_assoc($result);
    }        
    
    function updateGroup($params)
    {
        if( is_array($error = secureRequest($params, TRUE)) )
        {
          return $error;
        }
		
        global $groupEnforceGroupPerms, $requestingAgent, $uuidZero, $groupDBCon, $groupPowers;
        $groupID = mysql_real_escape_string( $params["GroupID"] );
        $charter = mysql_real_escape_string( $params["Charter"] );
        $insigniaID = mysql_real_escape_string( $params["InsigniaID"] );
        $membershipFee = mysql_real_escape_string( $params["MembershipFee"] );
        $openEnrollment = mysql_real_escape_string( $params["OpenEnrollment"] );
        $showInList = mysql_real_escape_string( $params["ShowInList"] );
        $allowPublish = mysql_real_escape_string( $params["AllowPublish"] );
        $maturePublish = mysql_real_escape_string( $params["MaturePublish"] );
        
        if( is_array($error = checkGroupPermission($groupID, $groupPowers['ChangeOptions'])) )
        {
            return $error;
        }
		
        // Create group
        $sql = "UPDATE osgroup
                SET
                    Charter = '$charter'
                    , InsigniaID = '$insigniaID'
                    , MembershipFee = $membershipFee
                    , OpenEnrollment= $openEnrollment
                    , ShowInList    = $showInList
                    , AllowPublish  = $allowPublish
                    , MaturePublish = $maturePublish
                WHERE
                    GroupID = '$groupID'";
        
        if (!mysql_query($sql, $groupDBCon))
        {
            return array('error' => "Could not successfully run query ($sql) from DB: " . mysql_error(), 'params' => var_export($params, TRUE));
        }

        return array('success' => 'true');
    }

    function findGroups($params)
    {
        if( is_array($error = secureRequest($params, FALSE)) )
        {
            return $error;
        }
		
        global $groupEnforceGroupPerms, $requestingAgent, $uuidZero, $groupDBCon;
        $search = mysql_real_escape_string( $params['Search'] );
        
        $sql = " SELECT osgroup.GroupID, osgroup.Name, count(osgroupmembership.AgentID) as Members "
              ." FROM osgroup LEFT JOIN osgroupmembership ON (osgroup.GroupID = osgroupmembership.GroupID) "
              ." WHERE "
			  ." (    MATCH (osgroup.name) AGAINST ('$search' IN BOOLEAN MODE)"
              ."   OR osgroup.name LIKE '%$search%'"
              ."   OR osgroup.name REGEXP '$search'"
			  ." ) AND ShowInList = 1" 
              ." GROUP BY osgroup.GroupID, osgroup.Name";
        
        $result = mysql_query($sql, $groupDBCon);
        
        if (!$result) 
        {
            return array('error' => "Could not successfully run query ($sql) from DB: " . mysql_error(), 'params' => var_export($params, TRUE));
        }

        if( mysql_num_rows($result) == 0 )
        {
            return array('succeed' => 'false', 'error' => 'No groups found.', 'params' => var_export($params, TRUE), 'sql' => $sql);
        }
        
        $results = array();

        while ($row = mysql_fetch_assoc($result)) 
        {
            $groupID = $row['GroupID'];
            $results[$groupID] = $row;
        }
        
        return array('results' => $results, 'success' => TRUE);
    }
    
    function _setAgentActiveGroup($params)
    {
        global $groupEnforceGroupPerms, $requestingAgent, $uuidZero, $groupDBCon;
        $agentID = mysql_real_escape_string( $params['AgentID'] );
        $groupID = mysql_real_escape_string( $params['GroupID'] );
		
        $sql = " UPDATE osagent "
              ." SET ActiveGroupID = '$groupID'"
              ." WHERE AgentID = '$agentID'";
    
        if (!mysql_query($sql, $groupDBCon))
        {
            return array('error' => "Could not successfully run query ($sql) from DB: " . mysql_error(), 'params' => var_export($params, TRUE));
        }
        
        if( mysql_affected_rows() == 0 )
        {
            $sql = " INSERT INTO osagent (ActiveGroupID, AgentID) VALUES "
                  ." ('$groupID', '$agentID')";
        
            if (!mysql_query($sql, $groupDBCon))
            {
                return array('error' => "Could not successfully run query ($sql) from DB: " . mysql_error(), 'params' => var_export($params, TRUE));
            }
        }
    
        return array("success" => "true");
    }

    function setAgentActiveGroup($params)
    {
        if( is_array($error = secureRequest($params, TRUE)) )
        {
            return $error;
        }
		
        global $groupEnforceGroupPerms, $requestingAgent, $uuidZero, $groupDBCon;
        $agentID = $params['AgentID'];
        $groupID = $params['GroupID'];
        
        if( isset($requestingAgent) && ($requestingAgent != $uuidZero) && ($requestingAgent != $agentID) )
        {
            return array('error' => "Agent can only change their own Selected Group Role", 'params' => var_export($params, TRUE));
        }
        
        return _setAgentActiveGroup($params);
    }
    
    function addAgentToGroup($params)
    {
        if( is_array($error = secureRequest($params, TRUE)) )
        {
            return $error;
        }
		
        global $groupEnforceGroupPerms, $requestingAgent, $uuidZero, $groupDBCon, $groupPowers;
        $groupID = $params["GroupID"];
        $agentID = $params["AgentID"];        
		
        if( is_array($error = checkGroupPermission($groupID, $groupPowers['AssignMember'])) )
        {
            // If they don't have direct permission, check to see if the group is marked for open enrollment
            $groupInfo = _getGroup( array ('GroupID' => $groupID) );
          
            if( isset($groupInfo['error']))
            {
                return $groupInfo;
            }

            if($groupInfo['OpenEnrollment'] != 1)
            {
                $escapedAgentID = mysql_real_escape_string($agentID);
                $escapedGroupID = mysql_real_escape_string($groupID);

                // Group is not open enrollment, check if the specified agentid has an invite
                $sql = " SELECT GroupID, RoleID, AgentID FROM osgroupinvite"
                      ." WHERE osgroupinvite.AgentID = '$escapedAgentID' AND osgroupinvite.GroupID = '$escapedGroupID'";
                        
                $results = mysql_query($sql, $groupDBCon);
                if (!$results) 
                {
                    return array('error' => "Could not successfully run query ($sql) from DB: " . mysql_error(), 'params' => var_export($params, TRUE));
                }
                  
                if( mysql_num_rows($results) == 1 )
                {
                    // if there is an invite, make sure we're adding the user to the role specified in the invite
                    $inviteInfo = mysql_fetch_assoc($results);
                    $params['RoleID'] = $inviteInfo['RoleID'];
                } 
                else 
                {
                    // Not openenrollment, not invited, return permission denied error
                    return $error;
                }
            } 
        }

        return _addAgentToGroup($params);
    }
    
	  // Private method, does not include security, to only be called from places that have already verified security
    function _addAgentToGroup($params)
    {
        global $groupEnforceGroupPerms, $requestingAgent, $uuidZero, $groupDBCon;
        $agentID = $params["AgentID"];
        $groupID = $params["GroupID"];
        
        $roleID  = $uuidZero;
        if( isset($params["RoleID"]) )
        {
            $roleID = $params["RoleID"];
        }

        $escapedAgentID = mysql_real_escape_string($agentID);
        $escapedGroupID = mysql_real_escape_string($groupID);
        $escapedRoleID = mysql_real_escape_string($roleID);
    
        // Check if agent already a member
        $sql = " SELECT count(AgentID) as isMember FROM osgroupmembership WHERE AgentID = '$escapedAgentID' AND GroupID = '$escapedGroupID'";
        $result = mysql_query($sql, $groupDBCon);
        if (!$result)
        {
            return array('error' => "Could not successfully run query ($sql) from DB: " . mysql_error(), 'params' => var_export($params, TRUE));
        }

        // If not a member, add membership, select role (defaults to uuidZero, or everyone role)
        if( mysql_result($result, 0) == 0 )
        {
            $sql = " INSERT INTO osgroupmembership (GroupID, AgentID, Contribution, ListInProfile, AcceptNotices, SelectedRoleID) VALUES "
                  ."('$escapedGroupID','$escapedAgentID', 0, 1, 1,'$escapedRoleID')";
        
            if (!mysql_query($sql, $groupDBCon))
            {
                return array('error' => "Could not successfully run query ($sql) from DB: " . mysql_error(), 'params' => var_export($params, TRUE));
            }
        }
        
        // Make sure they're in the Everyone role
        $result = _addAgentToGroupRole(array("GroupID" => $groupID, "RoleID" => $uuidZero, "AgentID" => $agentID));
        if( isset($result['error']) )
        {
            return $result;
        }
        
        // Make sure they're in specified role, if they were invited
        if( $roleID != $uuidZero )
        {
            $result = _addAgentToGroupRole(array("GroupID" => $groupID, "RoleID" => $roleID, "AgentID" => $agentID));
            if( isset($result['error']) )
            {
                return $result;
            }
        }

		    //Set the role they were invited to as their selected role
        _setAgentGroupSelectedRole(array('AgentID' => $agentID, 'RoleID' => $roleID, 'GroupID' => $groupID));
		
        // Set the group as their active group.
        // _setAgentActiveGroup(array("GroupID" => $groupID, "AgentID" => $agentID));
		
        return array("success" => "true");
    }
    
    function removeAgentFromGroup($params)
    {
        if( is_array($error = secureRequest($params, TRUE)) )
        {
            return $error;
        }
		
        global $groupEnforceGroupPerms, $requestingAgent, $uuidZero, $groupDBCon, $groupPowers;
        $agentID = $params["AgentID"];
        $groupID = $params["GroupID"];

        // An agent is always allowed to remove themselves from a group -- so only check if the requesting agent is different then the agent being removed.
        if( $agentID != $requestingAgent )
        {
            if( is_array($error = checkGroupPermission($groupID, $groupPowers['RemoveMember'])) )
            {
                return $error;
            }
        }

        $escapedAgentID = mysql_real_escape_string($agentID);
        $escapedGroupID = mysql_real_escape_string($groupID);
		
        // 1. If group is agent's active group, change active group to uuidZero
        // 2. Remove Agent from group (osgroupmembership)
        // 3. Remove Agent from all of the groups roles (osgrouprolemembership)
        
        $sql = " UPDATE osagent "
              ." SET ActiveGroupID = '$uuidZero'"
              ." WHERE AgentID = '$escapedAgentID' AND ActiveGroupID = '$escapedGroupID'";

        if (!mysql_query($sql, $groupDBCon))
        {
            return array('error' => "Could not successfully run query ($sql) from DB: " . mysql_error(), 'params' => var_export($params, TRUE));
        }
        
        $sql = " DELETE FROM osgroupmembership "
              ." WHERE AgentID = '$agentID' AND GroupID = '$groupID'";
        if (!mysql_query($sql, $groupDBCon))
        {
            return array('error' => "Could not successfully run query ($sql) from DB: " . mysql_error(), 'params' => var_export($params, TRUE));
        }
        
        $sql = " DELETE FROM osgrouprolemembership "
              ." WHERE AgentID = '$escapedAgentID' AND GroupID = '$escapedGroupID'";
        if (!mysql_query($sql, $groupDBCon))
        {
            return array('error' => "Could not successfully run query ($sql) from DB: " . mysql_error(), 'params' => var_export($params, TRUE));
        }
        
        return array("success" => "true");
    }
    
    function _addAgentToGroupRole($params)
    {
        global $groupEnforceGroupPerms, $requestingAgent, $uuidZero, $groupDBCon;
        $agentID = mysql_real_escape_string($params["AgentID"]);
        $groupID = mysql_real_escape_string($params["GroupID"]);
        $roleID = mysql_real_escape_string($params["RoleID"]);
    
        // Check if agent already a member
        $sql = " SELECT count(AgentID) as isMember FROM osgrouprolemembership WHERE AgentID = '$agentID' AND RoleID = '$roleID' AND GroupID = '$groupID'";
        $result = mysql_query($sql, $groupDBCon);
        if (!$result)
        {
            return array('error' => "Could not successfully run query ($sql) from DB: " . mysql_error(), 'params' => var_export($params, TRUE));
        }
    
        if( mysql_result($result, 0) == 0 )
        {
            $sql = " INSERT INTO osgrouprolemembership (GroupID, RoleID, AgentID) VALUES "
                  ."('$groupID', '$roleID', '$agentID')";
        
            if (!mysql_query($sql, $groupDBCon))
            {
                return array('error' => "Could not successfully run query ($sql) from DB: " . mysql_error(), 'params' => var_export($params, TRUE));
            }
        }
    
        return array("success" => "true");
    }
    
    function addAgentToGroupRole($params)
    {
        if( is_array($error = secureRequest($params, TRUE)) )
        {
            return $error;
        }
		
        global $groupEnforceGroupPerms, $requestingAgent, $uuidZero, $groupDBCon, $groupPowers;
        $agentID = $params["AgentID"];
        $groupID = $params["GroupID"];
        $roleID = $params["RoleID"];

        $escapedAgentID = mysql_real_escape_string($agentID);
        $escapedGroupID = mysql_real_escape_string($groupID);
        $escapedRoleID = mysql_real_escape_string($roleID);
    
        // Check if being assigned to Owners role, assignments to an owners role can only be requested by owners.
        $sql = " SELECT OwnerRoleID, osgrouprolemembership.AgentID "
              ." FROM osgroup LEFT JOIN osgrouprolemembership ON (osgroup.GroupID = osgrouprolemembership.GroupID AND osgroup.OwnerRoleID = osgrouprolemembership.RoleID) "
            ." WHERE osgrouprolemembership.AgentID = '" . mysql_real_escape_string($requestingAgent) . "' AND osgroup.GroupID = '$escapedGroupID'";
			  
        $results = mysql_query($sql, $groupDBCon);
        if (!$results) 
        {
            return array('error' => "Could not successfully run query ($sql) from DB: " . mysql_error(), 'params' => var_export($params, TRUE));
        }
		
        if( mysql_num_rows($results) == 0 )
        {
			return array('error' => "Group ($groupID) not found or Agent ($agentID) is not in the owner's role", 'params' => var_export($params, TRUE));
		}

        $ownerRoleInfo = mysql_fetch_assoc($results);
        if( ($ownerRoleInfo['OwnerRoleID'] == $roleID) && ($ownerRoleInfo['AgentID'] != $requestingAgent) )
        {
            return array('error' => "Requesting agent $requestingAgent is not a member of the Owners Role and cannot add members to the owners role.", 'params' => var_export($params, TRUE));
        }
	
        if( is_array($error = checkGroupPermission($groupID, $groupPowers['AssignMember'])) )
        {
            return $error;
        }
	
		return _addAgentToGroupRole($params);
    }
    
    function removeAgentFromGroupRole($params)
    {
        if( is_array($error = secureRequest($params, TRUE)) )
        {
            return $error;
        }
		
        global $groupEnforceGroupPerms, $requestingAgent, $uuidZero, $groupDBCon, $groupPowers;
        $agentID = mysql_real_escape_string($params["AgentID"]);
        $groupID = mysql_real_escape_string($params["GroupID"]);
        $roleID  = mysql_real_escape_string($params["RoleID"]);

        if( is_array($error = checkGroupPermission($groupID, $groupPowers['AssignMember'])) )
        {
            return $error;
        }
		
        // If agent has this role selected, change their selection to everyone (uuidZero) role
        $sql = " UPDATE osgroupmembership SET SelectedRoleID = '$uuidZero' WHERE AgentID = '$agentID' AND GroupID = '$groupID' AND SelectedRoleID = '$roleID'";
        $result = mysql_query($sql, $groupDBCon);
        if (!$result)
        {
            return array('error' => "Could not successfully run query ($sql) from DB: " . mysql_error(), 'params' => var_export($params, TRUE));
        }

        $sql = " DELETE FROM osgrouprolemembership WHERE AgentID = '$agentID' AND GroupID = '$groupID' AND RoleID = '$roleID'";
    
        if (!mysql_query($sql, $groupDBCon))
        {
            return array('error' => "Could not successfully run query ($sql) from DB: " . mysql_error(), 'params' => var_export($params, TRUE));
        }
        
        return array("success" => "true");
    }
    
    function _setAgentGroupSelectedRole($params)
    {
        global $groupEnforceGroupPerms, $requestingAgent, $uuidZero, $groupDBCon;
        $agentID = mysql_real_escape_string($params["AgentID"]);
        $groupID = mysql_real_escape_string($params["GroupID"]);
        $roleID = mysql_real_escape_string($params["RoleID"]);
    
        $sql = " UPDATE osgroupmembership SET SelectedRoleID = '$roleID' WHERE AgentID = '$agentID' AND GroupID = '$groupID'";
        $result = mysql_query($sql, $groupDBCon);
        if (!$result)
        {
            return array('error' => "Could not successfully run query ($sql) from DB: " . mysql_error(), 'params' => var_export($params, TRUE));
        }
    
        return array('success' => 'true');
    }

    function setAgentGroupSelectedRole($params)
    {
        if( is_array($error = secureRequest($params, TRUE)) )
        {
            return $error;
        }
		
        global $groupEnforceGroupPerms, $requestingAgent, $uuidZero, $groupDBCon;
        $agentID = $params["AgentID"];
        $groupID = $params["GroupID"];
        $roleID = $params["RoleID"];
    
        if( isset($requestingAgent) && ($requestingAgent != $uuidZero) && ($requestingAgent != $agentID) )
        {
            return array('error' => "Agent can only change their own Selected Group Role", 'params' => var_export($params, TRUE));
        }
	
        return _setAgentGroupSelectedRole($params);
    }
	
    function getAgentGroupMembership($params)
    {
        if( is_array($error = secureRequest($params, FALSE)) )
        {
            return $error;
        }
		
        global $groupEnforceGroupPerms, $requestingAgent, $uuidZero, $groupDBCon;
        $groupID = mysql_real_escape_string($params['GroupID']);
        $agentID = mysql_real_escape_string($params['AgentID']);
        
        $sql = " SELECT osgroup.GroupID, osgroup.Name as GroupName, osgroup.Charter, osgroup.InsigniaID, osgroup.FounderID, osgroup.MembershipFee, osgroup.OpenEnrollment, osgroup.ShowInList, osgroup.AllowPublish, osgroup.MaturePublish"
              ." , osgroupmembership.Contribution, osgroupmembership.ListInProfile, osgroupmembership.AcceptNotices"
              ." , osgroupmembership.SelectedRoleID, osrole.Title"
              ." , osagent.ActiveGroupID "
              ." FROM osgroup JOIN osgroupmembership ON (osgroup.GroupID = osgroupmembership.GroupID)"
              ."              JOIN osrole ON (osgroupmembership.SelectedRoleID = osrole.RoleID AND osgroupmembership.GroupID = osrole.GroupID)"
              ."              JOIN osagent ON (osagent.AgentID = osgroupmembership.AgentID)"
              ." WHERE osgroup.GroupID = '$groupID' AND osgroupmembership.AgentID = '$agentID'";
        
        $groupmembershipResult = mysql_query($sql, $groupDBCon);
        if (!$groupmembershipResult) 
        {
            return array('error' => "Could not successfully run query ($sql) from DB: " . mysql_error(), 'params' => var_export($params, TRUE));
        }
        
        if( mysql_num_rows($groupmembershipResult) == 0 )
        {
            return array('succeed' => 'false', 'error' => 'None Found', 'params' => var_export($params, TRUE), 'sql' => $sql);
        }
        
        $groupMembershipInfo = mysql_fetch_assoc($groupmembershipResult);
        
        $sql = " SELECT BIT_OR(osrole.Powers) AS GroupPowers"
              ." FROM osgrouprolemembership JOIN osrole ON (osgrouprolemembership.GroupID = osrole.GroupID AND osgrouprolemembership.RoleID = osrole.RoleID)"
              ." WHERE osgrouprolemembership.GroupID = '$groupID' AND osgrouprolemembership.AgentID = '$agentID'";
        $groupPowersResult = mysql_query($sql, $groupDBCon);
        if (!$groupPowersResult) 
        {
            return array('error' => "Could not successfully run query ($sql) from DB: " . mysql_error(), 'params' => var_export($params, TRUE));
        }
        $groupPowersInfo = mysql_fetch_assoc($groupPowersResult);
        
        return array_merge($groupMembershipInfo, $groupPowersInfo);
    }

    function getAgentGroupMemberships($params)
    {
        if( is_array($error = secureRequest($params, FALSE)) )
        {
            return $error;
        }
		
        global $groupEnforceGroupPerms, $requestingAgent, $uuidZero, $groupDBCon;
        $agentID = mysql_real_escape_string($params['AgentID']);
        
        $sql = " SELECT osgroup.GroupID, osgroup.Name as GroupName, osgroup.Charter, osgroup.InsigniaID, osgroup.FounderID, osgroup.MembershipFee, osgroup.OpenEnrollment, osgroup.ShowInList, osgroup.AllowPublish, osgroup.MaturePublish"
              ." , osgroupmembership.Contribution, osgroupmembership.ListInProfile, osgroupmembership.AcceptNotices"
              ." , osgroupmembership.SelectedRoleID, osrole.Title"
              ." , IFNULL(osagent.ActiveGroupID, '$uuidZero') AS ActiveGroupID"
              ." FROM osgroup JOIN osgroupmembership ON (osgroup.GroupID = osgroupmembership.GroupID)"
              ."              JOIN osrole ON (osgroupmembership.SelectedRoleID = osrole.RoleID AND osgroupmembership.GroupID = osrole.GroupID)"
              ."         LEFT JOIN osagent ON (osagent.AgentID = osgroupmembership.AgentID)"
              ." WHERE osgroupmembership.AgentID = '$agentID'";
        
        $groupmembershipResults = mysql_query($sql, $groupDBCon);
        if (!$groupmembershipResults) 
        {
            return array('error' => "Could not successfully run query ($sql) from DB: " . mysql_error(), 'params' => var_export($params, TRUE));
        }

        if( mysql_num_rows($groupmembershipResults) == 0 )
        {
            return array('succeed' => 'false', 'error' => 'No Memberships', 'params' => var_export($params, TRUE), 'sql' => $sql);
        }
        
        $groupResults = array();
        while($groupMembershipInfo = mysql_fetch_assoc($groupmembershipResults))
        {
            $groupID = $groupMembershipInfo['GroupID'];
            $sql = " SELECT BIT_OR(osrole.Powers) AS GroupPowers"
                  ." FROM osgrouprolemembership JOIN osrole ON (osgrouprolemembership.GroupID = osrole.GroupID AND osgrouprolemembership.RoleID = osrole.RoleID)"
                  ." WHERE osgrouprolemembership.GroupID = '$groupID' AND osgrouprolemembership.AgentID = '$agentID'";
            $groupPowersResult = mysql_query($sql, $groupDBCon);
            if (!$groupPowersResult) 
            {
                return array('error' => "Could not successfully run query ($sql) from DB: " . mysql_error(), 'params' => var_export($params, TRUE));
            }
            $groupPowersInfo = mysql_fetch_assoc($groupPowersResult);
            $groupResults[$groupID] = array_merge($groupMembershipInfo, $groupPowersInfo);
        }
        
        return $groupResults;
    }
    
    // Parameters should not already be mysql_real_escape_string() escaped
    function canAgentViewRoleMembers( $agentID, $groupID, $roleID )
    {
        global $membersVisibleTo, $groupDBCon;
		
        if( $membersVisibleTo == 'All' ) 
          return true;

        $agentID = mysql_real_escape_string($agentID);
        $groupID = mysql_real_escape_string($groupID);
        $roleID  = mysql_real_escape_string($roleID); 
		
        $sql  = " SELECT CASE WHEN min(OwnerRoleMembership.AgentID) IS NOT NULL THEN 1 ELSE 0 END AS IsOwner ";
        $sql .= " FROM osgroup JOIN osgroupmembership ON (osgroup.GroupID = osgroupmembership.GroupID AND osgroupmembership.AgentID = '$agentID')";
        $sql .= "         LEFT JOIN osgrouprolemembership AS OwnerRoleMembership ON (OwnerRoleMembership.GroupID = osgroup.GroupID ";
        $sql .= "                   AND OwnerRoleMembership.RoleID  = osgroup.OwnerRoleID ";
        $sql .= "                   AND OwnerRoleMembership.AgentID = '$agentID')";
        $sql .= " WHERE osgroup.GroupID = '$groupID' GROUP BY osgroup.GroupID";	
		
        $viewMemberResults = mysql_query($sql, $groupDBCon);
        if (!$viewMemberResults)
        {
            return array('error' => "Could not successfully run query ($sql) from DB: " . mysql_error());
        }
        
        if (mysql_num_rows($viewMemberResults) == 0) 
        {
            return false;
        }
		
        $viewMemberInfo = mysql_fetch_assoc($viewMemberResults);
		
        switch( $membersVisibleTo )
        {
            case 'Group':
                // if we get to here, there is at least one row, so they are a member of the group
                return true;
            case 'Owners':
            default:
                return $viewMemberInfo['IsOwner'];			
        }
    }
	
    function getGroupMembers($params)
    {
        if( is_array($error = secureRequest($params, FALSE)) )
        {
            return $error;
        }
		
        global $groupEnforceGroupPerms, $requestingAgent, $uuidZero, $groupDBCon, $groupPowers;
        $groupID = $params['GroupID'];
        $escapedGroupID = mysql_real_escape_string($groupID);
        
        $sql = " SELECT osgroupmembership.AgentID"
              ." , osgroupmembership.Contribution, osgroupmembership.ListInProfile, osgroupmembership.AcceptNotices"
              ." , osgroupmembership.SelectedRoleID, osrole.Title"
              ." , CASE WHEN OwnerRoleMembership.AgentID IS NOT NULL THEN 1 ELSE 0 END AS IsOwner"
              ." FROM osgroup JOIN osgroupmembership ON (osgroup.GroupID = osgroupmembership.GroupID)"
              ."              JOIN osrole ON (osgroupmembership.SelectedRoleID = osrole.RoleID AND osgroupmembership.GroupID = osrole.GroupID)"
              ."              JOIN osrole AS OwnerRole ON (osgroup.OwnerRoleID  = OwnerRole.RoleID AND osgroup.GroupID  = OwnerRole.GroupID)"
              ."         LEFT JOIN osgrouprolemembership AS OwnerRoleMembership ON (osgroup.OwnerRoleID       = OwnerRoleMembership.RoleID 
                                                                               AND (osgroup.GroupID           = OwnerRoleMembership.GroupID)
                                                                               AND (osgroupmembership.AgentID = OwnerRoleMembership.AgentID))"
              ." WHERE osgroup.GroupID = '$escapedGroupID'";
        
        $groupmemberResults = mysql_query($sql, $groupDBCon);
        if (!$groupmemberResults) 
        {
            return array('error' => "Could not successfully run query ($sql) from DB: " . mysql_error(), 'params' => var_export($params, TRUE));
        }
        
        if (mysql_num_rows($groupmemberResults) == 0) 
        {
            return array('succeed' => 'false', 'error' => 'No Group Members found', 'params' => var_export($params, TRUE), 'sql' => $sql);
        }
        
        $roleMembersVisibleBit = $groupPowers['RoleMembersVisible'];
        $canViewAllGroupRoleMembers = canAgentViewRoleMembers($requestingAgent, $groupID, '');
		
        $memberResults = array();
        while ($memberInfo = mysql_fetch_assoc($groupmemberResults))
        {
            $agentID = $memberInfo['AgentID'];
            $sql = " SELECT BIT_OR(osrole.Powers) AS AgentPowers, ( BIT_OR(osrole.Powers) & $roleMembersVisibleBit) as MemberVisible"
                  ." FROM osgrouprolemembership JOIN osrole ON (osgrouprolemembership.GroupID = osrole.GroupID AND osgrouprolemembership.RoleID = osrole.RoleID)"
                  ." WHERE osgrouprolemembership.GroupID = '$escapedGroupID' AND osgrouprolemembership.AgentID = '$agentID'";
            $memberPowersResult = mysql_query($sql, $groupDBCon);
            if (!$memberPowersResult) 
            {
                return array('error' => "Could not successfully run query ($sql) from DB: " . mysql_error(), 'params' => var_export($params, TRUE));
            }

            $memberPowersCount = mysql_num_rows($memberPowersResult);
            error_log("Found $memberPowersCount rows for agent $agentID for requesting agent $requestingAgent");

            if ($memberPowersCount == 0) 
            {
                if ($canViewAllGroupRoleMembers || $agentID == $requestingAgent)
                {
                    $memberResults[$agentID] = array_merge($memberInfo, array('AgentPowers' => 0));
                } 
                else 
                {
                    // if can't view all group role members and there is no Member Visible bit, then don't return this member's info
                    unset($memberResults[$agentID]);
                }
            } 
            else 
            {
                $memberPowersInfo = mysql_fetch_assoc($memberPowersResult);
                if ($memberPowersInfo['MemberVisible'] || $canViewAllGroupRoleMembers || $agentID == $requestingAgent)
                {
                    $memberResults[$agentID] = array_merge($memberInfo, $memberPowersInfo);
                } 
                else 
                {
                    // if can't view all group role members and there is no Member Visible bit, then don't return this member's info
                    unset($memberResults[$agentID]);
                }
            }
        }

        error_log("Returning " . count($memberResults) . " visible members for group $groupID for agent $agentID");
        
        if (count($memberResults) == 0) 
        {
            return array('succeed' => 'false', 'error' => 'No Visible Group Members found', 'params' => var_export($params, TRUE), 'sql' => $sql);
        }
		
        return $memberResults;
    }
    
    function getAgentActiveMembership($params)
    {
        if( is_array($error = secureRequest($params, FALSE)) )
        {
            return $error;
        }
		
        global $groupEnforceGroupPerms, $requestingAgent, $uuidZero, $groupDBCon;
        $agentID = mysql_real_escape_string($params['AgentID']);
        
        $sql = " SELECT osgroup.GroupID, osgroup.Name as GroupName, osgroup.Charter, osgroup.InsigniaID, osgroup.FounderID, osgroup.MembershipFee, osgroup.OpenEnrollment, osgroup.ShowInList, osgroup.AllowPublish, osgroup.MaturePublish"
              ." , osgroupmembership.Contribution, osgroupmembership.ListInProfile, osgroupmembership.AcceptNotices"
              ." , osgroupmembership.SelectedRoleID, osrole.Title"
              ." , osagent.ActiveGroupID "
              ." FROM osagent JOIN osgroup ON (osgroup.GroupID = osagent.ActiveGroupID)"
              ."              JOIN osgroupmembership ON (osgroup.GroupID = osgroupmembership.GroupID AND osagent.AgentID = osgroupmembership.AgentID)"
              ."              JOIN osrole ON (osgroupmembership.SelectedRoleID = osrole.RoleID AND osgroupmembership.GroupID = osrole.GroupID)"
              ." WHERE osagent.AgentID = '$agentID'";
        
        $groupmembershipResult = mysql_query($sql, $groupDBCon);
        if (!$groupmembershipResult) 
        {
            return array('error' => "Could not successfully run query ($sql) from DB: " . mysql_error(), 'params' => var_export($params, TRUE));
        }
        if (mysql_num_rows($groupmembershipResult) == 0) 
        {
            return array('succeed' => 'false', 'error' => 'No Active Group Specified', 'params' => var_export($params, TRUE), 'sql' => $sql);
        }
        $groupMembershipInfo = mysql_fetch_assoc($groupmembershipResult);
        
        $groupID = $groupMembershipInfo['GroupID'];
        $sql = " SELECT BIT_OR(osrole.Powers) AS GroupPowers"
              ." FROM osgrouprolemembership JOIN osrole ON (osgrouprolemembership.GroupID = osrole.GroupID AND osgrouprolemembership.RoleID = osrole.RoleID)"
              ." WHERE osgrouprolemembership.GroupID = '$groupID' AND osgrouprolemembership.AgentID = '$agentID'";
        $groupPowersResult = mysql_query($sql, $groupDBCon);
        if (!$groupPowersResult) 
        {
            return array('error' => "Could not successfully run query ($sql) from DB: " . mysql_error(), 'params' => var_export($params, TRUE));
        }
        $groupPowersInfo = mysql_fetch_assoc($groupPowersResult);
        
        return array_merge($groupMembershipInfo, $groupPowersInfo);
    }
    
    function getAgentRoles($params)
    {
        if( is_array($error = secureRequest($params, FALSE)) )
        {
            return $error;
        }
		
        global $groupEnforceGroupPerms, $requestingAgent, $uuidZero, $groupDBCon;
        $agentID = mysql_real_escape_string($params['AgentID']);
        
        $sql = " SELECT "
              ." osrole.RoleID, osrole.GroupID, osrole.Title, osrole.Name, osrole.Description, osrole.Powers"
              ." , CASE WHEN osgroupmembership.SelectedRoleID = osrole.RoleID THEN 1 ELSE 0 END AS Selected"
              ." FROM osgroupmembership JOIN osgrouprolemembership  ON (osgroupmembership.GroupID = osgrouprolemembership.GroupID AND osgroupmembership.AgentID = osgrouprolemembership.AgentID)"
              ."                        JOIN osrole ON ( osgrouprolemembership.RoleID = osrole.RoleID AND osgrouprolemembership.GroupID = osrole.GroupID)"
              ."                   LEFT JOIN osagent ON (osagent.AgentID = osgroupmembership.AgentID)"
              ." WHERE osgroupmembership.AgentID = '$agentID'";
              
        if( isset($params['GroupID']) )
        {
            $groupID = $params['GroupID'];
            $sql .= " AND osgroupmembership.GroupID = '$groupID'";
        }

        $roleResults = mysql_query($sql, $groupDBCon);
        if (!$roleResults) 
        {
            return array('error' => "Could not successfully run query ($sql) from DB: " . mysql_error(), 'params' => var_export($params, TRUE));
        }

        if( mysql_num_rows($roleResults) == 0 )
        {
            return array('succeed' => 'false', 'error' => 'None found', 'params' => var_export($params, TRUE), 'sql' => $sql);
        }
        
        $roles = array();
        while($role = mysql_fetch_assoc($roleResults))
        {
            $ID = $role['GroupID'].$role['RoleID'];
            $roles[$ID] = $role;
        }
        
        return $roles;
    }
    
    function getGroupRoles($params)
    {
        if( is_array($error = secureRequest($params, FALSE)) )
        {
          return $error;
        }
		
        global $groupEnforceGroupPerms, $requestingAgent, $uuidZero, $groupDBCon;
        $groupID = mysql_real_escape_string($params['GroupID']);
        
        $sql = " SELECT "
              ." osrole.RoleID, osrole.Name, osrole.Title, osrole.Description, osrole.Powers, count(osgrouprolemembership.AgentID) as Members"
              ." FROM osrole LEFT JOIN osgrouprolemembership ON (osrole.GroupID = osgrouprolemembership.GroupID AND osrole.RoleID = osgrouprolemembership.RoleID)"
              ." WHERE osrole.GroupID = '$groupID'"
              ." GROUP BY osrole.RoleID, osrole.Name, osrole.Title, osrole.Description, osrole.Powers";
              
        $roleResults = mysql_query($sql, $groupDBCon);
        if (!$roleResults) 
        {
            return array('error' => "Could not successfully run query ($sql) from DB: " . mysql_error(), 'params' => var_export($params, TRUE));
        }
        
        if( mysql_num_rows($roleResults) == 0 )
        {
            return array('succeed' => 'false', 'error' => 'No roles found for group', 'params' => var_export($params, TRUE), 'sql' => $sql);
        }
        
        $roles = array();
        while($role = mysql_fetch_assoc($roleResults))
        {
            $RoleID = $role['RoleID'];
            $roles[$RoleID] = $role;
        }
        
        return $roles;
    }

    function getGroupRoleMembers($params)
    {
        if( is_array($error = secureRequest($params, FALSE)) )
        {
            return $error;
        }
		
        global $groupEnforceGroupPerms, $requestingAgent, $uuidZero, $groupDBCon, $groupPowers;
        $groupID = $params['GroupID'];        
		
        $roleMembersVisibleBit = $groupPowers['RoleMembersVisible'];
        $canViewAllGroupRoleMembers = canAgentViewRoleMembers($requestingAgent, $groupID, '');
		
        $escapedGroupID = mysql_real_escape_string($groupID);

        $sql = " SELECT "
              ." osrole.RoleID, osgrouprolemembership.AgentID"
	      		  ." , (osrole.Powers & $roleMembersVisibleBit) as MemberVisible"
              ." FROM osrole JOIN osgrouprolemembership ON (osrole.GroupID = osgrouprolemembership.GroupID AND osrole.RoleID = osgrouprolemembership.RoleID)"
              ." WHERE osrole.GroupID = '$escapedGroupID'";
              
        $memberResults = mysql_query($sql, $groupDBCon);
        if (!$memberResults) 
        {
            return array('error' => "Could not successfully run query ($sql) from DB: " . mysql_error(), 'params' => var_export($params, TRUE));
        }
        
        if( mysql_num_rows($memberResults) == 0 )
        {
            return array('succeed' => 'false', 'error' => 'No role memberships found for group', 'params' => var_export($params, TRUE), 'sql' => $sql);
        }		

        $members = array();
        while($member = mysql_fetch_assoc($memberResults))
        {
            if( $canViewAllGroupRoleMembers || $member['MemberVisible'] || ($member['AgentID'] == $requestingAgent) )
            {
                $Key = $member['AgentID'] . $member['RoleID'];
                $members[$Key ] = $member;
            }
        }
		
        if( count($members) == 0 )
        {
            return array('succeed' => 'false', 'error' => 'No role memberships visible for group', 'params' => var_export($params, TRUE), 'sql' => $sql);
        }
        
        return $members;
    }
    
    function setAgentGroupInfo($params)
    {
        if( is_array($error = secureRequest($params, TRUE)) )
        {
            return $error;
        }
		
        global $groupEnforceGroupPerms, $requestingAgent, $uuidZero, $groupDBCon;
		
        if (isset($params['AgentID'])) {
            $agentID = mysql_real_escape_string($params['AgentID']);
        } else {
            $agentID = "";
        }
        if (isset($params['GroupID'])) {
            $groupID = mysql_real_escape_string($params['GroupID']);
        } else {
            $groupID = "";
        }
        if (isset($params['SelectedRoleID'])) {
            $roleID  = mysql_real_escape_string($params['SelectedRoleID']);
        } else {
            $roleID = "";
        }
        if (isset($params['AcceptNotices'])) {
            $acceptNotices = mysql_real_escape_string($params['AcceptNotices']);
        } else {
            $acceptNotices = 1;
        }
        if (isset($params['ListInProfile'])) {
            $listInProfile  = mysql_real_escape_string($params['ListInProfile']);
        } else {
            $listInProfile = 0;
        }

        if( isset($requestingAgent) && ($requestingAgent != $uuidZero) && ($requestingAgent != $agentID) )
        {
            return array('error' => "Agent can only change their own group info", 'params' => var_export($params, TRUE));
        }
    
        $sql = " UPDATE "
              ."     osgroupmembership"
              ." SET "
              ."    AgentID = '$agentID'";

        if( isset($params['SelectedRoleID']) )
        {
            $sql .="    , SelectedRoleID = '$roleID'";
        }
        if( isset($params['AcceptNotices']) )
        {
            $sql .="    , AcceptNotices = $acceptNotices";
        }
        if( isset($params['ListInProfile']) )
        {
            $sql .="    , ListInProfile = $listInProfile";
        }
        
        $sql .=" WHERE osgroupmembership.GroupID = '$groupID' AND osgroupmembership.AgentID = '$agentID'";
              
        $memberResults = mysql_query($sql, $groupDBCon);
        if (!$memberResults) 
        {
            return array('error' => "Could not successfully run query ($sql) from DB: " . mysql_error(), 'params' => var_export($params, TRUE));
        }
        
        return array('success'=> 'true');
    }
    
    function getGroupNotices($params)
    {
        if( is_array($error = secureRequest($params, FALSE)) )
        {
            return $error;
        }
		
        global $groupEnforceGroupPerms, $requestingAgent, $uuidZero, $groupDBCon;
        $groupID = mysql_real_escape_string($params['GroupID']);
        
        $sql = " SELECT "
              ." GroupID, NoticeID, Timestamp, FromName, Subject, Message, BinaryBucket"
              ." FROM osgroupnotice"
              ." WHERE osgroupnotice.GroupID = '$groupID'";
              
        $results = mysql_query($sql, $groupDBCon);
        if (!$results) 
        {
            return array('error' => "Could not successfully run query ($sql) from DB: " . mysql_error(), 'params' => var_export($params, TRUE));
        }
        
        if( mysql_num_rows($results) == 0 )
        {
            return array('succeed' => 'false', 'error' => 'No Notices', 'params' => var_export($params, TRUE), 'sql' => $sql);
        }
        
        $notices = array();
        while($notice = mysql_fetch_assoc($results))
        {
            $NoticeID = $notice['NoticeID'];
            $notices[$NoticeID] = $notice;
        }
        
        return $notices;
    }

    function getGroupNotice($params)
    {
        if( is_array($error = secureRequest($params, FALSE)) )
        {
            return $error;
        }
		
        global $groupEnforceGroupPerms, $requestingAgent, $uuidZero, $groupDBCon;
        $noticeID = mysql_real_escape_string($params['NoticeID']);
        
        $sql = " SELECT "
              ." GroupID, NoticeID, Timestamp, FromName, Subject, Message, BinaryBucket"
              ." FROM osgroupnotice"
              ." WHERE osgroupnotice.NoticeID = '$noticeID'";
              
        $results = mysql_query($sql, $groupDBCon);
        if (!$results) 
        {
            return array('error' => "Could not successfully run query ($sql) from DB: " . mysql_error(), 'params' => var_export($params, TRUE));
        }
        
        if( mysql_num_rows($results) == 0 )
        {
            return array('succeed' => 'false', 'error' => 'Group Notice Not Found', 'params' => var_export($params, TRUE), 'sql' => $sql);
        }
        
        return mysql_fetch_assoc($results);
    }
    
    function addGroupNotice($params)
    {
        if( is_array($error = secureRequest($params, TRUE)) )
        {
            return $error;
        }
		
        global $groupEnforceGroupPerms, $requestingAgent, $uuidZero, $groupDBCon, $groupPowers;
        $groupID        = mysql_real_escape_string($params['GroupID']);
        $noticeID       = mysql_real_escape_string($params['NoticeID']);
        $fromName       = mysql_real_escape_string($params['FromName']);
        $subject        = mysql_real_escape_string($params['Subject']);
        $binaryBucket   = mysql_real_escape_string($params['BinaryBucket']);
        $message        = mysql_real_escape_string($params['Message']);
        $timeStamp      = mysql_real_escape_string($params['TimeStamp']);

        if( is_array($error = checkGroupPermission($groupID, $groupPowers['SendNotices'])) )
        {
            return $error;
        }
        
        $sql = " INSERT INTO osgroupnotice"
              ." (GroupID, NoticeID, Timestamp, FromName, Subject, Message, BinaryBucket)"
              ." VALUES "
              ." ('$groupID', '$noticeID', $timeStamp, '$fromName', '$subject', '$message', '$binaryBucket')";
              
        $results = mysql_query($sql, $groupDBCon);
        if (!$results) 
        {
            return array('error' => "Could not successfully run query ($sql) from DB: " . mysql_error(), 'params' => var_export($params, TRUE));
        }
        
        return array('success' => 'true');
    }
    
    function addAgentToGroupInvite($params)
    {
        if( is_array($error = secureRequest($params, TRUE)) )
        {
            return $error;
        }
		
        global $groupEnforceGroupPerms, $requestingAgent, $uuidZero, $groupDBCon, $groupPowers;

        if( is_array($error = checkGroupPermission($params['GroupID'], $groupPowers['Invite'])) )
        {
            return $error;
        }

        $inviteID   = mysql_real_escape_string($params['InviteID']);
        $groupID    = mysql_real_escape_string($params['GroupID']);
        $roleID     = mysql_real_escape_string($params['RoleID']);
        $agentID    = mysql_real_escape_string($params['AgentID']);
		
        // Remove any existing invites for this agent to this group
        $sql = " DELETE FROM osgroupinvite"
              ." WHERE osgroupinvite.AgentID = '$agentID' AND osgroupinvite.GroupID = '$groupID'";
              
        $results = mysql_query($sql, $groupDBCon);
        if (!$results) 
        {
            return array('error' => "Could not successfully run query ($sql) from DB: " . mysql_error(), 'params' => var_export($params, TRUE));
        }
        
        // Add new invite for this agent to this group for the specifide role
        $sql = " INSERT INTO osgroupinvite"
              ." (InviteID, GroupID, RoleID, AgentID) VALUES ('$inviteID', '$groupID', '$roleID', '$agentID')";
              
        $results = mysql_query($sql, $groupDBCon);
        if (!$results) 
        {
            return array('error' => "Could not successfully run query ($sql) from DB: " . mysql_error(), 'params' => var_export($params, TRUE));
        }
        
        return array('success' => 'true');
    }

    function getAgentToGroupInvite($params)
    {
        if( is_array($error = secureRequest($params, FALSE)) )
        {
            return $error;
        }

        global $groupEnforceGroupPerms, $requestingAgent, $uuidZero, $groupDBCon;
        $inviteID = mysql_real_escape_string($params['InviteID']);

        $sql = " SELECT GroupID, RoleID, AgentID FROM osgroupinvite"
              ." WHERE osgroupinvite.InviteID = '$inviteID'";
              
        $results = mysql_query($sql, $groupDBCon);
        if (!$results) 
        {
            return array('error' => "Could not successfully run query ($sql) from DB: " . mysql_error(), 'params' => var_export($params, TRUE));
        }
        
        if( mysql_num_rows($results) == 1 )
        {
            $inviteInfo = mysql_fetch_assoc($results);
            $groupID  = $inviteInfo['GroupID'];
            $roleID   = $inviteInfo['RoleID'];
            $agentID  = $inviteInfo['AgentID'];
        
            return array('success' => 'true', 'GroupID'=>$groupID, 'RoleID'=>$roleID, 'AgentID'=>$agentID);
        } 
        else 
        {
            return array('succeed' => 'false', 'error' => 'Invitation not found', 'params' => var_export($params, TRUE), 'sql' => $sql);
        }
    }
    
    function removeAgentToGroupInvite($params)
    {
        if( is_array($error = secureRequest($params, TRUE)) )
        {
            return $error;
        }
	
        global $groupEnforceGroupPerms, $requestingAgent, $uuidZero, $groupDBCon;
        $inviteID = mysql_real_escape_string($params['InviteID']);
        
        $sql = " DELETE FROM osgroupinvite"
              ." WHERE osgroupinvite.InviteID = '$inviteID'";
              
        $results = mysql_query($sql, $groupDBCon);
        if (!$results) 
        {
            return array('error' => "Could not successfully run query ($sql) from DB: " . mysql_error(), 'params' => var_export($params, TRUE));
        }
        
        return array('success' => 'true');
    }
    
    function secureRequest($params, $write = FALSE)
    {
        global $groupWriteKey, $groupReadKey, $verifiedReadKey, $verifiedWriteKey, $groupRequireAgentAuthForWrite, $requestingAgent;
        global $overrideAgentUserService;

        // Cache this for access by other security functions
        $requestingAgent = $params['RequestingAgentID'];
        
        if( isset($groupReadKey) && ($groupReadKey != '') && (!isset($verifiedReadKey) || ($verifiedReadKey !== TRUE)) )
        {
            if( !isset($params['ReadKey']) || ($params['ReadKey'] != $groupReadKey ) )
            {
                return array('error' => "Invalid (or No) Read Key Specified", 'params' => var_export($params, TRUE));
            } 
            else 
            {
                $verifiedReadKey = TRUE;
            }
        }
        
        if( ($write == TRUE) && isset($groupWriteKey) && ($groupWriteKey != '') && (!isset($verifiedWriteKey) || ($verifiedWriteKey !== TRUE)) )
        {
            if( !isset($params['WriteKey']) || ($params['WriteKey'] != $groupWriteKey ) )
            {
                return array('error' => "Invalid (or No) Write Key Specified", 'params' => var_export($params, TRUE));
            } 
            else 
            {
                $verifiedWriteKey = TRUE;
            }
        }
        
        if( ($write == TRUE) && isset($groupRequireAgentAuthForWrite) && ($groupRequireAgentAuthForWrite == TRUE) )
        {
            // Note: my brain can't do boolean logic this morning, so just putting this here instead of integrating with line above.
            // If the write key has already been verified for this request, don't check it again.  This comes into play with methods that call other methods, such as CreateGroup() which calls Addrole()
            if( isset($verifiedWriteKey) && ($verifiedWriteKey !== TRUE))
            {
                return TRUE;
            }
          
            if( !isset($params['RequestingAgentID']) 
                || !isset($params['RequestingAgentUserService'])
                || !isset($params['RequestingSessionID']) )
            {
                return array('error' => "Requesting AgentID and SessionID must be specified", 'params' => var_export($params, TRUE));
            }
            
            // NOTE: an AgentID and SessionID of $uuidZero will likely be a region making a request, that is not tied to a specific agent making the request.
            
            $UserService = $params['RequestingAgentUserService'];
            if( isset($overrideAgentUserService) && ($overrideAgentUserService != "") )
            {
                $UserService = $overrideAgentUserService;
            }
            
            $client = new xmlrpc_client($UserService);
            $client->return_type = 'phpvals';
            
            $verifyParams = new xmlrpcval(array('avatar_uuid' => new xmlrpcval($params['RequestingAgentID'], 'string')
                           ,'session_id'  => new xmlrpcval($params['RequestingSessionID'], 'string'))
                           , 'struct');

            $message = new xmlrpcmsg("check_auth_session", array($verifyParams));
            $resp = $client->send($message, 5);
            if ($resp->faultCode()) 
            {
                return array('error' => "Error validating AgentID and SessionID"
                             , 'xmlrpcerror'=> $resp->faultString()
                             , 'params' => var_export($params, TRUE));
            } 
        
            $verifyReturn = $resp->value();
        
            if( !isset($verifyReturn['auth_session']) || ($verifyReturn['auth_session'] != 'TRUE') )
            {
                return array('error' => "UserService.check_auth_session() did not return TRUE"
                             , 'userservice' => var_export($verifyReturn, TRUE)
                             , 'params' => var_export($params, TRUE));
              
            }
        }
        
        return TRUE;
    }

    function checkGroupPermission($GroupID, $Permission)
    {
        global $groupEnforceGroupPerms, $requestingAgent, $uuidZero, $groupDBCon, $groupPowers;
		
        if( !isset($Permission) || ($Permission == 0) )
        {
            return array('error' => 'No Permission value specified for checkGroupPermission'
                       , 'Permission' => $Permission);
        }
		
        // If it isn't set to true, then always return true, otherwise verify they have perms
        if( !isset($groupEnforceGroupPerms) || ($groupEnforceGroupPerms != TRUE) )
        {
            return true;
        }
        
        if( !isset($requestingAgent) || ($requestingAgent == $uuidZero) )
        {
            return array('error' => 'Requesting agent was either not specified or not validated.'
                       , 'requestingAgent' => $requestingAgent);
        }
        
        $params = array('AgentID' => $requestingAgent, 'GroupID' => $GroupID);
        $reqAgentMembership = getAgentGroupMembership($params);

        if( isset($reqAgentMembership['error'] ) )
        {
            return array('error' => 'Could not get agent membership for group'
                       , 'params' => var_export($params, TRUE)
             , 'nestederror' => $reqAgentMembership['error']);
        }

        // Worlds ugliest bitwise operation, EVER
        $PermMask   = $reqAgentMembership['GroupPowers'];
        $PermValue  = $Permission;
        
        global $groupDBCon;
        $sql = " SELECT $PermMask & $PermValue AS Allowed";
        $results = mysql_query($sql, $groupDBCon);
        if (!$results) 
        {
            echo print_r( array('error' => "Could not successfully run query ($sql) from DB: " . mysql_error()));
        }
        $PermMasked = mysql_result($results, 0);
        
        if( $PermMasked != $Permission )
        {
            $permNames = array_flip($groupPowers);

            return array('error' => 'Agent does not have group power to ' . $Permission .'('.$permNames[$Permission].')'
             , 'PermMasked' => $PermMasked
                       , 'params' => var_export($params, TRUE)
             , 'permBitMaskSql' => $sql
             , 'Permission' => $Permission);
        }
        
        /*
        return array('error' => 'Reached end'
               , 'reqAgentMembership' => var_export($reqAgentMembership, TRUE)
               , 'GroupID' => $GroupID
               , 'Permission' => $Permission
               , 'PermMasked' => $PermMasked
               );
        */
        return TRUE;
    }
	
    
    $s = new xmlrpc_server(array(
                            "test"                               => array("function" => "test")
                          , "groups.createGroup"                => array("function" => "createGroup", "signature" => $common_sig)
                          , "groups.updateGroup"                => array("function" => "updateGroup", "signature" => $common_sig)
                          , "groups.getGroup"                   => array("function" => "getGroup", "signature" => $common_sig)
                          , "groups.findGroups"                    => array("function" => "findGroups", "signature" => $common_sig)

                          , "groups.getGroupRoles"                => array("function" => "getGroupRoles", "signature" => $common_sig)
                          , "groups.addRoleToGroup"                => array("function" => "addRoleToGroup", "signature" => $common_sig)
                          , "groups.removeRoleFromGroup"        => array("function" => "removeRoleFromGroup", "signature" => $common_sig)
                          , "groups.updateGroupRole"            => array("function" => "updateGroupRole", "signature" => $common_sig)
                          , "groups.getGroupRoleMembers"        => array("function" => "getGroupRoleMembers", "signature" => $common_sig)
                          
                          , "groups.setAgentGroupSelectedRole"    => array("function" => "setAgentGroupSelectedRole", "signature" => $common_sig)
                          , "groups.addAgentToGroupRole"        => array("function" => "addAgentToGroupRole", "signature" => $common_sig)
                          , "groups.removeAgentFromGroupRole"   => array("function" => "removeAgentFromGroupRole", "signature" => $common_sig)
                          
                          , "groups.getGroupMembers"            => array("function" => "getGroupMembers", "signature" => $common_sig)
                          , "groups.addAgentToGroup"            => array("function" => "addAgentToGroup", "signature" => $common_sig)
                          , "groups.removeAgentFromGroup"        => array("function" => "removeAgentFromGroup", "signature" => $common_sig)
                          , "groups.setAgentGroupInfo"            => array("function" => "setAgentGroupInfo", "signature" => $common_sig)

                          , "groups.addAgentToGroupInvite"        => array("function" => "addAgentToGroupInvite", "signature" => $common_sig)
                          , "groups.getAgentToGroupInvite"        => array("function" => "getAgentToGroupInvite", "signature" => $common_sig)
                          , "groups.removeAgentToGroupInvite"    => array("function" => "removeAgentToGroupInvite", "signature" => $common_sig)
                          
                          , "groups.setAgentActiveGroup"        => array("function" => "setAgentActiveGroup", "signature" => $common_sig)
                          , "groups.getAgentGroupMembership"    => array("function" => "getAgentGroupMembership", "signature" => $common_sig)
                          , "groups.getAgentGroupMemberships"    => array("function" => "getAgentGroupMemberships", "signature" => $common_sig)
                          , "groups.getAgentActiveMembership"    => array("function" => "getAgentActiveMembership", "signature" => $common_sig)
                          , "groups.getAgentRoles"                => array("function" => "getAgentRoles", "signature" => $common_sig)
                          
                          , "groups.getGroupNotices"            => array("function" => "getGroupNotices", "signature" => $common_sig)
                          , "groups.getGroupNotice"                => array("function" => "getGroupNotice", "signature" => $common_sig)
                          , "groups.addGroupNotice"                => array("function" => "addGroupNotice", "signature" => $common_sig)
                          
                          
                          
                          
                            ), false);

    $s->functions_parameters_type = 'phpvals';
    if (isset($debugXMLRPC) && $debugXMLRPC > 0 && isset($debugXMLRPCFile) && $debugXMLRPCFile != "") 
	  {
		    $s->setDebug($debugXMLRPC);
    }
    $s->service();

    if (isset($debugXMLRPC) && $debugXMLRPC > 0 && isset($debugXMLRPCFile) && $debugXMLRPCFile != "") 
	  {
        $f = fopen($debugXMLRPCFile,"a");
        fwrite($f,"\n----- " . date("Y-m-d H:i:s") . " -----\n");
        $debugInfo = $s->serializeDebug();
        $debugInfo = split("\n",$debugInfo);
        unset($debugInfo[0]);
        unset($debugInfo[count($debugInfo) -1]);
        $debugInfo = join("\n",$debugInfo);	
        fwrite($f,base64_decode($debugInfo));
        fclose($f);
    }
    
    mysql_close($groupDBCon);
?>
Back to Top