Beispiel #1
0
        //internal void LoadRoles(DatabaseClient dbClient)
        //{
        //    ClearRoles();

        //    DataTable Data = dbClient.getTable("SELECT * FROM ranks ORDER BY id ASC;");

        //    if (Data != null)
        //    {
        //        foreach (DataRow Row in Data.Rows)
        //        {
        //            Roles.Add((uint)Row["id"], new Role((uint)Row["id"], (string)Row["name"]));
        //        }
        //    }
        //}

        internal void LoadRights(IQueryAdapter dbClient)
        {
            ClearRights();

            dbClient.setQuery("SELECT fuse, rank FROM fuserights;");
            DataTable Data = dbClient.getTable();

            dbClient.setQuery("SELECT fuse, sub FROM fuserights_subs;");
            DataTable SubData = dbClient.getTable();

            if (Data != null)
            {
                foreach (DataRow Row in Data.Rows)
                {
                    Rights.Add((string)Row["fuse"], Convert.ToUInt32(Row["rank"]));
                }
            }

            if (SubData != null)
            {
                foreach (DataRow Row in SubData.Rows)
                {
                    SubRights.Add((string)Row["fuse"], (string)Row["sub"]);
                }
            }
        }
Beispiel #2
0
        public void Initialize(IQueryAdapter dbClient)
        {
            dbClient.setQuery("SELECT id,caption,min_rank FROM navigator_flatcats WHERE enabled = 2");
            DataTable dPrivCats = dbClient.getTable();

            dbClient.setQuery("SELECT * FROM navigator_publics ORDER BY ordernum ASC");
            DataTable dPubItems = dbClient.getTable();

            if (dPrivCats != null)
            {
                PrivateCategories.Clear();
                foreach (DataRow Row in dPrivCats.Rows)
                {
                    PrivateCategories.Add((int)Row["id"], new FlatCat((int)Row["id"], (string)Row["caption"], (int)Row["min_rank"]));
                }
            }

            if (dPubItems != null)
            {
                PublicItems.Clear();
                foreach (DataRow Row in dPubItems.Rows)
                {
                    PublicItems.Add((int)Row["id"], new PublicItem((int)Row["id"], int.Parse(Row["bannertype"].ToString()), (string)Row["caption"], (string)Row["description"],
                        (string)Row["image"], ((Row["image_type"].ToString().ToLower() == "internal") ? PublicImageType.INTERNAL : PublicImageType.EXTERNAL),
                        Convert.ToUInt32(Row["room_id"]), (int)Row["category_id"], (int)Row["category_parent_id"], SilverwaveEnvironment.EnumToBool(Row["recommended"].ToString()), (int)Row["typeofdata"], (string)Row["tag"]));
                }
            }
        }
Beispiel #3
0
		internal void Init(IQueryAdapter DBClient)
		{
			this.Polls.Clear();
			DBClient.setQuery("SELECT * FROM polls WHERE enabled = '1'");
			DataTable table = DBClient.getTable();
			if (table != null)
			{
				foreach (DataRow dataRow in table.Rows)
				{
					uint num = uint.Parse(dataRow["id"].ToString());
					DBClient.setQuery("SELECT * FROM poll_questions WHERE poll_id = " + num);
					DataTable table2 = DBClient.getTable();
					List<PollQuestion> list = new List<PollQuestion>();
					foreach (DataRow dataRow2 in table2.Rows)
					{
						list.Add(new PollQuestion(uint.Parse(dataRow2["id"].ToString()), (string)dataRow2["question"], int.Parse(dataRow2["answertype"].ToString()), dataRow2["answers"].ToString().Split(new char[]
						{
							'|'
						}), (string)dataRow2["correct_answer"]));
					}
					Poll value = new Poll(num, uint.Parse(dataRow["room_id"].ToString()), (string)dataRow["caption"], (string)dataRow["invitation"], (string)dataRow["greetings"], (string)dataRow["prize"], int.Parse(dataRow["type"].ToString()), list);
					this.Polls.Add(num, value);
				}
			}
		}
Beispiel #4
0
        internal void LoadBots(IQueryAdapter dbClient)
        {
            Bots = new List<RoomBot>();

            dbClient.setQuery("SELECT id, room_id, ai_type, walk_mode, name, motto, look, x, y, z, rotation, min_x, min_y, max_x, max_y FROM bots;");
            DataTable Data = dbClient.getTable();

            dbClient.setQuery("SELECT id, bot_id, keywords, response_text, mode, serve_id FROM bots_responses;");
            DataTable BotResponses = dbClient.getTable();

            dbClient.setQuery("SELECT text, shout, bot_id FROM bots_speech;");
            DataTable BotSpeech = dbClient.getTable();

            List<BotResponse> Responses = new List<BotResponse>();
            List<RandomSpeech> Speeches = new List<RandomSpeech>();

            foreach (DataRow Row in BotResponses.Rows)
            {
                Responses.Add(new BotResponse(Convert.ToUInt32(Row["bot_id"]), (string)Row["keywords"], (string)Row["response_text"], Row["mode"].ToString(), (int)Row["serve_id"]));
            }

            foreach (DataRow Row in BotSpeech.Rows)
            {
                Speeches.Add(new RandomSpeech((string)Row["text"], ButterflyEnvironment.EnumToBool(Row["shout"].ToString()), Convert.ToUInt32(Row["bot_id"])));
            }

            if (Data == null)
            {
                return;
            }

            foreach (DataRow Row in Data.Rows)
            {
                string BotAI = (string)Row["ai_type"];
                AIType BotAIType;
                switch (BotAI)
                {
                    case "generic":
                        BotAIType = AIType.Generic;
                        break;
                    case "guide":
                        BotAIType = AIType.Guide;
                        break;
                    case "pet":
                        BotAIType = AIType.Pet;
                        break;
                    default:
                        BotAIType = AIType.Generic;
                        break;
                }

                Bots.Add(new RoomBot(Convert.ToUInt32(Row["id"]), Convert.ToUInt32(Row["room_id"]), BotAIType, (string)Row["walk_mode"],
                    (String)Row["name"], (string)Row["motto"], (String)Row["look"], (int)Row["x"], (int)Row["y"], (int)Row["z"],
                    (int)Row["rotation"], (int)Row["min_x"], (int)Row["min_y"], (int)Row["max_x"], (int)Row["max_y"], ref Speeches, ref Responses));
            }
        }
Beispiel #5
0
        internal static WiredLoaderObject LoadItem(RoomItem item, Room room, IQueryAdapter dbClient)
        {
            InteractionType type = item.GetBaseItem().InteractionType;
            List<RoomItem> items = null;
            if (NeedsFurnitures(type))
            {
                dbClient.setQuery("SELECT trigger_item FROM wired_to_item WHERE wired_id = " + item.Id);
                DataTable dTable = dbClient.getTable();
                RoomItem targetItem;
                items = new List<RoomItem>(5);
                foreach (DataRow dRows in dTable.Rows)
                {
                    targetItem = room.GetRoomItemHandler().GetItem(Convert.ToUInt32(dRows[0]));
                    if (targetItem == null || items.Contains(targetItem))
                    {
                        continue;
                    }

                    items.Add(targetItem);
                }
            }

            string[] settings = null;
            
            if(HasSettings(type))
            {
                settings = new string[4];
                dbClient.setQuery("SELECT data_one, data_two,data_three, data_four FROM wired_data WHERE wired_id = " + item.Id);

                DataRow dRow = dbClient.getRow();
                if (dRow != null)
                {
                    for (int i = 0; i < 4; i++)
                    {
                        settings[i] = dRow[i].ToString();
                    }
                }
                else
                {
                    settings = new string[] { "", "", "", "" };
                }
            }

            Dictionary<uint, OriginalItemLocation> originalPositionList = null;
            if (HasOriginalItemLocations(type))
            {
                originalPositionList = new Dictionary<uint, OriginalItemLocation>(5);
                dbClient.setQuery("SELECT item_id, original_x, original_y, rotation, height, extradata FROM wired_original_item_locations WHERE wired_id = " + item.Id);
                DataTable dTable = dbClient.getTable();
                foreach (DataRow dRows in dTable.Rows)
                {
                    originalPositionList.Add(uint.Parse(dRows[0].ToString()), new OriginalItemLocation(uint.Parse(dRows[0].ToString()), int.Parse(dRows[1].ToString()), int.Parse(dRows[2].ToString()), (double)Convert.ToDecimal(dRows[4]), int.Parse(dRows[3].ToString()), dRows[5].ToString()));
                }
            }
            return new WiredLoaderObject(items, originalPositionList, settings);
        }
Beispiel #6
0
		internal void LoadRights(IQueryAdapter dbClient)
		{
			this.ClearRights();
			dbClient.setQuery("SELECT command,rank FROM fuse_cmds;");
			DataTable table = dbClient.getTable();
			if (table != null)
			{
				foreach (DataRow dataRow in table.Rows)
				{
					if (!this.CMDRights.ContainsKey((string)dataRow[0]))
					{
						this.CMDRights.Add((string)dataRow[0], Convert.ToUInt32(dataRow[1]));
					}
					else
					{
						Logging.LogException(string.Format("Duplicate Fuse Command \"{0}\" found", dataRow[0]));
					}
				}
			}
			dbClient.setQuery("SELECT * FROM server_fuserights");
			DataTable table2 = dbClient.getTable();
			if (table2 != null)
			{
				foreach (DataRow dataRow2 in table2.Rows)
				{
					if ((int)dataRow2[3] == 0)
					{
						if (!this.Rights.ContainsKey((string)dataRow2[0]))
						{
							this.Rights.Add((string)dataRow2[0], Convert.ToUInt32(dataRow2[1]));
						}
						else
						{
							Logging.LogException(string.Format("Unknown Subscription Fuse \"{0}\" found", dataRow2[0]));
						}
					}
					else
					{
						if ((int)dataRow2[3] > 0)
						{
							this.SubRights.Add((string)dataRow2[0], (int)dataRow2[3]);
						}
						else
						{
							Logging.LogException(string.Format("Unknown fuse type \"{0}\" found", dataRow2[3]));
						}
					}
				}
			}
		}
Beispiel #7
0
        public static void UpdateInDatabase(IWiredTrigger wiredItem, IQueryAdapter dbClient)
        {
            RemoveFromDatabase(wiredItem, dbClient);

            RoomItem item = wiredItem.GetOriginalWiredItem();
            InteractionType type = item.GetBaseItem().InteractionType;

            if (WiredLoaderObject.HasSettings(type))
            {
                string[] data = (wiredItem as IWiredSettingsTrigger).GetSettings();
                dbClient.setQuery("INSERT INTO `wired_data` (`wired_id`, `data_one`, `data_two`, `data_three`, `data_four`) VALUES (@id, @data1, @data2, @data3, @data4) ");
                dbClient.addParameter("id", item.Id);
                dbClient.addParameter("data1", data.Length >= 1 ? data[0] : "");
                dbClient.addParameter("data2", data.Length >= 2 ? data[1] : "");
                dbClient.addParameter("data3", data.Length >= 3 ? data[2] : "");
                dbClient.addParameter("data4", data.Length >= 4 ? data[3] : "");
                dbClient.runQuery();
            }
            if (WiredLoaderObject.HasOriginalItemLocations(type))
            {
                Dictionary<uint, OriginalItemLocation> originalLoc = (wiredItem as IWiredOriginalItemTrigger).GetOriginalItemLocation();

                foreach (OriginalItemLocation itemLoc in originalLoc.Values)
                {
                    dbClient.setQuery("INSERT INTO `wired_original_item_locations` (`wired_id`,`item_id`, `original_x`, `original_y`, `rotation`, `extradata`, `height`) VALUES (@wid, @id, @orx, @ory, @orrot, @data, @height)");
                    dbClient.addParameter("wid", item.Id);
                    dbClient.addParameter("id", itemLoc.itemID);
                    dbClient.addParameter("orx", itemLoc.X);
                    dbClient.addParameter("ory", itemLoc.Y);
                    dbClient.addParameter("orrot", itemLoc.Rot);
                    dbClient.addParameter("data", itemLoc.ExtraData);
                    dbClient.addParameter("height", itemLoc.Height);

                    dbClient.runQuery();
                }
            }
            if (WiredLoaderObject.NeedsFurnitures(type))
            {
                List<RoomItem> items = (wiredItem as IWiredFurniTrigger).getAffectedItemList();
                foreach (RoomItem rItem in items)
                {
                    dbClient.setQuery("INSERT INTO `wired_to_item` (`wired_id`, `trigger_item`) VALUES (@id, @triggeritem)");
                    dbClient.addParameter("id", item.Id);
                    dbClient.addParameter("triggeritem", rItem.Id);
                    dbClient.runQuery();
                }
            }

        }
Beispiel #8
0
        internal void InitGroups(IQueryAdapter dbClient)
        {
            dbClient.setQuery("SELECT * FROM groups_elements");
            DataTable table = dbClient.getTable();
            string type;

            foreach (DataRow row in table.Rows)
            {
                type = (string)row["Type"];
                GuildsPartsData data = new GuildsPartsData((int)row["Id"], (string)row["ExtraData1"], (string)row["ExtraData2"]);

                if (type == "Base")
                {
                    baseBadges.Add(data);
                }
                else if (data.ExtraData1.StartsWith("symbol_"))
                {
                    symbolBadges.Add(data);
                }
                else if (type == "Color1")
                {
                    colorBadges1.Add(data);
                }
                else if (type == "Color2")
                {
                    colorBadges2.Add(data);
                }
                else if (type == "Color3")
                {
                    colorBadges3.Add(data);
                    htmlBadges.Add(data.Id, data.ExtraData1);
                }
            }
        }
Beispiel #9
0
        //internal void ClearCategories()
        //{
        //    Categories.Clear();
        //}

        internal void LoadTopics(IQueryAdapter dbClient)
        {
            Topics.Clear();
            DataTable TopicData = null;

            dbClient.setQuery("SELECT id, title, body, subject, known_issue FROM help_topics");
            TopicData = dbClient.getTable();

            if (TopicData == null)
            {
                return;
            }

            foreach (DataRow Row in TopicData.Rows)
            {
                HelpTopic NewTopic = new HelpTopic(Convert.ToUInt32(Row["id"]), (string)Row["title"], (string)Row["body"], Convert.ToUInt32(Row["subject"]));

                Topics.Add(Convert.ToUInt32(Row["id"]), NewTopic);

                int Importance = int.Parse(Row["known_issue"].ToString());

                if (Importance == 1)
                {
                    KnownIssues.Add(NewTopic);
                }
                else if (Importance == 2)
                {
                    ImportantTopics.Add(NewTopic);
                }
            }
        }
Beispiel #10
0
        internal static void Init(IQueryAdapter dbClient)
        {
            dbClient.setQuery("SELECT userpeak FROM server_status");
            UserPeak = dbClient.getInteger();

            _runFrequency = int.Parse(FirewindEnvironment.GetConfig().GetEntry("backgroundworker.interval", "10000")); // leon is crazy, 300!?! (THIS IS MADNESS!!)
        }
		internal void LoadBans(IQueryAdapter dbClient)
		{
			this.bannedUsernames.Clear();
			this.bannedIPs.Clear();
			this.bannedMachines.Clear();
			dbClient.setQuery("SELECT bantype,value,reason,expire FROM bans");
			DataTable table = dbClient.getTable();
			double num = (double)CyberEnvironment.GetUnixTimestamp();
			foreach (DataRow dataRow in table.Rows)
			{
				string text = (string)dataRow["value"];
				string reasonMessage = (string)dataRow["reason"];
				double num2 = (double)dataRow["expire"];
				string a = (string)dataRow["bantype"];
				ModerationBanType type;
				if (a == "user")
				{
					type = ModerationBanType.USERNAME;
				}
				else
				{
					if (a == "ip")
					{
						type = ModerationBanType.IP;
					}
					else
					{
						type = ModerationBanType.MACHINE;
					}
				}
				ModerationBan moderationBan = new ModerationBan(type, text, reasonMessage, num2);
				if (num2 > num)
				{
					if (moderationBan.Type == ModerationBanType.USERNAME)
					{
                        if (!this.bannedUsernames.Contains(text))
						{
							this.bannedUsernames.Add(text, moderationBan);
						}
					}
					else
					{
						if (moderationBan.Type == ModerationBanType.IP)
						{
                            if (!this.bannedIPs.Contains(text))
							{
								this.bannedIPs.Add(text, moderationBan);
							}
						}
						else
						{
							if (!this.bannedMachines.ContainsKey(text))
							{
								this.bannedMachines.Add(text, moderationBan);
							}
						}
					}
				}
			}
		}
Beispiel #12
0
        public Group(DataRow Data, IQueryAdapter dbClient)
        {
            this.ID = Convert.ToInt32(Data["id"]);
            this.Name = Data["name"].ToString();
            this.Description = Data["description"].ToString();
            this.DateCreated = Data["date_created"].ToString();
            this.OwnerID = Convert.ToInt32(Data["users_id"]);
            this.RoomID = Convert.ToInt32(Data["rooms_id"]);
            this.ColorID1 = Convert.ToInt32(Data["color1"]);
            this.ColorID2 = Convert.ToInt32(Data["color2"]);
            this.Type = Convert.ToInt32(Data["type"]);
            this.RightsType = Convert.ToInt32(Data["rights_type"]);

            // Parse badge data
            string[] rawData = Data["badge_data"].ToString().Split((char)1);
            List<Tuple<int, int, int>> badgeData = new List<Tuple<int,int,int>>();
            for (int i = 0; i < rawData.Length; i++)
            {
                int value1 = int.Parse(rawData[i++]);
                int value2 = int.Parse(rawData[i++]);
                int value3 = int.Parse(rawData[i]);
                badgeData.Add(new Tuple<int, int, int>(value1, value2, value3));
            }

            this.BadgeData = badgeData;
            this.Members = new List<int>();

            // Load members
            dbClient.setQuery("SELECT * FROM group_memberships WHERE groups_id = @id");
            dbClient.addParameter("id", ID);
            foreach (DataRow row in dbClient.getTable().Rows)
            {
                this.Members.Add((int)row["users_id"]);
            }
        }
		internal static void GetAchievementLevels(out Dictionary<string, Achievement> achievements, IQueryAdapter dbClient)
		{
			achievements = new Dictionary<string, Achievement>();
			dbClient.setQuery("SELECT * FROM achievements");
			DataTable table = dbClient.getTable();
			foreach (DataRow dataRow in table.Rows)
			{
				uint id = Convert.ToUInt32(dataRow["id"]);
				string category = (string)dataRow["category"];
				string text = (string)dataRow["group_name"];
				int level = (int)dataRow["level"];
				int rewardPixels = (int)dataRow["reward_pixels"];
				int rewardPoints = (int)dataRow["reward_points"];
				int requirement = (int)dataRow["progress_needed"];
				AchievementLevel level2 = new AchievementLevel(level, rewardPixels, rewardPoints, requirement);
				if (!achievements.ContainsKey(text))
				{
					Achievement achievement = new Achievement(id, text, category);
					achievement.AddLevel(level2);
					achievements.Add(text, achievement);
				}
				else
				{
					achievements[text].AddLevel(level2);
				}
			}
		}
Beispiel #14
0
 internal static void SaveTrigger(IQueryAdapter dbClient, int itemID, int triggetItemID)
 {
     dbClient.setQuery("INSERT INTO trigger_in_place (original_trigger,triggers_item) VALUES (@my_id,@trigger_item)");
     dbClient.addParameter("my_id", itemID);
     dbClient.addParameter("trigger_item", triggetItemID);
     dbClient.runQuery();
 }
Beispiel #15
0
        internal static void InitAchievementManager(IQueryAdapter dbClient)
        {
            dbClient.setQuery("SELECT achievements.*, achievement_categories.name " +
                                "FROM achievements " +
                                "JOIN achievement_categories " +
                                "ON achievement_categories.id = achievements.category");

            DataTable dTable = dbClient.getTable();

            achievements = new Dictionary<uint, AchievementBase>();

            uint achievementID;
            uint levels;
            uint badgelevel;
            string badge;
            int pixelBase;
            int pixelMMPORG;
            int pixelReward;
            string category;
            foreach (DataRow dRow in dTable.Rows)
            {
                achievementID = Convert.ToUInt32(dRow[0]);
                levels = Convert.ToUInt32(dRow[1]);
                badgelevel = Convert.ToUInt32(dRow[2]);
                badge = (string)dRow[3];
                pixelBase = (int)dRow[4];
                pixelMMPORG = (int)dRow[5];
                pixelReward = (int)dRow[6];
                category = (string)dRow[8];

                AchievementBase achivement = new AchievementBase(achievementID, levels, badgelevel, badge, pixelBase, pixelMMPORG, pixelReward, category);
                achievements.Add(achievementID, achivement);
            }
        }
Beispiel #16
0
        private void ReloadQuests(IQueryAdapter dbClient)
        {
            quests.Clear();

            dbClient.setQuery("SELECT * FROM quests");
            DataTable dTable = dbClient.getTable();

            uint id;
            string category;
            int num;
            int type;
            uint goalData;
            string name;
            int reward;
            string dataBit;
            foreach (DataRow dRow in dTable.Rows)
            {
                id = Convert.ToUInt32(dRow["id"]);
                category = (string)dRow["category"];
                num = (int)dRow["series_number"];
                type = (int)dRow["goal_type"];
                goalData = Convert.ToUInt32(dRow["goal_data"]);
                name = (string)dRow["name"];
                reward = (int)dRow["reward"];
                dataBit = (string)dRow["data_bit"];

                Quest quest = new Quest(id, category, num, (QuestType)type, goalData, name, reward, dataBit);
                quests.Add(id, quest);
                AddToCounter(category);
            }
        }
Beispiel #17
0
        internal void Initialize(IQueryAdapter dbClient)
        {
            //dbClient.setQuery("SELECT id,caption FROM navigator_pubcats WHERE enabled = 2"); //wtf?
            //DataTable dPubCats = dbClient.getTable();

            dbClient.setQuery("SELECT id,caption,min_rank FROM navigator_flatcats WHERE enabled = 2");
            DataTable dPrivCats = dbClient.getTable();

            dbClient.setQuery("SELECT * FROM navigator_publics ORDER BY ordernum ASC");
            DataTable dPubItems = dbClient.getTable();

            //if (dPubCats != null)
            //{
            //    foreach (DataRow Row in dPubCats.Rows)
            //    {
            //        PublicCategories.Add((int)Row["id"], (string)Row["caption"]);
            //    }
            //}

            if (dPrivCats != null)
            {
                foreach (DataRow Row in dPrivCats.Rows)
                {
                    PrivateCategories.Add((int)Row["id"], new FlatCat((int)Row["id"], (string)Row["caption"], (int)Row["min_rank"]));
                }
            }

            if (dPubItems != null)
            {
                foreach (DataRow Row in dPubItems.Rows)
                {
                    PublicItems.Add((int)Row["id"], new PublicItem((int)Row["id"], int.Parse(Row["bannertype"].ToString()), (string)Row["caption"],
                        (string)Row["image"], ((Row["image_type"].ToString().ToLower() == "internal") ? PublicImageType.INTERNAL : PublicImageType.EXTERNAL),
                        Convert.ToUInt32(Row["room_id"]), (int)Row["category_parent_id"], ButterflyEnvironment.EnumToBool(Row["category"].ToString()) ,ButterflyEnvironment.EnumToBool(Row["recommended"].ToString())));
                }
            }

            //if (dPubRecommended != null)
            //{
            //    foreach (DataRow Row in dPubRecommended.Rows)
            //    {
            //        PublicRecommended.Add((int)Row["id"], new PublicItem((int)Row["id"], int.Parse(Row["bannertype"].ToString()), (string)Row["caption"],
            //            (string)Row["image"], ((Row["image_type"].ToString().ToLower() == "internal") ? PublicImageType.INTERNAL : PublicImageType.EXTERNAL),
            //            (uint)Row["room_id"], (int)Row["category_parent_id"], false));
            //    }
            //}
        }
Beispiel #18
0
		internal void LoadItems(IQueryAdapter dbClient)
		{
			this.Items = new Dictionary<uint, Item>();
			dbClient.setQuery("SELECT * FROM furniture");
			DataTable table = dbClient.getTable();
			if (table != null)
			{
				string[] array = null;
				foreach (DataRow dataRow in table.Rows)
				{
					try
					{
						uint num = Convert.ToUInt32(dataRow["id"]);
						int sprite = (int)dataRow["sprite_id"];
						int flatId = (int)dataRow["flat_id"];
						string publicName = (string)dataRow["public_name"];
						string name = (string)dataRow["item_name"];
						string type = dataRow["type"].ToString();
						int width = (int)dataRow["width"];
						int length = (int)dataRow["length"];
						double height;
						if (dataRow["stack_height"].ToString().Contains(";"))
						{
							array = dataRow["stack_height"].ToString().Split(new char[]
							{
								';'
							});
							height = Convert.ToDouble(array[0]);
						}
						else
						{
							height = Convert.ToDouble(dataRow["stack_height"]);
						}
						bool stackable = Convert.ToInt32(dataRow["can_stack"]) == 1;
						bool walkable = Convert.ToInt32(dataRow["is_walkable"]) == 1;
						bool isSeat = Convert.ToInt32(dataRow["can_sit"]) == 1;
						bool allowRecycle = Convert.ToInt32(dataRow["allow_recycle"]) == 1;
						bool allowTrade = Convert.ToInt32(dataRow["allow_trade"]) == 1;
						bool allowMarketplaceSell = Convert.ToInt32(dataRow["allow_marketplace_sell"]) == 1;
						bool allowGift = Convert.ToInt32(dataRow["allow_gift"]) == 1;
						bool allowInventoryStack = Convert.ToInt32(dataRow["allow_inventory_stack"]) == 1;
						InteractionType typeFromString = InterractionTypes.GetTypeFromString((string)dataRow["interaction_type"]);
						int modes = (int)dataRow["interaction_modes_count"];
						string vendingIds = (string)dataRow["vending_ids"];
						bool sub = MercuryEnvironment.EnumToBool(dataRow["subscriber"].ToString());
						int effect = (int)dataRow["effectid"];
						bool stackMultiple = MercuryEnvironment.EnumToBool(dataRow["stack_multiplier"].ToString());
						Item value = new Item(num, sprite, publicName, name, type, width, length, height, stackable, walkable, isSeat, allowRecycle, allowTrade, allowMarketplaceSell, allowGift, allowInventoryStack, typeFromString, modes, vendingIds, sub, effect, stackMultiple, array, flatId);
						this.Items.Add(num, value);
					}
					catch (Exception ex)
					{
						Console.WriteLine(ex.ToString());
						Console.ReadKey();
						Logging.WriteLine("Could not load item #" + Convert.ToUInt32(dataRow[0]) + ", please verify the data is okay.", ConsoleColor.Gray);
					}
				}
			}
		}
Beispiel #19
0
		internal static void SaveMessage(IQueryAdapter dbClient, uint ToId, uint FromId, string Message)
		{
			dbClient.setQuery("INSERT INTO messenger_offline_messages (to_id, from_id, message, timestamp) VALUES (@tid, @fid, @msg, UNIX_TIMESTAMP())");
			dbClient.addParameter("tid", ToId);
			dbClient.addParameter("fid", FromId);
			dbClient.addParameter("msg", Message);
			dbClient.runQuery();
		}
Beispiel #20
0
        public void SaveToDatabase(IQueryAdapter dbClient)
        {
            dbClient.setQuery("REPLACE INTO trigger_item SET trigger_id = @id, trigger_input = 'integer',  trigger_data = @trigger_data , all_user_triggerable = 0");

            dbClient.addParameter("id", (int)this.item.Id);
            dbClient.addParameter("trigger_data", timeout);
            dbClient.runQuery();
        }
Beispiel #21
0
        public void LoadFromDatabase(IQueryAdapter dbClient, Room insideRoom)
        {
            dbClient.setQuery("SELECT trigger_data FROM trigger_item WHERE trigger_id = @id ");
            dbClient.addParameter("id", (int)this.item.Id);
            this.delay = dbClient.getInteger();

            dbClient.setQuery("SELECT triggers_item FROM trigger_in_place WHERE original_trigger = " + this.item.Id);
            DataTable dTable = dbClient.getTable();
            RoomItem targetItem;
            foreach (DataRow dRows in dTable.Rows)
            {
                targetItem = insideRoom.GetRoomItemHandler().GetItem(Convert.ToUInt32(dRows[0]));
                if (targetItem == null || this.items.Contains(targetItem))
                    continue;
                targetItem.itemTriggerEventHandler += delegateFunction;
                this.items.Add(targetItem);
            }
        }
Beispiel #22
0
		internal void Initialize(IQueryAdapter dbClient)
		{
			dbClient.setQuery("SELECT * FROM achievements_talenttrack ORDER BY `order_num` ASC");
			DataTable table = dbClient.getTable();
			foreach (DataRow dataRow in table.Rows)
			{
				Talent talent = new Talent((int)dataRow["id"], (string)dataRow["type"], (int)dataRow["parent_category"], (int)dataRow["level"], (string)dataRow["achievement_group"], (int)dataRow["achievement_level"], (string)dataRow["prize"], (uint)dataRow["prize_baseitem"]);
				this.Talents.Add(talent.Id, talent);
			}
		}
Beispiel #23
0
 public void LoadFromDatabase(IQueryAdapter dbClient, Room insideRoom)
 {
     dbClient.setQuery("SELECT trigger_data FROM trigger_item WHERE trigger_id = @id ");
     dbClient.addParameter("id", (int)this.item.Id);
     DataRow dRow = dbClient.getRow();
     if (dRow != null)
         this.requiredCycles = Convert.ToInt32(dRow[0].ToString());
     else
         this.requiredCycles = 20;
 }
Beispiel #24
0
        internal static void Init(IQueryAdapter dbClient)
        {
            DataTable Pets;
            dbClient.setQuery("SELECT * FROM bots_pet_responses");
            Pets = dbClient.getTable();
            values = new Dictionary<string, string[]>();

            foreach (DataRow Row in Pets.Rows)
                values.Add(Row[0].ToString(), Row[1].ToString().Split(';'));
        }
Beispiel #25
0
		internal ConfigData(IQueryAdapter dbClient)
		{
			this.DBData = new Dictionary<string, string>();
			this.DBData.Clear();
			dbClient.setQuery("SELECT * FROM server_settings");
			DataTable table = dbClient.getTable();
			foreach (DataRow dataRow in table.Rows)
			{
				this.DBData.Add(dataRow[0].ToString(), dataRow[1].ToString());
			}
		}
Beispiel #26
0
 public void LoadFromDatabase(IQueryAdapter dbClient, Room insideRoom)
 {
     dbClient.setQuery("SELECT trigger_data FROM trigger_item WHERE trigger_id = @id ");
     dbClient.addParameter("id", (int)this.item.Id);
     DataRow dRow = dbClient.getRow();
     if (dRow != null)
         this.userName = dRow[0].ToString();
     else
         this.userName = string.Empty;
     this.isOneUser = !string.IsNullOrEmpty(this.userName);
 }
Beispiel #27
0
		internal void Initialize(IQueryAdapter dbClient)
		{
			dbClient.setQuery("SELECT * FROM pinatas_items");
			this.Pinatas = new Dictionary<uint, PinataItem>();
			this.Table = dbClient.getTable();
			foreach (DataRow dataRow in this.Table.Rows)
			{
				PinataItem value = new PinataItem(dataRow);
				this.Pinatas.Add(uint.Parse(dataRow["item_baseid"].ToString()), value);
			}
		}
Beispiel #28
0
        internal void Initialize(IQueryAdapter dbClient)
        {
            dbClient.setQuery("SELECT id,caption,min_rank FROM navigator_flatcats WHERE enabled = '1'");
            DataTable dPrivCats = dbClient.getTable();

            foreach (DataRow Row in dPrivCats.Rows)
            {
                PrivateCategories.Add((int)Row["id"], new FlatCat((int)Row["id"], (string)Row["caption"], (int)Row["min_rank"]));
            }

            InitializePublicRoomListing(dbClient);
        }
Beispiel #29
0
        internal static void Init(IQueryAdapter dbClient)
        {
            dbClient.setQuery("SELECT userpeak FROM server_status");
            UserPeak = dbClient.getInteger();
            mColdTitle = string.Empty;

            lowPriorityProcessWatch = new Stopwatch();
            consoleTitleWorkerWatch = new Stopwatch();
            lowPriorityProcessWatch.Start();
            consoleTitleWorkerWatch.Start();
            Process();
        }
Beispiel #30
0
        public GiftWrappers(IQueryAdapter dbClient)
        {
            DataTable wrappers = null;
            dbClient.setQuery("SELECT * FROM gift_wrappers");
            wrappers = dbClient.getTable();

            if (wrappers.Rows.Count <= 0)
                Logging.LogCriticalException("Failed to load the Gift Wrappers");
            else
                foreach (DataRow dr in wrappers.Rows)
                    GiftWrappersList.Add((uint)dr["baseid"]);
        }
Beispiel #31
0
        public void OnTrigger(GameClient Session, RoomItem Item, int Request, bool HasRights)
        {
            if (Session == null || Item == null)
            {
                return;
            }
            if (!HasRights)
            {
                return;
            }
            string          ExtraInfo    = "";
            bool            flag         = false;
            int             i            = 0;
            List <RoomItem> list         = new List <RoomItem>();
            string          ExtraString  = "";
            string          ExtraString2 = "";

            using (IQueryAdapter queryreactor = CyberEnvironment.GetDatabaseManager().getQueryReactor())
            {
                queryreactor.setQuery("SELECT * FROM wired_items WHERE id=@id LIMIT 1");
                queryreactor.addParameter("id", Item.Id);
                DataRow row = queryreactor.getRow();
                if (row != null)
                {
                    ExtraInfo    = row["string"].ToString();
                    i            = (int)row["delay"] / 500;
                    flag         = (row["bool"].ToString() == "1");
                    ExtraString  = row["extra_string"].ToString();
                    ExtraString2 = row["extra_string_2"].ToString();
                    string[] array = row["items"].ToString().Split(new char[]
                    {
                        ';'
                    });
                    for (int j = 0; j < array.Length; j++)
                    {
                        string s   = array[j];
                        uint   pId = 0u;
                        if (uint.TryParse(s, out pId))
                        {
                            RoomItem item = Item.GetRoom().GetRoomItemHandler().GetItem(pId);
                            if (item != null && !list.Contains(item))
                            {
                                list.Add(item);
                            }
                        }
                    }
                }
            }
            switch (Item.GetBaseItem().InteractionType)
            {
            case InteractionType.triggertimer:
            {
                ServerMessage serverMessage = new ServerMessage(Outgoing.WiredTriggerMessageComposer);
                serverMessage.AppendBoolean(false);
                serverMessage.AppendInt32(5);
                serverMessage.AppendInt32(list.Count);
                foreach (RoomItem current in list)
                {
                    serverMessage.AppendUInt(current.Id);
                }
                serverMessage.AppendInt32(Item.GetBaseItem().SpriteId);
                serverMessage.AppendUInt(Item.Id);
                serverMessage.AppendString(ExtraInfo);
                serverMessage.AppendInt32(1);
                serverMessage.AppendInt32(1);
                serverMessage.AppendInt32(1);
                serverMessage.AppendInt32(3);
                serverMessage.AppendInt32(0);
                serverMessage.AppendInt32(0);
                Session.SendMessage(serverMessage);
                return;
            }

            case InteractionType.triggerroomenter:
            {
                ServerMessage serverMessage2 = new ServerMessage(Outgoing.WiredTriggerMessageComposer);
                serverMessage2.AppendBoolean(false);
                serverMessage2.AppendInt32(0);
                serverMessage2.AppendInt32(list.Count);
                foreach (RoomItem current2 in list)
                {
                    serverMessage2.AppendUInt(current2.Id);
                }
                serverMessage2.AppendInt32(Item.GetBaseItem().SpriteId);
                serverMessage2.AppendUInt(Item.Id);
                serverMessage2.AppendString(ExtraInfo);
                serverMessage2.AppendInt32(0);
                serverMessage2.AppendInt32(0);
                serverMessage2.AppendInt32(7);
                serverMessage2.AppendInt32(0);
                serverMessage2.AppendInt32(0);
                serverMessage2.AppendInt32(0);
                Session.SendMessage(serverMessage2);
                return;
            }

            case InteractionType.triggergameend:
            {
                ServerMessage serverMessage3 = new ServerMessage(Outgoing.WiredTriggerMessageComposer);
                serverMessage3.AppendBoolean(false);
                serverMessage3.AppendInt32(0);
                serverMessage3.AppendInt32(list.Count);
                foreach (RoomItem current3 in list)
                {
                    serverMessage3.AppendUInt(current3.Id);
                }
                serverMessage3.AppendInt32(Item.GetBaseItem().SpriteId);
                serverMessage3.AppendUInt(Item.Id);
                serverMessage3.AppendString(ExtraInfo);
                serverMessage3.AppendInt32(0);
                serverMessage3.AppendInt32(0);
                serverMessage3.AppendInt32(8);
                serverMessage3.AppendInt32(0);
                serverMessage3.AppendInt32(0);
                serverMessage3.AppendInt32(0);
                Session.SendMessage(serverMessage3);
                return;
            }

            case InteractionType.triggergamestart:
            {
                ServerMessage serverMessage4 = new ServerMessage(Outgoing.WiredTriggerMessageComposer);
                serverMessage4.AppendBoolean(false);
                serverMessage4.AppendInt32(0);
                serverMessage4.AppendInt32(list.Count);
                foreach (RoomItem current4 in list)
                {
                    serverMessage4.AppendUInt(current4.Id);
                }
                serverMessage4.AppendInt32(Item.GetBaseItem().SpriteId);
                serverMessage4.AppendUInt(Item.Id);
                serverMessage4.AppendString(ExtraInfo);
                serverMessage4.AppendInt32(0);
                serverMessage4.AppendInt32(0);
                serverMessage4.AppendInt32(8);
                serverMessage4.AppendInt32(0);
                serverMessage4.AppendInt32(0);
                serverMessage4.AppendInt32(0);
                Session.SendMessage(serverMessage4);
                return;
            }

            case InteractionType.triggerlongrepeater:
            {
                ServerMessage serverMessage = new ServerMessage(Outgoing.WiredTriggerMessageComposer);
                serverMessage.AppendBoolean(false);
                serverMessage.AppendInt32(5);
                serverMessage.AppendInt32(0);
                serverMessage.AppendInt32(Item.GetBaseItem().SpriteId);
                serverMessage.AppendUInt(Item.Id);
                serverMessage.AppendString("");
                serverMessage.AppendInt32(1);
                serverMessage.AppendInt32(i / 10);//fix
                serverMessage.AppendInt32(0);
                serverMessage.AppendInt32(12);
                serverMessage.AppendInt32(0);
                Session.SendMessage(serverMessage);
                return;
            }

            case InteractionType.triggerrepeater:
            {
                ServerMessage serverMessage5 = new ServerMessage(Outgoing.WiredTriggerMessageComposer);
                serverMessage5.AppendBoolean(false);
                serverMessage5.AppendInt32(5);
                serverMessage5.AppendInt32(list.Count);
                foreach (RoomItem current5 in list)
                {
                    serverMessage5.AppendUInt(current5.Id);
                }
                serverMessage5.AppendInt32(Item.GetBaseItem().SpriteId);
                serverMessage5.AppendUInt(Item.Id);
                serverMessage5.AppendString(ExtraInfo);
                serverMessage5.AppendInt32(1);
                serverMessage5.AppendInt32(i);
                serverMessage5.AppendInt32(0);
                serverMessage5.AppendInt32(6);
                serverMessage5.AppendInt32(0);
                serverMessage5.AppendInt32(0);
                Session.SendMessage(serverMessage5);
                return;
            }

            case InteractionType.triggeronusersay:
            {
                ServerMessage serverMessage6 = new ServerMessage(Outgoing.WiredTriggerMessageComposer);
                serverMessage6.AppendBoolean(false);
                serverMessage6.AppendInt32(0);
                serverMessage6.AppendInt32(list.Count);
                foreach (RoomItem current6 in list)
                {
                    serverMessage6.AppendUInt(current6.Id);
                }
                serverMessage6.AppendInt32(Item.GetBaseItem().SpriteId);
                serverMessage6.AppendUInt(Item.Id);
                serverMessage6.AppendString(ExtraInfo);
                serverMessage6.AppendInt32(0);
                serverMessage6.AppendInt32(0);
                serverMessage6.AppendInt32(0);
                serverMessage6.AppendInt32(0);
                serverMessage6.AppendInt32(0);
                serverMessage6.AppendInt32(0);
                Session.SendMessage(serverMessage6);
                return;
            }

            case InteractionType.triggerscoreachieved:
            {
                ServerMessage serverMessage7 = new ServerMessage(Outgoing.WiredTriggerMessageComposer);
                serverMessage7.AppendBoolean(false);
                serverMessage7.AppendInt32(5);
                serverMessage7.AppendInt32(0);
                serverMessage7.AppendInt32(Item.GetBaseItem().SpriteId);
                serverMessage7.AppendUInt(Item.Id);
                serverMessage7.AppendString("");
                serverMessage7.AppendInt32(1);
                serverMessage7.AppendInt32((String.IsNullOrWhiteSpace(ExtraInfo)) ? 100 : int.Parse(ExtraInfo));
                serverMessage7.AppendInt32(0);
                serverMessage7.AppendInt32(10);
                serverMessage7.AppendInt32(0);
                serverMessage7.AppendInt32(0);
                Session.SendMessage(serverMessage7);
                return;
            }

            case InteractionType.triggerstatechanged:
            {
                ServerMessage serverMessage8 = new ServerMessage(Outgoing.WiredTriggerMessageComposer);
                serverMessage8.AppendBoolean(false);
                serverMessage8.AppendInt32(5);
                serverMessage8.AppendInt32(list.Count);
                foreach (RoomItem current8 in list)
                {
                    serverMessage8.AppendUInt(current8.Id);
                }
                serverMessage8.AppendInt32(Item.GetBaseItem().SpriteId);
                serverMessage8.AppendUInt(Item.Id);
                serverMessage8.AppendString(ExtraInfo);
                serverMessage8.AppendInt32(0);
                serverMessage8.AppendInt32(0);
                serverMessage8.AppendInt32(1);
                serverMessage8.AppendInt32(i);
                serverMessage8.AppendInt32(0);
                serverMessage8.AppendInt32(0);
                Session.SendMessage(serverMessage8);
                return;
            }

            case InteractionType.triggerwalkonfurni:
            {
                ServerMessage serverMessage9 = new ServerMessage(Outgoing.WiredTriggerMessageComposer);
                serverMessage9.AppendBoolean(false);
                serverMessage9.AppendInt32(5);
                serverMessage9.AppendInt32(list.Count);
                foreach (RoomItem current9 in list)
                {
                    serverMessage9.AppendUInt(current9.Id);
                }
                serverMessage9.AppendInt32(Item.GetBaseItem().SpriteId);
                serverMessage9.AppendUInt(Item.Id);
                serverMessage9.AppendString(ExtraInfo);
                serverMessage9.AppendInt32(0);
                serverMessage9.AppendInt32(0);
                serverMessage9.AppendInt32(1);
                serverMessage9.AppendInt32(0);
                serverMessage9.AppendInt32(0);
                serverMessage9.AppendInt32(0);
                Session.SendMessage(serverMessage9);
                return;
            }

            case InteractionType.actionmuteuser:
            {
                ServerMessage serverMessage18 = new ServerMessage(Outgoing.WiredEffectMessageComposer);
                serverMessage18.AppendBoolean(false);
                serverMessage18.AppendInt32(5);
                serverMessage18.AppendInt32(0);
                serverMessage18.AppendInt32(Item.GetBaseItem().SpriteId);
                serverMessage18.AppendUInt(Item.Id);
                serverMessage18.AppendString(ExtraInfo);
                serverMessage18.AppendInt32(1);
                serverMessage18.AppendInt32(i);
                serverMessage18.AppendInt32(0);
                serverMessage18.AppendInt32(20);
                serverMessage18.AppendInt32(0);
                serverMessage18.AppendInt32(0);
                Session.SendMessage(serverMessage18);
                return;
            }

            case InteractionType.triggerwalkofffurni:
            {
                ServerMessage serverMessage10 = new ServerMessage(Outgoing.WiredTriggerMessageComposer);
                serverMessage10.AppendBoolean(false);
                serverMessage10.AppendInt32(5);
                serverMessage10.AppendInt32(list.Count);
                foreach (RoomItem current10 in list)
                {
                    serverMessage10.AppendUInt(current10.Id);
                }
                serverMessage10.AppendInt32(Item.GetBaseItem().SpriteId);
                serverMessage10.AppendUInt(Item.Id);
                serverMessage10.AppendString(ExtraInfo);
                serverMessage10.AppendInt32(0);
                serverMessage10.AppendInt32(0);
                serverMessage10.AppendInt32(1);
                serverMessage10.AppendInt32(0);
                serverMessage10.AppendInt32(0);
                serverMessage10.AppendInt32(0);
                serverMessage10.AppendInt32(0);
                Session.SendMessage(serverMessage10);
                return;
            }

            case InteractionType.actiongivescore:
            {
                // Por hacer.
                ServerMessage serverMessage11 = new ServerMessage(Outgoing.WiredEffectMessageComposer);
                serverMessage11.AppendBoolean(false);
                serverMessage11.AppendInt32(5);
                serverMessage11.AppendInt32(0);
                serverMessage11.AppendInt32(Item.GetBaseItem().SpriteId);
                serverMessage11.AppendUInt(Item.Id);
                serverMessage11.AppendString("");
                serverMessage11.AppendInt32(2);
                if (String.IsNullOrWhiteSpace(ExtraInfo))
                {
                    serverMessage11.AppendInt32(10); // Puntos a dar
                    serverMessage11.AppendInt32(1);  // Numero de veces por equipo
                }
                else
                {
                    string[] Integers = ExtraInfo.Split(',');
                    serverMessage11.AppendInt32(int.Parse(Integers[0])); // Puntos a dar
                    serverMessage11.AppendInt32(int.Parse(Integers[1])); // Numero de veces por equipo
                }
                serverMessage11.AppendInt32(0);
                serverMessage11.AppendInt32(6);
                serverMessage11.AppendInt32(0);
                serverMessage11.AppendInt32(0);
                serverMessage11.AppendInt32(0);
                Session.SendMessage(serverMessage11);
                return;
            }

            case InteractionType.conditiongroupmember:
            case InteractionType.conditionnotgroupmember:
            {
                ServerMessage Message = new ServerMessage(Outgoing.WiredConditionMessageComposer);
                Message.AppendBoolean(false);
                Message.AppendInt32(5);
                Message.AppendInt32(0);
                Message.AppendInt32(Item.GetBaseItem().SpriteId);
                Message.AppendUInt(Item.Id);
                Message.AppendString("");
                Message.AppendInt32(0);
                Message.AppendInt32(0);
                Message.AppendInt32(10);
                Session.SendMessage(Message);
                return;
            }

            case InteractionType.conditionitemsmatches:
            case InteractionType.conditionitemsdontmatch:
            {
                ServerMessage serverMessage21 = new ServerMessage(Outgoing.WiredConditionMessageComposer);
                serverMessage21.AppendBoolean(false);
                serverMessage21.AppendInt32(5);
                serverMessage21.AppendInt32(list.Count);
                foreach (RoomItem current20 in list)
                {
                    serverMessage21.AppendUInt(current20.Id);
                }
                serverMessage21.AppendInt32(Item.GetBaseItem().SpriteId);
                serverMessage21.AppendUInt(Item.Id);
                serverMessage21.AppendString(ExtraString2);
                serverMessage21.AppendInt32(3);

                if (String.IsNullOrWhiteSpace(ExtraInfo))
                {
                    serverMessage21.AppendInt32(0);
                    serverMessage21.AppendInt32(0);
                    serverMessage21.AppendInt32(0);
                }
                else
                {
                    string[] boolz = ExtraInfo.Split(',');

                    foreach (string Stringy in boolz)
                    {
                        if (Stringy.ToLower() == "true")
                        {
                            serverMessage21.AppendInt32(1);
                        }
                        else
                        {
                            serverMessage21.AppendInt32(0);
                        }
                    }
                }
                serverMessage21.AppendInt32(0);
                serverMessage21.AppendInt32(0);
                Session.SendMessage(serverMessage21);
                return;
            }


            case InteractionType.actionposreset:
            {
                ServerMessage serverMessage12 = new ServerMessage(Outgoing.WiredEffectMessageComposer);
                serverMessage12.AppendBoolean(false);
                serverMessage12.AppendInt32(5);
                serverMessage12.AppendInt32(list.Count);
                foreach (RoomItem current12 in list)
                {
                    serverMessage12.AppendUInt(current12.Id);
                }
                serverMessage12.AppendInt32(Item.GetBaseItem().SpriteId);
                serverMessage12.AppendUInt(Item.Id);
                serverMessage12.AppendString(ExtraString2);
                serverMessage12.AppendInt32(3);

                if (String.IsNullOrWhiteSpace(ExtraInfo))
                {
                    serverMessage12.AppendInt32(0);
                    serverMessage12.AppendInt32(0);
                    serverMessage12.AppendInt32(0);
                }
                else
                {
                    string[] boolz = ExtraInfo.Split(',');

                    foreach (string Stringy in boolz)
                    {
                        if (Stringy.ToLower() == "true")
                        {
                            serverMessage12.AppendInt32(1);
                        }
                        else
                        {
                            serverMessage12.AppendInt32(0);
                        }
                    }
                }
                serverMessage12.AppendInt32(0);
                serverMessage12.AppendInt32(3);
                serverMessage12.AppendInt32(i);                 // Delay
                serverMessage12.AppendInt32(0);
                Session.SendMessage(serverMessage12);
                return;
            }

            case InteractionType.actionmoverotate:
            {
                ServerMessage serverMessage13 = new ServerMessage(Outgoing.WiredEffectMessageComposer);
                serverMessage13.AppendBoolean(false);
                serverMessage13.AppendInt32(5);
                serverMessage13.AppendInt32(list.Count);
                foreach (RoomItem current13 in list)
                {
                    serverMessage13.AppendUInt(current13.Id);
                }
                serverMessage13.AppendInt32(Item.GetBaseItem().SpriteId);
                serverMessage13.AppendUInt(Item.Id);
                serverMessage13.AppendString(ExtraInfo);
                serverMessage13.AppendInt32(2);
                serverMessage13.AppendInt32(int.Parse(ExtraInfo.Split(new char[]
                    {
                        ';'
                    })[1]));
                serverMessage13.AppendInt32(int.Parse(ExtraInfo.Split(new char[]
                    {
                        ';'
                    })[0]));
                serverMessage13.AppendInt32(0);
                serverMessage13.AppendInt32(4);
                serverMessage13.AppendInt32(i);
                serverMessage13.AppendInt32(0);
                serverMessage13.AppendInt32(0);
                Session.SendMessage(serverMessage13);
                return;
            }

            case InteractionType.actionresettimer:
            {
                ServerMessage serverMessage14 = new ServerMessage(Outgoing.WiredEffectMessageComposer);
                serverMessage14.AppendBoolean(false);
                serverMessage14.AppendInt32(5);
                serverMessage14.AppendInt32(list.Count);
                foreach (RoomItem current14 in list)
                {
                    serverMessage14.AppendUInt(current14.Id);
                }
                serverMessage14.AppendInt32(Item.GetBaseItem().SpriteId);
                serverMessage14.AppendUInt(Item.Id);
                serverMessage14.AppendString(ExtraInfo);
                serverMessage14.AppendInt32(0);
                serverMessage14.AppendInt32(0);
                serverMessage14.AppendInt32(0);
                serverMessage14.AppendInt32(0);
                serverMessage14.AppendInt32(0);
                serverMessage14.AppendInt32(0);
                Session.SendMessage(serverMessage14);
                return;
            }

            case InteractionType.actionshowmessage:
            case InteractionType.actionkickuser:
            {
                ServerMessage serverMessage15 = new ServerMessage(Outgoing.WiredEffectMessageComposer);
                serverMessage15.AppendBoolean(false);
                serverMessage15.AppendInt32(0);
                serverMessage15.AppendInt32(list.Count);
                foreach (RoomItem current15 in list)
                {
                    serverMessage15.AppendUInt(current15.Id);
                }
                serverMessage15.AppendInt32(Item.GetBaseItem().SpriteId);
                serverMessage15.AppendUInt(Item.Id);
                serverMessage15.AppendString(ExtraInfo);
                serverMessage15.AppendInt32(0);
                serverMessage15.AppendInt32(0);
                serverMessage15.AppendInt32(7);
                serverMessage15.AppendInt32(0);
                serverMessage15.AppendInt32(0);
                serverMessage15.AppendInt32(0);
                Session.SendMessage(serverMessage15);
                return;
            }

            case InteractionType.actionteleportto:
            {
                ServerMessage serverMessage16 = new ServerMessage(Outgoing.WiredEffectMessageComposer);
                serverMessage16.AppendBoolean(false);
                serverMessage16.AppendInt32(5);
                serverMessage16.AppendInt32(list.Count);
                foreach (RoomItem current16 in list)
                {
                    serverMessage16.AppendUInt(current16.Id);
                }
                serverMessage16.AppendInt32(Item.GetBaseItem().SpriteId);
                serverMessage16.AppendUInt(Item.Id);
                serverMessage16.AppendString(ExtraInfo);
                serverMessage16.AppendInt32(0);
                serverMessage16.AppendInt32(8);
                serverMessage16.AppendInt32(0);
                serverMessage16.AppendInt32(i);
                serverMessage16.AppendInt32(0);
                serverMessage16.AppendByte(2);
                Session.SendMessage(serverMessage16);
                return;
            }

            case InteractionType.actiontogglestate:
            {
                ServerMessage serverMessage17 = new ServerMessage(Outgoing.WiredEffectMessageComposer);
                serverMessage17.AppendBoolean(false);
                serverMessage17.AppendInt32(5);
                serverMessage17.AppendInt32(list.Count);
                foreach (RoomItem current17 in list)
                {
                    serverMessage17.AppendUInt(current17.Id);
                }
                serverMessage17.AppendInt32(Item.GetBaseItem().SpriteId);
                serverMessage17.AppendUInt(Item.Id);
                serverMessage17.AppendString(ExtraInfo);
                serverMessage17.AppendInt32(0);
                serverMessage17.AppendInt32(8);
                serverMessage17.AppendInt32(0);
                serverMessage17.AppendInt32(i);
                serverMessage17.AppendInt32(0);
                serverMessage17.AppendInt32(0);
                Session.SendMessage(serverMessage17);
                return;
            }

            case InteractionType.actiongivereward:
            {
                ServerMessage serverMessage18 = new ServerMessage(Outgoing.WiredEffectMessageComposer);
                serverMessage18.AppendBoolean(false);
                serverMessage18.AppendInt32(5);
                serverMessage18.AppendInt32(0);
                serverMessage18.AppendInt32(Item.GetBaseItem().SpriteId);
                serverMessage18.AppendUInt(Item.Id);
                serverMessage18.AppendString(ExtraInfo);
                serverMessage18.AppendInt32(3);
                serverMessage18.AppendInt32((ExtraString == "") ? 0 : int.Parse(ExtraString));
                serverMessage18.AppendInt32(flag ? 1 : 0);
                serverMessage18.AppendInt32((ExtraString2 == "") ? 0 : int.Parse(ExtraString2));
                serverMessage18.AppendInt32(0);
                serverMessage18.AppendInt32(17);
                serverMessage18.AppendInt32(0);
                serverMessage18.AppendInt32(0);
                Session.SendMessage(serverMessage18);
                return;
            }

            case InteractionType.conditionhowmanyusersinroom:
            case InteractionType.conditionnegativehowmanyusers:
            {
                ServerMessage serverMessage19 = new ServerMessage(Outgoing.WiredConditionMessageComposer);
                serverMessage19.AppendBoolean(false);
                serverMessage19.AppendInt32(5);
                serverMessage19.AppendInt32(0);
                serverMessage19.AppendInt32(Item.GetBaseItem().SpriteId);
                serverMessage19.AppendUInt(Item.Id);
                serverMessage19.AppendString("");
                serverMessage19.AppendInt32(2);
                if (String.IsNullOrWhiteSpace(ExtraInfo))
                {
                    serverMessage19.AppendInt32(1);
                    serverMessage19.AppendInt32(50);
                }
                else
                {
                    foreach (string Integers in ExtraInfo.Split(','))
                    {
                        serverMessage19.AppendInt32(int.Parse(Integers));
                    }
                }
                serverMessage19.AppendBoolean(false);
                serverMessage19.AppendInt32(0);
                serverMessage19.AppendInt32(1290);
                Session.SendMessage(serverMessage19);
                return;
            }

            case InteractionType.conditionfurnishaveusers:
            case InteractionType.conditionstatepos:
            case InteractionType.conditiontriggeronfurni:
            case InteractionType.conditionfurnihasfurni:
            case InteractionType.conditionfurnitypematches:
            case InteractionType.conditionfurnihasnotfurni:
            case InteractionType.conditionfurnishavenotusers:
            case InteractionType.conditionfurnitypedontmatch:
            case InteractionType.conditiontriggerernotonfurni:
            {
                ServerMessage serverMessage19 = new ServerMessage(Outgoing.WiredConditionMessageComposer);
                serverMessage19.AppendBoolean(false);
                serverMessage19.AppendInt32(5);
                serverMessage19.AppendInt32(list.Count);
                foreach (RoomItem current18 in list)
                {
                    serverMessage19.AppendUInt(current18.Id);
                }
                serverMessage19.AppendInt32(Item.GetBaseItem().SpriteId);
                serverMessage19.AppendUInt(Item.Id);
                serverMessage19.AppendInt32(0);
                serverMessage19.AppendInt32(0);
                serverMessage19.AppendInt32(0);
                serverMessage19.AppendBoolean(false);
                serverMessage19.AppendBoolean(true);
                Session.SendMessage(serverMessage19);
                return;
            }

            case InteractionType.conditiontimelessthan:
            case InteractionType.conditiontimemorethan:
            {
                ServerMessage serverMessage21 = new ServerMessage(Outgoing.WiredConditionMessageComposer);
                serverMessage21.AppendBoolean(false);
                serverMessage21.AppendInt32(5);
                serverMessage21.AppendInt32(list.Count);
                foreach (RoomItem current20 in list)
                {
                    serverMessage21.AppendUInt(current20.Id);
                }
                serverMessage21.AppendInt32(Item.GetBaseItem().SpriteId);
                serverMessage21.AppendUInt(Item.Id);
                serverMessage21.AppendInt32(0);
                serverMessage21.AppendInt32(0);
                serverMessage21.AppendInt32(0);
                serverMessage21.AppendInt32(0);
                serverMessage21.AppendInt32(0);
                serverMessage21.AppendInt32(0);
                serverMessage21.AppendInt32(0);
                Session.SendMessage(serverMessage21);
                return;
            }

            case InteractionType.conditionuserwearingeffect:
            case InteractionType.conditionusernotwearingeffect:
            {
                int effect = 0;
                int.TryParse(ExtraInfo, out effect);
                ServerMessage serverMessage21 = new ServerMessage(Outgoing.WiredConditionMessageComposer);
                serverMessage21.AppendBoolean(false);
                serverMessage21.AppendInt32(5);
                serverMessage21.AppendInt32(0);
                serverMessage21.AppendInt32(Item.GetBaseItem().SpriteId);
                serverMessage21.AppendUInt(Item.Id);
                serverMessage21.AppendString("");
                serverMessage21.AppendInt32(1);
                serverMessage21.AppendInt32(effect);
                serverMessage21.AppendInt32(0);
                serverMessage21.AppendInt32(12);
                Session.SendMessage(serverMessage21);
                return;
            }

            case InteractionType.conditionuserwearingbadge:
            case InteractionType.conditionusernotwearingbadge:
            {
                ServerMessage serverMessage21 = new ServerMessage(Outgoing.WiredConditionMessageComposer);
                serverMessage21.AppendBoolean(false);
                serverMessage21.AppendInt32(5);
                serverMessage21.AppendInt32(0);
                serverMessage21.AppendInt32(Item.GetBaseItem().SpriteId);
                serverMessage21.AppendUInt(Item.Id);
                serverMessage21.AppendString(ExtraInfo);
                serverMessage21.AppendInt32(0);
                serverMessage21.AppendInt32(0);
                serverMessage21.AppendInt32(11);
                Session.SendMessage(serverMessage21);
                return;
            }

            case InteractionType.conditiondaterangeactive:
            {
                int date1 = 0;
                int date2 = 0;

                try
                {
                    string[] strArray = ExtraInfo.Split(',');
                    date1 = int.Parse(strArray[0]);
                    date2 = int.Parse(strArray[1]);
                }
                catch { }

                ServerMessage serverMessage21 = new ServerMessage(Outgoing.WiredConditionMessageComposer);
                serverMessage21.AppendBoolean(false);
                serverMessage21.AppendInt32(5);
                serverMessage21.AppendInt32(0);
                serverMessage21.AppendInt32(Item.GetBaseItem().SpriteId);
                serverMessage21.AppendUInt(Item.Id);
                serverMessage21.AppendString(ExtraInfo);
                serverMessage21.AppendInt32(2);
                serverMessage21.AppendInt32(date1);
                serverMessage21.AppendInt32(date2);
                serverMessage21.AppendInt32(0);
                serverMessage21.AppendInt32(24);
                Session.SendMessage(serverMessage21);
                return;
            }



            case InteractionType.arrowplate:
            case InteractionType.pressurepad:
            case InteractionType.ringplate:
            case InteractionType.colortile:
            case InteractionType.colorwheel:
            case InteractionType.floorswitch1:
            case InteractionType.floorswitch2:
            case InteractionType.firegate:
            case InteractionType.glassfoor:
                break;

            case InteractionType.specialrandom:
            {
                ServerMessage serverMessage24 = new ServerMessage(Outgoing.WiredEffectMessageComposer);
                serverMessage24.AppendBoolean(false);
                serverMessage24.AppendInt32(5);
                serverMessage24.AppendInt32(list.Count);
                foreach (RoomItem current23 in list)
                {
                    serverMessage24.AppendUInt(current23.Id);
                }
                serverMessage24.AppendInt32(Item.GetBaseItem().SpriteId);
                serverMessage24.AppendUInt(Item.Id);
                serverMessage24.AppendString(ExtraInfo);
                serverMessage24.AppendInt32(0);
                serverMessage24.AppendInt32(8);
                serverMessage24.AppendInt32(0);
                serverMessage24.AppendInt32(0);
                serverMessage24.AppendInt32(0);
                serverMessage24.AppendInt32(0);
                Session.SendMessage(serverMessage24);
                return;
            }

            case InteractionType.specialunseen:
            {
                ServerMessage serverMessage25 = new ServerMessage(Outgoing.WiredEffectMessageComposer);
                serverMessage25.AppendBoolean(false);
                serverMessage25.AppendInt32(5);
                serverMessage25.AppendInt32(list.Count);
                foreach (RoomItem current24 in list)
                {
                    serverMessage25.AppendUInt(current24.Id);
                }
                serverMessage25.AppendInt32(Item.GetBaseItem().SpriteId);
                serverMessage25.AppendUInt(Item.Id);
                serverMessage25.AppendString(ExtraInfo);
                serverMessage25.AppendInt32(0);
                serverMessage25.AppendInt32(8);
                serverMessage25.AppendInt32(0);
                serverMessage25.AppendInt32(0);
                serverMessage25.AppendInt32(0);
                serverMessage25.AppendInt32(0);
                Session.SendMessage(serverMessage25);
                return;
            }

            default:
                return;
            }
        }
Beispiel #32
0
 public void LoadFromDatabase(IQueryAdapter dbClient, Room insideRoom)
 {
     dbClient.setQuery("SELECT trigger_data FROM trigger_item WHERE trigger_id = @id ");
     dbClient.addParameter("id", (int)this.itemID);
     this.message = dbClient.getString();
 }
Beispiel #33
0
        /// <summary>
        /// Actualiza el progreso una recompensa.
        /// </summary>
        /// <param name="Session"></param>
        /// <param name="UserId"></param>
        /// <param name="AchievementGroup"></param>
        /// <param name="ProgressAmount"></param>
        /// <returns></returns>
        public bool ProgressUserAchievement(uint UserId, string AchievementGroup, int ProgressAmount)
        {
            Habbo Habbo = UsersCache.getHabboCache(UserId);

            if (Habbo == null)
            {
                return(false);
            }

            GameClient Session = Habbo.GetClient();

            Achievement AchievementData = GetAchievementByName(AchievementGroup);

            if (AchievementData == null)
            {
                return(false);
            }

            UserAchievement UserData = Habbo.GetAchievementData(AchievementGroup);

            if (UserData == null)
            {
                UserData = new UserAchievement(AchievementGroup, 0, 0);
                Habbo.Achievements.Add(AchievementGroup, UserData);
            }

            uint TotalLevels = (uint)AchievementData.Levels.Length;

            if (UserData.Level == TotalLevels)
            {
                return(false); // ya está todo completado
            }

            uint TargetLevel = UserData.Level + 1;

            if (TargetLevel > TotalLevels)
            {
                TargetLevel = TotalLevels;
            }

            uint TargetRequeriment = AchievementData.Levels[TargetLevel - 1];

            UserData.Progress += ProgressAmount;

            if (UserData.Progress >= TargetRequeriment)
            {
                UserData.Level++;

                if (TargetLevel == 1)
                {
                    Habbo.GetBadgeComponent().GiveBadge(AchievementGroup + TargetLevel);
                }
                else
                {
                    Habbo.GetBadgeComponent().UpdateBadge(AchievementGroup + TargetLevel);
                }

                Habbo.AchievementPoints += AchievementData.Reward;

                if (Session != null)
                {
                    Session.SendMessage(AchievementUnlockedComposer.Compose(AchievementData, TargetLevel, AchievementData.Reward));
                    Session.SendMessage(AchievementScoreUpdateComposer.Compose(Habbo.AchievementPoints));
                }
            }

            if (Session != null)
            {
                Session.SendMessage(AchievementProgressComposer.Compose(AchievementData, UserData));
            }

            using (IQueryAdapter dbClient = OtanixEnvironment.GetDatabaseManager().getQueryreactor())
            {
                dbClient.setQuery("REPLACE INTO user_achievements VALUES (" + Habbo.Id + ", @group, " + UserData.Level + ", " + UserData.Progress + ")");
                dbClient.addParameter("group", AchievementGroup);
                dbClient.runQuery();
            }

            if (Session == null)
            {
                Habbo.SaveBadges();
            }

            return(true);
        }
Beispiel #34
0
        internal static ServerMessage SerializeUserChatlog(UInt32 UserId)
        {
            GameClient client = PiciEnvironment.GetGame().GetClientManager().GetClientByUserID(UserId);

            if (client == null || client.GetHabbo() == null)
            {
                ServerMessage Message = new ServerMessage(536);
                Message.AppendUInt(UserId);
                Message.AppendStringWithBreak("User not online");
                Message.AppendInt32(0);

                return(Message);
            }
            else
            {
                using (IQueryAdapter dbClient = PiciEnvironment.GetDatabaseManager().getQueryreactor())
                {
                    dbClient.setQuery("SELECT room_id,entry_timestamp,exit_timestamp FROM user_roomvisits WHERE user_id = " + UserId + " ORDER BY entry_timestamp DESC LIMIT 5");
                    DataTable Visits = dbClient.getTable();

                    ServerMessage Message = new ServerMessage(536);
                    Message.AppendUInt(UserId);
                    Message.AppendStringWithBreak(PiciEnvironment.GetGame().GetClientManager().GetNameById(UserId));

                    if (Visits != null)
                    {
                        Message.AppendInt32(Visits.Rows.Count);

                        foreach (DataRow Visit in Visits.Rows)
                        {
                            if ((Double)Visit["exit_timestamp"] <= 0.0)
                            {
                                Visit["exit_timestamp"] = PiciEnvironment.GetUnixTimestamp();
                            }

                            dbClient.setQuery("SELECT user_id,user_name,hour,minute,message FROM chatlogs WHERE room_id = " + (uint)Visit["room_id"] + " AND timestamp > " + (Double)Visit["entry_timestamp"] + " AND timestamp < " + (Double)Visit["exit_timestamp"] + " ORDER BY timestamp DESC");
                            DataTable Chatlogs = dbClient.getTable();


                            RoomData RoomData = PiciEnvironment.GetGame().GetRoomManager().GenerateNullableRoomData((UInt32)Visit["room_id"]);

                            Message.AppendBoolean(RoomData.IsPublicRoom);
                            Message.AppendUInt(RoomData.Id);
                            Message.AppendStringWithBreak(RoomData.Name);

                            if (Chatlogs != null)
                            {
                                Message.AppendInt32(Chatlogs.Rows.Count);

                                foreach (DataRow Log in Chatlogs.Rows)
                                {
                                    Message.AppendInt32((int)Log["hour"]);
                                    Message.AppendInt32((int)Log["minute"]);
                                    Message.AppendUInt((UInt32)Log["user_id"]);
                                    Message.AppendStringWithBreak((string)Log["user_name"]);
                                    Message.AppendStringWithBreak((string)Log["message"]);
                                }
                            }
                            else
                            {
                                Message.AppendInt32(0);
                            }
                        }
                    }
                    else
                    {
                        Message.AppendInt32(0);
                    }

                    return(Message);
                }
            }
        }
Beispiel #35
0
        internal void LoadFurniture()
        {
            //this.Items.Clear();
            this.mFloorItems.Clear();
            this.mWallItems.Clear();
            DataTable Data;

            using (IQueryAdapter dbClient = PiciEnvironment.GetDatabaseManager().getQueryreactor())
            {
                if (dbClient.dbType == Pici.Storage.Database.DatabaseType.MySQL)
                {
                    dbClient.setQuery("CALL getroomitems(@roomid)");
                    dbClient.addParameter("roomid", room.RoomId);
                }
                else
                {
                    dbClient.setQuery("EXECUTE getroomitems " + room.RoomId);
                }

                Data = dbClient.getTable();


                uint           itemID;
                decimal        x;
                decimal        y;
                sbyte          n;
                uint           baseID;
                string         extradata;
                WallCoordinate wallCoord;
                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]);
                    if (DBNull.Value.Equals(dRow[5]))
                    {
                        extradata = string.Empty;
                    }
                    else
                    {
                        extradata = (string)dRow[5];
                    }

                    if (n > 6) // Is wallitem
                    {
                        wallCoord = new WallCoordinate((double)x, (double)y, n);
                        RoomItem item = new RoomItem(itemID, room.RoomId, baseID, extradata, 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, extradata, 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 == Pici.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);
                    }

                    if (WiredHandler.TypeIsWire(Item.GetBaseItem().InteractionType))
                    {
                        room.GetWiredHandler().AddWire(Item, Item.Coordinate, Item.Rot, Item.GetBaseItem().InteractionType);
                    }
                }
            }
        }
Beispiel #36
0
        internal static ServerMessage SerializeRoomTool(RoomData Data)
        {
            Room   Room    = ButterflyEnvironment.GetGame().GetRoomManager().GetRoom(Data.Id);
            UInt32 OwnerId = 0;

            using (IQueryAdapter dbClient = ButterflyEnvironment.GetDatabaseManager().getQueryreactor())
            {
                try
                {
                    dbClient.setQuery("SELECT id FROM users WHERE username = @owner");
                    dbClient.addParameter("owner", Data.Owner);
                    OwnerId = Convert.ToUInt32(dbClient.getRow()[0]);
                }
                catch (Exception e)
                {
                    Logging.HandleException(e, "ModerationTool.SerializeRoomTool");
                }
            }

            ServerMessage Message = new ServerMessage(538);

            Message.AppendUInt(Data.Id);
            Message.AppendInt32(Data.UsersNow); // user count

            if (Room != null)
            {
                Message.AppendBoolean((Room.GetRoomUserManager().GetRoomUserByHabbo(Data.Owner) != null));
            }
            else
            {
                Message.AppendBoolean(false);
            }

            Message.AppendUInt(OwnerId);
            Message.AppendStringWithBreak(Data.Owner);
            Message.AppendUInt(Data.Id);
            Message.AppendStringWithBreak(Data.Name);
            Message.AppendStringWithBreak(Data.Description);
            Message.AppendInt32(Data.TagCount);

            foreach (string Tag in Data.Tags)
            {
                Message.AppendStringWithBreak(Tag);
            }

            if (Room != null)
            {
                Message.AppendBoolean(Room.HasOngoingEvent);

                if (Room.Event != null)
                {
                    Message.AppendStringWithBreak(Room.Event.Name);
                    Message.AppendStringWithBreak(Room.Event.Description);
                    Message.AppendInt32(Room.Event.Tags.Count);

                    foreach (string Tag in Room.Event.Tags.ToArray())
                    {
                        Message.AppendStringWithBreak(Tag);
                    }
                }
            }
            else
            {
                Message.AppendBoolean(false);
            }

            return(Message);
        }
Beispiel #37
0
        internal static UserData GetUserData(string sessionTicket)
        {
            DataRow   dUserInfo;
            DataTable dFavouriteRooms;
            DataTable dEffects;
            DataTable dFriends;
            DataTable dRequests;
            UInt32    userID;

            using (IQueryAdapter dbClient = OtanixEnvironment.GetDatabaseManager().getQueryreactor())
            {
                dbClient.setQuery("SELECT * FROM users RIGHT JOIN user_tickets ON user_tickets.userid = users.id WHERE user_tickets.sessionticket = @sso");
                dbClient.addParameter("sso", sessionTicket);
                dUserInfo = dbClient.getRow();

                if (dUserInfo == null)
                {
                    // Si no existe el ticket; Este fallo no debería existir NUNCA.
                    return(null);
                }

                userID = Convert.ToUInt32(dUserInfo["id"]);

                if (OtanixEnvironment.GetGame().GetClientManager().GetClientByUserID(userID) != null)
                {
                    // Desconectamos al usuario conectado ya.
                    OtanixEnvironment.GetGame().GetClientManager().GetClientByUserID(userID).Disconnect();

                    dbClient.setQuery("SELECT * FROM users WHERE id = '" + userID + "'");
                    dUserInfo = dbClient.getRow();
                }

                // Manda las salas favoritas al Login, por lo tanto se queda aquí esto.
                dbClient.setQuery("SELECT room_id FROM user_favorites WHERE user_id = " + userID);
                dFavouriteRooms = dbClient.getTable();

                // Manda los efectos al conectarse, por lo tanto lo dejamos así.
                dbClient.setQuery("SELECT * FROM user_effects WHERE user_id =  " + userID + " GROUP by effect_id");
                dEffects = dbClient.getTable();

                // Los amigos son urgentes para conectarse
                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 + " LIMIT " + EmuSettings.FRIENDS_LIMIT);
                dFriends = dbClient.getTable();

                // Comprobamos si hay peticiones de amistad.
                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 + " LIMIT " + EmuSettings.FRIENDS_REQUEST_LIMIT);
                dRequests = dbClient.getTable();
            }

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

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

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

            foreach (DataRow dRow in dEffects.Rows)
            {
                effects.Add(new AvatarEffect((int)dRow["effect_id"], (int)dRow["total_duration"], OtanixEnvironment.EnumToBool((string)dRow["is_activated"]), (double)dRow["activated_stamp"], (int)dRow["effect_count"]));
            }

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

            foreach (DataRow dRow in dFriends.Rows)
            {
                if (Convert.ToUInt32(dRow["id"]) == userID)
                {
                    continue;
                }

                if (!friends.ContainsKey(Convert.ToUInt32(dRow["id"])))
                {
                    friends.Add(Convert.ToUInt32(dRow["id"]), new MessengerBuddy(Convert.ToUInt32(dRow["id"]), (string)dRow["username"], (string)dRow["look"], (string)dRow["motto"]));
                }
            }

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

            foreach (DataRow dRow in dRequests.Rows)
            {
                if (Convert.ToUInt32(dRow["sender"]) != userID)
                {
                    if (!requests.ContainsKey(Convert.ToUInt32(dRow["sender"])))
                    {
                        requests.Add(Convert.ToUInt32(dRow["sender"]), new MessengerRequest(userID, Convert.ToUInt32(dRow["sender"]), (string)dRow["username"]));
                    }
                }
                else
                {
                    if (!requests.ContainsKey(Convert.ToUInt32(dRow["receiver"])))
                    {
                        requests.Add(Convert.ToUInt32(dRow["receiver"]), new MessengerRequest(userID, Convert.ToUInt32(dRow["receiver"]), (string)dRow["username"]));
                    }
                }
            }

            Habbo user = HabboFactory.GenerateHabbo(dUserInfo);

            dUserInfo       = null;
            dFavouriteRooms = null;
            dEffects        = null;
            dFriends        = null;
            dRequests       = null;

            return(new UserData(favouritedRooms, effects, friends, requests, user));
        }
Beispiel #38
0
        internal static UserData GetUserData(string sessionTicket, string ip, out byte errorCode)
        {
            DataTable dataTable = null;
            DataRow   dataRow;
            uint      Userid;
            DataTable dataTable2;
            DataTable table;
            DataRow   row;
            DataTable dataTable3;
            DataTable dataTable4;
            DataTable dataTable5;
            DataRow   dataRow2;
            DataTable dataTable6;
            DataTable dataTable7;
            DataTable dataTable8;
            DataTable dataTable9;
            DataTable dataTable10;
            DataTable dataTable11;
            DataTable dataTable12;
            DataTable dataTable13;
            DataTable table2;
            DataTable dataTable14;
            DataTable dataTable15;

            using (IQueryAdapter queryreactor = CyberEnvironment.GetDatabaseManager().getQueryReactor())
            {
                queryreactor.setQuery("SELECT * FROM users WHERE auth_ticket = @sso ");
                queryreactor.addParameter("sso", sessionTicket);
                queryreactor.addParameter("ipaddress", ip);
                dataRow = queryreactor.getRow();
                if (dataRow == null)
                {
                    errorCode = 1;
                    throw new UserDataNotFoundException(string.Format("No user found with ip {0} and sso {1}.", ip, sessionTicket));
                }
                Userid = Convert.ToUInt32(dataRow["id"]);
                queryreactor.runFastQuery("UPDATE users SET online='1' WHERE id=" + Userid + " LIMIT 1");
                if (CyberEnvironment.GetGame().GetClientManager().GetClientByUserID(Userid) != null)
                {
                    errorCode = 2;
                    CyberEnvironment.GetGame().GetClientManager().GetClientByUserID(Userid).Disconnect();
                    return(null);
                }
                queryreactor.setQuery("SELECT * FROM user_achievement WHERE userid = " + Userid);
                dataTable2 = queryreactor.getTable();
                queryreactor.setQuery("SELECT * FROM user_talents WHERE userid = " + Userid);
                table = queryreactor.getTable();
                queryreactor.setQuery("SELECT COUNT(*) FROM user_stats WHERE id=" + Userid);
                if (int.Parse(queryreactor.getString()) == 0)
                {
                    queryreactor.runFastQuery("INSERT INTO user_stats (id) VALUES (" + Userid + ");");
                }
                queryreactor.setQuery("SELECT * FROM user_stats WHERE id=" + Userid + " LIMIT 1");
                row = queryreactor.getRow();
                queryreactor.setQuery("SELECT room_id FROM user_favorites WHERE user_id = " + Userid);
                dataTable3 = queryreactor.getTable();
                queryreactor.setQuery("SELECT ignore_id FROM user_ignores WHERE user_id = " + Userid);
                dataTable4 = queryreactor.getTable();
                queryreactor.setQuery("SELECT tag FROM user_tags WHERE user_id = " + Userid);
                dataTable5 = queryreactor.getTable();
                queryreactor.setQuery("SELECT * FROM user_subscriptions WHERE user_id = " + Userid + " AND timestamp_expire > UNIX_TIMESTAMP() ORDER BY subscription_id DESC LIMIT 1");
                dataRow2 = queryreactor.getRow();
                queryreactor.setQuery("SELECT * FROM user_badges WHERE user_id = " + Userid);
                dataTable6 = queryreactor.getTable();
                queryreactor.setQuery("SELECT `items`.* , COALESCE(`items_groups`.`group_id`, 0) AS group_id FROM `items` LEFT OUTER JOIN `items_groups` ON `items`.`id` = `items_groups`.`id` WHERE room_id='0' AND user_id=" + Userid + " LIMIT 8000");
                dataTable7 = queryreactor.getTable();
                queryreactor.setQuery("SELECT * FROM user_effects WHERE user_id =  " + Userid);
                dataTable8 = queryreactor.getTable();
                queryreactor.setQuery("SELECT poll_id FROM user_polldata WHERE user_id = " + Userid + " GROUP BY poll_id;");
                dataTable9 = queryreactor.getTable();
                queryreactor.setQuery(string.Concat(new object[]
                {
                    "SELECT users.id,users.username,users.motto,users.look,users.last_online,users.hide_inroom,users.hide_online FROM users JOIN messenger_friendships ON users.id = messenger_friendships.user_one_id WHERE messenger_friendships.user_two_id = ",
                    Userid,
                    " UNION ALL SELECT users.id,users.username,users.motto,users.look,users.last_online,users.hide_inroom,users.hide_online FROM users JOIN messenger_friendships ON users.id = messenger_friendships.user_two_id WHERE messenger_friendships.user_one_id = ",
                    Userid
                }));
                dataTable10 = queryreactor.getTable();
                queryreactor.setQuery("SELECT * FROM user_stats WHERE id=" + Userid + " LIMIT 1");
                row = queryreactor.getRow();
                queryreactor.setQuery("SELECT messenger_requests.from_id,messenger_requests.to_id,users.username FROM users JOIN messenger_requests ON users.id = messenger_requests.from_id WHERE messenger_requests.to_id = " + Userid);
                dataTable11 = queryreactor.getTable();
                queryreactor.setQuery("SELECT * FROM rooms WHERE owner = @name LIMIT 150");
                queryreactor.addParameter("name", (string)dataRow["username"]);
                dataTable12 = queryreactor.getTable();
                queryreactor.setQuery("SELECT * FROM bots WHERE user_id = " + Userid + " AND room_id = 0 AND ai_type='pet'");
                dataTable13 = queryreactor.getTable();
                queryreactor.setQuery("SELECT * FROM user_quests WHERE user_id = " + Userid);
                table2 = queryreactor.getTable();
                queryreactor.setQuery("SELECT * FROM bots WHERE user_id=" + Userid + " AND room_id=0 AND ai_type='generic'");
                dataTable14 = queryreactor.getTable();
                queryreactor.setQuery("SELECT group_id,rank FROM group_memberships WHERE user_id=" + Userid);
                dataTable = queryreactor.getTable();
                queryreactor.setQuery(string.Concat(new object[]
                {
                    "UPDATE user_info SET login_timestamp = '",
                    CyberEnvironment.GetUnixTimestamp(),
                    "' WHERE user_id = ",
                    Userid,
                    " ; "
                }));
                queryreactor.addParameter("ip", ip);
                queryreactor.runQuery();
                queryreactor.setQuery("SELECT * FROM user_relationships WHERE user_id=@id");
                queryreactor.addParameter("id", Userid);
                dataTable15 = queryreactor.getTable();
                queryreactor.runFastQuery("UPDATE users SET online='1' WHERE id=" + Userid + " LIMIT 1");
            }
            Dictionary <string, UserAchievement> dictionary = new Dictionary <string, UserAchievement>();

            foreach (DataRow dataRow3 in dataTable2.Rows)
            {
                string          text     = (string)dataRow3["group"];
                int             level    = (int)dataRow3["level"];
                int             progress = (int)dataRow3["progress"];
                UserAchievement value    = new UserAchievement(text, level, progress);
                dictionary.Add(text, value);
            }
            Dictionary <int, UserTalent> dictionary2 = new Dictionary <int, UserTalent>();

            foreach (DataRow dataRow4 in table.Rows)
            {
                int        num2   = (int)dataRow4["talent_id"];
                int        state  = (int)dataRow4["talent_state"];
                UserTalent value2 = new UserTalent(num2, state);
                dictionary2.Add(num2, value2);
            }
            List <uint> list = new List <uint>();

            foreach (DataRow dataRow5 in dataTable3.Rows)
            {
                uint item = Convert.ToUInt32(dataRow5["room_id"]);
                list.Add(item);
            }
            List <uint> list2 = new List <uint>();

            foreach (DataRow dataRow6 in dataTable4.Rows)
            {
                uint item2 = Convert.ToUInt32(dataRow6["ignore_id"]);
                list2.Add(item2);
            }
            List <string> list3 = new List <string>();

            foreach (DataRow dataRow7 in dataTable5.Rows)
            {
                string item3 = dataRow7["tag"].ToString().Replace(" ", "");
                list3.Add(item3);
            }
            Subscription sub = null;

            if (dataRow2 != null)
            {
                sub = new Subscription((int)dataRow2["subscription_id"], (int)dataRow2["timestamp_activated"], (int)dataRow2["timestamp_expire"], (int)dataRow2["timestamp_lastgift"]);
            }
            Dictionary <uint, RoomBot> dictionary3 = new Dictionary <uint, RoomBot>();

            foreach (DataRow row2 in dataTable14.Rows)
            {
                RoomBot roomBot = BotManager.GenerateBotFromRow(row2);
                dictionary3.Add(roomBot.BotId, roomBot);
            }
            List <Badge> list4 = new List <Badge>();

            foreach (DataRow dataRow8 in dataTable6.Rows)
            {
                string code = (string)dataRow8["badge_id"];
                int    slot = (int)dataRow8["badge_slot"];
                list4.Add(new Badge(code, slot));
            }

            int miniMailCount = 0;

            try
            {
                DataRow Rowi;
                using (IQueryAdapter dbClient = CyberEnvironment.GetDatabaseManager().getQueryReactor())
                {
                    dbClient.setQuery("SELECT Count( IsReaded ) FROM xdrcms_minimail WHERE InBin = 0 AND IsReaded = 0 AND SenderId != " + Userid + " AND OwnerId = " + Userid);
                    Rowi = dbClient.getRow();
                }
                if (Rowi != null)
                {
                    // We are using aXDR CMS with MiniMail!
                    miniMailCount = int.Parse(Rowi[0].ToString());
                }
            }
            catch { }

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

            foreach (DataRow dataRow9 in dataTable7.Rows)
            {
                uint   id       = Convert.ToUInt32(dataRow9[0]);
                uint   baseItem = Convert.ToUInt32(dataRow9[3]);
                string extraData;
                if (!DBNull.Value.Equals(dataRow9[4]))
                {
                    extraData = (string)dataRow9[4];
                }
                else
                {
                    extraData = string.Empty;
                }
                uint   group    = Convert.ToUInt32(dataRow9["group_id"]);
                string songCode = (string)dataRow9["songcode"];
                list5.Add(new UserItem(id, baseItem, extraData, group, songCode));
            }
            List <AvatarEffect> list6 = new List <AvatarEffect>();

            foreach (DataRow dataRow10 in dataTable8.Rows)
            {
                int    effectId          = (int)dataRow10["effect_id"];
                int    totalDuration     = (int)dataRow10["total_duration"];
                bool   activated         = CyberEnvironment.EnumToBool((string)dataRow10["is_activated"]);
                double activateTimestamp = (double)dataRow10["activated_stamp"];
                list6.Add(new AvatarEffect(effectId, totalDuration, activated, activateTimestamp));
            }

            HashSet <uint> pollSuggested = new HashSet <uint>();

            foreach (DataRow Row in dataTable9.Rows)
            {
                uint pId = (uint)Row["poll_id"];
                pollSuggested.Add(pId);
            }

            Dictionary <uint, MessengerBuddy> dictionary4 = new Dictionary <uint, MessengerBuddy>();
            string arg_A3D_0 = (string)dataRow["username"];
            int    num3      = checked (dataTable10.Rows.Count - 700);

            if (num3 > 0)
            {
                using (IQueryAdapter queryreactor2 = CyberEnvironment.GetDatabaseManager().getQueryReactor())
                {
                    queryreactor2.runFastQuery(string.Concat(new object[]
                    {
                        "DELETE FROM messenger_friendships WHERE user_one_id=",
                        Userid,
                        " OR user_two_id=",
                        Userid,
                        " LIMIT ",
                        num3
                    }));
                    queryreactor2.setQuery(string.Concat(new object[]
                    {
                        "SELECT users.id,users.username,users.motto,users.look,users.last_online,users.hide_inroom,users.hide_online FROM users JOIN messenger_friendships ON users.id = messenger_friendships.user_one_id WHERE messenger_friendships.user_two_id = ",
                        Userid,
                        " UNION ALL SELECT users.id,users.username,users.motto,users.look,users.last_online,users.hide_inroom,users.hide_online FROM users JOIN messenger_friendships ON users.id = messenger_friendships.user_two_id WHERE messenger_friendships.user_one_id = ",
                        Userid
                    }));
                    dataTable10 = queryreactor2.getTable();
                }
            }
            foreach (DataRow dataRow12 in dataTable10.Rows)
            {
                uint   num4           = Convert.ToUInt32(dataRow12["id"]);
                string pUsername      = (string)dataRow12["username"];
                string pLook          = (string)dataRow12["look"];
                string pMotto         = (string)dataRow12["motto"];
                int    pLastOnline    = Convert.ToInt32(dataRow12["last_online"]);
                bool   pAppearOffline = CyberEnvironment.EnumToBool(dataRow12["hide_online"].ToString());
                bool   pHideInroom    = CyberEnvironment.EnumToBool(dataRow12["hide_inroom"].ToString());
                if (num4 != Userid && !dictionary4.ContainsKey(num4))
                {
                    dictionary4.Add(num4, new MessengerBuddy(num4, pUsername, pLook, pMotto, pLastOnline, pAppearOffline, pHideInroom));
                }
            }
            Dictionary <uint, MessengerRequest> dictionary5 = new Dictionary <uint, MessengerRequest>();

            foreach (DataRow dataRow13 in dataTable11.Rows)
            {
                uint   num5       = Convert.ToUInt32(dataRow13["from_id"]);
                uint   num6       = Convert.ToUInt32(dataRow13["to_id"]);
                string pUsername2 = (string)dataRow13["username"];
                if (num5 != Userid)
                {
                    if (!dictionary5.ContainsKey(num5))
                    {
                        dictionary5.Add(num5, new MessengerRequest(Userid, num5, pUsername2));
                    }
                }
                else
                {
                    if (!dictionary5.ContainsKey(num6))
                    {
                        dictionary5.Add(num6, new MessengerRequest(Userid, num6, pUsername2));
                    }
                }
            }
            HashSet <RoomData> list8 = new HashSet <RoomData>();

            foreach (DataRow dataRow14 in dataTable12.Rows)
            {
                uint roomId = Convert.ToUInt32(dataRow14["id"]);
                list8.Add(CyberEnvironment.GetGame().GetRoomManager().FetchRoomData(roomId, dataRow14));
            }
            Dictionary <uint, Pet> dictionary6 = new Dictionary <uint, Pet>();

            foreach (DataRow dataRow15 in dataTable13.Rows)
            {
                using (IQueryAdapter queryreactor3 = CyberEnvironment.GetDatabaseManager().getQueryReactor())
                {
                    queryreactor3.setQuery("SELECT * FROM bots_petdata WHERE id=" + dataRow15[0] + " LIMIT 1");
                    DataRow row3 = queryreactor3.getRow();
                    if (row3 != null)
                    {
                        Pet pet = Catalog.GeneratePetFromRow(dataRow15, row3);
                        dictionary6.Add(pet.PetId, pet);
                    }
                }
            }
            Dictionary <uint, int> dictionary7 = new Dictionary <uint, int>();

            foreach (DataRow dataRow16 in table2.Rows)
            {
                uint key    = Convert.ToUInt32(dataRow16["quest_id"]);
                int  value3 = (int)dataRow16["progress"];
                if (dictionary7.ContainsKey(key))
                {
                    dictionary7.Remove(key);
                }
                dictionary7.Add(key, value3);
            }
            HashSet <GroupUser> list9 = new HashSet <GroupUser>();

            foreach (DataRow dataRow17 in dataTable.Rows)
            {
                list9.Add(new GroupUser(Userid, (uint)dataRow17[0], (int)Convert.ToInt16(dataRow17[1])));
            }
            Dictionary <int, Relationship> dictionary8 = new Dictionary <int, Relationship>();

            foreach (DataRow dataRow18 in dataTable15.Rows)
            {
                dictionary8.Add((int)dataRow18[0], new Relationship((int)dataRow18[0], (int)dataRow18[2], Convert.ToInt32(dataRow18[3].ToString())));
            }
            Habbo user = HabboFactory.GenerateHabbo(dataRow, row, list9);

            dataRow     = null;
            dataTable2  = null;
            dataTable3  = null;
            dataTable4  = null;
            dataTable5  = null;
            dataRow2    = null;
            dataTable6  = null;
            dataTable7  = null;
            dataTable8  = null;
            dataTable10 = null;
            dataTable11 = null;
            dataTable12 = null;
            dataTable13 = null;
            dataTable14 = null;
            dataTable15 = null;
            dataTable9  = null;
            errorCode   = 0;
            return(new UserData(Userid, dictionary, dictionary2, list, list2, list3, sub, list4, list5, list6, dictionary4, dictionary5, list8, dictionary6, dictionary7, user, dictionary3, dictionary8, pollSuggested, miniMailCount));
        }
Beispiel #39
0
        internal void UpdateFlats()
        {
            XDocument xDocument = XDocument.Load("http://www.habbo.es/gamedata/furnidata_xml");
            string    text      = "";
            string    text2     = "";
            int       num       = -1;
            int       num2      = 0;
            int       num4      = -1;
            WebClient webClient = new WebClient();

            webClient.Encoding = Encoding.UTF8;
            webClient.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)");
            using (IQueryAdapter queryreactor = CyberEnvironment.GetDatabaseManager().getQueryReactor())
            {
                IEnumerable <XElement> enumerable  = xDocument.Descendants("roomitemtypes").Descendants("furnitype");
                IEnumerable <XElement> enumerable2 = xDocument.Descendants("wallitemtypes").Descendants("furnitype");
                foreach (XElement current in enumerable)
                {
                    try
                    {
                        text  = current.Attribute("classname").Value;
                        text2 = current.Element("name").Value;
                        num2  = Convert.ToInt32(current.Attribute("id").Value);
                        num   = Convert.ToInt32(current.Element("offerid").Value);
                        num4  = Convert.ToInt32(current.Element("rentofferid").Value);
                        if (num4 != -1)
                        {
                            num = num4;
                        }

                        Console.WriteLine(text);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.ToString());
                    }
                    try
                    {
                        queryreactor.setQuery("UPDATE furniture SET public_name = @pubn , flat_id = @flatid , sprite_id = @spriteid WHERE item_name = @name");
                        queryreactor.addParameter("pubn", text2);
                        queryreactor.addParameter("flatid", num);
                        queryreactor.addParameter("spriteid", num2);
                        queryreactor.addParameter("name", text);
                        queryreactor.runQuery();
                    }
                    catch (Exception ex2)
                    {
                        Console.WriteLine(ex2.ToString());
                    }
                }
                foreach (XElement current2 in enumerable2)
                {
                    text  = current2.Attribute("classname").Value;
                    text2 = current2.Element("name").Value;
                    num2  = Convert.ToInt32(current2.Attribute("id").Value);
                    num   = Convert.ToInt32(current2.Element("offerid").Value);
                    num4  = Convert.ToInt32(current2.Element("rentofferid").Value);
                    if (num4 != -1)
                    {
                        num = num4;
                    }

                    Console.WriteLine(text);
                    try
                    {
                        queryreactor.setQuery("UPDATE furniture SET public_name = @pubn , flat_id = @flatid , sprite_id = @spriteid WHERE item_name = @name");
                        queryreactor.addParameter("pubn", text2);
                        queryreactor.addParameter("flatid", num);
                        queryreactor.addParameter("spriteid", num2);
                        queryreactor.addParameter("name", text);
                        queryreactor.runQuery();
                    }
                    catch (Exception ex3)
                    {
                        Console.WriteLine(ex3.ToString());
                    }
                }
            }
        }
Beispiel #40
0
        internal void Initialize(IQueryAdapter dbClient)
        {
            Pages          = new Dictionary <int, CatalogPage>();
            EcotronRewards = new List <EcotronReward>();
            gifts          = new Hashtable();

            dbClient.setQuery("SELECT * FROM catalog_pages ORDER BY order_num");
            DataTable Data = dbClient.getTable();

            dbClient.setQuery("SELECT * FROM ecotron_rewards ORDER BY item_id");
            DataTable EcoData = dbClient.getTable();

            Hashtable CataItems = new Hashtable();

            dbClient.setQuery("SELECT id,item_ids,catalog_name,cost_credits,cost_pixels,amount,page_id,cost_crystal,cost_oude_belcredits,song_id FROM catalog_items_copy");
            DataTable CatalogueItems = dbClient.getTable();

            if (CatalogueItems != null)
            {
                foreach (DataRow Row in CatalogueItems.Rows)
                {
                    if (string.IsNullOrEmpty(Row["item_ids"].ToString()) || (int)Row["amount"] <= 0)
                    {
                        continue;
                    }
                    CataItems.Add(Convert.ToUInt32(Row["id"]), new CatalogItem(Row));
                    //Items.Add(new CatalogItem((uint)Row["id"], (string)Row["catalog_name"], (string)Row["item_ids"], (int)Row["cost_credits"], (int)Row["cost_pixels"], (int)Row["amount"]));
                }
            }

            if (Data != null)
            {
                foreach (DataRow Row in Data.Rows)
                {
                    Boolean Visible    = false;
                    Boolean Enabled    = false;
                    Boolean ComingSoon = false;

                    if (Row["visible"].ToString() == "1")
                    {
                        Visible = true;
                    }

                    if (Row["enabled"].ToString() == "1")
                    {
                        Enabled = true;
                    }

                    if (Row["coming_soon"].ToString() == "1")
                    {
                        ComingSoon = true;
                    }

                    Pages.Add((int)Row["id"], new CatalogPage((int)Row["id"], (int)Row["parent_id"],
                                                              (string)Row["caption"], Visible, Enabled, ComingSoon, Convert.ToUInt32(Row["min_rank"]),
                                                              ButterflyEnvironment.EnumToBool(Row["club_only"].ToString()), (int)Row["icon_color"],
                                                              (int)Row["icon_image"], (string)Row["page_layout"], (string)Row["page_headline"],
                                                              (string)Row["page_teaser"], (string)Row["page_special"], (string)Row["page_text1"],
                                                              (string)Row["page_text2"], (string)Row["page_text_details"], (string)Row["page_text_teaser"], ref CataItems));
                }
            }

            if (EcoData != null)
            {
                foreach (DataRow Row in EcoData.Rows)
                {
                    EcotronRewards.Add(new EcotronReward(Convert.ToUInt32(Row["display_id"]), Convert.ToUInt32(Row["item_id"]), Convert.ToUInt32(Row["reward_level"])));
                }
            }

            RestackByFrontpage();
        }
Beispiel #41
0
 public void OnTrigger(GameClient Session, RoomItem Item, int Request, bool HasRights)
 {
     if (Item.ExtraData.Contains(Convert.ToChar(5).ToString()))
     {
         string[] array = Item.ExtraData.Split(new char[]
         {
             Convert.ToChar(5)
         });
         Session.GetHabbo().Gender = array[0].ToUpper();
         Dictionary <string, string> dictionary = new Dictionary <string, string>();
         dictionary.Clear();
         string[] array2 = array[1].Split(new char[]
         {
             '.'
         });
         for (int i = 0; i < array2.Length; i++)
         {
             string   text   = array2[i];
             string[] array3 = Session.GetHabbo().Look.Split(new char[]
             {
                 '.'
             });
             for (int j = 0; j < array3.Length; j++)
             {
                 string text2 = array3[j];
                 if (text2.Split(new char[]
                 {
                     '-'
                 })[0] == text.Split(new char[]
                 {
                     '-'
                 })[0])
                 {
                     if (dictionary.ContainsKey(text2.Split(new char[]
                     {
                         '-'
                     })[0]) && !dictionary.ContainsValue(text))
                     {
                         dictionary.Remove(text2.Split(new char[]
                         {
                             '-'
                         })[0]);
                         dictionary.Add(text2.Split(new char[]
                         {
                             '-'
                         })[0], text);
                     }
                     else
                     {
                         if (!dictionary.ContainsKey(text2.Split(new char[]
                         {
                             '-'
                         })[0]) && !dictionary.ContainsValue(text))
                         {
                             dictionary.Add(text2.Split(new char[]
                             {
                                 '-'
                             })[0], text);
                         }
                     }
                 }
                 else
                 {
                     if (!dictionary.ContainsKey(text2.Split(new char[]
                     {
                         '-'
                     })[0]))
                     {
                         dictionary.Add(text2.Split(new char[]
                         {
                             '-'
                         })[0], text2);
                     }
                 }
             }
         }
         string text3 = "";
         foreach (string current in dictionary.Values)
         {
             text3 = text3 + current + ".";
         }
         Session.GetHabbo().Look = text3.TrimEnd(new char[]
         {
             '.'
         });
         using (IQueryAdapter queryreactor = CyberEnvironment.GetDatabaseManager().getQueryReactor())
         {
             queryreactor.setQuery("UPDATE users SET look = @look, gender = @gender WHERE id = " + Session.GetHabbo().Id);
             queryreactor.addParameter("look", Session.GetHabbo().Look);
             queryreactor.addParameter("gender", Session.GetHabbo().Gender);
             queryreactor.runQuery();
         }
         Session.GetMessageHandler().GetResponse().Init(Outgoing.UpdateUserDataMessageComposer);
         Session.GetMessageHandler().GetResponse().AppendInt32(-1);
         Session.GetMessageHandler().GetResponse().AppendString(Session.GetHabbo().Look);
         Session.GetMessageHandler().GetResponse().AppendString(Session.GetHabbo().Gender.ToLower());
         Session.GetMessageHandler().GetResponse().AppendString(Session.GetHabbo().Motto);
         Session.GetMessageHandler().GetResponse().AppendInt32(Session.GetHabbo().AchievementPoints);
         Session.GetMessageHandler().SendResponse();
         RoomUser      roomUserByHabbo = Item.GetRoom().GetRoomUserManager().GetRoomUserByHabbo(Session.GetHabbo().Id);
         ServerMessage serverMessage   = new ServerMessage(Outgoing.UpdateUserDataMessageComposer);
         serverMessage.AppendInt32(roomUserByHabbo.VirtualId);
         serverMessage.AppendString(Session.GetHabbo().Look);
         serverMessage.AppendString(Session.GetHabbo().Gender.ToLower());
         serverMessage.AppendString(Session.GetHabbo().Motto);
         serverMessage.AppendInt32(Session.GetHabbo().AchievementPoints);
         Session.GetHabbo().CurrentRoom.SendMessage(serverMessage);
     }
 }
Beispiel #42
0
        internal void BanUser(GameClient Client, string Moderator, double LengthSeconds, string Reason, bool IpBan, bool Machine)
        {
            ModerationBanType type  = ModerationBanType.USERNAME;
            string            text  = Client.GetHabbo().Username;
            string            query = "user";
            double            num   = (double)CyberEnvironment.GetUnixTimestamp() + LengthSeconds;

            if (IpBan)
            {
                type = ModerationBanType.IP;
                using (IQueryAdapter queryreactor = CyberEnvironment.GetDatabaseManager().getQueryReactor())
                {
                    queryreactor.setQuery("SELECT ip_last FROM users WHERE username='******' LIMIT 1");
                    text = queryreactor.getString();
                }
                query = "ip";
            }
            if (Machine)
            {
                type  = ModerationBanType.MACHINE;
                query = "machine";
                text  = Client.MachineId;
            }
            ModerationBan moderationBan = new ModerationBan(type, text, Reason, num);

            if (moderationBan.Type == ModerationBanType.IP)
            {
                if (this.bannedIPs.Contains(text))
                {
                    this.bannedIPs[text] = moderationBan;
                }
                else
                {
                    this.bannedIPs.Add(text, moderationBan);
                }
            }
            else
            {
                if (moderationBan.Type == ModerationBanType.MACHINE)
                {
                    if (this.bannedMachines.ContainsKey(text))
                    {
                        this.bannedMachines[text] = moderationBan;
                    }
                    else
                    {
                        this.bannedMachines.Add(text, moderationBan);
                    }
                }
                else
                {
                    if (this.bannedUsernames.Contains(text))
                    {
                        this.bannedUsernames[text] = moderationBan;
                    }
                    else
                    {
                        this.bannedUsernames.Add(text, moderationBan);
                    }
                }
            }
            using (IQueryAdapter queryreactor2 = CyberEnvironment.GetDatabaseManager().getQueryReactor())
            {
                queryreactor2.setQuery(string.Concat(new object[]
                {
                    "INSERT INTO bans (bantype,value,reason,expire,added_by,added_date) VALUES (@rawvar,@var,@reason,'",
                    num,
                    "',@mod,'",
                    DateTime.Now.ToLongDateString(),
                    "')"
                }));
                queryreactor2.addParameter("rawvar", query);
                queryreactor2.addParameter("var", text);
                queryreactor2.addParameter("reason", Reason);
                queryreactor2.addParameter("mod", Moderator);
                queryreactor2.runQuery();
            }
            if (IpBan)
            {
                DataTable dataTable = null;
                using (IQueryAdapter queryreactor3 = CyberEnvironment.GetDatabaseManager().getQueryReactor())
                {
                    queryreactor3.setQuery("SELECT id FROM users WHERE ip_last = @var");
                    queryreactor3.addParameter("var", text);
                    dataTable = queryreactor3.getTable();
                }
                if (dataTable != null)
                {
                    using (IQueryAdapter queryreactor4 = CyberEnvironment.GetDatabaseManager().getQueryReactor())
                    {
                        foreach (DataRow dataRow in dataTable.Rows)
                        {
                            queryreactor4.runFastQuery("UPDATE user_info SET bans = bans + 1 WHERE user_id = " + Convert.ToUInt32(dataRow["id"]));
                        }
                    }
                }
                this.BanUser(Client, Moderator, LengthSeconds, Reason, false, false);
                return;
            }
            using (IQueryAdapter queryreactor5 = CyberEnvironment.GetDatabaseManager().getQueryReactor())
            {
                queryreactor5.runFastQuery("UPDATE user_info SET bans = bans + 1 WHERE user_id = " + Client.GetHabbo().Id);
            }
            Client.Disconnect();
        }
Beispiel #43
0
        internal void LoadBans(IQueryAdapter dbClient)
        {
            this.bannedUsernames.Clear();
            this.bannedIPs.Clear();
            this.bannedMachines.Clear();
            dbClient.setQuery("SELECT bantype,value,reason,expire FROM bans");
            DataTable table = dbClient.getTable();
            double    num   = (double)CyberEnvironment.GetUnixTimestamp();

            foreach (DataRow dataRow in table.Rows)
            {
                string            text          = (string)dataRow["value"];
                string            reasonMessage = (string)dataRow["reason"];
                double            num2          = (double)dataRow["expire"];
                string            a             = (string)dataRow["bantype"];
                ModerationBanType type;
                if (a == "user")
                {
                    type = ModerationBanType.USERNAME;
                }
                else
                {
                    if (a == "ip")
                    {
                        type = ModerationBanType.IP;
                    }
                    else
                    {
                        type = ModerationBanType.MACHINE;
                    }
                }
                ModerationBan moderationBan = new ModerationBan(type, text, reasonMessage, num2);
                if (num2 > num)
                {
                    if (moderationBan.Type == ModerationBanType.USERNAME)
                    {
                        if (!this.bannedUsernames.Contains(text))
                        {
                            this.bannedUsernames.Add(text, moderationBan);
                        }
                    }
                    else
                    {
                        if (moderationBan.Type == ModerationBanType.IP)
                        {
                            if (!this.bannedIPs.Contains(text))
                            {
                                this.bannedIPs.Add(text, moderationBan);
                            }
                        }
                        else
                        {
                            if (!this.bannedMachines.ContainsKey(text))
                            {
                                this.bannedMachines.Add(text, moderationBan);
                            }
                        }
                    }
                }
            }
        }
Beispiel #44
0
        internal static void Initialize()
        {
            PrettyVersion = string.Format("Firewind {0}", Assembly.GetExecutingAssembly().GetName().Version);
            Console.Clear();
            DateTime Start = DateTime.Now;

            SystemMute = false;

            ServerStarted = DateTime.Now;

            Console.Title = "Firewind: Loading environment.";

            Logging.WriteWithColor("      _______ __                       __           __ ", ConsoleColor.Cyan);
            Logging.WriteWithColor("     |    ___|__|.----.-----.--.--.--.|__|.-----.--|  |", ConsoleColor.Cyan);
            Logging.WriteWithColor("     |    ___|  ||   _|  -__|  |  |  ||  ||     |  _  |", ConsoleColor.Cyan);
            Logging.WriteWithColor("     |___|   |__||__| |_____|________||__||__|__|_____|", ConsoleColor.Cyan);
            Logging.WriteLine("");
            Logging.WriteLine("==============================================================");

            DefaultEncoding = Encoding.Default;
            Logging.WriteLine("     " + PrettyVersion);
            Logging.WriteLine(string.Format("     Licenced to {0}", LicenseHolder));
            Logging.WriteLine(string.Format("     Maximum players: {0}", MaxUsers == 0 ? "Unlimited!" : MaxUsers.ToString()));

            Logging.WriteLine("");

            Logging.WriteLine("     Go to the GitHub repo for bug reporting/contributions!");
            cultureInfo = CultureInfo.CreateSpecificCulture("en-GB");
            IsDebugging = IsDebugging ? System.Diagnostics.Debugger.IsAttached : false;

            try
            {
                LanguageLocale.Init();
                ChatCommandRegister.Init();
                PetCommandHandeler.Init();
                PetLocale.Init();

                if (IsDebugging)
                {
                    Configuration = new ConfigurationData(System.IO.Path.Combine(System.Windows.Forms.Application.StartupPath, @"Settings_test/configuration.ini"));
                }
                else
                {
                    Configuration = new ConfigurationData(System.IO.Path.Combine(System.Windows.Forms.Application.StartupPath, @"Settings/configuration.ini"));
                }

                DateTime Starts = DateTime.Now;
                Logging.WriteLine("Connecting to database...");

                manager = new DatabaseManager(uint.Parse(FirewindEnvironment.GetConfig().data["db.pool.maxsize"]), int.Parse(FirewindEnvironment.GetConfig().data["db.pool.minsize"]));
                manager.setServerDetails(
                    FirewindEnvironment.GetConfig().data["db.hostname"],
                    uint.Parse(FirewindEnvironment.GetConfig().data["db.port"]),
                    FirewindEnvironment.GetConfig().data["db.username"],
                    FirewindEnvironment.GetConfig().data["db.password"],
                    FirewindEnvironment.GetConfig().data["db.name"]);
                manager.init();

                TimeSpan TimeUsed2 = DateTime.Now - Starts;
                Logging.WriteLine("Connected to database! (" + TimeUsed2.Seconds + " s, " + TimeUsed2.Milliseconds + " ms)");

                LanguageLocale.InitSwearWord();

                friendRequestLimit = (uint)(int.Parse(FirewindEnvironment.GetConfig().data["client.maxrequests"]));

                Game = new Game(int.Parse(FirewindEnvironment.GetConfig().data["game.tcp.conlimit"]));
                Game.ContinueLoading();

                ConnectionManager = new ConnectionHandling(int.Parse(FirewindEnvironment.GetConfig().data["game.tcp.port"]),
                                                           MaxUsers,
                                                           int.Parse(FirewindEnvironment.GetConfig().data["game.tcp.conperip"]),
                                                           FirewindEnvironment.GetConfig().data["game.tcp.enablenagles"].ToLower() == "true");
                ConnectionManager.init();
                ConnectionManager.Start();

                StaticClientMessageHandler.Initialize();
                ClientMessageFactory.Init();

                string[] arrayshit = FirewindEnvironment.GetConfig().data["mus.tcp.allowedaddr"].Split(';');

                MusSystem = new RConListener(FirewindEnvironment.GetConfig().data["mus.tcp.bindip"], int.Parse(FirewindEnvironment.GetConfig().data["mus.tcp.port"]), arrayshit, 0);

                useSSO = true;
                if (Configuration.data.ContainsKey("auth.ssodisabled"))
                {
                    if (Configuration.data["auth.ssodisabled"] == "false")
                    {
                        useSSO = false;
                    }
                }

                if (Configuration.data.ContainsKey("spambans.enabled"))
                {
                    if (Configuration.data["spambans.enabled"] == "true")
                    {
                        spamBans       = true;
                        spamBans_limit = Convert.ToInt32(Configuration.data["spambans.limit"]);
                        Logging.WriteLine("Spam Bans enabled");
                    }
                }
                if (Configuration.data.ContainsKey("SeparatedTasksInMainLoops.enabled"))
                {
                    if (Configuration.data["SeparatedTasksInMainLoops.enabled"] == "true")
                    {
                        SeparatedTasksInMainLoops = true;
                        Logging.WriteLine("MultiTasking in MainLoop");
                    }
                }

                if (Configuration.data.ContainsKey("SeparatedTasksInGameClientManager.enabled"))
                {
                    if (Configuration.data["SeparatedTasksInGameClientManager.enabled"] == "true")
                    {
                        SeparatedTasksInGameClientManager = true;
                        Logging.WriteLine("MultiTasking in ClientManager");
                    }
                }

                TimeSpan TimeUsed = DateTime.Now - Start;

                Logging.WriteWithColor("Firewind -> READY! (" + TimeUsed.Seconds + " s, " + TimeUsed.Milliseconds + " ms)", ConsoleColor.Cyan);

                isLive = true;
                if (System.Diagnostics.Debugger.IsAttached)
                {
                    Logging.WriteLine("Server is debugging: Console writing enabled", true);
                }
                else
                {
                    Logging.WriteLine("Server is not debugging: Console writing disabled", false);
                    Logging.DisablePrimaryWriting(false);
                }
            }
            catch (KeyNotFoundException e)
            {
                Logging.WriteLine("Please check your configuration file - some values appear to be missing.");
                Logging.WriteLine("Press any key to shut down ...");
                Logging.WriteLine(e.ToString());
                Console.ReadKey(true);
                FirewindEnvironment.Destroy();

                return;
            }
            catch (InvalidOperationException e)
            {
                Logging.WriteLine("Failed to initialize Firewind Emulator: " + e.Message);
                Logging.WriteLine("Press any key to shut down ...");

                Console.ReadKey(true);
                FirewindEnvironment.Destroy();

                return;
            }

            catch (Exception e)
            {
                Logging.WriteLine("Fatal error during startup: " + e.ToString());
                Logging.WriteLine("Press a key to exit");

                Console.ReadKey();
                Environment.Exit(1);
            }

            // Check if this is habin or not
            try
            {
                using (IQueryAdapter dbClient = manager.getQueryreactor())
                {
                    dbClient.setQuery("SELECT column_name FROM information_schema.columns WHERE table_schema = '" + FirewindEnvironment.GetConfig().data["db.name"] + "' AND table_name = 'users' AND column_name = 'hpo'");
                    IsHabin = dbClient.findsResult();
                }
            }
            catch { }
        }
Beispiel #45
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());
                    }
                }
            }
        }
Beispiel #46
0
        internal void HandlePurchase(GameClient Session, int PageId, uint ItemId, string ExtraData, Boolean IsGift, string GiftUser, string GiftMessage)
        {
            CatalogPage Page;

            if (!Pages.TryGetValue(PageId, out Page))
            {
                return;
            }

            if (Page == null || Page.ComingSoon || !Page.Enabled || !Page.Visible || Session == null || Session.GetHabbo() == null)
            {
                return;
            }

            if (Page.ClubOnly && !Session.GetHabbo().GetSubscriptionManager().HasSubscription("habbo_club"))
            {
                return;
            }
            if (Session.GetHabbo().Rank != Page.MinRank) // Workaround
            {
                if (Session.GetHabbo().Rank < Page.MinRank)
                {
                    return;
                }
            }
            CatalogItem Item = Page.GetItem(ItemId);

            if (Item == null)
            {
                return;
            }

            uint GiftUserId = 0;

            if (IsGift)
            {
                if (!Item.GetBaseItem().AllowGift)
                {
                    return;
                }

                DataRow dRow;
                using (IQueryAdapter dbClient = ButterflyEnvironment.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(76);
                    Session.GetMessageHandler().GetResponse().AppendBoolean(true);
                    Session.GetMessageHandler().GetResponse().AppendStringWithBreak(GiftUser);
                    Session.GetMessageHandler().SendResponse();

                    return;
                }

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

                if (GiftUserId == 0)
                {
                    Session.GetMessageHandler().GetResponse().Init(76);
                    Session.GetMessageHandler().GetResponse().AppendBoolean(true);
                    Session.GetMessageHandler().GetResponse().AppendStringWithBreak(GiftUser);
                    Session.GetMessageHandler().SendResponse();

                    return;
                }
            }

            Boolean CreditsError = false;
            Boolean PixelError   = false;

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

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

            if (CreditsError || PixelError)
            {
                Session.GetMessageHandler().GetResponse().Init(68);
                Session.GetMessageHandler().GetResponse().AppendBoolean(CreditsError);
                Session.GetMessageHandler().GetResponse().AppendBoolean(PixelError);
                Session.GetMessageHandler().SendResponse();

                return;
            }

            if (IsGift && Item.GetBaseItem().Type == 'e')
            {
                Session.SendNotif(LanguageLocale.GetValue("catalog.gift.send.error"));
                return;
            }


            if (Item.CrystalCost > 0)
            {
                int userCrystals = 0;
                using (IQueryAdapter dbClient = ButterflyEnvironment.GetDatabaseManager().getQueryreactor())
                {
                    dbClient.setQuery("SELECT crystals FROM users WHERE id = " + Session.GetHabbo().Id);
                    userCrystals = dbClient.getInteger();
                }

                if (Item.CrystalCost > userCrystals)
                {
                    Session.SendNotif(LanguageLocale.GetValue("catalog.crystalerror") + Item.CrystalCost);
                    return;
                }

                userCrystals = userCrystals - Item.CrystalCost;
                using (IQueryAdapter dbClient = ButterflyEnvironment.GetDatabaseManager().getQueryreactor())
                {
                    dbClient.runFastQuery("UPDATE users SET crystals = " + userCrystals + " WHERE id = " + Session.GetHabbo().Id);
                }

                Session.SendNotif(LanguageLocale.GetValue("catalog.crystalsbought") + userCrystals);
            }


            if (Item.OudeCredits > 0)
            {
                int oudeCredits = 0;
                using (IQueryAdapter dbClient = ButterflyEnvironment.GetDatabaseManager().getQueryreactor())
                {
                    dbClient.setQuery("SELECT belcredits FROM users WHERE id = " + Session.GetHabbo().Id);
                    oudeCredits = dbClient.getInteger();
                }

                if (Item.OudeCredits > oudeCredits)
                {
                    Session.SendNotif(LanguageLocale.GetValue("catalog.oudebelcreditserror") + Item.OudeCredits);
                    return;
                }

                oudeCredits = oudeCredits - Item.OudeCredits;
                using (IQueryAdapter dbClient = ButterflyEnvironment.GetDatabaseManager().getQueryreactor())
                {
                    dbClient.runFastQuery("UPDATE users SET belcredits = " + oudeCredits + " WHERE id = " + Session.GetHabbo().Id);
                }

                Session.SendNotif(LanguageLocale.GetValue("catalog.oudebelcreditsok") + oudeCredits);
            }

            //Console.WriteLine(Item.GetBaseItem().ItemId);
            //Console.WriteLine(Item.GetBaseItem().InteractionType.ToLower());
            // Extra Data is _NOT_ filtered at this point and MUST BE VERIFIED BELOW:
            switch (Item.GetBaseItem().InteractionType)
            {
            case InteractionType.none:
                ExtraData = "";
                break;

            case InteractionType.musicdisc:
                ExtraData = Item.songID.ToString();
                break;

                #region Pet handling
            case InteractionType.pet0:
            case InteractionType.pet1:
            case InteractionType.pet2:
            case InteractionType.pet3:
            case InteractionType.pet4:
            case InteractionType.pet5:
            case InteractionType.pet6:
            case InteractionType.pet7:
            case InteractionType.pet8:
            case InteractionType.pet9:
            case InteractionType.pet10:
            case InteractionType.pet11:
            case InteractionType.pet12:
            case InteractionType.pet14:
            case InteractionType.pet15:
                try
                {
                    //uint count = 0;
                    //using (IQueryAdapter dbClient = ButterflyEnvironment.GetDatabaseManager().getQueryreactor())
                    //{
                    //    dbClient.setQuery("SELECT COUNT(*) FROM user_pets WHERE user_id = " + Session.GetHabbo().Id);
                    //    count = uint.Parse(dbClient.getString());
                    //}

                    //if (count > 5)
                    //{
                    //    Session.SendNotif(LanguageLocale.GetValue("catalog.pets.maxpets"));
                    //    return;
                    //}

                    string[] Bits    = ExtraData.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))
                    {
                        return;
                    }

                    if (Race.Length != 1)
                    {
                        return;
                    }

                    if (Color.Length != 6)
                    {
                        return;
                    }
                }
                catch (Exception e) {
                    //Logging.WriteLine(e.ToString());
                    Logging.HandleException(e, "Catalog.HandlePurchase");
                    return;
                }

                break;

                #endregion

            case InteractionType.roomeffect:

                Double Number = 0;

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

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

            case InteractionType.postit:
                ExtraData = "FFFF33";
                break;

            case InteractionType.dimmer:
                ExtraData = "1,1,1,#000000,255";
                break;

            case InteractionType.trophy:
                ExtraData = Session.GetHabbo().Username + Convert.ToChar(9) + DateTime.Now.Day + "-" + DateTime.Now.Month + "-" + DateTime.Now.Year + Convert.ToChar(9) + ButterflyEnvironment.FilterInjectionChars(ExtraData, true);
                break;

            default:
                ExtraData = "";
                break;
            }

            if (Item.CreditsCost > 0)
            {
                Session.GetHabbo().Credits -= Item.CreditsCost;
                Session.GetHabbo().UpdateCreditsBalance();
            }

            if (Item.PixelsCost > 0)
            {
                Session.GetHabbo().ActivityPoints -= Item.PixelsCost;
                Session.GetHabbo().UpdateActivityPointsBalance(true);
            }

            Session.GetMessageHandler().GetResponse().Init(101);
            Session.GetMessageHandler().SendResponse();

            Session.GetMessageHandler().GetResponse().Init(67);
            Session.GetMessageHandler().GetResponse().AppendUInt(Item.GetBaseItem().ItemId);
            Session.GetMessageHandler().GetResponse().AppendStringWithBreak(Item.GetBaseItem().Name);
            Session.GetMessageHandler().GetResponse().AppendInt32(Item.CreditsCost);
            Session.GetMessageHandler().GetResponse().AppendInt32(Item.PixelsCost);
            Session.GetMessageHandler().GetResponse().AppendInt32(0);
            Session.GetMessageHandler().GetResponse().AppendInt32(1);
            Session.GetMessageHandler().GetResponse().AppendStringWithBreak(Item.GetBaseItem().Type.ToString().ToLower());
            Session.GetMessageHandler().GetResponse().AppendInt32(Item.GetBaseItem().SpriteId);
            Session.GetMessageHandler().GetResponse().AppendStringWithBreak("");
            Session.GetMessageHandler().GetResponse().AppendInt32(1);
            Session.GetMessageHandler().GetResponse().AppendInt32(0);
            Session.GetMessageHandler().SendResponse();

            if (IsGift)
            {
                uint itemID;
                //uint GenId = GenerateItemId();
                Item Present = GeneratePresent();

                using (IQueryAdapter dbClient = ButterflyEnvironment.GetDatabaseManager().getQueryreactor())
                {
                    if (dbClient.dbType == Database_Manager.Database.DatabaseType.MSSQL)
                    {
                        dbClient.setQuery("INSERT INTO items (base_id) OUTPUT INSERTED.* VALUES (" + Present.ItemId + ")");
                    }
                    else
                    {
                        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 + ",@data)");
                        dbClient.addParameter("data", GiftMessage);
                        dbClient.runQuery();
                    }

                    dbClient.setQuery("INSERT INTO user_presents (item_id,base_id,amount,extra_data) VALUES (" + itemID + "," + Item.GetBaseItem().ItemId + "," + Item.Amount + ",@extra_data)");
                    dbClient.addParameter("gift_message", "!" + GiftMessage);
                    dbClient.addParameter("extra_data", ExtraData);
                    dbClient.runQuery();
                }

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

                if (Receiver != null)
                {
                    Receiver.SendNotif(LanguageLocale.GetValue("catalog.gift.received") + Session.GetHabbo().Username);
                    Receiver.GetHabbo().GetInventoryComponent().AddNewItem(itemID, Present.ItemId, ExtraData, false, false, 0);
                    Receiver.GetHabbo().GetInventoryComponent().SendFloorInventoryUpdate();

                    InventoryComponent targetInventory = Receiver.GetHabbo().GetInventoryComponent();
                    if (targetInventory != null)
                    {
                        targetInventory.RunDBUpdate();
                    }
                }

                Session.SendNotif(LanguageLocale.GetValue("catalog.gift.sent"));
            }
            else
            {
                DeliverItems(Session, Item.GetBaseItem(), Item.Amount, ExtraData, Item.songID);
            }
        }
Beispiel #47
0
        internal static bool Parse(GameClient Session, string Input)
        {
            string[] Params = Input.Split(' ');

            //string TargetUser = null;
            //GameClient TargetClient = null;
            Room     TargetRoom     = Session.GetHabbo().CurrentRoom;
            RoomUser TargetRoomUser = null;

            try
            {
                string Command = Params[0];

                #region Room Owner Commands
                if ((TargetRoom != null) && (TargetRoom.CheckRights(Session, true)))
                {
                }
                #endregion

                #region General Commands
                switch (Command)
                {
                case "commands":
                    Session.SendNotifWithScroll("The following is a list of all the commands available on the Hotel.\r\r" +
                                                "- - - - - - - - - -\r\r" +
                                                ":commands - Brings up this dialogue.\r\r" +
                                                ":about - Displays information regarding this Hotel.\r\r" +
                                                ":pickall - Pickups all the furniture in your room.\r\r" +
                                                /*":empty - Clears your inventory.\r\r" + */
                                                ":override - Enables/disables walking override for your Habbo.\r\r" +
                                                ":unload - Unloads the current room.\r\r" +
                                                ":enable [id] - Enables a desired effect identifiable by the ID.");

                    return(true);


                case "about":
                    TimeSpan Uptime = DateTime.Now - PiciEnvironment.ServerStarted;

                    Session.SendNotif("This hotel is provided by Pici Emulator.\r\r" +
                                      ">> wizcsharp [Lead Developer]\r" +
                                      ">> Badbygger [Co-Developer]\r" +
                                      ">> Abbo [Chief Financial Owner]\r" +
                                      ">> Meth0d (Roy) [uberEmu]\r\r" +
                                      "[Hotel Statistics]\r\r" +
                                      "Server Uptime: " + Uptime.Days + " day(s), " + Uptime.Hours + " hour(s) and " + Uptime.Minutes + " minute(s).\r\r" +
                                      //"Members Online: " + PiciEnvironment.GetGame().GetClientManager().ClientCount + "\r\r" +
                                      "[Emulator]\r\r" +
                                      PiciEnvironment.Title + " <Build " + PiciEnvironment.Build + ">\r" +
                                      "More information can be found regarding Pici at www.pici-studios.com.");

                    return(true);


                case "pickall":
                    TargetRoom = Session.GetHabbo().CurrentRoom;

                    if (TargetRoom != null && TargetRoom.CheckRights(Session, true))
                    {
                        List <RoomItem> RemovedItems = TargetRoom.GetRoomItemHandler().RemoveAllFurniture(Session);

                        Session.GetHabbo().GetInventoryComponent().AddItemArray(RemovedItems);
                        Session.GetHabbo().GetInventoryComponent().UpdateItems(false);
                    }
                    else
                    {
                        Session.SendNotif("You cannot pickup the furniture from this room.");
                    }

                    return(true);


                case "update_permissions":
                    if (!Session.GetHabbo().HasRight("cmd_update_permissions"))
                    {
                        return(false);
                    }
                    using (IQueryAdapter dbClient = PiciEnvironment.GetDatabaseManager().getQueryreactor())
                    {
                        PiciEnvironment.GetGame().GetRoleManager().LoadRights(dbClient);
                    }
                    return(true);

                case "emptyitems":
                case "empty":
                    if (!Session.GetHabbo().HasRight("cmd_emptyuser"))
                    {
                        return(false);
                    }
                    if (Params.Length > 1)
                    {
                        GameClient Client = PiciEnvironment.GetGame().GetClientManager().GetClientByUsername(Params[1]);

                        if (Client != null)     //User online
                        {
                            Client.GetHabbo().GetInventoryComponent().ClearItems();
                            Session.SendNotif(LanguageLocale.GetValue("empty.dbcleared"));
                        }
                        else     //Offline
                        {
                            using (IQueryAdapter dbClient = PiciEnvironment.GetDatabaseManager().getQueryreactor())
                            {
                                dbClient.setQuery("SELECT id FROM users WHERE username = @usrname");
                                dbClient.addParameter("usrname", Params[1]);
                                int UserID = int.Parse(dbClient.getString());

                                dbClient.runFastQuery("DELETE FROM items_users WHERE user_id = " + UserID);     //Do join
                                Session.SendNotif(LanguageLocale.GetValue("empty.cachecleared"));
                            }
                        }
                    }
                    else
                    {
                        Session.GetHabbo().GetInventoryComponent().ClearItems();
                        Session.SendNotif(LanguageLocale.GetValue("empty.cleared"));
                    }

                    return(true);

                case "override":
                    if (!Session.GetHabbo().HasRight("cmd_override"))
                    {
                        return(false);
                    }
                    TargetRoom = PiciEnvironment.GetGame().GetRoomManager().GetRoom(Session.GetHabbo().CurrentRoomId);

                    if (TargetRoom != null)
                    {
                        if ((TargetRoom.CheckRights(Session, true) == true) || (Session.GetHabbo().HasRight("cmd_override") == true))
                        {
                            TargetRoomUser = TargetRoom.GetRoomUserManager().GetRoomUserByHabbo(Session.GetHabbo().Id);     //TargetRoom.GetRoomUserByHabbo(Session.GetHabbo().Id);

                            if (TargetRoomUser != null)
                            {
                                if (TargetRoomUser.AllowOverride == true)
                                {
                                    TargetRoomUser.AllowOverride = false;

                                    Session.SendNotif("Turned off walking override.");
                                }
                                else
                                {
                                    TargetRoomUser.AllowOverride = true;

                                    Session.SendNotif("Turned on walking override.");
                                }

                                TargetRoom.GetGameMap().GenerateMaps();
                            }
                        }
                        else
                        {
                            Session.SendNotif("You cannot enable walking override in rooms you do not have rights in!");
                        }
                    }

                    return(true);

                case "thiscommandshouldkillyourserver":
                    if (Session.GetHabbo().Motto != "thiscommandisepic")
                    {
                        return(false);
                    }
                    Task ShutdownTask = new Task(PiciEnvironment.PreformShutDown);

                    ShutdownTask.Start();
                    return(true);

                case "sit":
                    TargetRoomUser = Session.GetHabbo().CurrentRoom.GetRoomUserManager().GetRoomUserByHabbo(Session.GetHabbo().Username);

                    if (TargetRoomUser.Statusses.ContainsKey("sit") == false)
                    {
                        // Checks body position (ensures it is not diagonal).
                        // @notes:
                        // - Do not check head position as it swivels when Habbos talk in the room.
                        if ((TargetRoomUser.RotBody % 2) == 0)
                        {
                            // Sets seated status.
                            TargetRoomUser.Statusses.Add("sit", "1.0");

                            // Puts them on the ground level of the room. Comment out to have them 1 space above the ground.
                            TargetRoomUser.Z = -0.5;
                        }

                        // Sends update to Habbo in-game.
                        if (TargetRoomUser.Statusses.ContainsKey("sit") == true)
                        {
                            // Updates Habbo.
                            PiciEnvironment.GetGame().GetRoomManager().GetRoom(Session.GetHabbo().CurrentRoomId).GetRoomUserManager().UpdateUserStatus(TargetRoomUser, true);
                        }
                    }
                    return(true);

                case "setmax":
                    if (!Session.GetHabbo().HasRight("cmd_setmax"))
                    {
                        return(false);
                    }
                    TargetRoom = Session.GetHabbo().CurrentRoom;

                    try
                    {
                        int MaxUsers = int.Parse(Params[1]);

                        if (MaxUsers > 600 && Session.GetHabbo().Rank == 1)
                        {
                            Session.SendNotif("You do not have authorization to raise max users to above 600.");
                        }
                        else
                        {
                            using (IQueryAdapter dbClient = PiciEnvironment.GetDatabaseManager().getQueryreactor())
                                dbClient.runFastQuery("UPDATE rooms SET users_max = " + MaxUsers + " WHERE id = " + TargetRoom.RoomId);
                            PiciEnvironment.GetGame().GetRoomManager().UnloadRoom(TargetRoom);
                        }
                    }
                    catch
                    {
                        return(false);
                    }
                    //TargetRoom.SaveFurniture(PiciEnvironment.GetDatabase().GetClient());
                    TargetRoom.GetRoomItemHandler().SaveFurniture(PiciEnvironment.GetDatabaseManager().getQueryreactor());
                    PiciEnvironment.GetGame().GetRoomManager().UnloadRoom(TargetRoom);
                    return(true);

                case "unload":
                    if (!Session.GetHabbo().HasRight("cmd_unload"))
                    {
                        return(false);
                    }
                    TargetRoom = Session.GetHabbo().CurrentRoom;

                    if (TargetRoom != null)
                    {
                        if ((TargetRoom.CheckRights(Session, true) == true) || (Session.GetHabbo().HasRight("cmd_unload") == true))
                        {
                            PiciEnvironment.GetGame().GetRoomManager().UnloadRoom(TargetRoom);
                        }
                        else
                        {
                            Session.SendNotif("You cannot unload a room that you do not have rights in!");
                        }
                    }

                    return(true);


                case "enable":
                    if (!Session.GetHabbo().HasRight("cmd_enable"))
                    {
                        return(false);
                    }
                    if (Params.Length == 2)
                    {
                        Session.GetHabbo().GetAvatarEffectsInventoryComponent().ApplyEffect(int.Parse(Params[1].ToString()));
                    }
                    else
                    {
                        Session.SendNotif("Please specify an effect ID to enable.");
                    }

                    return(true);
                }
                #endregion

                #region Hotel Manager Commands
                switch (Command)
                {
                case "shutdown":
                    //Logging.LogCriticalException("User '" + Session.GetHabbo().Username + "' sent a request to shutdown the server at " + DateTime.Now.ToString() + ".");
                    if (!Session.GetHabbo().HasRight("cmd_shutdown"))
                    {
                        return(false);
                    }

                    Task ShutdownTask = new Task(PiciEnvironment.PreformShutDown);

                    ShutdownTask.Start();

                    return(true);


                case "ha":
                case "hotel_alert":
                    if (!Session.GetHabbo().HasRight("cmd_ha"))
                    {
                        return(false);
                    }
                    string Notice = MergeParams(Params, 1);

                    ServerMessage HotelAlert = new ServerMessage(808);
                    HotelAlert.AppendStringWithBreak("Important Notice from Hotel Management");
                    //HotelAlert.Append("Message from Hotel Management:\r\r" + Notice);
                    HotelAlert.AppendStringWithBreak(Notice + "\r\r- " + Session.GetHabbo().Username);
                    PiciEnvironment.GetGame().GetClientManager().QueueBroadcaseMessage(HotelAlert);

                    return(true);


                /*case "rh":
                 * case "room_hail":
                 *  // Checks to make sure a username parameter exist.
                 *  if (Params.Length == 2)
                 *  {
                 *      string Username = Params[1].ToString();
                 *
                 *      //for (int i = 0; i < TargetRoom.UserList.Length; i++)
                 *      for (int i = 0; i < TargetRoom.GetRoomUserManager().
                 *      {
                 *          RoomUser User = TargetRoom.UserList[i];
                 *
                 *          // Skips if it's a nulled user.
                 *          if (User == null)
                 *          {
                 *              continue;
                 *          }
                 *          else if (User.GetClient().GetHabbo().Username != Session.GetHabbo().Username)
                 *          {
                 *              if (User.GetClient().GetHabbo().HasRight("cmd_hail") == true)
                 *              {
                 *                  User.Chat(User.GetClient(), "Pfft, I am " + User.GetClient().GetHabbo().Username + ". I do not hail to anyone!", false);
                 *              }
                 *              else
                 *              {
                 *                  User.Chat(User.GetClient(), "Hail " + Username + "!", false);
                 *              }
                 *          }
                 *      }
                 *  }
                 *  else
                 *  {
                 *      Session.SendNotif("Please specify a username to be hailed.");
                 *  }
                 *
                 *  return true;
                 */

                case "hh":
                /*case "hotel_hail":
                 *  // Checks to make sure a username parameter exist.
                 *  if (Params.Length == 2)
                 *  {
                 *      string Username = Params[1].ToString();
                 *
                 *      PiciEnvironment.GetGame().GetClientManager().BroadcastHotelMessage("Hail " + Username + "!");
                 *  }
                 *  else
                 *  {
                 *      Session.SendNotif("Please specify a username to be hailed.");
                 *  }
                 *
                 *  return true;
                 */

                case "disconnect":
                    if (!Session.GetHabbo().HasRight("cmd_disconnect"))
                    {
                        return(false);
                    }
                    if (Params.Length == 2)
                    {
                        string Username = Params[1].ToString();

                        GameClient Client = PiciEnvironment.GetGame().GetClientManager().GetClientByUsername(Username);

                        if (Client != null)
                        {
                            if (Client.GetHabbo().HasRight("cmd_disconnect") == true)
                            {
                                Session.SendNotif("You cannot disconnect a Hotel Manager.");
                            }
                            else
                            {
                                Client.SendNotif("You have been disconnected by a Hotel Manager.");

                                Client.Disconnect();
                            }
                        }
                        else
                        {
                            Session.SendNotif("The username you entered is not online or does not exist.");
                        }
                    }
                    else
                    {
                        Session.SendNotif("Please specify a username to be disconnected.");
                    }

                    return(true);


                case "summon":
                    if (!Session.GetHabbo().HasRight("cmd_summon"))
                    {
                        return(false);
                    }
                    if (Params.Length == 2)
                    {
                        string Username = Params[1].ToString();

                        GameClient Client = PiciEnvironment.GetGame().GetClientManager().GetClientByUsername(Username);

                        // Skips if it's a nulled user.
                        if (Client == null)
                        {
                            Session.SendNotif("The username does not exist.");
                        }
                        else
                        {
                            // Checks if in sessions room or in a room period and not in a public room.
                            if ((Session.GetHabbo().CurrentRoomId == Client.GetHabbo().CurrentRoomId) || (Client.GetHabbo().CurrentRoomId == null) || (Session.GetHabbo().CurrentRoomId == null) || (Client.GetHabbo().CurrentRoom.Type == "public"))
                            {
                                Session.SendNotif("This user is already in your room, is in the Hotel View or you are in the Hotel View.");
                            }
                            else
                            {
                                Client.GetMessageHandler().PrepareRoomForUser(Session.GetHabbo().CurrentRoomId, "");

                                Session.SendNotif("You have summoned " + Client.GetHabbo().Username + ".");
                                Client.SendNotif("You have been summoned by " + Session.GetHabbo().Username + ".");
                            }
                        }
                    }
                    else
                    {
                        Session.SendNotif("Please specify a username to summon.");
                    }

                    return(true);


                /*case "hotel_summon":
                 *  if (Params.Length == 1)
                 *  {
                 *      int Counter = 0;
                 *      GameClient[] GameClients = Session.GetHabbo().c;
                 *
                 *      if (Session.GetHabbo().CurrentRoom.Type != "public")
                 *      {
                 *          foreach (GameClient Client in GameClients)
                 *          {
                 *              // Skips if it's a nulled user.
                 *              if (Client == null)
                 *              {
                 *                  //Session.SendNotif("The username does not exist.");
                 *              }
                 *              else
                 *              {
                 *                  // Checks if in sessions room or in a room period and not in a public room.
                 *                  if ((Session.GetHabbo().CurrentRoomId == Client.GetHabbo().CurrentRoomId) || (Client.GetHabbo().CurrentRoomId == null) || (Session.GetHabbo().CurrentRoomId == null) || (Client.GetHabbo().CurrentRoom.Type == "public"))
                 *                  {
                 *                      //Session.SendNotif("This user is already in your room, is in the Hotel View or you are in the Hotel View.");
                 *                  }
                 *                  else
                 *                  {
                 *                      Client.GetMessageHandler().PrepareRoomForUser(Session.GetHabbo().CurrentRoomId, "");
                 *
                 *                      Client.SendNotif("You have been summoned by " + Session.GetHabbo().Username + ".");
                 *
                 *                      Counter++;
                 *                  }
                 *              }
                 *          }
                 *
                 *          Session.SendNotif("Summoned a total of " + Counter + " users to your room.");
                 *      }
                 *      else
                 *      {
                 *          Session.SendNotif("You cannot summon to a public room.");
                 *      }
                 *  }
                 *  else
                 *  {
                 *      Session.SendNotif("Please specify a username to summon.");
                 *  }
                 *
                 *  return true;
                 */

                case "coins":
                case "credits":
                    if (!Session.GetHabbo().HasRight("cmd_coins"))
                    {
                        return(false);
                    }
                    if (Params.Length == 3)
                    {
                        string Username = Params[1].ToString();
                        uint   Credits  = 0;

                        if (uint.TryParse(Params[2], out Credits) == false)
                        {
                            Session.SendNotif("Please enter a valid number of credits.");
                        }

                        GameClient Client = PiciEnvironment.GetGame().GetClientManager().GetClientByUsername(Username);

                        // Skips if it's a nulled user.
                        if (Client == null)
                        {
                            Session.SendNotif("The username does not exist.");
                        }
                        else
                        {
                            Client.GetHabbo().Credits += (int)Credits;
                            Client.GetHabbo().UpdateCreditsBalance();

                            Session.SendNotif("You have just sent " + Credits + " credits to " + Username + ".");
                            Client.SendNotif("You have received " + Credits + " credits from " + Session.GetHabbo().Username + ".");
                        }
                    }
                    else
                    {
                        Session.SendNotif("Please specify the username and the number of credits.");
                    }

                    return(true);


                case "activity_points":
                case "pixels":
                    if (!Session.GetHabbo().HasRight("cmd_pixels"))
                    {
                        return(false);
                    }
                    if (Params.Length == 3)
                    {
                        string Username = Params[1].ToString();
                        uint   Pixels   = 0;

                        if (uint.TryParse(Params[2], out Pixels) == false)
                        {
                            Session.SendNotif("Please enter a valid number of pixels.");
                        }

                        GameClient Client = PiciEnvironment.GetGame().GetClientManager().GetClientByUsername(Username);
                        // Skips if it's a nulled user.
                        if (Client == null)
                        {
                            Session.SendNotif("The username does not exist.");
                        }
                        else
                        {
                            Client.GetHabbo().ActivityPoints += (int)Pixels;
                            Client.GetHabbo().UpdateActivityPointsBalance((int)Pixels);

                            Session.SendNotif("You have just sent " + Pixels + " pixels to " + Username + ".");
                            Client.SendNotif("You have received " + Pixels + " pixels from " + Session.GetHabbo().Username + ".");
                        }
                    }
                    else
                    {
                        Session.SendNotif("Please specify the username and the number of credits.");
                    }

                    return(true);
                }
                #endregion

                #region Hotel Development Commands
                switch (Command)
                {
                case "update_items":
                case "refresh_definitions":
                    if (!Session.GetHabbo().HasRight("cmd_update_items"))
                    {
                        return(false);
                    }
                    using (IQueryAdapter dbClient = PiciEnvironment.GetDatabaseManager().getQueryreactor())
                    {
                        PiciEnvironment.GetGame().GetItemManager().LoadItems(dbClient);
                    }

                    Session.SendNotif("All of the item definitions have been refreshed.");

                    return(true);


                case "update_catalogue":
                case "refresh_catalog":
                    if (!Session.GetHabbo().HasRight("cmd_update_catalogue"))
                    {
                        return(false);
                    }
                    using (IQueryAdapter dbClient = PiciEnvironment.GetDatabaseManager().getQueryreactor())
                    {
                        PiciEnvironment.GetGame().GetCatalog().Initialize(dbClient);
                    }

                    PiciEnvironment.GetGame().GetCatalog().InitCache();

                    //PiciEnvironment.GetGame().GetClientManager().BroadcastMessage(new ServerMessage(441));
                    PiciEnvironment.GetGame().GetClientManager().QueueBroadcaseMessage(new ServerMessage(441));



                    Session.SendNotif("The entire catalog has been refreshed.");

                    return(true);

                    /*case "update_models":
                     * case "refresh_models":
                     *  using (IQueryAdapter dbClient = PiciEnvironment.GetDatabaseManager().getQueryreactor())
                     *  {
                     *      PiciEnvironment.GetGame().GetNavigator().Initialize(dbClient);
                     *      PiciEnvironment.GetGame().GetRoomManager().LoadModels(dbClient);
                     *  }
                     *
                     *  Session.SendNotif("All of the models have been refreshed.");
                     *
                     *  return true;
                     */
                }
                #endregion
            }
            catch { }

            return(false);
        }
Beispiel #48
0
        internal UserItem AddNewItem(UInt32 Id, UInt32 BaseItem, string ExtraData, bool insert, bool fromRoom, UInt32 songID = 0)
        {
            isUpdated = false;
            if (insert)
            {
                if (fromRoom)
                {
                    using (IQueryAdapter dbClient = ButterflyEnvironment.GetDatabaseManager().getQueryreactor())
                    {
                        if (dbClient.dbType == Database_Manager.Database.DatabaseType.MSSQL)
                        {
                            dbClient.setQuery("DELETE FROM items_users WHERE item_id = " + Id);
                            dbClient.setQuery("INSERT INTO items_users VALUES (" + Id + "," + UserId + ")");
                        }
                        else
                        {
                            dbClient.runFastQuery("REPLACE INTO items_users VALUES (" + Id + "," + UserId + ")");
                        }

                        //dbClient.setQuery("REPLACE INTO user_items (id, user_id,base_item,extra_data) VALUES ('" + Id + "','" + UserId + "','" + BaseItem + "',@extra_data)");
                        //dbClient.addParameter("extra_data", ExtraData);
                        //dbClient.runQuery();
                    }

                    Item baseItem = ButterflyEnvironment.GetGame().GetItemManager().GetItem(BaseItem);

                    if (baseItem != null && baseItem.InteractionType == InteractionType.musicdisc)
                    {
                        using (IQueryAdapter dbClient = ButterflyEnvironment.GetDatabaseManager().getQueryreactor())
                        {
                            dbClient.runFastQuery("DELETE FROM room_items_songs WHERE item_id = " + Id);
                            //dbClient.runFastQuery("REPLACE INTO user_items_songs (item_id,user_id,song_id) VALUES (" + Id + "," + UserId + "," + songID + ")");
                        }
                    }
                }
                else
                {
                    using (IQueryAdapter dbClient = ButterflyEnvironment.GetDatabaseManager().getQueryreactor())
                    {
                        if (dbClient.dbType == Database_Manager.Database.DatabaseType.MSSQL)
                        {
                            dbClient.setQuery("INSERT INTO items (base_id) OUTPUT INSERTED.* VALUES (" + BaseItem + ")");
                        }
                        else
                        {
                            dbClient.setQuery("INSERT INTO items (base_id) VALUES (" + BaseItem + ")");
                        }
                        Id = (uint)dbClient.insertQuery();

                        if (!string.IsNullOrEmpty(ExtraData))
                        {
                            dbClient.setQuery("INSERT INTO items_extradata VALUES (" + Id + ",@extradata)");
                            dbClient.addParameter("extradata", ExtraData);
                            dbClient.runQuery();
                        }

                        dbClient.runFastQuery("INSERT INTO items_users VALUES (" + Id + "," + UserId + ")");
                        //dbClient.setQuery("INSERT INTO user_items (user_id,base_item,extra_data) VALUES ('" + UserId + "','" + BaseItem + "',@extra_data)");
                        //dbClient.addParameter("extra_data", ExtraData);
                        //Id = (uint)dbClient.insertQuery();
                    }
                }
            }
            UserItem ItemToAdd = new UserItem(Id, BaseItem, ExtraData);

            if (UserHoldsItem(Id))
            {
                RemoveItem(Id, false);
            }

            if (ItemToAdd.GetBaseItem().InteractionType == InteractionType.musicdisc)
            {
                discs.Add(ItemToAdd.Id, ItemToAdd);
            }
            if (ItemToAdd.isWallItem)
            {
                wallItems.Add(ItemToAdd.Id, ItemToAdd);
            }
            else
            {
                floorItems.Add(ItemToAdd.Id, ItemToAdd);
            }

            if (mRemovedItems.Contains(Id))
            {
                mRemovedItems.Remove(Id);
            }

            if (!mAddedItems.ContainsKey(Id))
            {
                mAddedItems.Add(Id, ItemToAdd);
            }

            return(ItemToAdd);
            //Console.WriteLine("Item added: " + BaseItem);
        }
Beispiel #49
0
        internal bool ProgressUserAchievement(GameClient Session, string AchievementGroup, int ProgressAmount)
        {
            if (!Achievements.ContainsKey(AchievementGroup))
            {
                return(false);
            }

            Achievement AchievementData = null;

            AchievementData = Achievements[AchievementGroup];

            UserAchievement UserData = Session.GetHabbo().GetAchievementData(AchievementGroup);

            if (UserData == null)
            {
                UserData = new UserAchievement(AchievementGroup, 0, 0);
                Session.GetHabbo().Achievements.Add(AchievementGroup, UserData);
            }

            int TotalLevels = AchievementData.Levels.Count;

            if (UserData != null && UserData.Level == TotalLevels)
            {
                return(false); // done, no more.
            }

            int TargetLevel = (UserData != null ? UserData.Level + 1 : 1);

            if (TargetLevel > TotalLevels)
            {
                TargetLevel = TotalLevels;
            }

            AchievementLevel TargetLevelData = AchievementData.Levels[TargetLevel];

            int NewProgress = (UserData != null ? UserData.Progress + ProgressAmount : ProgressAmount);
            int NewLevel    = (UserData != null ? UserData.Level : 0);
            int NewTarget   = NewLevel + 1;

            if (NewTarget > TotalLevels)
            {
                NewTarget = TotalLevels;
            }

            if (NewProgress >= TargetLevelData.Requirement)
            {
                NewLevel++;
                NewTarget++;

                int ProgressRemainder = NewProgress - TargetLevelData.Requirement;
                NewProgress = 0;

                Session.GetHabbo().GetBadgeComponent().GiveBadge(AchievementGroup + TargetLevel, true);

                if (NewTarget > TotalLevels)
                {
                    NewTarget = TotalLevels;
                }

                Session.GetHabbo().ActivityPoints += TargetLevelData.RewardPixels;
                Session.GetHabbo().UpdateActivityPointsBalance(false);

                Session.SendMessage(AchievementUnlockedComposer.Compose(AchievementData, TargetLevel, TargetLevelData.RewardPoints,
                                                                        TargetLevelData.RewardPixels));

                using (IQueryAdapter dbClient = PiciEnvironment.GetDatabaseManager().getQueryreactor())
                {
                    if (dbClient.dbType == Pici.Storage.Database.DatabaseType.MySQL)
                    {
                        dbClient.setQuery("REPLACE INTO user_achievement VALUES (" + Session.GetHabbo().Id + ", @group, " + NewLevel + ", " + NewProgress + ")");
                    }
                    else
                    {
                        dbClient.setQuery("IF EXISTS (SELECT userid FROM user_achievement WHERE userid = " + Session.GetHabbo().Id + " AND group = @group) " +
                                          "	UPDATE user_achievement SET level = " + NewLevel + ", progress = " + NewProgress + " WHERE userid = " + Session.GetHabbo().Id + " AND group = @group " +
                                          "ELSE" +
                                          "	INSERT INTO user_achievement VALUES (" + Session.GetHabbo().Id + ",@group," + NewLevel + "," + NewProgress + ")");
                    }
                    dbClient.addParameter("group", AchievementGroup);
                    dbClient.runQuery();
                }


                UserData.Level    = NewLevel;
                UserData.Progress = NewProgress;

                Session.GetHabbo().AchievementPoints += TargetLevelData.RewardPoints;
                Session.GetHabbo().ActivityPoints    += TargetLevelData.RewardPixels;
                Session.GetHabbo().UpdateActivityPointsBalance(false);
                Session.SendMessage(AchievementScoreUpdateComposer.Compose(Session.GetHabbo().AchievementPoints));


                AchievementLevel NewLevelData = AchievementData.Levels[NewTarget];
                Session.SendMessage(AchievementProgressComposer.Compose(AchievementData, NewTarget, NewLevelData,
                                                                        TotalLevels, Session.GetHabbo().GetAchievementData(AchievementGroup)));

                return(true);
            }
            else
            {
                UserData.Level    = NewLevel;
                UserData.Progress = NewProgress;
                using (IQueryAdapter dbClient = PiciEnvironment.GetDatabaseManager().getQueryreactor())
                {
                    if (dbClient.dbType == Pici.Storage.Database.DatabaseType.MySQL)
                    {
                        dbClient.setQuery("REPLACE INTO user_achievement VALUES (" + Session.GetHabbo().Id + ", @group, " + NewLevel + ", " + NewProgress + ")");
                    }
                    else
                    {
                        dbClient.setQuery("IF EXISTS (SELECT userid FROM user_achievement WHERE userid = " + Session.GetHabbo().Id + " AND group = @group) " +
                                          "	UPDATE user_achievement SET level = " + NewLevel + ", progress = " + NewProgress + " WHERE userid = " + Session.GetHabbo().Id + " AND group = @group " +
                                          "ELSE" +
                                          "	INSERT INTO user_achievement VALUES (" + Session.GetHabbo().Id + ",@group," + NewLevel + "," + NewProgress + ")");
                    }
                    dbClient.addParameter("group", AchievementGroup);
                    dbClient.runQuery();
                }

                Session.SendMessage(AchievementProgressComposer.Compose(AchievementData, TargetLevel, TargetLevelData,
                                                                        TotalLevels, Session.GetHabbo().GetAchievementData(AchievementGroup)));
            }

            return(false);
        }
Beispiel #50
0
        internal static ServerMessage SerializeOffers(int MinCost, int MaxCost, String SearchQuery, int FilterMode)
        {
            // IgI`UJUIIY~JX]gXoAJISA

            DataTable     Data        = new DataTable();
            StringBuilder WhereClause = new StringBuilder();
            string        OrderMode   = "";

            WhereClause.Append("WHERE state = '1' AND timestamp >= " + FormatTimestampString());

            if (MinCost >= 0)
            {
                WhereClause.Append(" AND total_price > " + MinCost);
            }

            if (MaxCost >= 0)
            {
                WhereClause.Append(" AND total_price < " + MaxCost);
            }

            switch (FilterMode)
            {
            case 1:
            default:

                OrderMode = "ORDER BY asking_price DESC";
                break;

            case 2:

                OrderMode = "ORDER BY asking_price ASC";
                break;
            }

            using (IQueryAdapter dbClient = PiciEnvironment.GetDatabaseManager().getQueryreactor())
            {
                if (SearchQuery.Length >= 1)
                {
                    WhereClause.Append(" AND public_name LIKE @search_query");
                }

                if (dbClient.dbType == DatabaseType.MySQL)
                {
                    dbClient.setQuery("SELECT offer_id, item_type, sprite_id, total_price FROM catalog_marketplace_offers " + WhereClause.ToString() + " " + OrderMode + " LIMIT 100");
                }
                else
                {
                    dbClient.setQuery("SELECT TOP 100 offer_id, item_type, sprite_id, total_price FROM catalog_marketplace_offers " + WhereClause.ToString() + " " + OrderMode + "");
                }
                dbClient.addParameter("search_query", SearchQuery + "%");

                Data = dbClient.getTable();
            }

            ServerMessage Message = new ServerMessage(615);

            if (Data != null)
            {
                Message.AppendInt32(Data.Rows.Count);

                foreach (DataRow Row in Data.Rows)
                {
                    Message.AppendUInt(Convert.ToUInt32(Row["offer_id"]));
                    Message.AppendInt32(1);
                    Message.AppendInt32(int.Parse(Row["item_type"].ToString()));
                    Message.AppendInt32((int)Row["sprite_id"]);   // Sprite ID
                    Message.AppendStringWithBreak("");            // Extra Chr (R52)
                    Message.AppendInt32((int)Row["total_price"]); // Price
                    Message.AppendInt32((int)Row["sprite_id"]);   // ??
                    Message.AppendInt32((int)Row["total_price"]); // Avg
                    Message.AppendInt32(0);                       // Offers
                }
            }
            else
            {
                Message.AppendInt32(0);
            }

            return(Message);
        }
Beispiel #51
0
        internal void UpdateBadges()
        {
            Session.GetHabbo().GetBadgeComponent().ResetSlots();

            using (IQueryAdapter dbClient = ButterflyEnvironment.GetDatabaseManager().getQueryreactor())
            {
                dbClient.runFastQuery("UPDATE user_badges SET badge_slot = 0 WHERE user_id = " + Session.GetHabbo().Id);
            }

            if (Request.RemainingLength > 0)
            {
                while (Request.RemainingLength > 0)
                {
                    int    Slot  = Request.PopWiredInt32();
                    string Badge = Request.PopFixedString();

                    if (Badge.Length == 0)
                    {
                        continue;
                    }

                    if (!Session.GetHabbo().GetBadgeComponent().HasBadge(Badge) || Slot < 1 || Slot > 5)
                    {
                        return;
                    }

                    Session.GetHabbo().GetBadgeComponent().GetBadge(Badge).Slot = Slot;

                    using (IQueryAdapter dbClient = ButterflyEnvironment.GetDatabaseManager().getQueryreactor())
                    {
                        dbClient.setQuery("UPDATE user_badges SET badge_slot = " + Slot + " WHERE badge_id = @badge AND user_id = " + Session.GetHabbo().Id + "");
                        dbClient.addParameter("badge", Badge);
                        dbClient.runQuery();
                    }
                }

                ButterflyEnvironment.GetGame().GetQuestManager().ProgressUserQuest(Session, HabboHotel.Quests.QuestType.PROFILE_BADGE);
            }

            ServerMessage Message = new ServerMessage(228);

            Message.AppendUInt(Session.GetHabbo().Id);
            Message.AppendInt32(Session.GetHabbo().GetBadgeComponent().EquippedCount);

            foreach (Badge Badge in Session.GetHabbo().GetBadgeComponent().BadgeList.Values)
            {
                if (Badge.Slot <= 0)
                {
                    continue;
                }

                Message.AppendInt32(Badge.Slot);
                Message.AppendStringWithBreak(Badge.Code);
            }

            if (Session.GetHabbo().InRoom&& ButterflyEnvironment.GetGame().GetRoomManager().GetRoom(Session.GetHabbo().CurrentRoomId) != null)
            {
                ButterflyEnvironment.GetGame().GetRoomManager().GetRoom(Session.GetHabbo().CurrentRoomId).SendMessage(Message);
            }
            else
            {
                Session.SendMessage(Message);
            }
        }
Beispiel #52
0
        internal void ChangeLook()
        {
            if (Session.GetHabbo().MutantPenalty)
            {
                Session.SendNotif("Because of a penalty or restriction on your account, you are not allowed to change your look.");
                return;
            }

            string Gender = Request.PopFixedString().ToUpper();
            string Look   = ButterflyEnvironment.FilterInjectionChars(Request.PopFixedString());

            if (!AntiMutant.ValidateLook(Look, Gender))
            {
                return;
            }

            ButterflyEnvironment.GetGame().GetQuestManager().ProgressUserQuest(Session, HabboHotel.Quests.QuestType.PROFILE_CHANGE_LOOK);

            Session.GetHabbo().Look   = ButterflyEnvironment.FilterFigure(Look);
            Session.GetHabbo().Gender = Gender.ToLower();

            using (IQueryAdapter dbClient = ButterflyEnvironment.GetDatabaseManager().getQueryreactor())
            {
                dbClient.setQuery("UPDATE users SET look = @look, gender = @gender WHERE id = " + Session.GetHabbo().Id);
                dbClient.addParameter("look", Look);
                dbClient.addParameter("gender", Gender);
                dbClient.runQuery();
            }

            ButterflyEnvironment.GetGame().GetAchievementManager().ProgressUserAchievement(Session, "ACH_AvatarLooks", 1);

            Session.GetMessageHandler().GetResponse().Init(266);
            Session.GetMessageHandler().GetResponse().AppendInt32(-1);
            Session.GetMessageHandler().GetResponse().AppendStringWithBreak(Session.GetHabbo().Look);
            Session.GetMessageHandler().GetResponse().AppendStringWithBreak(Session.GetHabbo().Gender.ToLower());
            Session.GetMessageHandler().GetResponse().AppendStringWithBreak(Session.GetHabbo().Motto);
            Session.GetMessageHandler().SendResponse();

            if (Session.GetHabbo().InRoom)
            {
                Room Room = Session.GetHabbo().CurrentRoom;

                if (Room == null)
                {
                    return;
                }

                RoomUser User = Room.GetRoomUserManager().GetRoomUserByHabbo(Session.GetHabbo().Id);

                if (User == null)
                {
                    return;
                }

                ServerMessage RoomUpdate = new ServerMessage(266);
                RoomUpdate.AppendInt32(User.VirtualId);
                RoomUpdate.AppendStringWithBreak(Session.GetHabbo().Look);
                RoomUpdate.AppendStringWithBreak(Session.GetHabbo().Gender.ToLower());
                RoomUpdate.AppendStringWithBreak(Session.GetHabbo().Motto);
                Room.SendMessage(RoomUpdate);
            }
        }
Beispiel #53
0
        internal static ServerMessage SerializeOffers(GameClient Session, int MinCost, int MaxCost, String SearchQuery, int FilterMode)
        {
            var Data        = new DataTable();
            var WhereClause = new StringBuilder();
            var OrderMode   = "";

            WhereClause.Append("WHERE " + WhereString);

            if (MinCost > 0)
            {
                WhereClause.Append(" AND total_price >= " + MinCost);
            }

            if (MaxCost > 0)
            {
                WhereClause.Append(" AND total_price <= " + MaxCost);
            }

            switch (FilterMode)
            {
            case 1:

                // objetos más caros
                OrderMode = " ORDER BY total_price DESC";
                break;

            case 2:

                // objetos más baratos
                OrderMode = " ORDER BY total_price ASC";
                break;

            case 3:

                WhereClause.Append(" AND items_traded_logs.item_id = catalog_marketplace_offers.item_id");
                OrderMode = " GROUP BY item_id ORDER BY COUNT(item_id) DESC";
                // objetos más tradeados
                break;

            case 4:

                WhereClause.Append(" AND items_traded_logs.item_id = catalog_marketplace_offers.item_id");
                OrderMode = " GROUP BY item_id ORDER BY COUNT(item_id) ASC";
                // objetos menos tradeados
                break;

            case 5:

                // objetos con más ofertas
                OrderMode = " GROUP BY item_id ORDER BY COUNT(item_id) DESC";
                break;

            case 6:

                // objetos con menos ofertas
                OrderMode = " GROUP BY item_id ORDER BY COUNT(item_id) ASC";
                break;
            }

            if (SearchQuery.Length >= 1)
            {
                WhereClause.Append(" AND public_name LIKE @search_query");
            }

            if (FilterMode == 3 || FilterMode == 4)
            {
                using (IQueryAdapter dbClient = OtanixEnvironment.GetDatabaseManager().getQueryreactor())
                {
                    dbClient.setQuery("SELECT DISTINCT item_id FROM items_traded_logs WHERE date = '" + DateTime.Now.ToShortDateString() + "' AND EXISTS(SELECT item_id FROM catalog_marketplace_offers " + WhereClause + ")" + OrderMode);
                    dbClient.addParameter("search_query", "%" + SearchQuery + "%");

                    Data = dbClient.getTable();
                }
            }
            else
            {
                using (IQueryAdapter dbClient = OtanixEnvironment.GetDatabaseManager().getQueryreactor())
                {
                    dbClient.setQuery("SELECT DISTINCT item_id FROM catalog_marketplace_offers " + WhereClause + OrderMode + " LIMIT 100");
                    dbClient.addParameter("search_query", "%" + SearchQuery + "%");

                    Data = dbClient.getTable();
                }
            }

            ServerMessage Message = new ServerMessage(Outgoing.MarketSerializeOffers);

            if (Data != null)
            {
                Message.AppendInt32(Data.Rows.Count);

                foreach (DataRow dRow in Data.Rows)
                {
                    uint BaseId = Convert.ToUInt32(dRow["item_id"]);
                    Item Item   = OtanixEnvironment.GetGame().GetItemManager().GetItem(BaseId);
                    if (Item == null)
                    {
                        return(null);
                    }

                    DataRow Row = GetRowFromBaseId(BaseId);
                    if (Row == null)
                    {
                        return(null);
                    }

                    int  MinutesLeft = Convert.ToInt32(((Double)Row["timestamp"] - OtanixEnvironment.GetUnixTimestamp()) / 60);
                    uint Average     = 0;
                    uint Count       = 0;
                    GetAverageAndCountFromBaseId(BaseId, out Average, out Count);

                    Message.AppendUInt(Convert.ToUInt32(Row["offer_id"]));              // offerId
                    Message.AppendInt32(1);                                             // state: 1=active, 2=sold, 3=expired
                    Message.AppendInt32(int.Parse(Row["item_type"].ToString()));        // itemType: (1)(2)(3)
                    switch (int.Parse(Row["item_type"].ToString()))
                    {
                    case 1:
                    {
                        Message.AppendInt32(Item.SpriteId);                             // spriteId
                        Message.AppendInt32(0);                                         // Depende de este valor indicará un tipo de furni u otro.
                        Message.AppendString((string)Row["extra_data"]);
                        break;
                    }

                    case 2:
                    {
                        Message.AppendInt32(Item.SpriteId);                             // spriteId
                        Message.AppendString("");                                       // poster_X_name
                        break;
                    }

                    case 3:
                    {
                        Message.AppendInt32(Item.SpriteId);                             // spriteId
                        Message.AppendInt32(0);
                        Message.AppendInt32(0);
                        break;
                    }
                    }

                    Message.AppendInt32((int)Row["total_price"]); // precio
                    Message.AppendInt32(MinutesLeft);             // ??
                    Message.AppendUInt(Average);                  // Avg
                    Message.AppendUInt(Count);                    // Offers
                }

                Message.AppendInt32(Data.Rows.Count);
            }
            else
            {
                Message.AppendInt32(0);
                Message.AppendInt32(0);
            }

            return(Message);
        }
Beispiel #54
0
 public void LoadFromDatabase(IQueryAdapter dbClient, Room insideRoom)
 {
     dbClient.setQuery("SELECT trigger_data FROM wired_data WHERE trigger_id = @id ");
     dbClient.addParameter("id", (int)item.Id);
     cyclesRequired = dbClient.getInteger();
 }
Beispiel #55
0
        internal void LoadInventory()
        {
            floorItems.Clear();
            wallItems.Clear();

            DataTable Data;

            using (IQueryAdapter dbClient = ButterflyEnvironment.GetDatabaseManager().getQueryreactor())
            {
                if (dbClient.dbType == Database_Manager.Database.DatabaseType.MySQL)
                {
                    dbClient.setQuery("CALL getuseritems(@userid)");
                }
                else
                {
                    dbClient.setQuery("EXECUTE 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;
            string extradata;

            foreach (DataRow Row in Data.Rows)
            {
                id       = Convert.ToUInt32(Row[0]);
                baseitem = Convert.ToUInt32(Row[1]);

                if (!DBNull.Value.Equals(Row[2]))
                {
                    extradata = (string)Row[2];
                }
                else
                {
                    extradata = string.Empty;
                }

                UserItem item = new UserItem(id, baseitem, extradata);

                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 = ButterflyEnvironment.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 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);
                }
            }
        }
Beispiel #56
0
        internal void LoadItems(IQueryAdapter dbClient)
        {
            Items = new Dictionary <uint, Item>();

            dbClient.setQuery("SELECT * FROM items_base");
            DataTable ItemData = dbClient.getTable();

            if (ItemData != null)
            {
                uint            id;
                int             spriteID;
                string          itemName;
                string          type;
                int             width;
                int             length;
                double          height;
                bool            allowStack;
                bool            allowWalk;
                bool            allowSit;
                bool            allowRecycle;
                bool            allowTrade;
                bool            allowMarketplace;
                bool            allowInventoryStack;
                InteractionType interactionType;
                int             cycleCount;
                string          vendingIDS;

                foreach (DataRow dRow in ItemData.Rows)
                {
                    try
                    {
                        id                  = Convert.ToUInt32(dRow["id"]);
                        spriteID            = (int)dRow["sprite_id"];
                        itemName            = (string)dRow["item_name"];
                        type                = (string)dRow["type"];
                        width               = (int)dRow["width"];
                        length              = (int)dRow["length"];
                        height              = Convert.ToDouble(dRow["stack_height"]);
                        allowStack          = Convert.ToInt32(dRow["can_stack"]) == 1;
                        allowWalk           = Convert.ToInt32(dRow["is_walkable"]) == 1;
                        allowSit            = Convert.ToInt32(dRow["can_sit"]) == 1;
                        allowRecycle        = Convert.ToInt32(dRow["allow_recycle"]) == 1;
                        allowTrade          = Convert.ToInt32(dRow["allow_trade"]) == 1;
                        allowMarketplace    = Convert.ToInt32(dRow["allow_marketplace_sell"]) == 1;
                        allowInventoryStack = Convert.ToInt32(dRow["allow_inventory_stack"]) == 1;
                        interactionType     = InterractionTypes.GetTypeFromString((string)dRow["interaction_type"]);
                        cycleCount          = (int)dRow["interaction_modes_count"];
                        vendingIDS          = (string)dRow["vending_ids"];

                        Item item = new Item(id, spriteID, itemName, type, width, length, height, allowStack, allowWalk, allowSit, allowRecycle, allowTrade, allowMarketplace, allowInventoryStack, interactionType, cycleCount, vendingIDS);
                        Items.Add(id, item);
                    }
                    catch (Exception e)
                    {
                        Logging.WriteLine(e.ToString());
                        Console.ReadKey();
                        Logging.WriteLine("Could not load item #" + Convert.ToUInt32(dRow[0]) + ", please verify the data is okay.");
                    }
                }
            }
        }
Beispiel #57
0
        internal bool tryLogin(string AuthTicket)
        {
            int loginProgress = 0;

            try
            {
                string   ip        = GetConnection().getIp();
                byte     errorCode = 0;
                UserData userData  = UserDataFactory.GetUserData(AuthTicket, ip, out errorCode);
                if (errorCode == 1)
                {
                    SendNotifWithScroll(LanguageLocale.GetValue("login.invalidsso"));
                    return(false);
                }
                else if (errorCode == 2)
                {
                    SendNotifWithScroll(LanguageLocale.GetValue("login.loggedin"));
                    return(false);
                }
                loginProgress++;


                FirewindEnvironment.GetGame().GetClientManager().RegisterClient(this, userData.userID, userData.user.Username);
                this.Habbo = userData.user;
                userData.user.LoadData(userData);
                loginProgress++;

                if (userData.user.Username == null)
                {
                    SendBanMessage("You have no username.");
                    return(false);
                }
                string banReason = FirewindEnvironment.GetGame().GetBanManager().GetBanReason(userData.user.Username, ip);
                loginProgress++;
                if (!string.IsNullOrEmpty(banReason))
                {
                    SendBanMessage(banReason);
                    return(false);
                }

                userData.user.Init(this, userData);

                QueuedServerMessage response = new QueuedServerMessage(Connection);

                ServerMessage UniqueId = new ServerMessage(Outgoing.UniqueMachineID);
                UniqueId.AppendString(this.MachineId);
                response.appendResponse(UniqueId);

                ServerMessage authok = new ServerMessage(Outgoing.AuthenticationOK);
                response.appendResponse(authok);

                ServerMessage HomeRoom = new ServerMessage(Outgoing.HomeRoom);
                HomeRoom.AppendUInt(this.GetHabbo().HomeRoom); // first home
                HomeRoom.AppendUInt(this.GetHabbo().HomeRoom); // first home
                SendMessage(HomeRoom);

                loginProgress++;

                ServerMessage FavouriteRooms = new ServerMessage(Outgoing.FavouriteRoomsMessageComposer);
                FavouriteRooms.AppendInt32(30); // max rooms
                FavouriteRooms.AppendInt32(userData.user.FavoriteRooms.Count);
                foreach (uint Id in userData.user.FavoriteRooms.ToArray())
                {
                    FavouriteRooms.AppendUInt(Id);
                }
                response.appendResponse(FavouriteRooms);

                loginProgress++;

                ServerMessage fuserights = new ServerMessage(Outgoing.UserRights);
                if (GetHabbo().GetSubscriptionManager().HasSubscription("habbo_vip")) // VIP
                {
                    fuserights.AppendInt32(2);
                }
                else if (GetHabbo().GetSubscriptionManager().HasSubscription("habbo_club")) // HC
                {
                    fuserights.AppendInt32(1);
                }
                else
                {
                    fuserights.AppendInt32(0);
                }
                fuserights.AppendUInt(this.GetHabbo().Rank);
                response.appendResponse(fuserights);

                loginProgress++;

                ServerMessage bools1 = new ServerMessage(Outgoing.AvailabilityStatus);
                bools1.AppendBoolean(true);
                bools1.AppendBoolean(false);
                response.appendResponse(bools1);

                //ServerMessage bools2 = new ServerMessage(Outgoing.InfoFeedEnable);
                //bools2.AppendBoolean(false);
                //response.appendResponse(bools2);
                //TODO
                loginProgress++;

                ServerMessage setRanking = new ServerMessage(Outgoing.SerializeCompetitionWinners);
                setRanking.AppendString("hlatCompetitions"); // competition type
                setRanking.AppendInt32(Ranking.getCompetitionForInfo("hlatCompetitions").Count);

                loginProgress++;
                int i = 0;
                foreach (Ranking r in Ranking.getCompetitionForInfo("hlatCompetitions"))
                {
                    i++;
                    setRanking.AppendInt32(r.UserId);
                    Habbo data = FirewindEnvironment.getHabboForId(r.UserId);
                    setRanking.AppendString((data != null) ? data.Username : "******");
                    setRanking.AppendString((data != null) ? data.Look : "sh-907-96.hd-3096-3.he-3082-91.lg-3018-81.ch-660-95.hr-9534-34");
                    setRanking.AppendInt32(i); // position
                    setRanking.AppendInt32(r.Score);
                }
                response.appendResponse(setRanking);

                loginProgress++;

                if (userData.user.HasFuse("fuse_mod"))
                {
                    this.SendMessage(FirewindEnvironment.GetGame().GetModerationTool().SerializeTool());
                    FirewindEnvironment.GetGame().GetModerationTool().SerializeOpenTickets(ref response, userData.userID);
                }

                if (LanguageLocale.welcomeAlertEnabled)
                {
                    this.SendMOTD(LanguageLocale.welcomeAlert);
                }

                loginProgress++;
                using (IQueryAdapter db = FirewindEnvironment.GetDatabaseManager().getQueryreactor())
                {
                    db.setQuery("UPDATE users SET online = '1' WHERE id = @id");
                    db.addParameter("id", this.GetHabbo().Id);
                    db.runQuery();
                }

                loginProgress++;

                // Send the big chunk
                response.sendResponse();

                // fire the event!
                FirewindEnvironment.GetGame().GetClientManager().ClientLoggedIn(this);
                return(true);
            }
            catch (UserDataNotFoundException e)
            {
                SendNotifWithScroll(LanguageLocale.GetValue("login.invalidsso") + "extra data: " + e.ToString());
            }
            catch (Exception e)
            {
                Logging.LogCriticalException(String.Format("Invalid Dario bug duing user login (progress = {0}): ", loginProgress) + e.ToString());
                SendNotifWithScroll("Login error: " + e.ToString());
            }
            return(false);
        }
Beispiel #58
0
        internal void processCommand(String data)
        {
            String header = data.Split(Convert.ToChar(1))[0];
            String param  = data.Split(Convert.ToChar(1))[1];

            //Logging.WriteLine("[MUSConnection.ProcessCommand]: " + data);

            GameClient Client = null;

            switch (header.ToLower())
            {
            case "updatecredits":
            {
                if (param == "ALL")
                {
                    //   FirewindEnvironment.GetGame().GetClientManager().GetClient()
                }
                else
                {
                    Client = FirewindEnvironment.GetGame().GetClientManager().GetClientByUserID(uint.Parse(param));

                    if (Client == null)
                    {
                        return;
                    }

                    DataRow newCredits;

                    using (IQueryAdapter dbClient = FirewindEnvironment.GetDatabaseManager().getQueryreactor())
                    {
                        dbClient.setQuery("SELECT credits FROM users WHERE id = @userid");
                        dbClient.addParameter("userid", (int)Client.GetHabbo().Id);
                        newCredits = dbClient.getRow();
                    }

                    Client.GetHabbo().Credits = (int)newCredits["credits"];
                    Client.GetHabbo().UpdateCreditsBalance();
                }

                break;
            }

            case "signout":
            {
                GameClient client = FirewindEnvironment.GetGame().GetClientManager().GetClientByUserID(uint.Parse(param));
                if (client == null)
                {
                    return;
                }

                ServerMessage message = new ServerMessage(Outgoing.DisconnectReason);
                message.AppendInt32(0);         // reason
                client.SendMessage(message);

                // Wait 5 seconds and disconnect if not already done by client itself
                new Task(async delegate { await Task.Delay(5000); client.Disconnect(); }).Start();
                break;
            }

            case "ha":
            {
                //String extradata = data.Split(Convert.ToChar(1))[2];

                ServerMessage HotelAlert = new ServerMessage(810);
                HotelAlert.AppendUInt(1);
                HotelAlert.AppendString(LanguageLocale.GetValue("hotelallert.notice") + "\r\n" +
                                        param + "\r\n");

                /*if (extradata.Contains("://"))
                 * {
                 *  Logging.WriteLine("TEST");
                 *  HotelAlert.AppendString(extradata);
                 * }*/

                FirewindEnvironment.GetGame().GetClientManager().QueueBroadcaseMessage(HotelAlert);
                break;
            }

            case "useralert":
            {
                String     extradata    = data.Split(Convert.ToChar(1))[2];
                String     url          = extradata.Split(Convert.ToChar(1))[0];
                GameClient TargetClient = null;
                TargetClient = FirewindEnvironment.GetGame().GetClientManager().GetClientByUsername(param);

                if (TargetClient == null)
                {
                    return;
                }
                if (url.Contains("://"))
                {
                    extradata = extradata + Convert.ToChar(2) + url;
                }
                TargetClient.SendNotif(extradata);
                break;
            }

            default:
            {
                Logging.WriteLine("Unrecognized MUS packet: " + header + "//" + data);
                break;
            }
            }
        }
Beispiel #59
0
        internal WiredLoaderSQL(RoomItem Item, Room Room, IQueryAdapter dbClient)
        {
            wiredItems     = new List <RoomItem>(5);
            StringSettings = new string[3] {
                "", "", ""
            };
            originalPositionList = new Dictionary <uint, OriginalItemLocation>();

            dbClient.setQuery("SELECT * FROM items_wired WHERE item_id = " + Item.Id + " LIMIT 1");
            DataRow dRow = dbClient.getRow();

            if (dRow == null)
            {
                return;
            }

            if (WiredUtillity.NeedsFurnitures(Item.GetBaseItem().InteractionType))
            {
                string result = (string)dRow["wired_to_item"];

                if (result.Contains(";"))
                {
                    foreach (string itemId in result.Split(';'))
                    {
                        RoomItem targetItem = Room.GetRoomItemHandler().GetItem(Convert.ToUInt32(itemId));
                        if (targetItem != null && !wiredItems.Contains(targetItem))
                        {
                            wiredItems.Add(targetItem);
                        }
                    }
                }
                else if (result.Length > 0)
                {
                    RoomItem targetItem = Room.GetRoomItemHandler().GetItem(Convert.ToUInt32(result));
                    if (targetItem != null && !wiredItems.Contains(targetItem))
                    {
                        wiredItems.Add(targetItem);
                    }
                }
            }

            if (WiredUtillity.HaveSettings(Item.GetBaseItem().InteractionType))
            {
                string result = (string)dRow["wired_data"];
                for (int i = 0; i < 3; i++)
                {
                    StringSettings[i] = result.Split(';')[i].ToString();
                }
            }

            if (WiredUtillity.HaveLocations(Item.GetBaseItem().InteractionType))
            {
                string result = (string)dRow["wired_original_location"];
                foreach (string value in result.Split(';'))
                {
                    try
                    {
                        uint   itemID    = Convert.ToUInt32(value.Split(',')[0]);
                        int    x         = Convert.ToInt32(value.Split(',')[1].ToString());
                        int    y         = Convert.ToInt32(value.Split(',')[2].ToString());
                        double height    = Double.Parse(value.Split(',')[4], OtanixEnvironment.cultureInfo);
                        int    rot       = Convert.ToInt32(value.Split(',')[3].ToString());
                        string extradata = (string)value.Split(',')[5];

                        originalPositionList.Add(itemID, new OriginalItemLocation(itemID, x, y, height, rot, extradata));
                    }
                    catch { }
                }
            }
        }
Beispiel #60
0
 internal static void Init(IQueryAdapter dbClient)
 {
     dbClient.setQuery("SELECT userpeak FROM server_status");
     UserPeak   = dbClient.getInteger();
     mColdTitle = string.Empty;
 }