async-sim-testing /Aurora/Services/DataService/Connectors/Local/LocalDirectoryServiceConnector.cs

Language C# Lines 1306
MD5 Hash a44b79b4172db8beeceb589123767eb5 Estimated Cost $26,734 (why?)
Repository https://bitbucket.org/VirtualReality/async-sim-testing.git View Raw File
   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
/*
 * Copyright (c) Contributors, http://aurora-sim.org/
 * See CONTRIBUTORS.TXT for a full list of copyright holders.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of the Aurora-Sim Project nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

using Aurora.Framework.ClientInterfaces;
using Aurora.Framework.DatabaseInterfaces;
using Aurora.Framework.Modules;
using Aurora.Framework.PresenceInfo;
using Aurora.Framework.SceneInfo;
using Aurora.Framework.Services;
using Aurora.Framework.Services.ClassHelpers.Profile;
using Aurora.Framework.Utilities;
using Nini.Config;
using OpenMetaverse;
using OpenMetaverse.StructuredData;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using EventFlags = OpenMetaverse.DirectoryManager.EventFlags;
using GridRegion = Aurora.Framework.Services.GridRegion;

namespace Aurora.Services.DataService
{
    public class LocalDirectoryServiceConnector : ConnectorBase, IDirectoryServiceConnector
    {
        private IGenericData GD;

        #region IDirectoryServiceConnector Members

        public void Initialize(IGenericData GenericData, IConfigSource source, IRegistryCore simBase,
                               string defaultConnectionString)
        {
            GD = GenericData;
            m_registry = simBase;

            if (source.Configs[Name] != null)
                defaultConnectionString = source.Configs[Name].GetString("ConnectionString", defaultConnectionString);

            if (GD != null)
                GD.ConnectToDatabase(defaultConnectionString, "Directory",
                                     source.Configs["AuroraConnectors"].GetBoolean("ValidateTables", true));

            Framework.Utilities.DataManager.RegisterPlugin(Name + "Local", this);

            if (source.Configs["AuroraConnectors"].GetString("DirectoryServiceConnector", "LocalConnector") ==
                "LocalConnector")
            {
                Framework.Utilities.DataManager.RegisterPlugin(this);
            }
            Init(simBase, Name);
        }

        public string Name
        {
            get { return "IDirectoryServiceConnector"; }
        }

        public void Dispose()
        {
        }

        #region Region

        /// <summary>
        ///     This also updates the parcel, not for just adding a new one
        /// </summary>
        /// <param name="parcels"></param>
        [CanBeReflected(ThreatLevel = ThreatLevel.Low)]
        public void AddRegion(List<LandData> parcels)
        {
            object remoteValue = DoRemote(parcels);
            if (remoteValue != null || m_doRemoteOnly)
                return;

            if (parcels.Count == 0)
                return;

            ClearRegion(parcels[0].RegionID);

            foreach (var parcel in parcels)
            {
                var OrFilters = new Dictionary<string, object>();
                OrFilters.Add("ParcelID", parcel.GlobalID);
                OrFilters.Add("InfoUUID", parcel.InfoUUID);
                GD.Delete("searchparcel", new QueryFilter {orFilters = OrFilters});
            }

            List<object[]> insertValues = parcels.Select(args => new List<object>
                                                                     {
                                                                         args.RegionID,
                                                                         args.GlobalID,
                                                                         args.LocalID,
                                                                         args.UserLocation.X,
                                                                         args.UserLocation.Y,
                                                                         args.UserLocation.Z,
                                                                         args.Name,
                                                                         args.Description,
                                                                         args.Flags,
                                                                         args.Dwell,
                                                                         args.InfoUUID,
                                                                         ((args.Flags & (uint) ParcelFlags.ForSale) ==
                                                                          (uint) ParcelFlags.ForSale)
                                                                             ? 1
                                                                             : 0,
                                                                         args.SalePrice,
                                                                         args.AuctionID,
                                                                         args.Area,
                                                                         0,
                                                                         args.Maturity,
                                                                         args.OwnerID,
                                                                         args.GroupID,
                                                                         ((args.Flags & (uint) ParcelFlags.ShowDirectory) ==
                                                                          (uint) ParcelFlags.ShowDirectory)
                                                                             ? 1
                                                                             : 0,
                                                                         args.SnapshotID,
                                                                         OSDParser.SerializeLLSDXmlString(args.Bitmap),
                                                                         (int) args.Category,
                                                                         args.ScopeID
                                                                     }).Select(Values => Values.ToArray()).ToList();

            GD.InsertMultiple("searchparcel", insertValues);
        }

        [CanBeReflected(ThreatLevel = ThreatLevel.Low)]
        public void ClearRegion(UUID regionID)
        {
            object remoteValue = DoRemote(regionID);
            if (remoteValue != null || m_doRemoteOnly)
                return;

            QueryFilter filter = new QueryFilter();
            filter.andFilters["RegionID"] = regionID;
            GD.Delete("searchparcel", filter);
        }

        #endregion

        #region Parcels

        private static List<LandData> Query2LandData(List<string> Query)
        {
            List<LandData> Lands = new List<LandData>();

            for (int i = 0; i < Query.Count; i += 24)
            {
                LandData LandData = new LandData
                                        {
                                            RegionID = UUID.Parse(Query[i]),
                                            GlobalID = UUID.Parse(Query[i + 1]),
                                            LocalID = int.Parse(Query[i + 2]),
                                            UserLocation =
                                                new Vector3(float.Parse(Query[i + 3]), float.Parse(Query[i + 4]),
                                                            float.Parse(Query[i + 5])),
                                            Name = Query[i + 6],
                                            Description = Query[i + 7],
                                            Flags = uint.Parse(Query[i + 8]),
                                            Dwell = int.Parse(Query[i + 9]),
                                            InfoUUID = UUID.Parse(Query[i + 10]),
                                            AuctionID = uint.Parse(Query[i + 13]),
                                            Area = int.Parse(Query[i + 14]),
                                            Maturity = int.Parse(Query[i + 16]),
                                            OwnerID = UUID.Parse(Query[i + 17]),
                                            GroupID = UUID.Parse(Query[i + 18]),
                                            SnapshotID = UUID.Parse(Query[i + 20])
                                        };
                try
                {
                    LandData.Bitmap = OSDParser.DeserializeLLSDXml(Query[i + 21]);
                }
                catch
                {
                }
                LandData.Category = (string.IsNullOrEmpty(Query[i + 22]))
                                        ? ParcelCategory.None
                                        : (ParcelCategory) int.Parse(Query[i + 22]);
                LandData.ScopeID = UUID.Parse(Query[i + 23]);

                Lands.Add(LandData);
            }
            return Lands;
        }

        /// <summary>
        ///     Gets a parcel from the search database by Info UUID (the true cross instance parcel ID)
        /// </summary>
        /// <param name="InfoUUID"></param>
        /// <returns></returns>
        [CanBeReflected(ThreatLevel = ThreatLevel.Low)]
        public LandData GetParcelInfo(UUID InfoUUID)
        {
            object remoteValue = DoRemote(InfoUUID);
            if (remoteValue != null || m_doRemoteOnly)
                return (LandData) remoteValue;

            //Split the InfoUUID so that we get the regions, we'll check for positions in a bit
            int RegionX, RegionY;
            uint X, Y;
            ulong RegionHandle;
            Util.ParseFakeParcelID(InfoUUID, out RegionHandle, out X, out Y);

            Util.UlongToInts(RegionHandle, out RegionX, out RegionY);

            GridRegion r = m_registry.RequestModuleInterface<IGridService>().GetRegionByPosition(null, RegionX,
                                                                                                 RegionY);
            if (r == null)
            {
//                m_log.Warn("[DirectoryService]: Could not find region for ParcelID: " + InfoUUID);
                return null;
            }
            //Get info about a specific parcel somewhere in the metaverse
            QueryFilter filter = new QueryFilter();
            filter.andFilters["RegionID"] = r.RegionID;
            List<string> Query = GD.Query(new[] {"*"}, "searchparcel", filter, null, null, null);
            //Cant find it, return
            if (Query.Count == 0)
            {
                return null;
            }

            List<LandData> Lands = Query2LandData(Query);
            LandData LandData = null;

            bool[,] tempConvertMap = new bool[r.RegionSizeX/4,r.RegionSizeX/4];
            tempConvertMap.Initialize();

            foreach (LandData land in Lands.Where(land => land.Bitmap != null))
            {
                ConvertBytesToLandBitmap(ref tempConvertMap, land.Bitmap, r.RegionSizeX);
                if (tempConvertMap[X/64, Y/64])
                {
                    LandData = land;
                    break;
                }
            }

            if (LandData == null && Lands.Count != 0)
                LandData = Lands[0];
            return LandData;
        }

        [CanBeReflected(ThreatLevel = ThreatLevel.Low)]
        public LandData GetParcelInfo(UUID RegionID, string ParcelName)
        {
            object remoteValue = DoRemote(RegionID, ParcelName);
            if (remoteValue != null || m_doRemoteOnly)
                return (LandData) remoteValue;

            IRegionData regiondata = Framework.Utilities.DataManager.RequestPlugin<IRegionData>();
            if (regiondata != null)
            {
                GridRegion region = regiondata.Get(RegionID, null);
                if (region != null)
                {
                    UUID parcelInfoID = UUID.Zero;
                    QueryFilter filter = new QueryFilter();
                    filter.andFilters["RegionID"] = RegionID;
                    filter.andFilters["Name"] = ParcelName;

                    List<string> query = GD.Query(new[] {"InfoUUID"}, "searchparcel", filter, null, 0, 1);

                    if (query.Count >= 1 && UUID.TryParse(query[0], out parcelInfoID))
                    {
                        return GetParcelInfo(parcelInfoID);
                    }
                }
            }

            return null;
        }

        /// <summary>
        ///     Gets all parcels owned by the given user
        /// </summary>
        /// <param name="OwnerID"></param>
        /// <returns></returns>
        [CanBeReflected(ThreatLevel = ThreatLevel.Low)]
        public List<ExtendedLandData> GetParcelByOwner(UUID OwnerID)
        {
            //NOTE: this does check for group deeded land as well, so this can check for that as well
            object remoteValue = DoRemote(OwnerID);
            if (remoteValue != null || m_doRemoteOnly)
                return (List<ExtendedLandData>) remoteValue;
            QueryFilter filter = new QueryFilter();
            filter.andFilters["OwnerID"] = OwnerID;
            List<string> Query = GD.Query(new[] {"*"}, "searchparcel", filter, null, null, null);

            return (Query.Count == 0) ? new List<ExtendedLandData>() : LandDataToExtendedLandData(Query2LandData(Query));
        }

        public List<ExtendedLandData> LandDataToExtendedLandData(List<LandData> data)
        {
            return (from land in data
                    let region = m_registry.RequestModuleInterface<IGridService>().GetRegionByUUID(null, land.RegionID)
                    where region != null
                    select new ExtendedLandData
                               {
                                   LandData = land,
                                   RegionType = region.RegionType,
                                   RegionName = region.RegionName,
                                   GlobalPosX = region.RegionLocX + land.UserLocation.X,
                                   GlobalPosY = region.RegionLocY + land.UserLocation.Y
                               }).ToList();
        }

        private static QueryFilter GetParcelsByRegionWhereClause(UUID RegionID, UUID owner, ParcelFlags flags,
                                                                 ParcelCategory category)
        {
            QueryFilter filter = new QueryFilter();
            filter.andFilters["RegionID"] = RegionID;

            if (owner != UUID.Zero)
            {
                filter.andFilters["OwnerID"] = owner;
            }

            if (flags != ParcelFlags.None)
            {
                filter.andBitfieldAndFilters["Flags"] = (uint) flags;
            }

            if (category != ParcelCategory.Any)
            {
                filter.andFilters["Category"] = (int) category;
            }

            return filter;
        }

        [CanBeReflected(ThreatLevel = ThreatLevel.Low)]
        public List<LandData> GetParcelsByRegion(uint start, uint count, UUID RegionID, UUID owner, ParcelFlags flags,
                                                 ParcelCategory category)
        {
            object remoteValue = DoRemote(start, count, RegionID, owner, flags, category);
            if (remoteValue != null || m_doRemoteOnly)
                return (List<LandData>) remoteValue;

            List<LandData> resp = new List<LandData>(0);
            if (count == 0)
            {
                return resp;
            }

            IRegionData regiondata = Framework.Utilities.DataManager.RequestPlugin<IRegionData>();
            if (regiondata != null)
            {
                GridRegion region = regiondata.Get(RegionID, null);
                if (region != null)
                {
                    QueryFilter filter = GetParcelsByRegionWhereClause(RegionID, owner, flags, category);
                    Dictionary<string, bool> sort = new Dictionary<string, bool>(1);
                    sort["OwnerID"] = false;
                    return Query2LandData(GD.Query(new[] {"*"}, "searchparcel", filter, sort, start, count));
                }
            }
            return resp;
        }

        [CanBeReflected(ThreatLevel = ThreatLevel.Low)]
        public uint GetNumberOfParcelsByRegion(UUID RegionID, UUID owner, ParcelFlags flags, ParcelCategory category)
        {
            object remoteValue = DoRemote(RegionID, owner, flags, category);
            if (remoteValue != null || m_doRemoteOnly)
                return (uint) remoteValue;

            IRegionData regiondata = Framework.Utilities.DataManager.RequestPlugin<IRegionData>();
            if (regiondata != null)
            {
                GridRegion region = regiondata.Get(RegionID, null);
                if (region != null)
                {
                    QueryFilter filter = GetParcelsByRegionWhereClause(RegionID, owner, flags, category);
                    return uint.Parse(GD.Query(new[] {"COUNT(ParcelID)"}, "searchparcel", filter, null, null, null)[0]);
                }
            }
            return 0;
        }

        [CanBeReflected(ThreatLevel = ThreatLevel.Low)]
        public List<LandData> GetParcelsWithNameByRegion(uint start, uint count, UUID RegionID, string name)
        {
            object remoteValue = DoRemote(start, count, RegionID, name);
            if (remoteValue != null || m_doRemoteOnly)
                return (List<LandData>) remoteValue;

            List<LandData> resp = new List<LandData>(0);
            if (count == 0)
            {
                return resp;
            }

            IRegionData regiondata = Framework.Utilities.DataManager.RequestPlugin<IRegionData>();
            if (regiondata != null)
            {
                GridRegion region = regiondata.Get(RegionID, null);
                if (region != null)
                {
                    QueryFilter filter = new QueryFilter();
                    filter.andFilters["RegionID"] = RegionID;
                    filter.andFilters["Name"] = name;

                    Dictionary<string, bool> sort = new Dictionary<string, bool>(1);
                    sort["OwnerID"] = false;

                    return Query2LandData(GD.Query(new[] {"*"}, "searchparcel", filter, sort, start, count));
                }
            }

            return resp;
        }

        [CanBeReflected(ThreatLevel = ThreatLevel.Low)]
        public uint GetNumberOfParcelsWithNameByRegion(UUID RegionID, string name)
        {
            object remoteValue = DoRemote(RegionID, name);
            if (remoteValue != null || m_doRemoteOnly)
                return (uint) remoteValue;

            IRegionData regiondata = Framework.Utilities.DataManager.RequestPlugin<IRegionData>();
            if (regiondata != null)
            {
                GridRegion region = regiondata.Get(RegionID, null);
                if (region != null)
                {
                    QueryFilter filter = new QueryFilter();
                    filter.andFilters["RegionID"] = RegionID;
                    filter.andFilters["Name"] = name;

                    return uint.Parse(GD.Query(new[] {"COUNT(ParcelID)"}, "searchparcel", filter, null, null, null)[0]);
                }
            }
            return 0;
        }

        /// <summary>
        ///     Searches for parcels around the grid
        /// </summary>
        /// <param name="queryText"></param>
        /// <param name="category"></param>
        /// <param name="StartQuery"></param>
        /// <param name="Flags"> </param>
        /// <param name="scopeID"> </param>
        /// <returns></returns>
        [CanBeReflected(ThreatLevel = ThreatLevel.Low)]
        public List<DirPlacesReplyData> FindLand(string queryText, string category, int StartQuery, uint Flags,
                                                 UUID scopeID)
        {
            object remoteValue = DoRemote(queryText, category, StartQuery, Flags, scopeID);
            if (remoteValue != null || m_doRemoteOnly)
                return (List<DirPlacesReplyData>) remoteValue;

            QueryFilter filter = new QueryFilter();
            Dictionary<string, bool> sort = new Dictionary<string, bool>();

            //If they dwell sort flag is there, sort by dwell going down
            if ((Flags & (uint) DirectoryManager.DirFindFlags.DwellSort) ==
                (uint) DirectoryManager.DirFindFlags.DwellSort)
            {
                sort["Dwell"] = false;
            }
            if (scopeID != UUID.Zero)
                filter.andFilters["ScopeID"] = scopeID;

            filter.orLikeFilters["Name"] = "%" + queryText + "%";
            filter.orLikeFilters["Description"] = "%" + queryText + "%";
            filter.andFilters["ShowInSearch"] = 1;
            if (category != "-1")
                filter.andFilters["Category"] = category;
            if ((Flags & (uint) DirectoryManager.DirFindFlags.AreaSort) == (uint) DirectoryManager.DirFindFlags.AreaSort)
                sort["Area"] = false;
            if ((Flags & (uint) DirectoryManager.DirFindFlags.NameSort) == (uint) DirectoryManager.DirFindFlags.NameSort)
                sort["Name"] = false;

            List<string> retVal = GD.Query(new[]
                                               {
                                                   "InfoUUID",
                                                   "Name",
                                                   "ForSale",
                                                   "Auction",
                                                   "Dwell",
                                                   "Flags"
                                               }, "searchparcel", filter, sort, (uint) StartQuery, 50);

            if (retVal.Count == 0)
            {
                return new List<DirPlacesReplyData>();
            }

            List<DirPlacesReplyData> Data = new List<DirPlacesReplyData>();

            for (int i = 0; i < retVal.Count; i += 6)
            {
                //Check to make sure we are sending the requested maturity levels
                if (
                    !((int.Parse(retVal[i + 5]) & (int) ParcelFlags.MaturePublish) == (int) ParcelFlags.MaturePublish &&
                      ((Flags & (uint) DirectoryManager.DirFindFlags.IncludeMature)) == 0))
                {
                    Data.Add(new DirPlacesReplyData
                                 {
                                     parcelID = new UUID(retVal[i]),
                                     name = retVal[i + 1],
                                     forSale = int.Parse(retVal[i + 2]) == 1,
                                     auction = retVal[i + 3] == "0", //Auction is stored as a 0 if there is no auction
                                     dwell = float.Parse(retVal[i + 4])
                                 });
                }
            }

            return Data;
        }

        /// <summary>
        ///     Searches for parcels for sale around the grid
        /// </summary>
        /// <param name="searchType">2 = Auction only, 8 = For Sale - Mainland, 16 = For Sale - Estate, 4294967295 = All</param>
        /// <param name="price"></param>
        /// <param name="area"></param>
        /// <param name="StartQuery"></param>
        /// <param name="Flags"> </param>
        /// <param name="scopeID"> </param>
        /// <returns></returns>
        [CanBeReflected(ThreatLevel = ThreatLevel.Low)]
        public List<DirLandReplyData> FindLandForSale(string searchType, uint price, uint area, int StartQuery,
                                                      uint Flags, UUID scopeID)
        {
            object remoteValue = DoRemote(searchType, price, area, StartQuery, Flags, scopeID);
            if (remoteValue != null || m_doRemoteOnly)
                return (List<DirLandReplyData>) remoteValue;

            QueryFilter filter = new QueryFilter();

            //Only parcels set for sale will be checked
            filter.andFilters["ForSale"] = "1";
            if (scopeID != UUID.Zero)
                filter.andFilters["ScopeID"] = scopeID;

            //They requested a sale price check
            if ((Flags & (uint) DirectoryManager.DirFindFlags.LimitByPrice) ==
                (uint) DirectoryManager.DirFindFlags.LimitByPrice)
            {
                filter.andLessThanEqFilters["SalePrice"] = (int) price;
            }

            //They requested a 
            if ((Flags & (uint) DirectoryManager.DirFindFlags.LimitByArea) ==
                (uint) DirectoryManager.DirFindFlags.LimitByArea)
            {
                filter.andGreaterThanEqFilters["Area"] = (int) area;
            }
            Dictionary<string, bool> sort = new Dictionary<string, bool>();
            if ((Flags & (uint) DirectoryManager.DirFindFlags.AreaSort) == (uint) DirectoryManager.DirFindFlags.AreaSort)
                sort["Area"] = false;
            if ((Flags & (uint) DirectoryManager.DirFindFlags.NameSort) == (uint) DirectoryManager.DirFindFlags.NameSort)
                sort["Name"] = false;

            List<string> retVal = GD.Query(new[]
                                               {
                                                   "InfoUUID",
                                                   "Name",
                                                   "Auction",
                                                   "SalePrice",
                                                   "Area",
                                                   "Flags"
                                               }, "searchparcel", filter, sort, (uint) StartQuery, 50);

            //if there are none, return
            if (retVal.Count == 0)
                return new List<DirLandReplyData>();

            List<DirLandReplyData> Data = new List<DirLandReplyData>();
            for (int i = 0; i < retVal.Count; i += 6)
            {
                DirLandReplyData replyData = new DirLandReplyData
                                                 {
                                                     forSale = true,
                                                     parcelID = new UUID(retVal[i]),
                                                     name = retVal[i + 1],
                                                     auction = (retVal[i + 2] != "0")
                                                 };
                //If its an auction and we didn't request to see auctions, skip to the next and continue
                if ((Flags & (uint) DirectoryManager.SearchTypeFlags.Auction) ==
                    (uint) DirectoryManager.SearchTypeFlags.Auction && !replyData.auction)
                {
                    continue;
                }

                replyData.salePrice = Convert.ToInt32(retVal[i + 3]);
                replyData.actualArea = Convert.ToInt32(retVal[i + 4]);

                //Check maturity levels depending on what flags the user has set
                //0 flag is an override so that we can get all lands for sale, regardless of maturity
                if (Flags == 0 ||
                    !((int.Parse(retVal[i + 5]) & (int) ParcelFlags.MaturePublish) == (int) ParcelFlags.MaturePublish &&
                      ((Flags & (uint) DirectoryManager.DirFindFlags.IncludeMature)) == 0))
                {
                    Data.Add(replyData);
                }
            }

            return Data;
        }

        /// <summary>
        ///     Searches for parcels for sale around the grid
        /// </summary>
        /// <param name="searchType">2 = Auction only, 8 = For Sale - Mainland, 16 = For Sale - Estate, 4294967295 = All</param>
        /// <param name="price"></param>
        /// <param name="area"></param>
        /// <param name="StartQuery"></param>
        /// <param name="Flags"> </param>
        /// <param name="regionID"> </param>
        /// <returns></returns>
        [CanBeReflected(ThreatLevel = ThreatLevel.Low)]
        public List<DirLandReplyData> FindLandForSaleInRegion(string searchType, uint price, uint area, int StartQuery,
                                                              uint Flags, UUID regionID)
        {
            object remoteValue = DoRemote(searchType, price, area, StartQuery, Flags, regionID);
            if (remoteValue != null || m_doRemoteOnly)
                return (List<DirLandReplyData>) remoteValue;

            QueryFilter filter = new QueryFilter();

            //Only parcels set for sale will be checked
            filter.andFilters["ForSale"] = "1";
            filter.andFilters["RegionID"] = regionID;

            //They requested a sale price check
            if ((Flags & (uint) DirectoryManager.DirFindFlags.LimitByPrice) ==
                (uint) DirectoryManager.DirFindFlags.LimitByPrice)
            {
                filter.andLessThanEqFilters["SalePrice"] = (int) price;
            }

            //They requested a 
            if ((Flags & (uint) DirectoryManager.DirFindFlags.LimitByArea) ==
                (uint) DirectoryManager.DirFindFlags.LimitByArea)
            {
                filter.andGreaterThanEqFilters["Area"] = (int) area;
            }
            Dictionary<string, bool> sort = new Dictionary<string, bool>();
            if ((Flags & (uint) DirectoryManager.DirFindFlags.AreaSort) == (uint) DirectoryManager.DirFindFlags.AreaSort)
                sort["Area"] = false;
            if ((Flags & (uint) DirectoryManager.DirFindFlags.NameSort) == (uint) DirectoryManager.DirFindFlags.NameSort)
                sort["Name"] = false;
            //if ((queryFlags & (uint)DirectoryManager.DirFindFlags.PerMeterSort) == (uint)DirectoryManager.DirFindFlags.PerMeterSort)
            //    sort["Area"] = (queryFlags & (uint)DirectoryManager.DirFindFlags.SortAsc) == (uint)DirectoryManager.DirFindFlags.SortAsc);
            if ((Flags & (uint) DirectoryManager.DirFindFlags.PricesSort) ==
                (uint) DirectoryManager.DirFindFlags.PricesSort)
                sort["SalePrice"] = (Flags & (uint) DirectoryManager.DirFindFlags.SortAsc) ==
                                    (uint) DirectoryManager.DirFindFlags.SortAsc;

            List<string> retVal = GD.Query(new[]
                                               {
                                                   "InfoUUID",
                                                   "Name",
                                                   "Auction",
                                                   "SalePrice",
                                                   "Area",
                                                   "Flags"
                                               }, "searchparcel", filter, sort, (uint) StartQuery, 50);

            //if there are none, return
            if (retVal.Count == 0)
                return new List<DirLandReplyData>();

            List<DirLandReplyData> Data = new List<DirLandReplyData>();
            for (int i = 0; i < retVal.Count; i += 6)
            {
                DirLandReplyData replyData = new DirLandReplyData
                                                 {
                                                     forSale = true,
                                                     parcelID = new UUID(retVal[i]),
                                                     name = retVal[i + 1],
                                                     auction = (retVal[i + 2] != "0")
                                                 };
                //If its an auction and we didn't request to see auctions, skip to the next and continue
                if ((Flags & (uint) DirectoryManager.SearchTypeFlags.Auction) ==
                    (uint) DirectoryManager.SearchTypeFlags.Auction && !replyData.auction)
                {
                    continue;
                }

                replyData.salePrice = Convert.ToInt32(retVal[i + 3]);
                replyData.actualArea = Convert.ToInt32(retVal[i + 4]);

                //Check maturity levels depending on what flags the user has set
                //0 flag is an override so that we can get all lands for sale, regardless of maturity
                if (Flags == 0 ||
                    !((int.Parse(retVal[i + 5]) & (int) ParcelFlags.MaturePublish) == (int) ParcelFlags.MaturePublish &&
                      ((Flags & (uint) DirectoryManager.DirFindFlags.IncludeMature)) == 0))
                {
                    Data.Add(replyData);
                }
            }

            return Data;
        }

        /// <summary>
        ///     Searches for the most popular places around the grid
        /// </summary>
        /// <param name="queryFlags"></param>
        /// <param name="scopeID"></param>
        /// <returns></returns>
        [CanBeReflected(ThreatLevel = ThreatLevel.Low)]
        public List<DirPopularReplyData> FindPopularPlaces(uint queryFlags, UUID scopeID)
        {
            object remoteValue = DoRemote(queryFlags, scopeID);
            if (remoteValue != null || m_doRemoteOnly)
                return (List<DirPopularReplyData>) remoteValue;

            QueryFilter filter = new QueryFilter();
            Dictionary<string, bool> sort = new Dictionary<string, bool>();

            if ((queryFlags & (uint) DirectoryManager.DirFindFlags.AreaSort) ==
                (uint) DirectoryManager.DirFindFlags.AreaSort)
                sort["Area"] = false;
            else if ((queryFlags & (uint) DirectoryManager.DirFindFlags.NameSort) ==
                     (uint) DirectoryManager.DirFindFlags.NameSort)
                sort["Name"] = false;
                //else if ((queryFlags & (uint)DirectoryManager.DirFindFlags.PerMeterSort) == (uint)DirectoryManager.DirFindFlags.PerMeterSort)
                //    sort["Area"] = (queryFlags & (uint)DirectoryManager.DirFindFlags.SortAsc) == (uint)DirectoryManager.DirFindFlags.SortAsc);
                //else if ((queryFlags & (uint)DirectoryManager.DirFindFlags.PricesSort) == (uint)DirectoryManager.DirFindFlags.PricesSort)
                //    sort["SalePrice"] = (queryFlags & (uint)DirectoryManager.DirFindFlags.SortAsc) == (uint)DirectoryManager.DirFindFlags.SortAsc;
            else
                sort["Dwell"] = false;

            if (scopeID != UUID.Zero)
                filter.andFilters["ScopeID"] = scopeID;


            List<string> retVal = GD.Query(new[]
                                               {
                                                   "InfoUUID",
                                                   "Name",
                                                   "Dwell",
                                                   "Flags"
                                               }, "searchparcel", filter, null, 0, 25);

            //if there are none, return
            if (retVal.Count == 0)
                return new List<DirPopularReplyData>();

            List<DirPopularReplyData> Data = new List<DirPopularReplyData>();
            for (int i = 0; i < retVal.Count; i += 4)
            {
                //Check maturity levels depending on what flags the user has set
                //0 flag is an override so that we can get all lands for sale, regardless of maturity
                if (queryFlags == 0 ||
                    !((int.Parse(retVal[i + 3]) & (int) ParcelFlags.MaturePublish) == (int) ParcelFlags.MaturePublish &&
                      ((queryFlags & (uint) DirectoryManager.DirFindFlags.IncludeMature)) == 0))
                    Data.Add(new DirPopularReplyData
                                 {
                                     ParcelID = new UUID(retVal[i]),
                                     Name = retVal[i + 1],
                                     Dwell = int.Parse(retVal[i + 2])
                                 });
            }

            return Data;
        }

        private void ConvertBytesToLandBitmap(ref bool[,] tempConvertMap, byte[] Bitmap, int sizeX)
        {
            try
            {
                int x = 0, y = 0, i = 0;
                int avg = (sizeX*sizeX/128);
                for (i = 0; i < avg; i++)
                {
                    byte tempByte = Bitmap[i];
                    int bitNum = 0;
                    for (bitNum = 0; bitNum < 8; bitNum++)
                    {
                        bool bit = Convert.ToBoolean(Convert.ToByte(tempByte >> bitNum) & 1);
                        tempConvertMap[x, y] = bit;
                        x++;
                        if (x > (sizeX/4) - 1)
                        {
                            x = 0;
                            y++;
                        }
                    }
                }
            }
            catch
            {
            }
        }

        #endregion

        #region Classifieds

        /// <summary>
        ///     Searches for classifieds
        /// </summary>
        /// <param name="queryText"></param>
        /// <param name="category"></param>
        /// <param name="queryFlags"></param>
        /// <param name="StartQuery"></param>
        /// <param name="scopeID"> </param>
        /// <returns></returns>
        [CanBeReflected(ThreatLevel = ThreatLevel.Low)]
        public List<DirClassifiedReplyData> FindClassifieds(string queryText, string category, uint queryFlags,
                                                            int StartQuery, UUID scopeID)
        {
            object remoteValue = DoRemote(queryText, category, queryFlags, StartQuery, scopeID);
            if (remoteValue != null || m_doRemoteOnly)
                return (List<DirClassifiedReplyData>) remoteValue;

            QueryFilter filter = new QueryFilter();

            filter.andLikeFilters["Name"] = "%" + queryText + "%";
            if (int.Parse(category) != (int) DirectoryManager.ClassifiedCategories.Any) //Check the category
                filter.andFilters["Category"] = category;
            if (scopeID != UUID.Zero)
                filter.andFilters["ScopeID"] = scopeID;

            List<string> retVal = GD.Query(new[] {"*"}, "userclassifieds", filter, null, (uint) StartQuery, 50);
            if (retVal.Count == 0)
                return new List<DirClassifiedReplyData>();

            List<DirClassifiedReplyData> Data = new List<DirClassifiedReplyData>();
            for (int i = 0; i < retVal.Count; i += 9)
            {
                //Pull the classified out of OSD
                Classified classified = new Classified();
                classified.FromOSD((OSDMap) OSDParser.DeserializeJson(retVal[i + 5]));

                DirClassifiedReplyData replyData = new DirClassifiedReplyData
                                                       {
                                                           classifiedFlags = classified.ClassifiedFlags,
                                                           classifiedID = classified.ClassifiedUUID,
                                                           creationDate = classified.CreationDate,
                                                           expirationDate = classified.ExpirationDate,
                                                           price = classified.PriceForListing,
                                                           name = classified.Name
                                                       };
                //Check maturity levels
                if ((replyData.classifiedFlags & (uint) DirectoryManager.ClassifiedFlags.Mature) !=
                    (uint) DirectoryManager.ClassifiedFlags.Mature)
                {
                    if ((queryFlags & (uint) DirectoryManager.ClassifiedQueryFlags.Mature) ==
                        (uint) DirectoryManager.ClassifiedQueryFlags.Mature)
                        Data.Add(replyData);
                }
                else
                    //Its Mature, add all
                    Data.Add(replyData);
            }
            return Data;
        }

        /// <summary>
        ///     Gets all classifieds in the given region
        /// </summary>
        /// <param name="regionName"></param>
        /// <returns></returns>
        [CanBeReflected(ThreatLevel = ThreatLevel.Low)]
        public List<Classified> GetClassifiedsInRegion(string regionName)
        {
            object remoteValue = DoRemote(regionName);
            if (remoteValue != null || m_doRemoteOnly)
                return (List<Classified>) remoteValue;

            QueryFilter filter = new QueryFilter();
            filter.andFilters["SimName"] = regionName;
            List<string> retVal = GD.Query(new[] {"*"}, "userclassifieds", filter, null, null, null);

            if (retVal.Count == 0)
            {
                return new List<Classified>();
            }

            List<Classified> Classifieds = new List<Classified>();
            for (int i = 0; i < retVal.Count; i += 9)
            {
                Classified classified = new Classified();
                //Pull the classified out of OSD
                classified.FromOSD((OSDMap) OSDParser.DeserializeJson(retVal[i + 6]));
                Classifieds.Add(classified);
            }
            return Classifieds;
        }

        /// <summary>
        ///     Get a classified by its UUID
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [CanBeReflected(ThreatLevel = ThreatLevel.Low)]
        public Classified GetClassifiedByID(UUID id)
        {
            object remoteValue = DoRemote(id);
            if (remoteValue != null || m_doRemoteOnly)
                return (Classified) remoteValue;

            QueryFilter filter = new QueryFilter();
            Dictionary<string, object> where = new Dictionary<string, object>(1);
            where.Add("ClassifiedUUID", id);
            filter.andFilters = where;
            List<string> retVal = GD.Query(new[] {"*"}, "userclassifieds", filter, null, null, null);
            if ((retVal == null) || (retVal.Count == 0)) return null;
            Classified classified = new Classified();
            classified.FromOSD((OSDMap) OSDParser.DeserializeJson(retVal[6]));
            return classified;
        }

        #endregion

        #region Events

        /// <summary>
        ///     Searches for events with the given parameters
        /// </summary>
        /// <param name="queryText"></param>
        /// <param name="eventFlags"></param>
        /// <param name="StartQuery"></param>
        /// <param name="scopeID"> </param>
        /// <returns></returns>
        [CanBeReflected(ThreatLevel = ThreatLevel.Low)]
        public List<DirEventsReplyData> FindEvents(string queryText, uint eventFlags, int StartQuery, UUID scopeID)
        {
            object remoteValue = DoRemote(queryText, eventFlags, StartQuery, scopeID);
            if (remoteValue != null || m_doRemoteOnly)
                return (List<DirEventsReplyData>) remoteValue;

            List<DirEventsReplyData> Data = new List<DirEventsReplyData>();

            QueryFilter filter = new QueryFilter();

            //|0| means search between some days
            if (queryText.Contains("|0|"))
            {
                string StringDay = queryText.Split('|')[0];
                if (StringDay == "u") //"u" means search for events that are going on today
                {
                    filter.andGreaterThanEqFilters["UNIX_TIMESTAMP(date)"] = Util.ToUnixTime(DateTime.Today);
                }
                else
                {
                    //Pull the day out then and search for that many days in the future/past
                    int Day = int.Parse(StringDay);
                    DateTime SearchedDay = DateTime.Today.AddDays(Day);
                    //We only look at one day at a time
                    DateTime NextDay = SearchedDay.AddDays(1);
                    filter.andGreaterThanEqFilters["UNIX_TIMESTAMP(date)"] = Util.ToUnixTime(SearchedDay);
                    filter.andLessThanEqFilters["UNIX_TIMESTAMP(date)"] = Util.ToUnixTime(NextDay);
                    filter.andLessThanEqFilters["flags"] = (int) eventFlags;
                }
            }
            else
            {
                filter.andLikeFilters["name"] = "%" + queryText + "%";
            }
            if (scopeID != UUID.Zero)
                filter.andFilters["scopeID"] = scopeID;

            List<string> retVal = GD.Query(new[]
                                               {
                                                   "EID",
                                                   "creator",
                                                   "date",
                                                   "maturity",
                                                   "flags",
                                                   "name"
                                               }, "asevents", filter, null, (uint) StartQuery, 50);

            if (retVal.Count > 0)
            {
                for (int i = 0; i < retVal.Count; i += 6)
                {
                    DirEventsReplyData replyData = new DirEventsReplyData
                                                       {
                                                           eventID = Convert.ToUInt32(retVal[i]),
                                                           ownerID = new UUID(retVal[i + 1]),
                                                           name = retVal[i + 5],
                                                       };
                    DateTime date = DateTime.Parse(retVal[i + 2]);
                    replyData.date = date.ToString(new DateTimeFormatInfo());
                    replyData.unixTime = (uint) Util.ToUnixTime(date);
                    replyData.eventFlags = Convert.ToUInt32(retVal[i + 4]);

                    //Check the maturity levels
                    uint maturity = Convert.ToUInt32(retVal[i + 3]);
                    if (
                        (maturity == 0 && (eventFlags & (uint) EventFlags.PG) == (uint) EventFlags.PG) ||
                        (maturity == 1 && (eventFlags & (uint) EventFlags.Mature) == (uint) EventFlags.Mature) ||
                        (maturity == 2 && (eventFlags & (uint) EventFlags.Adult) == (uint) EventFlags.Adult)
                        )
                    {
                        Data.Add(replyData);
                    }
                }
            }

            return Data;
        }

        /// <summary>
        ///     Retrives all events in the given region by their maturity level
        /// </summary>
        /// <param name="regionName"></param>
        /// <param name="maturity">Uses DirectoryManager.EventFlags to determine the maturity requested</param>
        /// <returns></returns>
        [CanBeReflected(ThreatLevel = ThreatLevel.Low)]
        public List<DirEventsReplyData> FindAllEventsInRegion(string regionName, int maturity)
        {
            object remoteValue = DoRemote(regionName, maturity);
            if (remoteValue != null || m_doRemoteOnly)
                return (List<DirEventsReplyData>) remoteValue;

            List<DirEventsReplyData> Data = new List<DirEventsReplyData>();

            IRegionData regiondata = Framework.Utilities.DataManager.RequestPlugin<IRegionData>();
            if (regiondata != null)
            {
                List<GridRegion> regions = regiondata.Get(regionName, null, null, null);
                if (regions.Count >= 1)
                {
                    QueryFilter filter = new QueryFilter();
                    filter.andFilters["region"] = regions[0].RegionID.ToString();
                    filter.andFilters["maturity"] = maturity;

                    List<string> retVal = GD.Query(new[]
                                                       {
                                                           "EID",
                                                           "creator",
                                                           "date",
                                                           "maturity",
                                                           "flags",
                                                           "name"
                                                       }, "asevents", filter, null, null, null);

                    if (retVal.Count > 0)
                    {
                        for (int i = 0; i < retVal.Count; i += 6)
                        {
                            DirEventsReplyData replyData = new DirEventsReplyData
                                                               {
                                                                   eventID = Convert.ToUInt32(retVal[i]),
                                                                   ownerID = new UUID(retVal[i + 1]),
                                                                   name = retVal[i + 5],
                                                               };
                            DateTime date = DateTime.Parse(retVal[i + 2]);
                            replyData.date = date.ToString(new DateTimeFormatInfo());
                            replyData.unixTime = (uint) Util.ToUnixTime(date);
                            replyData.eventFlags = Convert.ToUInt32(retVal[i + 4]);

                            Data.Add(replyData);
                        }
                    }
                }
            }

            return Data;
        }

        private static List<EventData> Query2EventData(List<string> RetVal)
        {
            List<EventData> Events = new List<EventData>();
            IRegionData regiondata = Framework.Utilities.DataManager.RequestPlugin<IRegionData>();
            if (RetVal.Count%16 != 0 || regiondata == null)
            {
                return Events;
            }

            for (int i = 0; i < RetVal.Count; i += 16)
            {
                EventData data = new EventData();

                GridRegion region = regiondata.Get(UUID.Parse(RetVal[2]), null);
                if (region == null)
                {
                    continue;
                }
                data.simName = region.RegionName;

                data.eventID = Convert.ToUInt32(RetVal[i]);
                data.creator = RetVal[i + 1];

                //Parse the time out for the viewer
                DateTime date = DateTime.Parse(RetVal[i + 4]);
                data.date = date.ToString(new DateTimeFormatInfo());
                data.dateUTC = (uint) Util.ToUnixTime(date);

                data.cover = data.amount = Convert.ToUInt32(RetVal[i + 5]);
                data.maturity = Convert.ToInt32(RetVal[i + 6]);
                data.eventFlags = Convert.ToUInt32(RetVal[i + 7]);
                data.duration = Convert.ToUInt32(RetVal[i + 8]);

                data.regionPos = new Vector3(
                    float.Parse(RetVal[i + 9]),
                    float.Parse(RetVal[i + 10]),
                    float.Parse(RetVal[i + 11])
                    );

                data.globalPos = new Vector3(
                    region.RegionLocX + data.regionPos.X,
                    region.RegionLocY + data.regionPos.Y,
                    region.RegionLocZ + data.regionPos.Z
                    );

                data.name = RetVal[i + 12];
                data.description = RetVal[i + 13];
                data.category = RetVal[i + 14];

                Events.Add(data);
            }

            return Events;
        }

        /// <summary>
        ///     Gets more info about the event by the events unique event ID
        /// </summary>
        /// <param name="EventID"></param>
        /// <returns></returns>
        [CanBeReflected(ThreatLevel = ThreatLevel.Low)]
        public EventData GetEventInfo(uint EventID)
        {
            object remoteValue = DoRemote(EventID);
            if (remoteValue != null || m_doRemoteOnly)
                return (EventData) remoteValue;

            QueryFilter filter = new QueryFilter();
            filter.andFilters["EID"] = EventID;
            List<string> RetVal = GD.Query(new[] {"*"}, "asevents", filter, null, null, null);
            return (RetVal.Count == 0) ? null : Query2EventData(RetVal)[0];
        }

        [CanBeReflected(ThreatLevel = ThreatLevel.Low)]
        public EventData CreateEvent(UUID creator, UUID regionID, UUID parcelID, DateTime date, uint cover,
                                     EventFlags maturity, uint flags, uint duration, Vector3 localPos, string name,
                                     string description, string category)
        {
            object remoteValue = DoRemote(creator, regionID, parcelID, date, cover, maturity, flags, duration, localPos,
                                          name, description, category);
            if (remoteValue != null || m_doRemoteOnly)
                return (EventData) remoteValue;

            IRegionData regiondata = Framework.Utilities.DataManager.RequestPlugin<IRegionData>();
            if (regiondata == null)
            {
                return null;
            }

            GridRegion region = regiondata.Get(regionID, null);
            if (region == null)
            {
                return null;
            }

            EventData eventData = new EventData
                                      {
                                          eventID = GetMaxEventID() + 1,
                                          creator = creator.ToString(),
                                          simName = region.RegionName,
                                          date = date.ToString(new DateTimeFormatInfo()),
                                          dateUTC = (uint) Util.ToUnixTime(date),
                                          amount = cover,
                                          cover = cover,
                                          maturity = (int) maturity,
                                          eventFlags = flags | (uint) maturity,
                                          duration = duration,
                                          globalPos = new Vector3(
                                              region.RegionLocX + localPos.X,
                                              region.RegionLocY + localPos.Y,
                                              region.RegionLocZ + localPos.Z
                                              ),
                                          regionPos = localPos,
                                          name = name,
                                          description = description,
                                          category = category
                                      };

            Dictionary<string, object> row = new Dictionary<string, object>(15);
            row["EID"] = eventData.eventID;
            row["creator"] = creator.ToString();
            row["region"] = regionID.ToString();
            row["parcel"] = parcelID.ToString();
            row["date"] = date.ToString("s");
            row["cover"] = eventData.cover;
            row["maturity"] = (uint) maturity;
            row["flags"] = flags;
            row["duration"] = duration;
            row["localPosX"] = localPos.X;
            row["localPosY"] = localPos.Y;
            row["localPosZ"] = localPos.Z;
            row["name"] = name;
            row["description"] = description;
            row["category"] = category;

            GD.Insert("asevents", row);

            return eventData;
        }

        public List<EventData> GetEvents(uint start, uint count, Dictionary<string, bool> sort,
                                         Dictionary<string, object> filter)
        {
            return (count == 0)
                       ? new List<EventData>(0)
                       : Query2EventData(GD.Query(new[] {"*"}, "asevents", new QueryFilter
                                                                               {
                                                                                   andFilters = filter
                                                                               }, sort, start, count));
        }

        public uint GetNumberOfEvents(Dictionary<string, object> filter)
        {
            return uint.Parse(GD.Query(new[]
                                           {
                                               "COUNT(EID)"
                                           }, "asevents", new QueryFilter
                                                              {
                                                                  andFilters = filter
                                                              }, null, null, null)[0]);
        }

        public uint GetMaxEventID()
        {
            if (GetNumberOfEvents(new Dictionary<string, object>(0)) == 0)
            {
                return 0;
            }
            return uint.Parse(GD.Query(new[] {"MAX(EID)"}, "asevents", null, null, null, null)[0]);
        }

        [CanBeReflected(ThreatLevel = ThreatLevel.Low)]
        public void AddEventNofication(UUID user, uint EventID)
        {
            if (m_doRemoteOnly)
            {
                DoRemote(user, EventID);
                return;
            }

            GD.Insert("event_notifications", new object[2] {user.ToString(), EventID});
        }

        [CanBeReflected(ThreatLevel = ThreatLevel.Low)]
        public void RemoveEventNofication(UUID user, uint EventID)
        {
            if (m_doRemoteOnly)
            {
                DoRemote(user, EventID);
                return;
            }

            QueryFilter filter = new QueryFilter();
            filter.andFilters.Add("UserID", user.ToString());
            filter.andFilters.Add("EventID", EventID);
            GD.Delete("event_notifications", filter);
        }

        [CanBeReflected(ThreatLevel = ThreatLevel.Low)]
        public List<EventData> GetEventNotifications(UUID user)
        {
            object remoteValue = DoRemote(user);
            if (remoteValue != null || m_doRemoteOnly)
                return (List<EventData>) remoteValue;

            QueryFilter filter = new QueryFilter();
            filter.andFilters.Add("UserID", user.ToString());
            List<string> data = GD.Query(new string[1] {"EventID"}, "event_notifications", filter, null, null, null);
            List<EventData> events = new List<EventData>();
            if (data.Count == 0)
                return events;

            foreach (string eventID in data)
                events.Add(GetEventInfo(uint.Parse(eventID)));

            return events;
        }

        #endregion

        #endregion
    }
}
Back to Top