Exemple #1
0
        internal static UserData GetUserData(string sessionTicket, string ip, out byte errorCode)
        {
            DataRow dUserInfo;

            DataTable dAchievements;
            DataTable dFavouriteRooms;
            DataTable dIgnores;
            DataTable dTags;
            DataTable dSubscriptions;
            DataTable dBadges;
            DataTable dInventory;
            DataTable dEffects;
            DataTable dFriends;
            DataTable dRequests;
            DataTable dRooms;
            DataTable dPets;
            DataTable dQuests;
            //DataTable dSongs;
            DataTable dGroups = null;

            UInt32 userID;

            using (IQueryAdapter dbClient = FirewindEnvironment.GetDatabaseManager().getQueryreactor())
            {
                if (FirewindEnvironment.useSSO)
                {
                    dbClient.setQuery("SELECT * " +
                                        "FROM users " +
                                        "WHERE auth_ticket = @sso ");
                }
                else
                {
                    dbClient.setQuery("SELECT * " +
                                        "FROM users " +
                                        "WHERE auth_ticket = @sso ");
                }

                dbClient.addParameter("sso", sessionTicket);
                //dbClient.addParameter("ipaddress", ip);
                dUserInfo = dbClient.getRow();

                if (dUserInfo == null)
                {
                    errorCode = 1;
                    return null;
                    //Logging.LogException("No user found. Debug data: [" + sessionTicket + "], [" + ip + "]");
                    //throw new UserDataNotFoundException(string.Format("No user found with ip {0} and sso {1}. Use SSO: {2} ", ip, sessionTicket, FirewindEnvironment.useSSO.ToString()));
                }

                userID = Convert.ToUInt32(dUserInfo["id"]);
                if (FirewindEnvironment.GetGame().GetClientManager().GetClientByUserID(userID) != null)
                {
                    errorCode = 2;
                    return null;
                }

                string creditsTimestamp = (string)dUserInfo["lastdailycredits"];
                string todayTimestamp = DateTime.Today.ToString("MM/dd");
                if (creditsTimestamp != todayTimestamp)
                {
                    dbClient.runFastQuery("UPDATE users SET credits = credits + 3000, daily_respect_points = 3, lastdailycredits = '" + todayTimestamp + "' WHERE id = " + userID);
                    dUserInfo["credits"] = (int)dUserInfo["credits"] + 3000;
                }

                dbClient.setQuery("SELECT * FROM user_achievement WHERE userid = " + userID);
                dAchievements = dbClient.getTable();

                dbClient.setQuery("SELECT room_id FROM user_favorites WHERE user_id = " + userID);
                dFavouriteRooms = dbClient.getTable();

                dbClient.setQuery("SELECT ignore_id FROM user_ignores WHERE user_id = " + userID);
                dIgnores = dbClient.getTable();

                dbClient.setQuery("SELECT tag FROM user_tags WHERE user_id = " + userID);
                dTags = dbClient.getTable();

                dbClient.setQuery("SELECT * FROM user_subscriptions WHERE user_id = " + userID);
                dSubscriptions = dbClient.getTable();

                dbClient.setQuery("SELECT * FROM user_badges WHERE user_id = " + userID);
                dBadges = dbClient.getTable();

                dbClient.setQuery("CALL getuseritems(" + userID + ")");
                dInventory = dbClient.getTable();

                dbClient.setQuery("SELECT * FROM user_effects WHERE user_id =  " + userID);
                dEffects = dbClient.getTable();

                dbClient.setQuery("SELECT users.id,users.username,users.motto,users.look,users.last_online " +
                                        "FROM users " +
                                        "JOIN messenger_friendships " +
                                        "ON users.id = messenger_friendships.sender " +
                                        "WHERE messenger_friendships.receiver = " + userID + " " +
                                        "UNION ALL " +
                                        "SELECT users.id,users.username,users.motto,users.look,users.last_online " +
                                        "FROM users " +
                                        "JOIN messenger_friendships " +
                                        "ON users.id = messenger_friendships.receiver " +
                                        "WHERE messenger_friendships.sender = " + userID);
                dFriends = dbClient.getTable();

                dbClient.setQuery("SELECT messenger_requests.sender,messenger_requests.receiver,users.username " +
                                        "FROM users " +
                                        "JOIN messenger_requests " +
                                        "ON users.id = messenger_requests.sender " +
                                        "WHERE messenger_requests.receiver = " + userID);
                dRequests = dbClient.getTable();

                dbClient.setQuery("SELECT rooms.*, room_active.active_users FROM rooms LEFT JOIN room_active ON (room_active.roomid = rooms.id) WHERE owner = @name");
                dbClient.addParameter("name", (string)dUserInfo["username"]);
                dRooms = dbClient.getTable();

                dbClient.setQuery("SELECT * FROM user_pets WHERE user_id = " + userID + " AND room_id = 0");
                dPets = dbClient.getTable();

                dbClient.setQuery("SELECT * FROM user_quests WHERE user_id = " + userID + "");
                dQuests = dbClient.getTable();

                //dbClient.setQuery("SELECT item_id, song_id FROM user_items_songs WHERE user_id = " + userID);
                //dSongs = dbClient.getTable();

                /* dbClient.setQuery("UPDATE users SET ip_last = @ip WHERE id = " + userID + " LIMIT 1; " +
                                       "UPDATE user_info SET login_timestamp = '" + FirewindEnvironment.GetUnixTimestamp() + "' WHERE user_id = " + userID + " LIMIT 1; " +
                                       "REPLACE INTO user_online VALUES (" + userID + "); " +
                                       "DELETE FROM user_tickets WHERE userid = " + userID + ";");*/

                dbClient.setQuery("UPDATE users SET ip_last = @ip WHERE id = " + userID + "; " +
                                      "UPDATE user_info SET login_timestamp = '" + FirewindEnvironment.GetUnixTimestamp() + "' WHERE user_id = " + userID + " ; " +
                                      "");
                dbClient.addParameter("ip", ip);
                dbClient.runQuery();

                dbClient.runFastQuery("REPLACE INTO user_online VALUES (" + userID + ")");
            }

            Dictionary<string, UserAchievement> achievements = new Dictionary<string, UserAchievement>();

            string achievementGroup;
            int achievementLevel;
            int achievementProgress;
            foreach (DataRow dRow in dAchievements.Rows)
            {
                achievementGroup = (string)dRow["group"];
                achievementLevel = (int)dRow["level"];
                achievementProgress = (int)dRow["progress"];

                UserAchievement achievement = new UserAchievement(achievementGroup, achievementLevel, achievementProgress);
                achievements.Add(achievementGroup, achievement);
            }

            List<uint> favouritedRooms = new List<uint>();

            uint favoritedRoomID;
            foreach (DataRow dRow in dFavouriteRooms.Rows)
            {
                favoritedRoomID = Convert.ToUInt32(dRow["room_id"]);
                favouritedRooms.Add(favoritedRoomID);
            }

            List<uint> ignores = new List<uint>();

            uint ignoredUserID;
            foreach (DataRow dRow in dIgnores.Rows)
            {
                ignoredUserID = Convert.ToUInt32(dRow["ignore_id"]);
                ignores.Add(ignoredUserID);
            }

            List<string> tags = new List<string>();

            string tag;
            foreach (DataRow dRow in dTags.Rows)
            {
                tag = (string)dRow["tag"];
                tags.Add(tag);
            }

            Dictionary<string, Subscription> subscriptions = new Dictionary<string, Subscription>();

            string subscriptionID;
            int expireTimestamp;
            foreach (DataRow dRow in dSubscriptions.Rows)
            {
                subscriptionID = (string)dRow["subscription_id"];
                expireTimestamp = (int)dRow["timestamp_expire"];

                subscriptions.Add(subscriptionID, new Subscription(subscriptionID, expireTimestamp));
            }

            List<Badge> badges = new List<Badge>();

            string badgeID;
            int slotID;
            foreach (DataRow dRow in dBadges.Rows)
            {
                badgeID = (string)dRow["badge_id"];
                slotID = (int)dRow["badge_slot"];
                badges.Add(new Badge(badgeID, slotID));
            }

            List<UserItem> inventory = new List<UserItem>();

            uint itemID;
            uint baseItem;
            int dataType;
            string extradata;
            int extra;
            foreach (DataRow Row in dInventory.Rows)
            {
                itemID = Convert.ToUInt32(Row[0]);
                baseItem = Convert.ToUInt32(Row[1]);

                    IRoomItemData data;
                    if (DBNull.Value.Equals(Row[2]))
                    {
                        data = new StringData("");
                        extra = 0;
                    }
                    else
                    {
                        dataType = Convert.ToInt32(Row[2]);
                        extradata = (string)Row[3];
                        extra = Convert.ToInt32(Row[4]);
                        switch (dataType)
                        {
                            case 0:
                                data = new StringData(extradata);
                                break;
                            case 1:
                                data = new MapStuffData();
                                break;
                            case 2:
                                data = new StringArrayStuffData();
                                break;
                            case 3:
                                data = new StringIntData();
                                break;
                            default:
                                data = new StringData(extradata);
                                break;
                        }
                        try
                        {
                            data.Parse(extradata);
                        }
                        catch
                        {
                            Logging.LogException(string.Format("Error in furni data! Item ID: \"{0}\" and data: \"{1}\"", itemID, extradata.Replace(Convert.ToChar(1).ToString(), "[1]")));
                        }
                    }

                inventory.Add(new UserItem(itemID, baseItem, data, extra));
            }

            List<AvatarEffect> effects = new List<AvatarEffect>();

            int effectID;
            int duration;
            bool isActivated;
            double activatedTimeStamp;
            foreach (DataRow dRow in dEffects.Rows)
            {
                effectID = (int)dRow["effect_id"];
                duration = (int)dRow["total_duration"];
                isActivated = Convert.ToInt32(dRow["is_activated"]) == 1;
                activatedTimeStamp = (double)dRow["activated_stamp"];

                effects.Add(new AvatarEffect(effectID, duration, isActivated, activatedTimeStamp));
            }

            Dictionary<uint, MessengerBuddy> friends = new Dictionary<uint, MessengerBuddy>();

            string username = (string)dUserInfo["username"];

            UInt32 friendID;
            string friendName;
            string friendLook;
            string friendMotto;
            string friendLastOnline;
            foreach (DataRow dRow in dFriends.Rows)
            {
                friendID = Convert.ToUInt32(dRow["id"]);
                friendName = (string)dRow["username"];
                friendLook = (string)dRow["look"];
                friendMotto = (string)dRow["motto"];
                friendLastOnline = Convert.ToString(dRow["last_online"]);

                if (friendID == userID)
                    continue;

                if (!friends.ContainsKey(friendID))
                    friends.Add(friendID, new MessengerBuddy(friendID, friendName, friendLook, friendMotto, friendLastOnline));
            }

            Dictionary<uint, MessengerRequest> requests = new Dictionary<uint, MessengerRequest>();

            uint receiverID;
            uint senderID;
            string requestUsername;
            foreach (DataRow dRow in dRequests.Rows)
            {
                receiverID = Convert.ToUInt32(dRow["sender"]);
                senderID = Convert.ToUInt32(dRow["receiver"]);

                requestUsername = (string)dRow["username"];

                if (receiverID != userID)
                {
                    if (!requests.ContainsKey(receiverID))
                        requests.Add(receiverID, new MessengerRequest(userID, receiverID, requestUsername));
                }
                else
                {
                    if (!requests.ContainsKey(senderID))
                        requests.Add(senderID, new MessengerRequest(userID, senderID, requestUsername));
                }
            }

            List<RoomData> rooms = new List<RoomData>();

            uint roomID;
            foreach (DataRow dRow in dRooms.Rows)
            {
                roomID = Convert.ToUInt32(dRow["id"]);
                rooms.Add(FirewindEnvironment.GetGame().GetRoomManager().FetchRoomData(roomID, dRow));
            }

            Dictionary<uint, Pet> pets = new Dictionary<uint, Pet>();

            Pet pet;
            foreach (DataRow dRow in dPets.Rows)
            {
                pet = Catalog.GeneratePetFromRow(dRow);
                pets.Add(pet.PetId, pet);
            }

            Dictionary<uint, int> quests = new Dictionary<uint, int>();

            uint questId;
            int progress;
            foreach (DataRow dRow in dQuests.Rows)
            {
                questId = Convert.ToUInt32(dRow["quest_id"]);
                progress = (int)dRow["progress"];
                quests.Add(questId, progress);
            }

            Hashtable songs = new Hashtable();

            //uint songItemID;
            //uint songID;
            //foreach (DataRow dRow in dSongs.Rows)
            //{
            //    songItemID = (uint)dRow[0];
            //    songID = (uint)dRow[1];

            //    SongItem song = new SongItem(songItemID, songID);
            //    songs.Add(songItemID, song);
            //}

            Habbo user = HabboFactory.GenerateHabbo(dUserInfo, dGroups);

            dUserInfo = null;
            dAchievements = null;
            dFavouriteRooms = null;
            dIgnores = null;
            dTags = null;
            dSubscriptions = null;
            dBadges = null;
            dInventory = null;
            dEffects = null;
            dFriends = null;
            dRequests = null;
            dRooms = null;
            dPets = null;

            errorCode = 0;
            return new UserData(userID, achievements, favouritedRooms, ignores, tags, subscriptions, badges, inventory, effects, friends, requests, rooms, pets, quests, songs, user);
        }
        internal void LoadInventory()
        {
            floorItems.Clear();
            wallItems.Clear();

            DataTable Data;

            using (IQueryAdapter dbClient = FirewindEnvironment.GetDatabaseManager().getQueryreactor())
            {
                dbClient.setQuery("CALL getuseritems(@userid)");
                dbClient.addParameter("userid", (int)UserId);

                Data = dbClient.getTable();

                //dbClient.setQuery("SELECT item_id, song_id FROM user_items_songs WHERE user_id = " + UserId);
                //dSongs = dbClient.getTable();
            }

            uint id;
            uint baseitem;
            int dataType;
            string extradata;
            int extra;
            foreach (DataRow Row in Data.Rows)
            {
                id = Convert.ToUInt32(Row[0]);
                baseitem = Convert.ToUInt32(Row[1]);

                    IRoomItemData data;
                    if (DBNull.Value.Equals(Row[2]))
                    {
                        data = new StringData("");
                        extra = 0;
                    }
                    else
                    {
                        dataType = Convert.ToInt32(Row[2]);
                        extradata = (string)Row[3];
                        extra = Convert.ToInt32(Row[4]);
                        switch (dataType)
                        {
                            case 0:
                                data = new StringData(extradata);
                                break;
                            case 1:
                                data = new MapStuffData();
                                break;
                            case 2:
                                data = new StringArrayStuffData();
                                break;
                            case 3:
                                data = new StringIntData();
                                break;
                            default:
                                data = new StringData(extradata);
                                break;
                        }
                        try
                        {
                            data.Parse(extradata);
                        }
                        catch
                        {
                            Logging.LogException(string.Format("Error in furni data! Item ID: \"{0}\" and data: \"{1}\"", id, extradata.Replace(Convert.ToChar(1).ToString(), "[1]")));
                        }
                    }

                UserItem item = new UserItem(id, baseitem, data, extra);

                if (item.GetBaseItem().InteractionType == InteractionType.musicdisc)
                    discs.Add(id, item);
                if (item.isWallItem)
                    wallItems.Add(id, item);
                else
                    floorItems.Add(id, item);
            }

            discs.Clear();

            //uint songItemID;
            //uint songID;
            //foreach (DataRow dRow in dSongs.Rows)
            //{
            //    songItemID = (uint)dRow[0];
            //    songID = (uint)dRow[1];

            //    SongItem song = new SongItem(songItemID, songID);
            //    songs.Add(songItemID, song);
            //}

            this.InventoryPets.Clear();
            DataTable Data2;
            using (IQueryAdapter dbClient = FirewindEnvironment.GetDatabaseManager().getQueryreactor())
            {
                //dbClient.addParameter("userid", UserId);
                dbClient.setQuery("SELECT id, user_id, room_id, name, type, race, color, expirience, energy, nutrition, respect, createstamp, x, y, z, have_saddle FROM user_pets WHERE user_id = " + UserId + " AND room_id = 0");
                Data2 = dbClient.getTable();
            }

            if (Data2 != null)
            {
                foreach (DataRow Row in Data2.Rows)
                {
                    Pet newPet = Catalog.GeneratePetFromRow(Row);
                    InventoryPets.Add(newPet.PetId, newPet);
                }
            }
        }
Exemple #3
0
        internal void LoadFurniture()
        {
            //this.Items.Clear();
            this.mFloorItems.Clear();
            this.mWallItems.Clear();
            DataTable Data;

            using (IQueryAdapter dbClient = FirewindEnvironment.GetDatabaseManager().getQueryreactor())
            {
                dbClient.setQuery("CALL getroomitems(@roomid)");
                dbClient.addParameter("roomid", room.RoomId);
                Data = dbClient.getTable();


                uint           itemID;
                decimal        x;
                decimal        y;
                sbyte          n;
                uint           baseID;
                int            dataType;
                string         extradata;
                WallCoordinate wallCoord;
                int            extra;
                foreach (DataRow dRow in Data.Rows)
                {
                    itemID = Convert.ToUInt32(dRow[0]);
                    x      = Convert.ToDecimal(dRow[1]);
                    y      = Convert.ToDecimal(dRow[2]);
                    n      = Convert.ToSByte(dRow[3]);
                    baseID = Convert.ToUInt32(dRow[4]);
                    IRoomItemData data;
                    if (DBNull.Value.Equals(dRow[5]))
                    {
                        data  = new StringData("");
                        extra = 0;
                    }
                    else
                    {
                        dataType  = Convert.ToInt32(dRow[5]);
                        extradata = (string)dRow[6];
                        extra     = Convert.ToInt32(dRow[7]);
                        switch (dataType)
                        {
                        case 0:
                            data = new StringData(extradata);
                            break;

                        case 1:
                            data = new MapStuffData();
                            break;

                        case 2:
                            data = new StringArrayStuffData();
                            break;

                        case 3:
                            data = new StringIntData();
                            break;

                        default:
                            data = new StringData(extradata);
                            break;
                        }
                        try
                        {
                            data.Parse(extradata);
                        }
                        catch
                        {
                            Logging.LogException(string.Format("Error in furni data! Item ID: \"{0}\" and data: \"{1}\"", itemID, extradata.Replace(Convert.ToChar(1).ToString(), "[1]")));
                            dbClient.runFastQuery(string.Format("DELETE FROM items_extradata WHERE item_id = {0}", itemID));
                        }
                    }

                    if (FirewindEnvironment.GetGame().GetItemManager().GetItem(baseID).Type == 'i') // Is wallitem
                    {
                        wallCoord = new WallCoordinate((double)x, (double)y, n);
                        RoomItem item = new RoomItem(itemID, room.RoomId, baseID, data, extra, wallCoord, room);

                        if (!mWallItems.ContainsKey(itemID))
                        {
                            mWallItems.Inner.Add(itemID, item);
                        }
                    }
                    else //Is flooritem
                    {
                        int coordX, coordY;
                        TextHandling.Split((double)x, out coordX, out coordY);

                        RoomItem item = new RoomItem(itemID, room.RoomId, baseID, data, extra, coordX, coordY, (double)y, n, room);
                        if (!mFloorItems.ContainsKey(itemID))
                        {
                            mFloorItems.Inner.Add(itemID, item);
                        }
                    }
                }

                foreach (RoomItem Item in mFloorItems.Values)
                {
                    if (Item.IsRoller)
                    {
                        mGotRollers = true;
                    }
                    else if (Item.GetBaseItem().InteractionType == Firewind.HabboHotel.Items.InteractionType.dimmer)
                    {
                        if (room.MoodlightData == null)
                        {
                            room.MoodlightData = new MoodlightData(Item.Id);
                        }
                    }
                    else if (WiredUtillity.TypeIsWired(Item.GetBaseItem().InteractionType))
                    {
                        WiredLoader.LoadWiredItem(Item, room, dbClient);
                        room.GetWiredHandler().AddWire(Item, Item.Coordinate, Item.Rot, Item.GetBaseItem().InteractionType);
                    }
                }
            }
        }
Exemple #4
0
        internal void HandlePurchase(GameClient Session, int PageId, uint ItemId, string extraParameter, int buyAmount, Boolean IsGift, string GiftUser, string GiftMessage, int GiftSpriteId, int GiftLazo, int GiftColor, bool giftShowIdentity)
        {
            int finalAmount = buyAmount;
            if (buyAmount > 5) // Possible discount!
            {
                // Nearest number that increases the amount of free items
                int nearestDiscount = ((int)Math.Floor(buyAmount / 6.0) * 6);

                // How many free ones we get
                int freeItemsCount = (nearestDiscount - 3) / 3;

                // Add 1 free if more than 42
                if (buyAmount >= 42)
                    freeItemsCount++;

                // Doesn't follow rules as it isn't dividable by 6, but still increases free items
                if (buyAmount >= 99)
                {
                    freeItemsCount = 33;
                }

                // This is how many we pay for in the end
                finalAmount = buyAmount - freeItemsCount;
            }

            //Logging.WriteLine("Amount: " + priceAmount + "; withOffer= " + finalAmount);
            CatalogPage Page;
            if (!Pages.TryGetValue(PageId, out Page))
                return;
            if (Page == null || !Page.Enabled || !Page.Visible || Session == null || Session.GetHabbo() == null)
            {
                Session.SendMessage(new ServerMessage(Outgoing.PurchaseError));
                return;
            }
            if (Page.ClubOnly && !Session.GetHabbo().GetSubscriptionManager().HasSubscription("habbo_club") && !Session.GetHabbo().GetSubscriptionManager().HasSubscription("habbo_vip"))
            {
                Session.SendMessage(new ServerMessage(Outgoing.PurchaseError));
                return;
            }
            if (Page.MinRank > Session.GetHabbo().Rank)
            {
                Session.SendMessage(new ServerMessage(Outgoing.PurchaseError));
                return;
            }
            CatalogItem Item = Page.GetItem(ItemId);

            if (Item == null) // TODO: Check item minimum club rank
            {
                Session.SendMessage(new ServerMessage(Outgoing.PurchaseError));
                return;
            }
            if (!Item.HaveOffer && buyAmount > 1) // Check if somebody is bulk-buying when not allowed
            {
                Session.SendMessage(new ServerMessage(Outgoing.PurchaseError));
                return;
            }
            if (Item.IsLimited && Item.LimitedStack <= Item.LimitedSelled)
            {
                Session.SendMessage(new ServerMessage(Outgoing.PurchaseError));
                return;
            }

            uint GiftUserId = 0;
            //int giftWrappingCost = 0;
            if (IsGift)
            {
                if(!Item.AllowGift)
                {
                    Session.SendMessage(new ServerMessage(Outgoing.PurchaseError));
                    return;
                }
                if(Item.Items.Count > 1 || Item.Amount > 1) // Gifts can only have 1 item?
                {
                    Session.SendMessage(new ServerMessage(Outgoing.PurchaseError));
                    return;
                }

                DataRow dRow;
                using (IQueryAdapter dbClient = FirewindEnvironment.GetDatabaseManager().getQueryreactor())
                {
                    dbClient.setQuery("SELECT id FROM users WHERE username = @gift_user");
                    dbClient.addParameter("gift_user", GiftUser);

                    dRow = dbClient.getRow();
                }

                if (dRow == null)
                {
                    Session.GetMessageHandler().GetResponse().Init(Outgoing.GiftError);
                    Session.GetMessageHandler().GetResponse().AppendString(GiftUser);
                    Session.GetMessageHandler().SendResponse();

                    return;
                }

                GiftUserId = Convert.ToUInt32(dRow[0]);

                if (GiftUserId == 0)
                {
                    Session.GetMessageHandler().GetResponse().Init(Outgoing.GiftError);
                    Session.GetMessageHandler().GetResponse().AppendString(GiftUser);
                    Session.GetMessageHandler().SendResponse();

                    return;
                }
            }

            Boolean CreditsError = false;
            Boolean PixelError = false;
            Boolean CrystalError = false;

            if (Session.GetHabbo().Credits < (Item.CreditsCost * finalAmount))
            {
                CreditsError = true;
            }

            if (Session.GetHabbo().VipPoints < (Item.CrystalCost * finalAmount))
            {
                CrystalError = true;
            }

            if (Session.GetHabbo().ActivityPoints < (Item.PixelsCost * finalAmount))
            {
                PixelError = true;
            }

            if (CreditsError || PixelError)
            {
                ServerMessage message = new ServerMessage(Outgoing.NotEnoughBalance);
                message.AppendBoolean(CreditsError);
                message.AppendBoolean(PixelError);
                Session.SendMessage(message);
                return;
            }

            if (Item.CrystalCost > 0)
            {
                int cost = Item.CrystalCost * finalAmount;
                if (Session.GetHabbo().VipPoints < cost)
                {
                    Session.SendNotif("You can't afford that item!");
                    Session.SendMessage(new ServerMessage(Outgoing.PurchaseError));
                    return;
                }

                Session.GetHabbo().VipPoints -= cost;
                Session.GetHabbo().UpdateActivityPointsBalance(true);

                using (IQueryAdapter adapter = FirewindEnvironment.GetDatabaseManager().getQueryreactor())
                {
                    adapter.runFastQuery("UPDATE users SET vip_points = " + Session.GetHabbo().VipPoints + " WHERE id = " + Session.GetHabbo().Id);
                }

            }

            if (Item.CreditsCost > 0 && !IsGift)
            {
                Session.GetHabbo().Credits -= (Item.CreditsCost * finalAmount);
                Session.GetHabbo().UpdateCreditsBalance();
            }

            if (Item.PixelsCost > 0 && !IsGift)
            {
                Session.GetHabbo().ActivityPoints -= (Item.PixelsCost * finalAmount);
                Session.GetHabbo().UpdateActivityPointsBalance(true);
            }

            // Item is purchased, now do post-proccessing
            if (Item.IsLimited)
            {
                Item.LimitedSelled++;
                using (IQueryAdapter dbClient = FirewindEnvironment.GetDatabaseManager().getQueryreactor())
                {
                    dbClient.runFastQuery("UPDATE catalog_items SET limited_sells = " + Item.LimitedSelled + " WHERE id = " + Item.Id);
                }
                Page.InitMsg(); // update page!

                // send update
                Session.SendMessage(Page.GetMessage);
            }

            foreach (uint i in Item.Items)
            {
                //Logging.WriteLine(Item.GetBaseItem().ItemId);
                //Logging.WriteLine(Item.GetBaseItem().InteractionType.ToLower());
                // Extra Data is _NOT_ filtered at this point and MUST BE VERIFIED BELOW:
                if (Item.GetBaseItem(i).Type == 'h') // Subscription
                {
                    int Months = 0;
                    int Days = 0;
                    if (Item.Name.Contains("HABBO_CLUB_VIP_"))
                    {
                        if (Item.Name.Contains("_DAY"))
                        {
                            Days = int.Parse(Item.Name.Split('_')[3]);
                        }
                        else if (Item.Name.Contains("_MONTH"))
                        {
                            Months = int.Parse(Item.Name.Split('_')[3]);
                            Days = 31 * Months;
                        }
                    }
                    else if (Item.Name.Equals("deal_vip_1_year_and_badge"))
                    {
                        Months = 12;
                        Days = 31 * Months;
                    }
                    else if (Item.Name.Equals("HABBO_CLUB_VIP_5_YEAR"))
                    {
                        Months = 5 * 12;
                        Days = 31 * Months;
                    }
                    else if (Item.Name.StartsWith("DEAL_HC_"))
                    {
                        Months = int.Parse(Item.Name.Split('_')[2]);
                        Days = 31 * Months;

                        Session.GetHabbo().GetSubscriptionManager().AddOrExtendSubscription("habbo_club", Days * 24 * 3600);
                        Session.GetHabbo().SerializeClub();
                        return;
                    }

                    Session.GetHabbo().GetSubscriptionManager().AddOrExtendSubscription("habbo_vip", Days * 24 * 3600);
                    Session.GetHabbo().SerializeClub();
                    return;
                }

                if (IsGift && Item.GetBaseItem(i).Type == 'e')
                {
                    Session.SendNotif(LanguageLocale.GetValue("catalog.gift.send.error"));
                    return;
                }
                IRoomItemData itemData = new StringData(extraParameter);
                switch (Item.GetBaseItem(i).InteractionType)
                {
                    case InteractionType.none:
                        //itemData = new StringData(extraParameter);
                        break;

                    case InteractionType.musicdisc:
                        itemData = new StringData(Item.songID.ToString());
                        break;

                    #region Pet handling
                    case InteractionType.pet:
                        try
                        {
                            string[] Bits = extraParameter.Split('\n');
                            string PetName = Bits[0];
                            string Race = Bits[1];
                            string Color = Bits[2];

                            int.Parse(Race); // to trigger any possible errors

                            if (!CheckPetName(PetName))
                            {
                                Session.SendMessage(new ServerMessage(Outgoing.PurchaseError));
                                return;
                            }

                            //if (Race.Length != 1)
                            //    return;

                            if (Color.Length != 6)
                            {
                                Session.SendMessage(new ServerMessage(Outgoing.PurchaseError));
                                return;
                            }
                        }
                        catch (Exception e)
                        {
                            Logging.WriteLine(e.ToString());
                            Logging.HandleException(e, "Catalog.HandlePurchase");
                            Session.SendMessage(new ServerMessage(Outgoing.PurchaseError));
                            return;
                        }

                        break;

                    #endregion

                    case InteractionType.roomeffect:

                        Double Number = 0;

                        try
                        {
                            if (string.IsNullOrEmpty(extraParameter))
                                Number = 0;
                            else
                                Number = Double.Parse(extraParameter, FirewindEnvironment.cultureInfo);
                        }
                        catch (Exception e) { Logging.HandleException(e, "Catalog.HandlePurchase: " + extraParameter); }

                        itemData = new StringData(Number.ToString().Replace(',', '.'));
                        break; // maintain extra data // todo: validate

                    case InteractionType.postit:
                        itemData = new StringData("FFFF33");
                        break;

                    case InteractionType.dimmer:
                        itemData = new StringData("1,1,1,#000000,255");
                        break;

                    case InteractionType.trophy:
                        itemData = new StringData(String.Format("{0}\t{1}\t{2}", Session.GetHabbo().Username, DateTime.Now.ToString("d-M-yyy"), extraParameter));
                        break;

                    //case InteractionType.mannequin:
                    //    MapStuffData data = new MapStuffData();
                    //    data.Data.Add("OUTFIT_NAME", "");
                    //    data.Data.Add("FIGURE", "");
                    //    data.Data.Add("GENDER", "");
                    //    itemData = data;
                    //    break;
                    default:
                        //itemData = new StringData(extraParameter);
                        break;
                }

                //Session.GetMessageHandler().GetResponse().Init(Outgoing.UpdateInventary);
                //Session.GetMessageHandler().SendResponse();

                Session.GetMessageHandler().GetResponse().Init(Outgoing.PurchaseOK); // PurchaseOKMessageEvent
                Item.Serialize(Session.GetMessageHandler().GetResponse());
                Session.GetMessageHandler().SendResponse();

                if (IsGift)
                {
                    uint itemID;
                    //uint GenId = GenerateItemId();
                    Item Present = FirewindEnvironment.GetGame().GetItemManager().GetItemBySpriteID(GiftSpriteId);
                    if (Present == null)
                    {
                        Logging.LogDebug(string.Format("Somebody tried to purchase a present with invalid sprite ID: {0}", GiftSpriteId));
                        Session.SendMessage(new ServerMessage(Outgoing.PurchaseError));
                        return;
                    }

                    MapStuffData giftData = new MapStuffData();

                    if (giftShowIdentity)
                    {
                        giftData.Data.Add("PURCHASER_NAME", Session.GetHabbo().Username);
                        giftData.Data.Add("PURCHASER_FIGURE", Session.GetHabbo().Look);
                    }
                    giftData.Data.Add("MESSAGE", GiftMessage);
                    giftData.Data.Add("PRODUCT_CODE", "10");
                    giftData.Data.Add("EXTRA_PARAM", "test");
                    giftData.Data.Add("state", "1");

                    using (IQueryAdapter dbClient = FirewindEnvironment.GetDatabaseManager().getQueryreactor())
                    {
                        dbClient.setQuery("INSERT INTO items (base_id) VALUES (" + Present.ItemId + ")");
                        itemID = (uint)dbClient.insertQuery();

                        dbClient.runFastQuery("INSERT INTO items_users VALUES (" + itemID + "," + GiftUserId + ")");

                        if (!string.IsNullOrEmpty(GiftMessage))
                        {
                            dbClient.setQuery("INSERT INTO items_extradata VALUES (" + itemID + ",@datatype,@data,@extra)");
                            dbClient.addParameter("datatype", giftData.GetTypeID());
                            dbClient.addParameter("data", giftData.ToString());
                            dbClient.addParameter("extra", GiftColor * 1000 + GiftLazo);
                            dbClient.runQuery();
                        }

                        dbClient.setQuery("INSERT INTO user_presents (item_id,base_id,amount,extra_data) VALUES (" + itemID + "," + Item.GetBaseItem(i).ItemId + "," + Item.Amount + ",@extra_data)");
                        dbClient.addParameter("extra_data", itemData.ToString());
                        dbClient.runQuery();
                    }

                    GameClient Receiver = FirewindEnvironment.GetGame().GetClientManager().GetClientByUserID(GiftUserId);

                    if (Receiver != null)
                    {
                        Receiver.SendNotif(LanguageLocale.GetValue("catalog.gift.received") + Session.GetHabbo().Username);
                        UserItem u = Receiver.GetHabbo().GetInventoryComponent().AddNewItem(itemID, Present.ItemId, giftData, GiftColor * 1000 + GiftLazo, false, false, 0);
                        Receiver.GetHabbo().GetInventoryComponent().SendFloorInventoryUpdate();
                        Receiver.GetMessageHandler().GetResponse().Init(Outgoing.UnseenItems);
                        Receiver.GetMessageHandler().GetResponse().AppendInt32(1); // items
                        Receiver.GetMessageHandler().GetResponse().AppendInt32(1); // type (gift) == s
                        Receiver.GetMessageHandler().GetResponse().AppendInt32(1);
                        Receiver.GetMessageHandler().GetResponse().AppendUInt(u.Id);
                        Receiver.GetMessageHandler().SendResponse();
                        InventoryComponent targetInventory = Receiver.GetHabbo().GetInventoryComponent();
                        if (targetInventory != null)
                            targetInventory.RunDBUpdate();
                    }

                    Session.SendNotif(LanguageLocale.GetValue("catalog.gift.sent"));
                }
                else
                {
                    List<UserItem> items = DeliverItems(Session, Item.GetBaseItem(i), (buyAmount * Item.Amount), itemData.ToString(), Item.songID);
                    int Type = 2;
                    if (Item.GetBaseItem(i).Type.ToString().ToLower().Equals("s"))
                    {
                        if (Item.GetBaseItem(i).InteractionType == InteractionType.pet)
                            Type = 3;
                        else
                            Type = 1;
                    }

                    Session.GetMessageHandler().GetResponse().Init(Outgoing.UnseenItems);
                    Session.GetMessageHandler().GetResponse().AppendInt32(1); // items
                    Session.GetMessageHandler().GetResponse().AppendInt32(Type);

                    Session.GetMessageHandler().GetResponse().AppendInt32(items.Count);
                    foreach (UserItem u in items)
                        Session.GetMessageHandler().GetResponse().AppendUInt(u.Id);

                    Session.GetMessageHandler().SendResponse();

                    //Logging.WriteLine("Purchased " + items.Count);
                    Session.GetHabbo().GetInventoryComponent().UpdateItems(false);

                    if (Item.GetBaseItem(i).InteractionType == InteractionType.pet)
                    {
                        Session.SendMessage(Session.GetHabbo().GetInventoryComponent().SerializePetInventory());
                    }

                }
            }
        }
        internal void LoadFurniture()
        {
            //this.Items.Clear();
            this.mFloorItems.Clear();
            this.mWallItems.Clear();
            DataTable Data;
            using (IQueryAdapter dbClient = FirewindEnvironment.GetDatabaseManager().getQueryreactor())
            {
                dbClient.setQuery("CALL getroomitems(@roomid)");
                dbClient.addParameter("roomid", room.RoomId);
                Data = dbClient.getTable();

                uint itemID;
                decimal x;
                decimal y;
                sbyte n;
                uint baseID;
                int dataType;
                string extradata;
                WallCoordinate wallCoord;
                int extra;
                foreach (DataRow dRow in Data.Rows)
                {
                    itemID = Convert.ToUInt32(dRow[0]);
                    x = Convert.ToDecimal(dRow[1]);
                    y = Convert.ToDecimal(dRow[2]);
                    n = Convert.ToSByte(dRow[3]);
                    baseID = Convert.ToUInt32(dRow[4]);
                    IRoomItemData data;
                    if (DBNull.Value.Equals(dRow[5]))
                    {
                        data = new StringData("");
                        extra = 0;
                    }
                    else
                    {
                        dataType = Convert.ToInt32(dRow[5]);
                        extradata = (string)dRow[6];
                        extra = Convert.ToInt32(dRow[7]);
                        switch (dataType)
                        {
                            case 0:
                                data = new StringData(extradata);
                                break;
                            case 1:
                                data = new MapStuffData();
                                break;
                            case 2:
                                data = new StringArrayStuffData();
                                break;
                            case 3:
                                data = new StringIntData();
                                break;
                            default:
                                data = new StringData(extradata);
                                break;
                        }
                        try
                        {
                            data.Parse(extradata);
                        }
                        catch
                        {
                            Logging.LogException(string.Format("Error in furni data! Item ID: \"{0}\" and data: \"{1}\"", itemID, extradata.Replace(Convert.ToChar(1).ToString(), "[1]")));
                            dbClient.runFastQuery(string.Format("DELETE FROM items_extradata WHERE item_id = {0}", itemID));
                        }
                    }

                    if (FirewindEnvironment.GetGame().GetItemManager().GetItem(baseID).Type == 'i') // Is wallitem
                    {
                        wallCoord = new WallCoordinate((double)x, (double)y, n);
                        RoomItem item = new RoomItem(itemID, room.RoomId, baseID, data, extra, wallCoord, room);

                        if (!mWallItems.ContainsKey(itemID))
                            mWallItems.Inner.Add(itemID, item);
                    }
                    else //Is flooritem
                    {
                        int coordX, coordY;
                        TextHandling.Split((double)x, out coordX, out coordY);

                        RoomItem item = new RoomItem(itemID, room.RoomId, baseID, data, extra, coordX, coordY, (double)y, n, room);
                        if (!mFloorItems.ContainsKey(itemID))
                            mFloorItems.Inner.Add(itemID, item);
                    }
                }

                foreach (RoomItem Item in mFloorItems.Values)
                {
                    if (Item.IsRoller)
                        mGotRollers = true;
                    else if (Item.GetBaseItem().InteractionType == Firewind.HabboHotel.Items.InteractionType.dimmer)
                    {
                        if (room.MoodlightData == null)
                            room.MoodlightData = new MoodlightData(Item.Id);
                    }
                    else if (WiredUtillity.TypeIsWired(Item.GetBaseItem().InteractionType))
                    {
                        WiredLoader.LoadWiredItem(Item, room, dbClient);
                        room.GetWiredHandler().AddWire(Item, Item.Coordinate, Item.Rot, Item.GetBaseItem().InteractionType);
                    }

                }
            }
        }