aboutsummaryrefslogtreecommitdiffstatshomepage
path: root/OpenSim/Data/MySQL/MySQLUserProfilesData.cs
blob: 16637c39967676d8f58cdc9539e24cb2999d8a0b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
/*
 * Copyright (c) Contributors, http://opensimulator.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 OpenSimulator 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 System;
using System.Data;
using System.Reflection;
using OpenSim.Data;
using OpenSim.Framework;
using MySql.Data.MySqlClient;
using OpenMetaverse;
using OpenMetaverse.StructuredData;
using log4net;

namespace OpenSim.Data.MySQL
{
    public class UserProfilesData: IProfilesData
    {
        static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

        #region Properites
        string ConnectionString
        {
            get; set;
        }

        protected virtual Assembly Assembly
        {
            get { return GetType().Assembly; }
        }

        #endregion Properties

        #region class Member Functions
        public UserProfilesData(string connectionString)
        {
            ConnectionString = connectionString;
            Init();
        }

        void Init()
        {
            using (MySqlConnection dbcon = new MySqlConnection(ConnectionString))
            {
                dbcon.Open();

                Migration m = new Migration(dbcon, Assembly, "UserProfiles");
                m.Update();
                dbcon.Close();
            }
        }
        #endregion Member Functions

        #region Classifieds Queries
        /// <summary>
        /// Gets the classified records.
        /// </summary>
        /// <returns>
        /// Array of classified records
        /// </returns>
        /// <param name='creatorId'>
        /// Creator identifier.
        /// </param>
        public OSDArray GetClassifiedRecords(UUID creatorId)
        {
            OSDArray data = new OSDArray();

            using (MySqlConnection dbcon = new MySqlConnection(ConnectionString))
            {
                const string query = "SELECT classifieduuid, name FROM classifieds WHERE creatoruuid = ?Id";
                dbcon.Open();
                using (MySqlCommand cmd = new MySqlCommand(query, dbcon))
                {
                    cmd.Parameters.AddWithValue("?Id", creatorId);
                    using( MySqlDataReader reader = cmd.ExecuteReader(CommandBehavior.Default))
                    {
                        if(reader.HasRows)
                        {
                            while (reader.Read())
                            {
                                OSDMap n = new OSDMap();
                                UUID Id = UUID.Zero;

                                string Name = null;
                                try
                                {
                                    UUID.TryParse(Convert.ToString( reader["classifieduuid"]), out Id);
                                    Name = Convert.ToString(reader["name"]);
                                }
                                catch (Exception e)
                                {
                                    m_log.ErrorFormat("[PROFILES_DATA] GetClassifiedRecords exception {0}", e.Message);
                                }
                                n.Add("classifieduuid", OSD.FromUUID(Id));
                                n.Add("name", OSD.FromString(Name));
                                data.Add(n);
                            }
                        }
                    }
                }
                dbcon.Close();
            }
            return data;
        }

        public bool UpdateClassifiedRecord(UserClassifiedAdd ad, ref string result)
        {
             const string query = 
                "INSERT INTO classifieds ("
                + "`classifieduuid`,"
                +  "`creatoruuid`,"
                +  "`creationdate`,"
                +  "`expirationdate`,"
                +  "`category`,"
                +  "`name`,"
                +  "`description`,"
                +  "`parceluuid`,"
                +  "`parentestate`,"
                +  "`snapshotuuid`,"
                +  "`simname`,"
                +  "`posglobal`,"
                +  "`parcelname`,"
                + "`classifiedflags`,"
                + "`priceforlisting`) "
                + "VALUES ("
                + "?ClassifiedId,"
                + "?CreatorId,"
                + "?CreatedDate,"
                + "?ExpirationDate,"
                + "?Category,"
                + "?Name,"
                + "?Description,"
                + "?ParcelId,"
                + "?ParentEstate,"
                + "?SnapshotId,"
                + "?SimName,"
                + "?GlobalPos,"
                + "?ParcelName,"
                + "?Flags,"
                + "?ListingPrice ) "
                + "ON DUPLICATE KEY UPDATE "
                + "category=?Category, "
                + "expirationdate=?ExpirationDate, "
                + "name=?Name, "
                + "description=?Description, "
                + "parentestate=?ParentEstate, "
                + "posglobal=?GlobalPos, "
                + "parcelname=?ParcelName, "
                + "classifiedflags=?Flags, "
                + "priceforlisting=?ListingPrice, "
                + "snapshotuuid=?SnapshotId"
                ;

            if(string.IsNullOrEmpty(ad.ParcelName))
                ad.ParcelName = "Unknown";
            if(ad.ParcelId == null)
                ad.ParcelId = UUID.Zero;
            if(string.IsNullOrEmpty(ad.Description))
                ad.Description = "No Description";

            DateTime epoch = new DateTime(1970, 1, 1);
            DateTime now = DateTime.Now;
            TimeSpan epochnow = now - epoch;
            TimeSpan duration;
            DateTime expiration;
            TimeSpan epochexp;

            if(ad.Flags == 2)
            {
                duration = new TimeSpan(7,0,0,0);
                expiration = now.Add(duration);
                epochexp = expiration - epoch;
            }
            else
            {
                duration = new TimeSpan(365,0,0,0);
                expiration = now.Add(duration);
                epochexp = expiration - epoch;
            }
            ad.CreationDate = (int)epochnow.TotalSeconds;
            ad.ExpirationDate = (int)epochexp.TotalSeconds;

            try
            {
                using (MySqlConnection dbcon = new MySqlConnection(ConnectionString))
                {
                    dbcon.Open();
                    using (MySqlCommand cmd = new MySqlCommand(query, dbcon))
                    {
                        cmd.Parameters.AddWithValue("?ClassifiedId", ad.ClassifiedId.ToString());
                        cmd.Parameters.AddWithValue("?CreatorId", ad.CreatorId.ToString());
                        cmd.Parameters.AddWithValue("?CreatedDate", ad.CreationDate.ToString());
                        cmd.Parameters.AddWithValue("?ExpirationDate", ad.ExpirationDate.ToString());
                        cmd.Parameters.AddWithValue("?Category", ad.Category.ToString());
                        cmd.Parameters.AddWithValue("?Name", ad.Name.ToString());
                        cmd.Parameters.AddWithValue("?Description", ad.Description.ToString());
                        cmd.Parameters.AddWithValue("?ParcelId", ad.ParcelId.ToString());
                        cmd.Parameters.AddWithValue("?ParentEstate", ad.ParentEstate.ToString());
                        cmd.Parameters.AddWithValue("?SnapshotId", ad.SnapshotId.ToString ());
                        cmd.Parameters.AddWithValue("?SimName", ad.SimName.ToString());
                        cmd.Parameters.AddWithValue("?GlobalPos", ad.GlobalPos.ToString());
                        cmd.Parameters.AddWithValue("?ParcelName", ad.ParcelName.ToString());
                        cmd.Parameters.AddWithValue("?Flags", ad.Flags.ToString());
                        cmd.Parameters.AddWithValue("?ListingPrice", ad.Price.ToString ());

                        cmd.ExecuteNonQuery();
                    }
                    dbcon.Close();
                }
            }
            catch (Exception e)
            {
                m_log.ErrorFormat("[PROFILES_DATA]: UpdateClassifiedRecord exception {0}", e.Message);
                result = e.Message;
                return false;
            }
            return true;
        }

        public bool DeleteClassifiedRecord(UUID recordId)
        {
            const string query = "DELETE FROM classifieds WHERE classifieduuid = ?recordId";

            try
            {
                using (MySqlConnection dbcon = new MySqlConnection(ConnectionString))
                {
                    dbcon.Open();

                    using (MySqlCommand cmd = new MySqlCommand(query, dbcon))
                    {
                        cmd.Parameters.AddWithValue("?recordId", recordId.ToString());
                        cmd.ExecuteNonQuery();
                    }
                    dbcon.Close();
                }
            }
            catch (Exception e)
            {
                m_log.ErrorFormat("[PROFILES_DATA]: DeleteClassifiedRecord exception {0}", e.Message);
                return false;
            }
            return true;
        }

        public bool GetClassifiedInfo(ref UserClassifiedAdd ad, ref string result)
        {

            const string query = "SELECT * FROM classifieds WHERE classifieduuid = ?AdId";

            try
            {
                using (MySqlConnection dbcon = new MySqlConnection(ConnectionString))
                {
                    dbcon.Open();
                    using (MySqlCommand cmd = new MySqlCommand(query, dbcon))
                    {
                        cmd.Parameters.AddWithValue("?AdId", ad.ClassifiedId.ToString());

                        using (MySqlDataReader reader = cmd.ExecuteReader())
                        {
                            if(reader.Read ())
                            {
                                ad.CreatorId = new UUID(reader.GetGuid("creatoruuid"));
                                ad.ParcelId = new UUID(reader.GetGuid("parceluuid"));
                                ad.SnapshotId = new UUID(reader.GetGuid("snapshotuuid"));
                                ad.CreationDate = Convert.ToInt32(reader["creationdate"]);
                                ad.ExpirationDate = Convert.ToInt32(reader["expirationdate"]);
                                ad.ParentEstate = Convert.ToInt32(reader["parentestate"]);
                                ad.Flags = (byte)reader.GetUInt32("classifiedflags");
                                ad.Category = reader.GetInt32("category");
                                ad.Price = reader.GetInt16("priceforlisting");
                                ad.Name = reader.GetString("name");
                                ad.Description = reader.GetString("description");
                                ad.SimName = reader.GetString("simname");
                                ad.GlobalPos = reader.GetString("posglobal");
                                ad.ParcelName = reader.GetString("parcelname");

                            }
                        }
                    }
                    dbcon.Close();
                }
            }
            catch (Exception e)
            {
                m_log.ErrorFormat("[PROFILES_DATA]: GetClassifiedInfo exception {0}", e.Message);
            }
            return true;
        }
        #endregion Classifieds Queries

        #region Picks Queries
        public OSDArray GetAvatarPicks(UUID avatarId)
        {
            const string query = "SELECT `pickuuid`,`name` FROM userpicks WHERE creatoruuid = ?Id";

            OSDArray data = new OSDArray();

            try
            {
                using (MySqlConnection dbcon = new MySqlConnection(ConnectionString))
                {
                    dbcon.Open();
                    using (MySqlCommand cmd = new MySqlCommand(query, dbcon))
                    {
                        cmd.Parameters.AddWithValue("?Id", avatarId.ToString());

                        using (MySqlDataReader reader = cmd.ExecuteReader())
                        {
                            if(reader.HasRows)
                            {
                                while (reader.Read())
                                {
                                    OSDMap record = new OSDMap();

                                    record.Add("pickuuid",OSD.FromString((string)reader["pickuuid"]));
                                    record.Add("name",OSD.FromString((string)reader["name"]));
                                    data.Add(record);
                                }
                            }
                        }
                    }
                    dbcon.Close();
                }
            }
            catch (Exception e)
            {
                m_log.ErrorFormat("[PROFILES_DATA]: GetAvatarPicks exception {0}", e.Message);
            }
            return data;
        }

        public UserProfilePick GetPickInfo(UUID avatarId, UUID pickId)
        {
            UserProfilePick pick = new UserProfilePick();
            const string query = "SELECT * FROM userpicks WHERE creatoruuid = ?CreatorId AND pickuuid =  ?PickId";

            try
            {
                using (MySqlConnection dbcon = new MySqlConnection(ConnectionString))
                {
                    dbcon.Open();
                    using (MySqlCommand cmd = new MySqlCommand(query, dbcon))
                    {
                        cmd.Parameters.AddWithValue("?CreatorId", avatarId.ToString());
                        cmd.Parameters.AddWithValue("?PickId", pickId.ToString());

                        using (MySqlDataReader reader = cmd.ExecuteReader())
                        {
                            if(reader.HasRows)
                            {
                                reader.Read();

                                string description = (string)reader["description"];

                                if (string.IsNullOrEmpty(description))
                                    description = "No description given.";

                                UUID.TryParse((string)reader["pickuuid"], out pick.PickId);
                                UUID.TryParse((string)reader["creatoruuid"], out pick.CreatorId);
                                UUID.TryParse((string)reader["parceluuid"], out pick.ParcelId);
                                UUID.TryParse((string)reader["snapshotuuid"], out pick.SnapshotId);
                                pick.GlobalPos = (string)reader["posglobal"];
                                pick.Gatekeeper = (string)reader["gatekeeper"];
                                bool.TryParse((string)reader["toppick"], out pick.TopPick);
                                bool.TryParse((string)reader["enabled"], out pick.Enabled);
                                pick.Name = (string)reader["name"];
                                pick.Desc = description;
                                pick.ParcelName = (string)reader["user"];
                                pick.OriginalName = (string)reader["originalname"];
                                pick.SimName = (string)reader["simname"];
                                pick.SortOrder = (int)reader["sortorder"];
                            }
                        }
                    }
                    dbcon.Close();
                }
            }
            catch (Exception e)
            {
                m_log.ErrorFormat("[PROFILES_DATA]: GetPickInfo exception {0}", e.Message);
            }
            return pick;
        }

        public bool UpdatePicksRecord(UserProfilePick pick)
        {
            const string query =
                "INSERT INTO userpicks VALUES ("
                + "?PickId,"
                + "?CreatorId,"
                + "?TopPick,"
                + "?ParcelId,"
                + "?Name,"
                + "?Desc,"
                + "?SnapshotId,"
                + "?User,"
                + "?Original,"
                + "?SimName,"
                + "?GlobalPos,"
                + "?SortOrder,"
                + "?Enabled,"
                + "?Gatekeeper)"
                + "ON DUPLICATE KEY UPDATE "
                + "parceluuid=?ParcelId,"
                + "name=?Name,"
                + "description=?Desc,"
                + "user=?User,"
                + "simname=?SimName,"
                + "snapshotuuid=?SnapshotId,"
                + "pickuuid=?PickId,"
                + "posglobal=?GlobalPos,"
                + "gatekeeper=?Gatekeeper"
                ;

            try
            {
                using (MySqlConnection dbcon = new MySqlConnection(ConnectionString))
                {
                    dbcon.Open();
                    using (MySqlCommand cmd = new MySqlCommand(query, dbcon))
                    {
                        cmd.Parameters.AddWithValue("?PickId", pick.PickId.ToString());
                        cmd.Parameters.AddWithValue("?CreatorId", pick.CreatorId.ToString());
                        cmd.Parameters.AddWithValue("?TopPick", pick.TopPick.ToString());
                        cmd.Parameters.AddWithValue("?ParcelId", pick.ParcelId.ToString());
                        cmd.Parameters.AddWithValue("?Name", pick.Name.ToString());
                        cmd.Parameters.AddWithValue("?Desc", pick.Desc.ToString());
                        cmd.Parameters.AddWithValue("?SnapshotId", pick.SnapshotId.ToString());
                        cmd.Parameters.AddWithValue("?User", pick.ParcelName.ToString());
                        cmd.Parameters.AddWithValue("?Original", pick.OriginalName.ToString());
                        cmd.Parameters.AddWithValue("?SimName",pick.SimName.ToString());
                        cmd.Parameters.AddWithValue("?GlobalPos", pick.GlobalPos);
                        cmd.Parameters.AddWithValue("?Gatekeeper",pick.Gatekeeper);
                        cmd.Parameters.AddWithValue("?SortOrder", pick.SortOrder.ToString ());
                        cmd.Parameters.AddWithValue("?Enabled", pick.Enabled.ToString());

                        cmd.ExecuteNonQuery();
                    }
                    dbcon.Close();
                }
            }
            catch (Exception e)
            {
                m_log.ErrorFormat("[PROFILES_DATA]: UpdatePicksRecord exception {0}", e.Message);
                return false;
            }
            return true;
        }

        public bool DeletePicksRecord(UUID pickId)
        {
            string query = "DELETE FROM userpicks WHERE pickuuid = ?PickId";

            try
            {
                using (MySqlConnection dbcon = new MySqlConnection(ConnectionString))
                {
                    dbcon.Open();

                    using (MySqlCommand cmd = new MySqlCommand(query, dbcon))
                    {
                        cmd.Parameters.AddWithValue("?PickId", pickId.ToString());

                        cmd.ExecuteNonQuery();
                    }
                    dbcon.Close();
                }
            }
            catch (Exception e)
            {
                m_log.ErrorFormat("[PROFILES_DATA]: DeletePicksRecord exception {0}", e.Message);
                return false;
            }
            return true;
        }
        #endregion Picks Queries

        #region Avatar Notes Queries
        public bool GetAvatarNotes(ref UserProfileNotes notes)
        {  // WIP
            const string query = "SELECT `notes` FROM usernotes WHERE useruuid = ?Id AND targetuuid = ?TargetId";

            try
            {
                using (MySqlConnection dbcon = new MySqlConnection(ConnectionString))
                {
                    dbcon.Open();
                    using (MySqlCommand cmd = new MySqlCommand(query, dbcon))
                    {
                        cmd.Parameters.AddWithValue("?Id", notes.UserId.ToString());
                        cmd.Parameters.AddWithValue("?TargetId", notes.TargetId.ToString());

                        using (MySqlDataReader reader = cmd.ExecuteReader(CommandBehavior.SingleRow))
                        {
                            if(reader.HasRows)
                            {
                                reader.Read();
                                notes.Notes = OSD.FromString((string)reader["notes"]);
                            }
                            else
                            {
                                notes.Notes = OSD.FromString("");
                            }
                        }
                    }
                    dbcon.Close();
                }
            }
            catch (Exception e)
            {
                m_log.ErrorFormat("[PROFILES_DATA]: GetAvatarNotes exception {0}", e.Message);
            }
            return true;
        }

        public bool UpdateAvatarNotes(ref UserProfileNotes note, ref string result)
        {
            string query;
            bool remove;

            if(string.IsNullOrEmpty(note.Notes))
            {
                remove = true;
                query = "DELETE FROM usernotes WHERE useruuid=?UserId AND targetuuid=?TargetId";
            }
            else
            {
                remove = false;
                query = "INSERT INTO usernotes VALUES (" 
                    + "?UserId,"
                    + "?TargetId,"
                    + "?Notes )"
                    + "ON DUPLICATE KEY "
                    + "UPDATE "
                    + "notes=?Notes"
                    ;
            }

            try
            {
                using (MySqlConnection dbcon = new MySqlConnection(ConnectionString))
                {
                    dbcon.Open();
                    using (MySqlCommand cmd = new MySqlCommand(query, dbcon))
                    {
                        if(!remove)
                            cmd.Parameters.AddWithValue("?Notes", note.Notes);
                        cmd.Parameters.AddWithValue("?TargetId", note.TargetId.ToString ());
                        cmd.Parameters.AddWithValue("?UserId", note.UserId.ToString());

                        cmd.ExecuteNonQuery();
                    }
                    dbcon.Close();
                }
            }
            catch (Exception e)
            {
                m_log.ErrorFormat("[PROFILES_DATA]: UpdateAvatarNotes exception {0}", e.Message);
                return false;
            }
            return true;

        }
        #endregion Avatar Notes Queries

        #region Avatar Properties
        public bool GetAvatarProperties(ref UserProfileProperties props, ref string result)
        {
            string query = "SELECT * FROM userprofile WHERE useruuid = ?Id";

            try
            {
                using (MySqlConnection dbcon = new MySqlConnection(ConnectionString))
                {
                    dbcon.Open();
                    using (MySqlCommand cmd = new MySqlCommand(query, dbcon))
                    {
                        cmd.Parameters.AddWithValue("?Id", props.UserId.ToString());

                        using (MySqlDataReader reader = cmd.ExecuteReader(CommandBehavior.SingleRow))
                        {
                            if(reader.HasRows)
                            {
                                m_log.DebugFormat("[PROFILES_DATA]" +
                                                  ": Getting data for {0}.", props.UserId);
                                reader.Read();
                                props.WebUrl = (string)reader["profileURL"];
                                UUID.TryParse((string)reader["profileImage"], out props.ImageId);
                                props.AboutText = (string)reader["profileAboutText"];
                                UUID.TryParse((string)reader["profileFirstImage"], out props.FirstLifeImageId);
                                props.FirstLifeText = (string)reader["profileFirstText"];
                                UUID.TryParse((string)reader["profilePartner"], out props.PartnerId);
                                props.WantToMask = (int)reader["profileWantToMask"];
                                props.WantToText = (string)reader["profileWantToText"];
                                props.SkillsMask = (int)reader["profileSkillsMask"];
                                props.SkillsText = (string)reader["profileSkillsText"];
                                props.Language = (string)reader["profileLanguages"];
                            }
                            else
                            {
                                m_log.DebugFormat("[PROFILES_DATA]" +
                                                 ": No data for {0}", props.UserId);

                                props.WebUrl = string.Empty;
                                props.ImageId = UUID.Zero;
                                props.AboutText = string.Empty;
                                props.FirstLifeImageId = UUID.Zero;
                                props.FirstLifeText = string.Empty;
                                props.PartnerId = UUID.Zero;
                                props.WantToMask = 0;
                                props.WantToText = string.Empty;
                                props.SkillsMask = 0;
                                props.SkillsText = string.Empty;
                                props.Language = string.Empty;
                                props.PublishProfile = false;
                                props.PublishMature = false;

                                query = "INSERT INTO userprofile ("
                                    + "useruuid, "
                                    + "profilePartner, "
                                    + "profileAllowPublish, "
                                    + "profileMaturePublish, "
                                    + "profileURL, "
                                    + "profileWantToMask, "
                                    + "profileWantToText, "
                                    + "profileSkillsMask, "
                                    + "profileSkillsText, "
                                    + "profileLanguages, "
                                    + "profileImage, "
                                    + "profileAboutText, "
                                    + "profileFirstImage, "
                                    + "profileFirstText) VALUES ("
                                    + "?userId, "
                                    + "?profilePartner, "
                                    + "?profileAllowPublish, "
                                    + "?profileMaturePublish, "
                                    + "?profileURL, "
                                    + "?profileWantToMask, "
                                    + "?profileWantToText, "
                                    + "?profileSkillsMask, "
                                    + "?profileSkillsText, "
                                    + "?profileLanguages, "
                                    + "?profileImage, "
                                    + "?profileAboutText, "
                                    + "?profileFirstImage, "
                                    + "?profileFirstText)"
                                    ;

                                dbcon.Close();
                                dbcon.Open();

                                using (MySqlCommand put = new MySqlCommand(query, dbcon))
                                {
                                    put.Parameters.AddWithValue("?userId", props.UserId.ToString());
                                    put.Parameters.AddWithValue("?profilePartner", props.PartnerId.ToString());
                                    put.Parameters.AddWithValue("?profileAllowPublish", props.PublishProfile);
                                    put.Parameters.AddWithValue("?profileMaturePublish", props.PublishMature);
                                    put.Parameters.AddWithValue("?profileURL", props.WebUrl);
                                    put.Parameters.AddWithValue("?profileWantToMask", props.WantToMask);
                                    put.Parameters.AddWithValue("?profileWantToText", props.WantToText);
                                    put.Parameters.AddWithValue("?profileSkillsMask", props.SkillsMask);
                                    put.Parameters.AddWithValue("?profileSkillsText", props.SkillsText);
                                    put.Parameters.AddWithValue("?profileLanguages", props.Language);
                                    put.Parameters.AddWithValue("?profileImage", props.ImageId.ToString());
                                    put.Parameters.AddWithValue("?profileAboutText", props.AboutText);
                                    put.Parameters.AddWithValue("?profileFirstImage", props.FirstLifeImageId.ToString());
                                    put.Parameters.AddWithValue("?profileFirstText", props.FirstLifeText);

                                    put.ExecuteNonQuery();
                                }
                            }
                        }
                    }
                    dbcon.Close();
                }
            }
            catch (Exception e)
            {
                m_log.ErrorFormat("[PROFILES_DATA]: GetAvatarProperties exception {0}", e.Message);
                result = e.Message;
                return false;
            }
            return true;
        }

        public bool UpdateAvatarProperties(ref UserProfileProperties props, ref string result)
        {
            const string query = "UPDATE userprofile SET profileURL=?profileURL,"
                + "profileImage=?image, profileAboutText=?abouttext,"
                + "profileFirstImage=?firstlifeimage, profileFirstText=?firstlifetext "
                + "WHERE useruuid=?uuid";

            try
            {
                using (MySqlConnection dbcon = new MySqlConnection(ConnectionString))
                {
                    dbcon.Open();
                    using (MySqlCommand cmd = new MySqlCommand(query, dbcon))
                    {
                        cmd.Parameters.AddWithValue("?profileURL", props.WebUrl);
                        cmd.Parameters.AddWithValue("?image", props.ImageId.ToString());
                        cmd.Parameters.AddWithValue("?abouttext", props.AboutText);
                        cmd.Parameters.AddWithValue("?firstlifeimage", props.FirstLifeImageId.ToString());
                        cmd.Parameters.AddWithValue("?firstlifetext", props.FirstLifeText);
                        cmd.Parameters.AddWithValue("?uuid", props.UserId.ToString());

                        cmd.ExecuteNonQuery();
                    }
                    dbcon.Close();
                }
            }
            catch (Exception e)
            {
                m_log.ErrorFormat("[PROFILES_DATA]: UpdateAvatarProperties exception {0}", e.Message);

                return false;
            }
            return true;
        }
        #endregion Avatar Properties

        #region Avatar Interests
        public bool UpdateAvatarInterests(UserProfileProperties up, ref string result)
        {
            const string query = "UPDATE userprofile SET "
                + "profileWantToMask=?WantMask, "
                + "profileWantToText=?WantText,"
                + "profileSkillsMask=?SkillsMask,"
                + "profileSkillsText=?SkillsText, "
                + "profileLanguages=?Languages "
                + "WHERE useruuid=?uuid";

            try
            {
                using (MySqlConnection dbcon = new MySqlConnection(ConnectionString))
                {
                    dbcon.Open();
                    using (MySqlCommand cmd = new MySqlCommand(query, dbcon))
                    {
                        cmd.Parameters.AddWithValue("?WantMask", up.WantToMask);
                        cmd.Parameters.AddWithValue("?WantText", up.WantToText);
                        cmd.Parameters.AddWithValue("?SkillsMask", up.SkillsMask);
                        cmd.Parameters.AddWithValue("?SkillsText", up.SkillsText);
                        cmd.Parameters.AddWithValue("?Languages", up.Language);
                        cmd.Parameters.AddWithValue("?uuid", up.UserId.ToString());

                        cmd.ExecuteNonQuery();
                    }
                }
            }
            catch (Exception e)
            {
                m_log.ErrorFormat("[PROFILES_DATA]: UpdateAvatarInterests exception {0}", e.Message);
                result = e.Message;
                return false;
            }
            return true;
        }
        #endregion Avatar Interests

        public OSDArray GetUserImageAssets(UUID avatarId)
        {
            OSDArray data = new OSDArray();
            const string queryA = "SELECT `snapshotuuid` FROM {0} WHERE `creatoruuid` = ?Id";

            // Get classified image assets

            try
            {
                using (MySqlConnection dbcon = new MySqlConnection(ConnectionString))
                {
                    dbcon.Open();

                    using (MySqlCommand cmd = new MySqlCommand(string.Format (queryA,"`classifieds`"), dbcon))
                    {
                        cmd.Parameters.AddWithValue("?Id", avatarId.ToString());

                        using (MySqlDataReader reader = cmd.ExecuteReader(CommandBehavior.SingleRow))
                        {
                            if(reader.HasRows)
                            {
                                while (reader.Read())
                                {
                                    data.Add(new OSDString((string)reader["snapshotuuid"].ToString ()));
                                }
                            }
                        }
                    }

                    dbcon.Close();
                    dbcon.Open();

                    using (MySqlCommand cmd = new MySqlCommand(string.Format (queryA,"`userpicks`"), dbcon))
                    {
                        cmd.Parameters.AddWithValue("?Id", avatarId.ToString());

                        using (MySqlDataReader reader = cmd.ExecuteReader(CommandBehavior.SingleRow))
                        {
                            if(reader.HasRows)
                            {
                                while (reader.Read())
                                {
                                    data.Add(new OSDString((string)reader["snapshotuuid"].ToString ()));
                                }
                            }
                        }
                    }

                    dbcon.Close();
                    dbcon.Open();

                    const string queryB = "SELECT `profileImage`, `profileFirstImage` FROM `userprofile` WHERE `useruuid` = ?Id";

                    using (MySqlCommand cmd = new MySqlCommand(string.Format (queryB,"`userpicks`"), dbcon))
                    {
                        cmd.Parameters.AddWithValue("?Id", avatarId.ToString());

                        using (MySqlDataReader reader = cmd.ExecuteReader(CommandBehavior.SingleRow))
                        {
                            if(reader.HasRows)
                            {
                                while (reader.Read())
                                {
                                    data.Add(new OSDString((string)reader["profileImage"].ToString ()));
                                    data.Add(new OSDString((string)reader["profileFirstImage"].ToString ()));
                                }
                            }
                        }
                    }
                    dbcon.Close();
                }
            }
            catch (Exception e)
            {
                m_log.ErrorFormat("[PROFILES_DATA]: GetUserImageAssets exception {0}", e.Message);
            }
            return data;
        }

        #region User Preferences
        public bool GetUserPreferences(ref UserPreferences pref, ref string result)
        {
            const string query = "SELECT imviaemail,visible,email FROM usersettings WHERE useruuid = ?Id";

            try
            {
                using (MySqlConnection dbcon = new MySqlConnection(ConnectionString))
                {
                    dbcon.Open();
                    using (MySqlCommand cmd = new MySqlCommand(query, dbcon))
                    {
                        cmd.Parameters.AddWithValue("?Id", pref.UserId.ToString());
                        using (MySqlDataReader reader = cmd.ExecuteReader())
                        {
                            if (reader.HasRows)
                            {
                                reader.Read();
                                bool.TryParse((string)reader["imviaemail"], out pref.IMViaEmail);
                                bool.TryParse((string)reader["visible"], out pref.Visible);
                                pref.EMail = (string)reader["email"];
                            }
                            else
                            {
                                dbcon.Close();
                                dbcon.Open();

                                const string queryB = "INSERT INTO usersettings VALUES (?uuid,'false','false', ?Email)";

                                using (MySqlCommand put = new MySqlCommand(queryB, dbcon))
                                {

                                    put.Parameters.AddWithValue("?Email", pref.EMail);
                                    put.Parameters.AddWithValue("?uuid", pref.UserId.ToString());

                                    put.ExecuteNonQuery();
                                }
                            }
                        }
                    }
                    dbcon.Close();
                }
            }
            catch (Exception e)
            {
                m_log.ErrorFormat("[PROFILES_DATA]: GetUserPreferences exception {0}", e.Message);
                result = e.Message;
                return false;
            }
            return true;
        }

        public bool UpdateUserPreferences(ref UserPreferences pref, ref string result)
        {
            const string query = "UPDATE usersettings SET imviaemail=?ImViaEmail," 
                + "visible=?Visible, email=?EMail "
                + "WHERE useruuid=?uuid";

            try
            {
                using (MySqlConnection dbcon = new MySqlConnection(ConnectionString))
                {
                    dbcon.Open();
                    using (MySqlCommand cmd = new MySqlCommand(query, dbcon))
                    {
                        cmd.Parameters.AddWithValue("?ImViaEmail", pref.IMViaEmail.ToString().ToLower());
                        cmd.Parameters.AddWithValue("?Visible", pref.Visible.ToString().ToLower());
                        cmd.Parameters.AddWithValue("?uuid", pref.UserId.ToString());
                        cmd.Parameters.AddWithValue("?EMail", pref.EMail.ToString().ToLower());

                        cmd.ExecuteNonQuery();
                    }
                    dbcon.Close();
                }
            }
            catch (Exception e)
            {
                m_log.ErrorFormat("[PROFILES_DATA]: UpdateUserPreferences exception {0} {1}", e.Message, e.InnerException);
                result = e.Message;
                return false;
            }
            return true;
        }
        #endregion User Preferences

        #region Integration
        public bool GetUserAppData(ref UserAppData props, ref string result)
        {
            const string query = "SELECT * FROM `userdata` WHERE UserId = ?Id AND TagId = ?TagId";

            try
            {
                using (MySqlConnection dbcon = new MySqlConnection(ConnectionString))
                {
                    dbcon.Open();
                    using (MySqlCommand cmd = new MySqlCommand(query, dbcon))
                    {
                        cmd.Parameters.AddWithValue("?Id", props.UserId.ToString());
                        cmd.Parameters.AddWithValue ("?TagId", props.TagId.ToString());

                        using (MySqlDataReader reader = cmd.ExecuteReader(CommandBehavior.SingleRow))
                        {
                            if(reader.HasRows)
                            {
                                reader.Read();
                                props.DataKey = (string)reader["DataKey"];
                                props.DataVal = (string)reader["DataVal"];
                            }
                            else
                            {
                                const string queryB = "INSERT INTO userdata VALUES (?UserId, ?TagId, ?DataKey, ?DataVal)";
                                using (MySqlCommand put = new MySqlCommand(queryB, dbcon))
                                {
                                    put.Parameters.AddWithValue("?UserId", props.UserId.ToString());
                                    put.Parameters.AddWithValue("?TagId", props.TagId.ToString());
                                    put.Parameters.AddWithValue("?DataKey", props.DataKey.ToString());
                                    put.Parameters.AddWithValue("?DataVal", props.DataVal.ToString());

                                    put.ExecuteNonQuery();
                                }
                            }
                        }
                    }
                    dbcon.Close();
                }
            }
            catch (Exception e)
            {
                m_log.ErrorFormat("[PROFILES_DATA]: GetUserAppData exception {0}", e.Message);
                result = e.Message;
                return false;
            }
            return true;
        }

        public bool SetUserAppData(UserAppData props, ref string result)
        {
            const string query = "UPDATE userdata SET TagId = ?TagId, DataKey = ?DataKey, DataVal = ?DataVal WHERE UserId = ?UserId AND TagId = ?TagId";

            try
            {
                using (MySqlConnection dbcon = new MySqlConnection(ConnectionString))
                {
                    dbcon.Open();
                    using (MySqlCommand cmd = new MySqlCommand(query, dbcon))
                    {
                        cmd.Parameters.AddWithValue("?UserId", props.UserId.ToString());
                        cmd.Parameters.AddWithValue("?TagId", props.TagId.ToString());
                        cmd.Parameters.AddWithValue("?DataKey", props.DataKey.ToString());
                        cmd.Parameters.AddWithValue("?DataVal", props.DataKey.ToString());

                        cmd.ExecuteNonQuery();
                    }
                    dbcon.Close();
                }
            }
            catch (Exception e)
            {
                m_log.ErrorFormat("[PROFILES_DATA]: SetUserAppData exception {0}", e.Message);
                return false;
            }
            return true;
        }
        #endregion Integration
    }
}