Exemplo n.º 1
0
        public int AvgPriceForSprite(int SpriteID)
        {
            int num  = 0;
            int num2 = 0;

            if (this.MarketAverages.ContainsKey(SpriteID) && this.MarketCounts.ContainsKey(SpriteID))
            {
                if (this.MarketCounts[SpriteID] > 0)
                {
                    return(this.MarketAverages[SpriteID] / this.MarketCounts[SpriteID]);
                }
                return(0);
            }

            using (IQueryAdapter dbClient = ButterflyEnvironment.GetDatabaseManager().GetQueryReactor())
            {
                dbClient.SetQuery("SELECT `avgprice` FROM `catalog_marketplace_data` WHERE `sprite` = '" + SpriteID + "' LIMIT 1");
                num = dbClient.GetInteger();

                dbClient.SetQuery("SELECT `sold` FROM `catalog_marketplace_data` WHERE `sprite` = '" + SpriteID + "' LIMIT 1");
                num2 = dbClient.GetInteger();
            }

            this.MarketAverages.Add(SpriteID, num);
            this.MarketCounts.Add(SpriteID, num2);

            if (num2 > 0)
            {
                return(Convert.ToInt32(Math.Ceiling((double)(num / num2))));
            }

            return(0);
        }
Exemplo n.º 2
0
        public int AvgPriceForSprite(int spriteId)
        {
            int num  = 0;
            int num2 = 0;

            if (MarketAverages.ContainsKey(spriteId) && MarketCounts.ContainsKey(spriteId))
            {
                if (MarketCounts[spriteId] > 0)
                {
                    return(MarketAverages[spriteId] / MarketCounts[spriteId]);
                }
                return(0);
            }

            using (IQueryAdapter dbClient = PlusEnvironment.GetDatabaseManager().GetQueryReactor())
            {
                dbClient.SetQuery("SELECT `avgprice` FROM `catalog_marketplace_data` WHERE `sprite` = '" + spriteId + "' LIMIT 1");
                num = dbClient.GetInteger();

                dbClient.SetQuery("SELECT `sold` FROM `catalog_marketplace_data` WHERE `sprite` = '" + spriteId + "' LIMIT 1");
                num2 = dbClient.GetInteger();
            }

            MarketAverages.Add(spriteId, num);
            MarketCounts.Add(spriteId, num2);

            if (num2 > 0)
            {
                return(Convert.ToInt32(Math.Ceiling((double)(num / num2))));
            }

            return(0);
        }
Exemplo n.º 3
0
        /// <summary>
        ///     Destroys the friendship.
        /// </summary>
        /// <param name="friendId">The friend identifier.</param>
        internal void DestroyFriendship(uint friendId)
        {
            Habbo habbo = GetClient().GetHabbo();

            Habbo habboFriend = Yupi.GetHabboById(friendId);

            if (habbo != null && habboFriend != null)
            {
                using (IQueryAdapter queryReactor = Yupi.GetDatabaseManager().GetQueryReactor())
                {
                    queryReactor.RunFastQuery(string.Concat("DELETE FROM messenger_friendships WHERE (user_one_id = ", habbo.Id, " AND user_two_id = ", habboFriend.Id, ")"));

                    queryReactor.RunFastQuery(string.Concat("SELECT id FROM users_relationships WHERE user_id = ", habbo.Id, " AND target = ", habboFriend.Id, " LIMIT 1"));

                    object integerResultUser = queryReactor.GetInteger();

                    int idUser;

                    int.TryParse(integerResultUser.ToString(), out idUser);

                    if (idUser > 0 && habbo.Relationships.ContainsKey(idUser))
                    {
                        queryReactor.RunFastQuery(string.Concat("DELETE FROM users_relationships WHERE (user_id = ", habbo.Id, " AND target = ", habboFriend.Id, ")"));

                        if (habbo.Relationships.ContainsKey(idUser))
                        {
                            habbo.Relationships.Remove(idUser);
                        }
                    }

                    queryReactor.RunFastQuery(string.Concat("DELETE FROM messenger_friendships WHERE (user_one_id = ", habboFriend.Id, " AND user_two_id = ", habbo.Id, ")"));

                    queryReactor.RunFastQuery(string.Concat("SELECT id FROM users_relationships WHERE user_id = ", habboFriend.Id, " AND target = ", habbo.Id, " LIMIT 1"));

                    object integerResultFriend = queryReactor.GetInteger();

                    int idFriend;

                    int.TryParse(integerResultFriend.ToString(), out idFriend);

                    if (idFriend > 0 && habboFriend.Relationships.ContainsKey(idFriend))
                    {
                        queryReactor.RunFastQuery(string.Concat("DELETE FROM users_relationships WHERE (user_id = ", habboFriend.Id, " AND target = ", habbo.Id, ")"));

                        if (habboFriend.Relationships.ContainsKey(idFriend))
                        {
                            habboFriend.Relationships.Remove(idFriend);
                        }
                    }
                }

                OnDestroyFriendship(habboFriend.Id);

                habboFriend.GetMessenger().OnDestroyFriendship(habbo.Id);
            }
        }
Exemplo n.º 4
0
        public bool TryExecute(string[] parameters)
        {
            if (!int.TryParse(parameters[0], out int userId))
            {
                return(false);
            }

            GameClient client = PlusEnvironment.GetGame().GetClientManager().GetClientByUserId(userId);

            if (client == null || client.Habbo == null)
            {
                return(false);
            }

            using (IQueryAdapter dbClient = PlusEnvironment.GetDatabaseManager().GetQueryReactor())
            {
                dbClient.SetQuery("SELECT `rank` FROM `users` WHERE `id` = @userId LIMIT 1");
                dbClient.AddParameter("userId", userId);
                client.Habbo.Rank = dbClient.GetInteger();
            }

            client.Habbo.GetPermissions().Init(client.Habbo);

            if (client.Habbo.GetPermissions().HasRight("mod_tickets"))
            {
                client.SendPacket(new ModeratorInitComposer(
                                      PlusEnvironment.GetGame().GetModerationManager().UserMessagePresets,
                                      PlusEnvironment.GetGame().GetModerationManager().RoomMessagePresets,
                                      PlusEnvironment.GetGame().GetModerationManager().GetTickets));
            }
            return(true);
        }
Exemplo n.º 5
0
        internal void ToggleStaffPick()
        {
            uint roomId  = Request.GetUInteger();
            bool current = Request.GetBool();
            Room room    = Yupi.GetGame().GetRoomManager().GetRoom(roomId);

            Yupi.GetGame().GetAchievementManager().ProgressUserAchievement(Session, "ACH_Spr", 1, true);
            if (room == null)
            {
                return;
            }
            using (IQueryAdapter queryReactor = Yupi.GetDatabaseManager().GetQueryReactor())
            {
                PublicItem pubItem = Yupi.GetGame().GetNavigator().GetPublicItem(roomId);
                if (pubItem == null) // not picked
                {
                    queryReactor.SetQuery("INSERT INTO navigator_publics (bannertype, room_id, category_parent_id) VALUES ('0', @roomId, '-2')");
                    queryReactor.AddParameter("roomId", room.RoomId);
                    queryReactor.RunQuery();
                    queryReactor.RunFastQuery("SELECT last_insert_id()");
                    uint       publicItemId = (uint)queryReactor.GetInteger();
                    PublicItem publicItem   = new PublicItem(publicItemId, 0, string.Empty, string.Empty, string.Empty, PublicImageType.Internal, room.RoomId, 0, -2, false, 1, string.Empty);
                    Yupi.GetGame().GetNavigator().AddPublicItem(publicItem);
                }
                else // picked
                {
                    queryReactor.SetQuery("DELETE FROM navigator_publics WHERE id = @pubId");
                    queryReactor.AddParameter("pubId", pubItem.Id);
                    queryReactor.RunQuery();
                    Yupi.GetGame().GetNavigator().RemovePublicItem(pubItem.Id);
                }
                room.RoomData.SerializeRoomData(Response, Session, false, true);
                Yupi.GetGame().GetNavigator().LoadNewPublicRooms();
            }
        }
Exemplo n.º 6
0
 /// <summary>
 ///     Initializes the specified database client.
 /// </summary>
 /// <param name="dbClient">The database client.</param>
 internal static void Init(IQueryAdapter dbClient)
 {
     dbClient.SetQuery("SELECT userpeak FROM server_status");
     _userPeak = dbClient.GetInteger();
     _lowPriorityStopWatch = new Stopwatch();
     _lowPriorityStopWatch.Start();
 }
Exemplo n.º 7
0
        public void Parse(GameClient session, ClientPacket packet)
        {
            int userId = packet.PopInt();

            packet.PopBoolean(); //IsMe?

            Habbo targetData = PlusEnvironment.GetHabboById(userId);

            if (targetData == null)
            {
                session.SendNotification("An error occured whilst finding that user's profile.");
                return;
            }

            List <Group> groups = PlusEnvironment.GetGame().GetGroupManager().GetGroupsForUser(targetData.Id);

            int friendCount;

            using (IQueryAdapter dbClient = PlusEnvironment.GetDatabaseManager().GetQueryReactor())
            {
                dbClient.SetQuery("SELECT COUNT(0) FROM `messenger_friendships` WHERE (`user_one_id` = @userid OR `user_two_id` = @userid)");
                dbClient.AddParameter("userid", userId);
                friendCount = dbClient.GetInteger();
            }

            session.SendPacket(new ProfileInformationComposer(targetData, session, groups, friendCount));
        }
Exemplo n.º 8
0
        public void Parse(GameClient Session, ClientPacket Packet)
        {
            int     userID = Packet.PopInt();
            Boolean IsMe   = Packet.PopBoolean();

            Habbo targetData = ButterflyEnvironment.GetHabboById(userID);

            if (targetData == null)
            {
                return;
            }

            List <Group> Groups = ButterflyEnvironment.GetGame().GetGroupManager().GetGroupsForUser(targetData.MyGroups);

            int friendCount = 0;

            if (targetData.GetMessenger() != null)
            {
                friendCount = targetData.GetMessenger().Count;
            }
            else
            {
                using (IQueryAdapter dbClient = ButterflyEnvironment.GetDatabaseManager().GetQueryReactor())
                {
                    dbClient.SetQuery("SELECT COUNT(0) FROM `messenger_friendships` WHERE (`user_one_id` = @userid);");
                    dbClient.AddParameter("userid", userID);
                    friendCount = dbClient.GetInteger();
                }
            }

            Session.SendPacket(new ProfileInformationComposer(targetData, Session, Groups, friendCount));
        }
        public bool TryExecute(string[] parameters)
        {
            int userId = 0;

            if (!int.TryParse(parameters[0].ToString(), out userId))
            {
                return(false);
            }

            GameClient client = PlusEnvironment.GetGame().GetClientManager().GetClientByUserID(userId);

            if (client == null || client.GetHabbo() == null)
            {
                return(false);
            }

            using (IQueryAdapter dbClient = PlusEnvironment.GetDatabaseManager().GetQueryReactor())
            {
                dbClient.SetQuery("SELECT `rank_vip` FROM `users` WHERE `id` = @userId LIMIT 1");
                dbClient.AddParameter("userId", userId);
                client.GetHabbo().VIPRank = dbClient.GetInteger();
            }

            client.GetHabbo().GetPermissions().Init(client.GetHabbo());
            return(true);
        }
Exemplo n.º 10
0
Arquivo: Yupi.cs Projeto: dm5wg/Yupi
        /// <summary>
        ///     Get a Habbo With the Habbo's Username
        /// </summary>
        /// <param name="userName">Name of the user.</param>
        /// <returns>Habbo.</returns>
        /// Table: users.username
        internal static Habbo GetHabboForName(string userName)
        {
            try
            {
                using (IQueryAdapter commitableQueryReactor = GetDatabaseManager().GetQueryReactor())
                {
                    commitableQueryReactor.SetQuery("SELECT id FROM users WHERE username = @user");

                    commitableQueryReactor.AddParameter("user", userName);

                    int integer = commitableQueryReactor.GetInteger();

                    if (integer > 0)
                    {
                        Habbo result = GetHabboById((uint)integer);

                        return(result);
                    }
                }
            }
            catch (Exception)
            {
                // ignored
            }
            return(null);
        }
Exemplo n.º 11
0
        /// <summary>
        /// Initializes the specified database client.
        /// </summary>
        /// <param name="dbClient">The database client.</param>
        internal static void Init(IQueryAdapter dbClient)
        {
            dbClient.SetQuery("SELECT `userpeak` FROM `server_status`");
            _userPeak = dbClient.GetInteger();

            lowPriorityProcessWatch = new Stopwatch();
            lowPriorityProcessWatch.Start();
        }
Exemplo n.º 12
0
        /// <summary>
        ///     Initializes the specified database client.
        /// </summary>
        /// <param name="dbClient">The database client.</param>
        internal static void Init(IQueryAdapter dbClient)
        {
            dbClient.SetQuery("SELECT userpeak FROM server_status");

            _userPeak = dbClient.GetInteger();

            _lowPriorityStopWatch = new Stopwatch();
            _lowPriorityStopWatch.Start();
        }
Exemplo n.º 13
0
        /// <summary>
        /// Initializes the specified database client.
        /// </summary>
        /// <param name="dbClient">The database client.</param>
        internal static void Init(IQueryAdapter dbClient)
        {
            dbClient.SetQuery("SELECT userpeak FROM server_status");
            _userPeak = dbClient.GetInteger();

            lowPriorityProcessWatch = new Stopwatch();
            consoleTitleWorkerWatch = new Stopwatch();
            lowPriorityProcessWatch.Start();
            consoleTitleWorkerWatch.Start();
        }
Exemplo n.º 14
0
 public static int GetAHopper(int CurRoom)
 {
     using (IQueryAdapter dbClient = PlusEnvironment.GetDatabaseManager().GetQueryReactor())
     {
         int RoomId = 0;
         dbClient.SetQuery("SELECT room_id FROM items_hopper WHERE room_id <> @room ORDER BY room_id ASC LIMIT 1");
         dbClient.AddParameter("room", CurRoom);
         RoomId = dbClient.GetInteger();
         return(RoomId);
     }
 }
Exemplo n.º 15
0
        /// <summary>
        ///     Initializes the specified database client.
        /// </summary>
        internal static void Load()
        {
            using (IQueryAdapter queryReactor = Yupi.GetDatabaseManager().GetQueryReactor())
            {
                queryReactor.SetQuery("SELECT userpeak FROM server_status");

                _userPeak = queryReactor.GetInteger();

                _lowPriorityStopWatch = new Stopwatch();
                _lowPriorityStopWatch.Start();
            }
        }
Exemplo n.º 16
0
        public static void Init()
        {
            using (IQueryAdapter dbClient = ButterflyEnvironment.GetDatabaseManager().GetQueryReactor())
            {
                dbClient.SetQuery("SELECT userpeak FROM server_status");
                UserPeak = dbClient.GetInteger();
            }
            mColdTitle = string.Empty;

            lowPriorityProcessWatch = new Stopwatch();
            lowPriorityProcessWatch.Start();
        }
Exemplo n.º 17
0
Arquivo: Others.cs Projeto: sgf/Yupi
        /// <summary>
        /// Gets the friends count.
        /// </summary>
        /// <param name="userId">The user identifier.</param>
        /// <returns>System.Int32.</returns>
        private static int GetFriendsCount(uint userId)
        {
            int result;

            using (IQueryAdapter queryReactor = Yupi.GetDatabaseManager().GetQueryReactor())
            {
                queryReactor.SetQuery("SELECT COUNT(*) FROM messenger_friendships WHERE user_one_id = @id OR user_two_id = @id;");
                queryReactor.AddParameter("id", userId);

                result = queryReactor.GetInteger();
            }

            return(result);
        }
Exemplo n.º 18
0
        /// <summary>
        ///     Gets a hopper.
        /// </summary>
        /// <param name="curRoom">The current room.</param>
        /// <returns>System.UInt32.</returns>
        internal static uint GetAHopper(uint curRoom)
        {
            uint result;

            using (IQueryAdapter queryReactor = Yupi.GetDatabaseManager().GetQueryReactor())
            {
                queryReactor.SetQuery(
                    $"SELECT room_id FROM items_hopper WHERE room_id <> '{curRoom}' ORDER BY RAND() LIMIT 1");

                uint num = Convert.ToUInt32(queryReactor.GetInteger());
                result = num;
            }

            return(result);
        }
Exemplo n.º 19
0
        public MarketPlaceOwnOffersComposer(int UserId)
            : base(ServerPacketHeader.MarketPlaceOwnOffersMessageComposer)
        {
            int       i     = 0;
            DataTable table = null;

            using (IQueryAdapter dbClient = PlusEnvironment.GetDatabaseManager().GetQueryReactor())
            {
                dbClient.SetQuery("SELECT timestamp, state, offer_id, item_type, sprite_id, total_price, limited_number, limited_stack FROM catalog_marketplace_offers WHERE user_id = '" + UserId + "'");
                table = dbClient.GetTable();

                dbClient.SetQuery("SELECT SUM(asking_price) FROM catalog_marketplace_offers WHERE state = '2' AND user_id = '" + UserId + "'");
                i = dbClient.GetInteger();

                base.WriteInteger(i);
                if (table != null)
                {
                    base.WriteInteger(table.Rows.Count);
                    foreach (DataRow row in table.Rows)
                    {
                        int num2 = Convert.ToInt32(Math.Floor((double)(((((double)row["timestamp"]) + 172800.0) - PlusEnvironment.GetUnixTimestamp()) / 60.0)));
                        int num3 = int.Parse(row["state"].ToString());
                        if ((num2 <= 0) && (num3 != 2))
                        {
                            num3 = 3;
                            num2 = 0;
                        }
                        base.WriteInteger(Convert.ToInt32(row["offer_id"]));
                        base.WriteInteger(num3);
                        base.WriteInteger(1);
                        base.WriteInteger(Convert.ToInt32(row["sprite_id"]));

                        base.WriteInteger(256);
                        base.WriteString("");
                        base.WriteInteger(Convert.ToInt32(row["limited_number"]));
                        base.WriteInteger(Convert.ToInt32(row["limited_stack"]));

                        base.WriteInteger(Convert.ToInt32(row["total_price"]));
                        base.WriteInteger(num2);
                        base.WriteInteger(Convert.ToInt32(row["sprite_id"]));
                    }
                }
                else
                {
                    base.WriteInteger(0);
                }
            }
        }
Exemplo n.º 20
0
        public static bool usernameExists(string username)
        {
            int integer;

            using (IQueryAdapter queryreactor = GetDatabaseManager().GetQueryReactor())
            {
                queryreactor.SetQuery("SELECT id FROM users WHERE username = @username LIMIT 1");
                queryreactor.AddParameter("username", username);
                integer = queryreactor.GetInteger();
            }
            if (integer <= 0)
            {
                return(false);
            }

            return(true);
        }
Exemplo n.º 21
0
 public static Habbo GetHabboByUsername(String UserName)
 {
     try
     {
         using (IQueryAdapter dbClient = GetDatabaseManager().GetQueryReactor())
         {
             dbClient.SetQuery("SELECT `id` FROM `users` WHERE `username` = @user LIMIT 1");
             dbClient.AddParameter("user", UserName);
             int id = dbClient.GetInteger();
             if (id > 0)
             {
                 return(GetHabboById(Convert.ToInt32(id)));
             }
         }
         return(null);
     }
     catch { return(null); }
 }
Exemplo n.º 22
0
        /// <summary>
        ///     Destroys the friendship.
        /// </summary>
        /// <param name="friendId">The friend identifier.</param>
        internal void DestroyFriendship(uint friendId)
        {
            Habbo habbo = GetClient().GetHabbo();

            using (IQueryAdapter commitableQueryReactor = Yupi.GetDatabaseManager().GetQueryReactor())
            {
                commitableQueryReactor.RunFastQuery(
                    string.Concat("DELETE FROM messenger_friendships WHERE (user_one_id = ", _userId,
                                  " AND user_two_id = ", friendId, ") OR (user_two_id = ", _userId, " AND user_one_id = ",
                                  friendId, ")"));

                commitableQueryReactor.RunFastQuery(string.Concat("SELECT id FROM users_relationships WHERE user_id=",
                                                                  habbo.Id, " AND target = ", friendId, " LIMIT 1"));

                int id = commitableQueryReactor.GetInteger();

                commitableQueryReactor.RunFastQuery(string.Concat("DELETE FROM users_relationships WHERE (user_id = ",
                                                                  habbo.Id, " AND target = ", friendId, ")"));

                if (id > 0)
                {
                    if (habbo.Relationships.ContainsKey(id))
                    {
                        habbo.Relationships.Remove(id);
                    }
                }
            }

            OnDestroyFriendship(friendId);

            GameClient clientRelationship = Yupi.GetGame().GetClientManager().GetClientByUserId(friendId);

            if (clientRelationship?.GetHabbo().GetMessenger() != null)
            {
                clientRelationship.GetHabbo().GetMessenger().OnDestroyFriendship(_userId);

                if (clientRelationship.GetHabbo().Relationships.ContainsKey((int)friendId))
                {
                    clientRelationship.GetHabbo().Relationships.Remove((int)friendId);
                }
            }
        }
Exemplo n.º 23
0
        public void Parse(HabboHotel.GameClients.GameClient Session, ClientPacket Packet)
        {
            bool   InUse = false;
            string Name  = Packet.PopString();

            using (IQueryAdapter dbClient = PlusEnvironment.GetDatabaseManager().GetQueryReactor())
            {
                dbClient.SetQuery("SELECT COUNT(0) FROM `users` WHERE `username` = @name LIMIT 1");
                dbClient.AddParameter("name", Name);
                InUse = dbClient.GetInteger() == 1;
            }

            char[] Letters           = Name.ToLower().ToCharArray();
            string AllowedCharacters = "abcdefghijklmnopqrstuvwxyz.,_-;:?!1234567890";

            foreach (char Chr in Letters)
            {
                if (!AllowedCharacters.Contains(Chr))
                {
                    Session.SendPacket(new NameChangeUpdateComposer(Name, 4));
                    return;
                }
            }

            if (PlusEnvironment.GetGame().GetChatManager().GetFilter().IsFiltered(Name))
            {
                Session.SendPacket(new NameChangeUpdateComposer(Name, 4));
                return;
            }

            if (!Session.GetHabbo().GetPermissions().HasRight("mod_tool") && Name.ToLower().Contains("mod") || Name.ToLower().Contains("adm") || Name.ToLower().Contains("admin") || Name.ToLower().Contains("m0d"))
            {
                Session.SendPacket(new NameChangeUpdateComposer(Name, 4));
                return;
            }
            else if (!Name.ToLower().Contains("mod") && (Session.GetHabbo().Rank == 2 || Session.GetHabbo().Rank == 3))
            {
                Session.SendPacket(new NameChangeUpdateComposer(Name, 4));
                return;
            }
            else if (Name.Length > 15)
            {
                Session.SendPacket(new NameChangeUpdateComposer(Name, 3));
                return;
            }
            else if (Name.Length < 3)
            {
                Session.SendPacket(new NameChangeUpdateComposer(Name, 2));
                return;
            }
            else if (InUse)
            {
                ICollection <string> Suggestions = new List <string>();
                for (int i = 100; i < 103; i++)
                {
                    Suggestions.Add(i.ToString());
                }

                Session.SendPacket(new NameChangeUpdateComposer(Name, 5, Suggestions));
                return;
            }
            else
            {
                Session.SendPacket(new NameChangeUpdateComposer(Name, 0));
                return;
            }
        }
Exemplo n.º 24
0
        /// <summary>
        ///     Tries the login.
        /// </summary>
        /// <param name="authTicket">The authentication ticket.</param>
        /// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns>
        internal bool TryLogin(string authTicket)
        {
            try
            {
                string ip = GetConnection().GetIp();

                uint errorCode;

                UserData userData = UserDataFactory.GetUserData(authTicket, out errorCode);

                if (errorCode == 1 || errorCode == 2)
                {
                    return(false);
                }

                Yupi.GetGame().GetClientManager().RegisterClient(this, userData.UserId, userData.User.UserName);

                _habbo = userData.User;
                userData.User.LoadData(userData);

                string banReason = Yupi.GetGame().GetBanManager().GetBanReason(userData.User.UserName, ip, MachineId);

                if (!string.IsNullOrEmpty(banReason) || userData.User.UserName == null)
                {
                    SendNotifWithScroll(banReason);
                    using (IQueryAdapter queryReactor = Yupi.GetDatabaseManager().GetQueryReactor())
                    {
                        queryReactor.SetQuery($"SELECT ip_last FROM users WHERE id={GetHabbo().Id} LIMIT 1");

                        string supaString = queryReactor.GetString();

                        queryReactor.SetQuery($"SELECT COUNT(0) FROM users_bans_access WHERE user_id={_habbo.Id} LIMIT 1");
                        int integer = queryReactor.GetInteger();

                        if (integer > 0)
                        {
                            queryReactor.RunFastQuery("UPDATE users_bans_access SET attempts = attempts + 1, ip='" + supaString + "' WHERE user_id=" + GetHabbo().Id + " LIMIT 1");
                        }
                        else
                        {
                            queryReactor.RunFastQuery("INSERT INTO users_bans_access (user_id, ip) VALUES (" + GetHabbo().Id + ", '" + supaString + "')");
                        }
                    }

                    return(false);
                }

                using (IQueryAdapter queryReactor = Yupi.GetDatabaseManager().GetQueryReactor())
                    queryReactor.RunFastQuery($"UPDATE users SET ip_last='{ip}' WHERE id={GetHabbo().Id}");

                userData.User.Init(this, userData);

                QueuedServerMessage queuedServerMessage = new QueuedServerMessage(_connection);

                ServerMessage serverMessage = new ServerMessage(LibraryParser.OutgoingRequest("UniqueMachineIDMessageComposer"));

                serverMessage.AppendString(MachineId);
                queuedServerMessage.AppendResponse(serverMessage);

                queuedServerMessage.AppendResponse(new ServerMessage(LibraryParser.OutgoingRequest("AuthenticationOKMessageComposer")));

                ServerMessage serverMessage2 = new ServerMessage(LibraryParser.OutgoingRequest("HomeRoomMessageComposer"));

                serverMessage2.AppendInteger(_habbo.HomeRoom);
                serverMessage2.AppendInteger(_habbo.HomeRoom);
                queuedServerMessage.AppendResponse(serverMessage2);

                serverMessage = new ServerMessage(LibraryParser.OutgoingRequest("MinimailCountMessageComposer"));

                serverMessage.AppendInteger(_habbo.MinimailUnreadMessages);
                queuedServerMessage.AppendResponse(serverMessage);

                serverMessage = new ServerMessage(LibraryParser.OutgoingRequest("FavouriteRoomsMessageComposer"));

                serverMessage.AppendInteger(30);

                if (userData.User.FavoriteRooms == null || !userData.User.FavoriteRooms.Any())
                {
                    serverMessage.AppendInteger(0);
                }
                else
                {
                    serverMessage.AppendInteger(userData.User.FavoriteRooms.Count);

                    foreach (uint i in userData.User.FavoriteRooms)
                    {
                        serverMessage.AppendInteger(i);
                    }
                }

                queuedServerMessage.AppendResponse(serverMessage);

                ServerMessage rightsMessage = new ServerMessage(LibraryParser.OutgoingRequest("UserClubRightsMessageComposer"));

                rightsMessage.AppendInteger(userData.User.GetSubscriptionManager().HasSubscription ? 2 : 0);
                rightsMessage.AppendInteger(userData.User.Rank);
                rightsMessage.AppendInteger(0);
                queuedServerMessage.AppendResponse(rightsMessage);

                serverMessage = new ServerMessage(LibraryParser.OutgoingRequest("EnableNotificationsMessageComposer"));
                serverMessage.AppendBool(true); //isOpen
                serverMessage.AppendBool(false);
                queuedServerMessage.AppendResponse(serverMessage);

                serverMessage = new ServerMessage(LibraryParser.OutgoingRequest("EnableTradingMessageComposer"));
                serverMessage.AppendBool(true);
                queuedServerMessage.AppendResponse(serverMessage);
                userData.User.UpdateCreditsBalance();

                serverMessage = new ServerMessage(LibraryParser.OutgoingRequest("ActivityPointsMessageComposer"));
                serverMessage.AppendInteger(2);
                serverMessage.AppendInteger(0);
                serverMessage.AppendInteger(userData.User.ActivityPoints);
                serverMessage.AppendInteger(5);
                serverMessage.AppendInteger(userData.User.Diamonds);
                queuedServerMessage.AppendResponse(serverMessage);

                if (userData.User.HasFuse("fuse_mod"))
                {
                    queuedServerMessage.AppendResponse(Yupi.GetGame().GetModerationTool().SerializeTool(this));
                }

                queuedServerMessage.AppendResponse(Yupi.GetGame().GetAchievementManager().AchievementDataCached);

                if (!GetHabbo().NuxPassed&& ServerExtraSettings.NewUsersGiftsEnabled)
                {
                    queuedServerMessage.AppendResponse(new ServerMessage(LibraryParser.OutgoingRequest("NuxSuggestFreeGiftsMessageComposer")));
                }

                queuedServerMessage.AppendResponse(GetHabbo().GetAvatarEffectsInventoryComponent().GetPacket());
                queuedServerMessage.SendResponse();

                Yupi.GetGame().GetAchievementManager().TryProgressHabboClubAchievements(this);
                Yupi.GetGame().GetAchievementManager().TryProgressRegistrationAchievements(this);
                Yupi.GetGame().GetAchievementManager().TryProgressLoginAchievements(this);

                return(true);
            }
            catch (Exception ex)
            {
                ServerLogManager.LogCriticalException($"Bug during user login: {ex}");
            }

            return(false);
        }
Exemplo n.º 25
0
        /// <summary>
        ///     Gets the user data.
        /// </summary>
        /// <param name="sessionTicket">The session ticket.</param>
        /// <param name="errorCode">The error code.</param>
        /// <returns>UserData.</returns>
        internal static UserData GetUserData(string sessionTicket, out uint errorCode)
        {
            errorCode = 1;

            DataTable groupsTable;
            DataRow   dataRow;
            DataTable achievementsTable;
            DataTable talentsTable;
            DataRow   statsTable;
            DataTable favoritesTable;
            DataTable ignoresTable;
            DataTable tagsTable;
            DataRow   subscriptionsRow;
            DataTable badgesTable;
            DataTable itemsTable;
            DataTable effectsTable;
            DataTable pollsTable;
            DataTable friendsTable;
            DataTable friendsRequestsTable;

            DataTable relationShipsTable;
            DataTable botsTable;
            DataTable questsTable;
            DataTable petsTable;

            DataTable myRoomsTable;

            uint   userId;
            string userName, userLook;

            using (IQueryAdapter commitableQueryReactor = Yupi.GetDatabaseManager().GetQueryReactor())
            {
                commitableQueryReactor.SetQuery("SELECT COUNT(auth_ticket) FROM users WHERE auth_ticket = @ticket");
                commitableQueryReactor.AddParameter("ticket", sessionTicket);

                if (commitableQueryReactor.GetInteger() == 0)
                {
                    Writer.WriteLine("The SSO key " + sessionTicket + " isn't attached to any User.", "Yupi.SSO",
                                     ConsoleColor.DarkRed);
                    Writer.WriteLine("Check if your CMS has the same SSO as in your Database.", "Yupi.SSO",
                                     ConsoleColor.DarkRed);
                    Writer.WriteLine("You can also check if is a valid SSO and not DDoS.", "Yupi.SSO",
                                     ConsoleColor.DarkRed);
                    return(null);
                }

                // Get User Data
                commitableQueryReactor.SetQuery("SELECT * FROM users WHERE auth_ticket = @ticket");

                // Execute User Data Query
                commitableQueryReactor.AddParameter("ticket", sessionTicket);
                dataRow = commitableQueryReactor.GetRow();

                if (dataRow == null)
                {
                    return(null);
                }

                userId   = (uint)dataRow["id"];
                userName = dataRow["username"].ToString();
                userLook = dataRow["look"].ToString();

                int regDate = (int)dataRow["account_created"] == 0
                    ? Yupi.GetUnixTimeStamp()
                    : (int)dataRow["account_created"];

                // Check Register Date
                if ((int)dataRow["account_created"] == 0)
                {
                    commitableQueryReactor.RunFastQuery(
                        $"UPDATE users SET account_created = {regDate} WHERE id = {userId}");
                }

                // Disconnect if user Already Logged-in, Doesn't need check. If user isn't logged, nothing will happen.
                if (Yupi.GetGame().GetClientManager().GetClientByUserId(userId) != null)
                {
                    Yupi.GetGame()
                    .GetClientManager()
                    .GetClientByUserId(userId)?
                    .Disconnect("User connected in other place");
                }

                // Update User statusses
                commitableQueryReactor.RunFastQuery($"UPDATE users SET online = 1 WHERE id = {userId};" +
                                                    $"REPLACE INTO users_info(user_id, login_timestamp) VALUES({userId}, '{Yupi.GetUnixTimeStamp()}');");

                commitableQueryReactor.RunFastQuery($"SELECT COUNT(id) FROM users_stats WHERE id = {userId}");

                if (commitableQueryReactor.GetInteger() == 0)
                {
                    commitableQueryReactor.RunFastQuery($"INSERT INTO users_stats (id) VALUES ({userId});");
                }

                // Get User Achievements Data
                commitableQueryReactor.SetQuery($"SELECT * FROM users_achievements WHERE user_id = {userId}");
                achievementsTable = commitableQueryReactor.GetTable();

                // Get User Talent Data
                commitableQueryReactor.SetQuery($"SELECT * FROM users_talents WHERE userid = {userId}");
                talentsTable = commitableQueryReactor.GetTable();

                // Get User Favorite Room
                commitableQueryReactor.SetQuery($"SELECT room_id FROM users_favorites WHERE user_id = {userId}");
                favoritesTable = commitableQueryReactor.GetTable();

                // Get User Ignored Users
                commitableQueryReactor.SetQuery($"SELECT ignore_id FROM users_ignores WHERE user_id = {userId}");
                ignoresTable = commitableQueryReactor.GetTable();

                // Get User Tags
                commitableQueryReactor.SetQuery($"SELECT tag FROM users_tags WHERE user_id = {userId}");
                tagsTable = commitableQueryReactor.GetTable();

                // Get User Subscriptions
                commitableQueryReactor.SetQuery(
                    $"SELECT * FROM users_subscriptions WHERE user_id = {userId} AND timestamp_expire > UNIX_TIMESTAMP() ORDER BY subscription_id DESC LIMIT 1");
                subscriptionsRow = commitableQueryReactor.GetRow();

                // Get User Badges
                commitableQueryReactor.SetQuery($"SELECT * FROM users_badges WHERE user_id = {userId}");
                badgesTable = commitableQueryReactor.GetTable();

                // Get User Inventory Items
                commitableQueryReactor.SetQuery(
                    $"SELECT items_rooms.*, COALESCE(items_groups.group_id, 0) AS group_id FROM items_rooms LEFT OUTER JOIN items_groups ON items_rooms.id = items_groups.id WHERE room_id = 0 AND user_id={userId} LIMIT 8000");
                itemsTable = commitableQueryReactor.GetTable();

                // Get user Effects
                commitableQueryReactor.SetQuery($"SELECT * FROM users_effects WHERE user_id = {userId}");
                effectsTable = commitableQueryReactor.GetTable();

                // Get User Polls
                commitableQueryReactor.SetQuery(
                    $"SELECT poll_id FROM users_polls WHERE user_id = {userId} GROUP BY poll_id;");
                pollsTable = commitableQueryReactor.GetTable();

                // Get User Friends
                commitableQueryReactor.SetQuery(
                    $"SELECT users.* FROM users JOIN messenger_friendships ON users.id = messenger_friendships.user_one_id WHERE messenger_friendships.user_two_id = {userId} UNION ALL SELECT users.* FROM users JOIN messenger_friendships ON users.id = messenger_friendships.user_two_id WHERE messenger_friendships.user_one_id = {userId}");
                friendsTable = commitableQueryReactor.GetTable();

                // Get User Stats
                commitableQueryReactor.SetQuery($"SELECT * FROM users_stats WHERE id = {userId}");
                statsTable = commitableQueryReactor.GetRow();

                // Get User Friends Requests
                commitableQueryReactor.SetQuery(
                    $"SELECT messenger_requests.*,users.* FROM users JOIN messenger_requests ON users.id = messenger_requests.from_id WHERE messenger_requests.to_id = {userId}");
                friendsRequestsTable = commitableQueryReactor.GetTable();

                // Get User Rooms Data
                commitableQueryReactor.SetQuery($"SELECT * FROM rooms_data WHERE owner = {userId} LIMIT 150");
                myRoomsTable = commitableQueryReactor.GetTable();

                // Get User Pets Data
                commitableQueryReactor.SetQuery(
                    $"SELECT * FROM pets_data WHERE user_id = {userId} AND room_id = 0");
                petsTable = commitableQueryReactor.GetTable();

                // Get User Quests Data
                commitableQueryReactor.SetQuery($"SELECT * FROM users_quests_data WHERE user_id = {userId}");
                questsTable = commitableQueryReactor.GetTable();

                // Get User Bots Data
                commitableQueryReactor.SetQuery(
                    $"SELECT * FROM bots_data WHERE user_id = {userId} AND room_id = 0 AND ai_type='generic'");
                botsTable = commitableQueryReactor.GetTable();

                // Get User Groups Data
                commitableQueryReactor.SetQuery($"SELECT * FROM groups_members WHERE user_id = {userId}");
                groupsTable = commitableQueryReactor.GetTable();

                // Get User Relationships Data
                commitableQueryReactor.SetQuery($"SELECT * FROM users_relationships WHERE user_id = {userId}");
                relationShipsTable = commitableQueryReactor.GetTable();
            }

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

            foreach (DataRow row in achievementsTable.Rows)
            {
                string text = (string)row["achievement_group"];
                uint   level = (uint)row["achievement_level"], progress = (uint)row["user_progress"];

                achievements.Add(text, new UserAchievement(text, level, progress));
            }

            Dictionary <int, UserTalent> talents = new Dictionary <int, UserTalent>();

            foreach (DataRow row in talentsTable.Rows)
            {
                int num2  = (int)row["talent_id"];
                int state = (int)row["talent_state"];

                talents.Add(num2, new UserTalent(num2, state));
            }

            List <uint>   favorites   = favoritesTable.Rows.Cast <DataRow>().Select(row => (uint)row["room_id"]).ToList();
            List <uint>   ignoreUsers = ignoresTable.Rows.Cast <DataRow>().Select(row => (uint)row["ignore_id"]).ToList();
            List <string> tags        = tagsTable.Rows.Cast <DataRow>().Select(row => row["tag"].ToString().Replace(" ", "")).ToList();

            Dictionary <uint, RoomBot> inventoryBots =
                botsTable.Rows.Cast <DataRow>()
                .Select(BotManager.GenerateBotFromRow)
                .ToDictionary(roomBot => roomBot.BotId);

            List <Badge> badges =
                badgesTable.Rows.Cast <DataRow>()
                .Select(dataRow8 => new Badge((string)dataRow8["badge_id"], (int)dataRow8["badge_slot"]))
                .ToList();

            Subscription subscriptions = null;

            if (subscriptionsRow != null)
            {
                subscriptions = new Subscription((int)subscriptionsRow["subscription_id"],
                                                 (int)subscriptionsRow["timestamp_activated"], (int)subscriptionsRow["timestamp_expire"],
                                                 (int)subscriptionsRow["timestamp_lastgift"]);
            }

            List <UserItem> items = (from DataRow row in itemsTable.Rows
                                     let id = Convert.ToUInt32(row["id"])
                                              let itemName = row["item_name"].ToString()
                                                             where Yupi.GetGame().GetItemManager().ContainsItemByName(itemName)
                                                             let extraData = !DBNull.Value.Equals(row[4]) ? (string)row[4] : string.Empty
                                                                             let theGroup = Convert.ToUInt32(row["group_id"])
                                                                                            let songCode = (string)row["songcode"]
                                                                                                           select new UserItem(id, itemName, extraData, theGroup, songCode)).ToList();

            List <AvatarEffect> effects = (from DataRow row in effectsTable.Rows
                                           let effectId = (int)row["effect_id"]
                                                          let totalDuration = (int)row["total_duration"]
                                                                              let activated = Yupi.EnumToBool((string)row["is_activated"])
                                                                                              let activateTimestamp = (double)row["activated_stamp"]
                                                                                                                      let type = Convert.ToInt16(row["type"])
                                                                                                                                 select new AvatarEffect(effectId, totalDuration, activated, activateTimestamp, type)).ToList();

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

            foreach (uint pId in pollsTable.Rows.Cast <DataRow>().Select(row => (uint)row["poll_id"]))
            {
                pollSuggested.Add(pId);
            }

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

            foreach (DataRow row in friendsTable.Rows)
            {
                uint   num4           = (uint)row["id"];
                string pUsername      = (string)row["username"];
                string pLook          = (string)row["look"];
                string pMotto         = (string)row["motto"];
                bool   pAppearOffline = Yupi.EnumToBool(row["hide_online"].ToString());
                bool   pHideInroom    = Yupi.EnumToBool(row["hide_inroom"].ToString());

                if (!Equals(num4, userId) && !friends.ContainsKey(num4))
                {
                    friends.Add(num4, new MessengerBuddy(num4, pUsername, pLook, pMotto, pAppearOffline, pHideInroom));
                }
            }

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

            foreach (DataRow row in friendsRequestsTable.Rows)
            {
                uint   num5       = Convert.ToUInt32(row["from_id"]);
                uint   num6       = Convert.ToUInt32(row["to_id"]);
                string pUsername2 = row["username"].ToString();
                string pLook      = row["look"].ToString();

                if (num5 != userId)
                {
                    if (!friendsRequests.ContainsKey(num5))
                    {
                        friendsRequests.Add(num5, new MessengerRequest(userId, num5, pUsername2, pLook));
                    }
                    else if (!friendsRequests.ContainsKey(num6))
                    {
                        friendsRequests.Add(num6, new MessengerRequest(userId, num6, pUsername2, pLook));
                    }
                }
            }

            HashSet <RoomData> myRooms = new HashSet <RoomData>();

            foreach (DataRow row in myRoomsTable.Rows)
            {
                myRooms.Add(Yupi.GetGame().GetRoomManager().FetchRoomData((uint)row["id"], row));
            }

            Dictionary <uint, Pet> pets = petsTable.Rows.Cast <DataRow>()
                                          .ToDictionary(row => (uint)row["id"], CatalogManager.GeneratePetFromRow);

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

            foreach (DataRow row in questsTable.Rows)
            {
                int key    = (int)row["quest_id"];
                int value3 = (int)row["progress"];

                if (quests.ContainsKey(key))
                {
                    quests.Remove(key);
                }

                quests.Add(key, value3);
            }

            HashSet <GroupMember> groups = new HashSet <GroupMember>();

            foreach (DataRow row in groupsTable.Rows)
            {
                groups.Add(new GroupMember(userId, userName, userLook, (uint)row["group_id"],
                                           Convert.ToInt16(row["rank"]), (int)row["date_join"]));
            }

            Dictionary <int, Relationship> relationShips = relationShipsTable.Rows.Cast <DataRow>()
                                                           .ToDictionary(row => (int)row[0],
                                                                         row => new Relationship((int)row[0], (int)row[2], Convert.ToInt32(row[3].ToString())));

            Habbo user = HabboFactory.GenerateHabbo(dataRow, statsTable, groups);

            errorCode = 0;

            if (user.Rank >= Yupi.StaffAlertMinRank)
            {
                friends.Add(0,
                            new MessengerBuddy(0, "Staff Chat",
                                               "hr-831-45.fa-1206-91.sh-290-1331.ha-3129-100.hd-180-2.cc-3039-73.ch-3215-92.lg-270-73",
                                               string.Empty, false, true));
            }
            else if (user.Rank >= Convert.ToUInt32(Yupi.GetDbConfig().DbData["ambassador.minrank"]))
            {
                friends.Add(0,
                            new MessengerBuddy(0, "Ambassador Chat",
                                               "hr-831-45.fa-1206-91.sh-290-1331.ha-3129-100.hd-180-2.cc-3039-73.ch-3215-92.lg-270-73",
                                               string.Empty, false, true));
            }

            return(new UserData(userId, achievements, talents, favorites, ignoreUsers, tags, subscriptions, badges,
                                items, effects, friends, friendsRequests, myRooms, pets, quests, user, inventoryBots, relationShips,
                                pollSuggested, 0));
        }
Exemplo n.º 26
0
        public void Parse(GameClient session, ClientPacket packet)
        {
            if (session == null || session.Habbo == null)
            {
                return;
            }

            Room room = session.Habbo.CurrentRoom;

            if (room == null)
            {
                return;
            }

            RoomUser user = room.GetRoomUserManager().GetRoomUserByHabbo(session.Habbo.Username);

            if (user == null)
            {
                return;
            }

            string newName = packet.PopString();
            string oldName = session.Habbo.Username;

            if (newName == oldName)
            {
                session.Habbo.ChangeName(oldName);
                session.SendPacket(new UpdateUsernameComposer(newName));
                return;
            }

            if (!CanChangeName(session.Habbo))
            {
                session.SendNotification("Oops, it appears you currently cannot change your username!");
                return;
            }

            bool inUse;

            using (IQueryAdapter dbClient = PlusEnvironment.GetDatabaseManager().GetQueryReactor())
            {
                dbClient.SetQuery("SELECT COUNT(0) FROM `users` WHERE `username` = @name LIMIT 1");
                dbClient.AddParameter("name", newName);
                inUse = dbClient.GetInteger() == 1;
            }

            char[]       letters           = newName.ToLower().ToCharArray();
            const string allowedCharacters = "abcdefghijklmnopqrstuvwxyz.,_-;:?!1234567890";

            if (letters.Any(chr => !allowedCharacters.Contains(chr)))
            {
                return;
            }

            if (!session.Habbo.GetPermissions().HasRight("mod_tool") && newName.ToLower().Contains("mod") || newName.ToLower().Contains("adm") || newName.ToLower().Contains("admin") ||
                newName.ToLower().Contains("m0d") || newName.ToLower().Contains("mob") || newName.ToLower().Contains("m0b"))
            {
                return;
            }

            if (!newName.ToLower().Contains("mod") && (session.Habbo.Rank == 2 || session.Habbo.Rank == 3))
            {
                return;
            }

            if (newName.Length > 15)
            {
                return;
            }

            if (newName.Length < 3)
            {
                return;
            }

            if (inUse)
            {
                return;
            }

            if (!PlusEnvironment.GetGame().GetClientManager().UpdateClientUsername(session, oldName, newName))
            {
                session.SendNotification("Oops! An issue occoured whilst updating your username.");
                return;
            }

            session.Habbo.ChangingName = false;

            room.GetRoomUserManager().RemoveUserFromRoom(session, true);

            session.Habbo.ChangeName(newName);
            session.Habbo.GetMessenger().OnStatusChanged(true);

            session.SendPacket(new UpdateUsernameComposer(newName));
            room.SendPacket(new UserNameChangeComposer(room.Id, user.VirtualId, newName));

            using (IQueryAdapter dbClient = PlusEnvironment.GetDatabaseManager().GetQueryReactor())
            {
                dbClient.SetQuery("INSERT INTO `logs_client_namechange` (`user_id`,`new_name`,`old_name`,`timestamp`) VALUES ('" + session.Habbo.Id + "', @name, '" + oldName + "', '" + PlusEnvironment.GetUnixTimestamp() + "')");
                dbClient.AddParameter("name", newName);
                dbClient.RunQuery();
            }


            foreach (Room ownRooms in PlusEnvironment.GetGame().GetRoomManager().GetRooms().ToList())
            {
                if (ownRooms == null || ownRooms.OwnerId != session.Habbo.Id || ownRooms.OwnerName == newName)
                {
                    continue;
                }

                ownRooms.OwnerName = newName;
                ownRooms.SendPacket(new RoomInfoUpdatedComposer(ownRooms.Id));
            }

            _achievementManager.ProgressAchievement(session, "ACH_Name", 1);

            session.SendPacket(new RoomForwardComposer(room.Id));
        }
Exemplo n.º 27
0
        public void Parse(GameClient session, ClientPacket packet)
        {
            bool   inUse;
            string name = packet.PopString();

            using (IQueryAdapter dbClient = PlusEnvironment.GetDatabaseManager().GetQueryReactor())
            {
                dbClient.SetQuery("SELECT COUNT(0) FROM `users` WHERE `username` = @name LIMIT 1");
                dbClient.AddParameter("name", name);
                inUse = dbClient.GetInteger() == 1;
            }

            char[]       letters           = name.ToLower().ToCharArray();
            const string allowedCharacters = "abcdefghijklmnopqrstuvwxyz.,_-;:?!1234567890";

            if (letters.Any(chr => !allowedCharacters.Contains(chr)))
            {
                session.SendPacket(new NameChangeUpdateComposer(name, 4));
                return;
            }

            if (PlusEnvironment.GetGame().GetChatManager().GetFilter().IsFiltered(name))
            {
                session.SendPacket(new NameChangeUpdateComposer(name, 4));
                return;
            }

            if (!session.GetHabbo().GetPermissions().HasRight("mod_tool") && name.ToLower().Contains("mod") || name.ToLower().Contains("adm") || name.ToLower().Contains("admin") || name.ToLower().Contains("m0d"))
            {
                session.SendPacket(new NameChangeUpdateComposer(name, 4));
                return;
            }

            if (!name.ToLower().Contains("mod") && (session.GetHabbo().Rank == 2 || session.GetHabbo().Rank == 3))
            {
                session.SendPacket(new NameChangeUpdateComposer(name, 4));
                return;
            }

            if (name.Length > 15)
            {
                session.SendPacket(new NameChangeUpdateComposer(name, 3));
                return;
            }

            if (name.Length < 3)
            {
                session.SendPacket(new NameChangeUpdateComposer(name, 2));
                return;
            }

            if (inUse)
            {
                ICollection <string> suggestions = new List <string>();
                for (int i = 100; i < 103; i++)
                {
                    suggestions.Add(i.ToString());
                }

                session.SendPacket(new NameChangeUpdateComposer(name, 5, suggestions));
                return;
            }

            session.SendPacket(new NameChangeUpdateComposer(name, 0));
        }
Exemplo n.º 28
0
        public static void Search(ServerPacket Message, SearchResultList SearchResult, string SearchData, GameClient Session, int FetchLimit)
        {
            //Switching by categorys.
            switch (SearchResult.CategoryType)
            {
            default:
                Message.WriteInteger(0);
                break;

            case NavigatorCategoryType.QUERY:
            {
                #region Query
                if (SearchData.ToLower().StartsWith("owner:"))
                {
                    if (SearchData.Length > 0)
                    {
                        int       UserId   = 0;
                        DataTable GetRooms = null;
                        using (IQueryAdapter dbClient = PlusEnvironment.GetDatabaseManager().GetQueryReactor())
                        {
                            if (SearchData.ToLower().StartsWith("owner:"))
                            {
                                dbClient.SetQuery("SELECT `id` FROM `users` WHERE `username` = @username LIMIT 1");
                                dbClient.AddParameter("username", SearchData.Remove(0, 6));
                                UserId = dbClient.GetInteger();

                                dbClient.SetQuery("SELECT * FROM `rooms` WHERE `owner` = '" + UserId + "' and `state` != 'invisible' ORDER BY `users_now` DESC LIMIT 50");
                                GetRooms = dbClient.GetTable();
                            }
                        }

                        List <RoomData> Results = new List <RoomData>();
                        if (GetRooms != null)
                        {
                            foreach (DataRow Row in GetRooms.Rows)
                            {
                                RoomData RoomData = PlusEnvironment.GetGame().GetRoomManager().FetchRoomData(Convert.ToInt32(Row["id"]), Row);
                                if (RoomData != null && !Results.Contains(RoomData))
                                {
                                    Results.Add(RoomData);
                                }
                            }
                        }

                        Message.WriteInteger(Results.Count);
                        foreach (RoomData Data in Results.ToList())
                        {
                            RoomAppender.WriteRoom(Message, Data, Data.Promotion);
                        }
                    }
                }
                else if (SearchData.ToLower().StartsWith("tag:"))
                {
                    SearchData = SearchData.Remove(0, 4);
                    ICollection <RoomData> TagMatches = PlusEnvironment.GetGame().GetRoomManager().SearchTaggedRooms(SearchData);

                    Message.WriteInteger(TagMatches.Count);
                    foreach (RoomData Data in TagMatches.ToList())
                    {
                        RoomAppender.WriteRoom(Message, Data, Data.Promotion);
                    }
                }
                else if (SearchData.ToLower().StartsWith("group:"))
                {
                    SearchData = SearchData.Remove(0, 6);
                    ICollection <RoomData> GroupRooms = PlusEnvironment.GetGame().GetRoomManager().SearchGroupRooms(SearchData);

                    Message.WriteInteger(GroupRooms.Count);
                    foreach (RoomData Data in GroupRooms.ToList())
                    {
                        RoomAppender.WriteRoom(Message, Data, Data.Promotion);
                    }
                }
                else
                {
                    if (SearchData.Length > 0)
                    {
                        DataTable Table = null;
                        using (IQueryAdapter dbClient = PlusEnvironment.GetDatabaseManager().GetQueryReactor())
                        {
                            dbClient.SetQuery("SELECT `id`,`caption`,`description`,`roomtype`,`owner`,`state`,`category`,`users_now`,`users_max`,`model_name`,`score`,`allow_pets`,`allow_pets_eat`,`room_blocking_disabled`,`allow_hidewall`,`password`,`wallpaper`,`floor`,`landscape`,`floorthick`,`wallthick`,`mute_settings`,`kick_settings`,`ban_settings`,`chat_mode`,`chat_speed`,`chat_size`,`trade_settings`,`group_id`,`tags`,`push_enabled`,`pull_enabled`,`enables_enabled`,`respect_notifications_enabled`,`pet_morphs_allowed`,`spush_enabled`,`spull_enabled` FROM rooms WHERE `caption` LIKE @query ORDER BY `users_now` DESC LIMIT 50");
                            dbClient.AddParameter("query", "%" + SearchData + "%");
                            Table = dbClient.GetTable();
                        }

                        List <RoomData> Results = new List <RoomData>();
                        if (Table != null)
                        {
                            foreach (DataRow Row in Table.Rows)
                            {
                                if (Convert.ToString(Row["state"]) == "invisible")
                                {
                                    continue;
                                }

                                RoomData RData = PlusEnvironment.GetGame().GetRoomManager().FetchRoomData(Convert.ToInt32(Row["id"]), Row);
                                if (RData != null && !Results.Contains(RData))
                                {
                                    Results.Add(RData);
                                }
                            }
                        }

                        Message.WriteInteger(Results.Count);
                        foreach (RoomData Data in Results.ToList())
                        {
                            RoomAppender.WriteRoom(Message, Data, Data.Promotion);
                        }
                    }
                }
                #endregion

                break;
            }

            case NavigatorCategoryType.FEATURED:
                #region Featured
                List <RoomData>            Rooms    = new List <RoomData>();
                ICollection <FeaturedRoom> Featured = PlusEnvironment.GetGame().GetNavigator().GetFeaturedRooms();
                foreach (FeaturedRoom FeaturedItem in Featured.ToList())
                {
                    if (FeaturedItem == null)
                    {
                        continue;
                    }

                    RoomData Data = PlusEnvironment.GetGame().GetRoomManager().GenerateRoomData(FeaturedItem.RoomId);
                    if (Data == null)
                    {
                        continue;
                    }

                    if (!Rooms.Contains(Data))
                    {
                        Rooms.Add(Data);
                    }
                }

                Message.WriteInteger(Rooms.Count);
                foreach (RoomData Data in Rooms.ToList())
                {
                    RoomAppender.WriteRoom(Message, Data, Data.Promotion);
                }
                #endregion
                break;

            case NavigatorCategoryType.POPULAR:
            {
                List <RoomData> PopularRooms = PlusEnvironment.GetGame().GetRoomManager().GetPopularRooms(-1, FetchLimit);

                Message.WriteInteger(PopularRooms.Count);
                foreach (RoomData Data in PopularRooms.ToList())
                {
                    RoomAppender.WriteRoom(Message, Data, Data.Promotion);
                }
                break;
            }

            case NavigatorCategoryType.RECOMMENDED:
            {
                List <RoomData> RecommendedRooms = PlusEnvironment.GetGame().GetRoomManager().GetRecommendedRooms(FetchLimit);

                Message.WriteInteger(RecommendedRooms.Count);
                foreach (RoomData Data in RecommendedRooms.ToList())
                {
                    RoomAppender.WriteRoom(Message, Data, Data.Promotion);
                }
                break;
            }

            case NavigatorCategoryType.CATEGORY:
            {
                List <RoomData> GetRoomsByCategory = PlusEnvironment.GetGame().GetRoomManager().GetRoomsByCategory(SearchResult.Id, FetchLimit);

                Message.WriteInteger(GetRoomsByCategory.Count);
                foreach (RoomData Data in GetRoomsByCategory.ToList())
                {
                    RoomAppender.WriteRoom(Message, Data, Data.Promotion);
                }
                break;
            }

            case NavigatorCategoryType.MY_ROOMS:

                Message.WriteInteger(Session.GetHabbo().UsersRooms.Count);
                foreach (RoomData Data in Session.GetHabbo().UsersRooms.ToList())
                {
                    RoomAppender.WriteRoom(Message, Data, Data.Promotion);
                }
                break;

            case NavigatorCategoryType.MY_FAVORITES:
                List <RoomData> Favourites = new List <RoomData>();
                foreach (int Id in Session.GetHabbo().FavoriteRooms.ToArray())
                {
                    RoomData Room = PlusEnvironment.GetGame().GetRoomManager().GenerateRoomData(Id);
                    if (Room == null)
                    {
                        continue;
                    }

                    if (!Favourites.Contains(Room))
                    {
                        Favourites.Add(Room);
                    }
                }

                Favourites = Favourites.Take(FetchLimit).ToList();

                Message.WriteInteger(Favourites.Count);
                foreach (RoomData Data in Favourites.ToList())
                {
                    RoomAppender.WriteRoom(Message, Data, Data.Promotion);
                }
                break;

            case NavigatorCategoryType.MY_GROUPS:
                List <RoomData> MyGroups = new List <RoomData>();

                foreach (Group Group in PlusEnvironment.GetGame().GetGroupManager().GetGroupsForUser(Session.GetHabbo().Id).ToList())
                {
                    if (Group == null)
                    {
                        continue;
                    }

                    RoomData Data = PlusEnvironment.GetGame().GetRoomManager().GenerateRoomData(Group.RoomId);
                    if (Data == null)
                    {
                        continue;
                    }

                    if (!MyGroups.Contains(Data))
                    {
                        MyGroups.Add(Data);
                    }
                }

                MyGroups = MyGroups.Take(FetchLimit).ToList();

                Message.WriteInteger(MyGroups.Count);
                foreach (RoomData Data in MyGroups.ToList())
                {
                    RoomAppender.WriteRoom(Message, Data, Data.Promotion);
                }
                break;

            case NavigatorCategoryType.MY_FRIENDS_ROOMS:
                List <RoomData> MyFriendsRooms = new List <RoomData>();
                foreach (MessengerBuddy buddy in Session.GetHabbo().GetMessenger().GetFriends().Where(p => p.InRoom))
                {
                    if (buddy == null || !buddy.InRoom || buddy.UserId == Session.GetHabbo().Id)
                    {
                        continue;
                    }

                    if (!MyFriendsRooms.Contains(buddy.CurrentRoom.RoomData))
                    {
                        MyFriendsRooms.Add(buddy.CurrentRoom.RoomData);
                    }
                }

                Message.WriteInteger(MyFriendsRooms.Count);
                foreach (RoomData Data in MyFriendsRooms.ToList())
                {
                    RoomAppender.WriteRoom(Message, Data, Data.Promotion);
                }
                break;

            case NavigatorCategoryType.MY_RIGHTS:
                List <RoomData> MyRights = new List <RoomData>();

                DataTable GetRights = null;
                using (IQueryAdapter dbClient = PlusEnvironment.GetDatabaseManager().GetQueryReactor())
                {
                    dbClient.SetQuery("SELECT `room_id` FROM `room_rights` WHERE `user_id` = @UserId LIMIT @FetchLimit");
                    dbClient.AddParameter("UserId", Session.GetHabbo().Id);
                    dbClient.AddParameter("FetchLimit", FetchLimit);
                    GetRights = dbClient.GetTable();

                    foreach (DataRow Row in GetRights.Rows)
                    {
                        RoomData Data = PlusEnvironment.GetGame().GetRoomManager().GenerateRoomData(Convert.ToInt32(Row["room_id"]));
                        if (Data == null)
                        {
                            continue;
                        }

                        if (!MyRights.Contains(Data))
                        {
                            MyRights.Add(Data);
                        }
                    }
                }

                Message.WriteInteger(MyRights.Count);
                foreach (RoomData Data in MyRights.ToList())
                {
                    RoomAppender.WriteRoom(Message, Data, Data.Promotion);
                }
                break;

            case NavigatorCategoryType.TOP_PROMOTIONS:
            {
                List <RoomData> GetPopularPromotions = PlusEnvironment.GetGame().GetRoomManager().GetOnGoingRoomPromotions(16, FetchLimit);

                Message.WriteInteger(GetPopularPromotions.Count);
                foreach (RoomData Data in GetPopularPromotions.ToList())
                {
                    RoomAppender.WriteRoom(Message, Data, Data.Promotion);
                }
                break;
            }

            case NavigatorCategoryType.PROMOTION_CATEGORY:
            {
                List <RoomData> GetPromotedRooms = PlusEnvironment.GetGame().GetRoomManager().GetPromotedRooms(SearchResult.Id, FetchLimit);

                Message.WriteInteger(GetPromotedRooms.Count);
                foreach (RoomData Data in GetPromotedRooms.ToList())
                {
                    RoomAppender.WriteRoom(Message, Data, Data.Promotion);
                }
                break;
            }
            }
        }
Exemplo n.º 29
0
        public static void Search(ServerPacket packet, SearchResultList result, string query, Habbo habbo, int limit)
        {
            if (habbo == null)
            {
                return;
            }

            switch (result.CategoryType)
            {
            default:
            case NavigatorCategoryType.MyFavourites:
            case NavigatorCategoryType.MyHistory:
            case NavigatorCategoryType.Featured:
                packet.WriteInteger(0);
                break;

            case NavigatorCategoryType.Query:
            {
                #region Query
                if (query.ToLower().StartsWith("owner:"))
                {
                    if (query.Length > 0)
                    {
                        int       UserId   = 0;
                        DataTable GetRooms = null;
                        using (IQueryAdapter dbClient = PlusEnvironment.GetDatabaseManager().GetQueryReactor())
                        {
                            if (query.ToLower().StartsWith("owner:"))
                            {
                                dbClient.SetQuery("SELECT `id` FROM `users` WHERE `username` = @username LIMIT 1");
                                dbClient.AddParameter("username", query.Remove(0, 6));
                                UserId = dbClient.GetInteger();

                                dbClient.SetQuery("SELECT * FROM `rooms` WHERE `owner` = '" + UserId + "' and `state` != 'invisible' ORDER BY `users_now` DESC LIMIT 50");
                                GetRooms = dbClient.GetTable();
                            }
                        }

                        List <RoomData> Results = new List <RoomData>();
                        if (GetRooms != null)
                        {
                            foreach (DataRow Row in GetRooms.Rows)
                            {
                                RoomData Data = null;
                                if (!RoomFactory.TryGetData(Convert.ToInt32(Row["id"]), out Data))
                                {
                                    continue;
                                }

                                if (!Results.Contains(Data))
                                {
                                    Results.Add(Data);
                                }
                            }

                            GetRooms = null;
                        }

                        packet.WriteInteger(Results.Count);
                        foreach (RoomData Data in Results.ToList())
                        {
                            RoomAppender.WriteRoom(packet, Data, Data.Promotion);
                        }

                        Results = null;
                    }
                }
                else if (query.ToLower().StartsWith("tag:"))
                {
                    query = query.Remove(0, 4);
                    ICollection <Room> TagMatches = PlusEnvironment.GetGame().GetRoomManager().SearchTaggedRooms(query);

                    packet.WriteInteger(TagMatches.Count);
                    foreach (RoomData Data in TagMatches.ToList())
                    {
                        RoomAppender.WriteRoom(packet, Data, Data.Promotion);
                    }

                    TagMatches = null;
                }
                else if (query.ToLower().StartsWith("group:"))
                {
                    query = query.Remove(0, 6);
                    ICollection <Room> GroupRooms = PlusEnvironment.GetGame().GetRoomManager().SearchGroupRooms(query);

                    packet.WriteInteger(GroupRooms.Count);
                    foreach (RoomData Data in GroupRooms.ToList())
                    {
                        RoomAppender.WriteRoom(packet, Data, Data.Promotion);
                    }

                    GroupRooms = null;
                }
                else
                {
                    if (query.Length > 0)
                    {
                        DataTable Table = null;
                        using (IQueryAdapter dbClient = PlusEnvironment.GetDatabaseManager().GetQueryReactor())
                        {
                            dbClient.SetQuery("SELECT `id`,`caption`,`description`,`roomtype`,`owner`,`state`,`category`,`users_now`,`users_max`,`model_name`,`score`,`allow_pets`,`allow_pets_eat`,`room_blocking_disabled`,`allow_hidewall`,`password`,`wallpaper`,`floor`,`landscape`,`floorthick`,`wallthick`,`mute_settings`,`kick_settings`,`ban_settings`,`chat_mode`,`chat_speed`,`chat_size`,`trade_settings`,`group_id`,`tags`,`push_enabled`,`pull_enabled`,`enables_enabled`,`respect_notifications_enabled`,`pet_morphs_allowed`,`spush_enabled`,`spull_enabled`,`sale_price` FROM rooms WHERE `caption` LIKE @query ORDER BY `users_now` DESC LIMIT 50");
                            dbClient.AddParameter("query", query + "%");
                            Table = dbClient.GetTable();
                        }

                        List <RoomData> Results = new List <RoomData>();
                        if (Table != null)
                        {
                            foreach (DataRow Row in Table.Rows)
                            {
                                if (Convert.ToString(Row["state"]) == "invisible")
                                {
                                    continue;
                                }

                                RoomData Data = null;
                                if (!RoomFactory.TryGetData(Convert.ToInt32(Row["id"]), out Data))
                                {
                                    continue;
                                }

                                if (!Results.Contains(Data))
                                {
                                    Results.Add(Data);
                                }
                            }

                            Table = null;
                        }

                        packet.WriteInteger(Results.Count);
                        foreach (RoomData Data in Results.ToList())
                        {
                            RoomAppender.WriteRoom(packet, Data, Data.Promotion);
                        }

                        Results = null;
                    }
                }
                #endregion

                break;
            }

            case NavigatorCategoryType.Popular:
            {
                List <Room> PopularRooms = PlusEnvironment.GetGame().GetRoomManager().GetPopularRooms(-1, limit);

                packet.WriteInteger(PopularRooms.Count);
                foreach (RoomData Data in PopularRooms.ToList())
                {
                    RoomAppender.WriteRoom(packet, Data, Data.Promotion);
                }

                PopularRooms = null;
                break;
            }

            case NavigatorCategoryType.Recommended:
            {
                List <Room> RecommendedRooms = PlusEnvironment.GetGame().GetRoomManager().GetRecommendedRooms(limit);

                packet.WriteInteger(RecommendedRooms.Count);
                foreach (RoomData Data in RecommendedRooms.ToList())
                {
                    RoomAppender.WriteRoom(packet, Data, Data.Promotion);
                }

                RecommendedRooms = null;
                break;
            }

            case NavigatorCategoryType.Category:
            {
                List <Room> GetRoomsByCategory = PlusEnvironment.GetGame().GetRoomManager().GetRoomsByCategory(result.Id, limit);

                packet.WriteInteger(GetRoomsByCategory.Count);
                foreach (RoomData Data in GetRoomsByCategory.ToList())
                {
                    RoomAppender.WriteRoom(packet, Data, Data.Promotion);
                }

                GetRoomsByCategory = null;
                break;
            }

            case NavigatorCategoryType.MyRooms:
            {
                ICollection <RoomData> rooms = RoomFactory.GetRoomsDataByOwnerSortByName(habbo.Id).OrderByDescending(x => x.UsersNow).ToList();

                packet.WriteInteger(rooms.Count);
                foreach (RoomData Data in rooms.ToList())
                {
                    RoomAppender.WriteRoom(packet, Data, Data.Promotion);
                }

                break;
            }

            case NavigatorCategoryType.MyGroups:
            {
                List <RoomData> MyGroups = new List <RoomData>();

                foreach (Group Group in PlusEnvironment.GetGame().GetGroupManager().GetGroupsForUser(habbo.Id).ToList())
                {
                    if (Group == null)
                    {
                        continue;
                    }

                    RoomData Data = null;
                    if (!RoomFactory.TryGetData(Group.RoomId, out Data))
                    {
                        continue;
                    }

                    if (!MyGroups.Contains(Data))
                    {
                        MyGroups.Add(Data);
                    }
                }

                MyGroups = MyGroups.Take(limit).ToList();

                packet.WriteInteger(MyGroups.Count);
                foreach (RoomData Data in MyGroups.ToList())
                {
                    RoomAppender.WriteRoom(packet, Data, Data.Promotion);
                }

                MyGroups = null;

                break;
            }

            case NavigatorCategoryType.MyFriendsRooms:
            {
                List <int> RoomIds = new List <int>();

                if (habbo == null || habbo.GetMessenger() == null || habbo.GetMessenger().GetFriends() == null)
                {
                    return;
                }

                foreach (MessengerBuddy buddy in habbo.GetMessenger().GetFriends().Where(p => p.InRoom))
                {
                    if (buddy == null || !buddy.InRoom || buddy.UserId == habbo.Id)
                    {
                        continue;
                    }

                    if (!RoomIds.Contains(buddy.CurrentRoom.Id))
                    {
                        RoomIds.Add(buddy.CurrentRoom.Id);
                    }
                }

                List <Room> MyFriendsRooms = PlusEnvironment.GetGame().GetRoomManager().GetRoomsByIds(RoomIds.ToList());

                packet.WriteInteger(MyFriendsRooms.Count);
                foreach (RoomData Data in MyFriendsRooms.ToList())
                {
                    RoomAppender.WriteRoom(packet, Data, Data.Promotion);
                }

                MyFriendsRooms = null;
                break;
            }

            case NavigatorCategoryType.MyRights:
            {
                List <RoomData> MyRights = new List <RoomData>();

                if (habbo != null)
                {
                    DataTable GetRights = null;
                    using (IQueryAdapter dbClient = PlusEnvironment.GetDatabaseManager().GetQueryReactor())
                    {
                        dbClient.SetQuery("SELECT `room_id` FROM `room_rights` WHERE `user_id` = @UserId LIMIT @FetchLimit");
                        dbClient.AddParameter("UserId", habbo.Id);
                        dbClient.AddParameter("FetchLimit", limit);
                        GetRights = dbClient.GetTable();

                        foreach (DataRow Row in GetRights.Rows)
                        {
                            RoomData Data = null;
                            if (!RoomFactory.TryGetData(Convert.ToInt32(Row["room_id"]), out Data))
                            {
                                continue;
                            }

                            if (!MyRights.Contains(Data))
                            {
                                MyRights.Add(Data);
                            }
                        }
                    }
                }

                packet.WriteInteger(MyRights.Count);
                foreach (RoomData Data in MyRights.ToList())
                {
                    RoomAppender.WriteRoom(packet, Data, Data.Promotion);
                }

                MyRights = null;
                break;
            }

            case NavigatorCategoryType.TopPromotions:
            {
                List <Room> GetPopularPromotions = PlusEnvironment.GetGame().GetRoomManager().GetOnGoingRoomPromotions(16, limit);

                packet.WriteInteger(GetPopularPromotions.Count);
                foreach (RoomData Data in GetPopularPromotions.ToList())
                {
                    RoomAppender.WriteRoom(packet, Data, Data.Promotion);
                }

                GetPopularPromotions = null;

                break;
            }


            case NavigatorCategoryType.PromotionCategory:
            {
                List <Room> GetPromotedRooms = PlusEnvironment.GetGame().GetRoomManager().GetPromotedRooms(result.OrderId, limit);

                packet.WriteInteger(GetPromotedRooms.Count);
                foreach (RoomData Data in GetPromotedRooms.ToList())
                {
                    RoomAppender.WriteRoom(packet, Data, Data.Promotion);
                }

                GetPromotedRooms = null;

                break;
            }
            }
        }
Exemplo n.º 30
0
        public void Parse(GameClient session, ClientPacket packet)
        {
            if (session == null || session.GetHabbo() == null || session.GetHabbo().GetMessenger() == null)
            {
                return;
            }

            int user = packet.PopInt();
            int type = packet.PopInt();

            if (!session.GetHabbo().GetMessenger().FriendshipExists(user))
            {
                session.SendPacket(new BroadcastMessageAlertComposer("Oops, you can only set a relationship where a friendship exists."));
                return;
            }

            if (type < 0 || type > 3)
            {
                session.SendPacket(new BroadcastMessageAlertComposer("Oops, you've chosen an invalid relationship type."));
                return;
            }

            if (session.GetHabbo().Relationships.Count > 2000)
            {
                session.SendPacket(new BroadcastMessageAlertComposer("Sorry, you're limited to a total of 2000 relationships."));
                return;
            }

            using (IQueryAdapter dbClient = PlusEnvironment.GetDatabaseManager().GetQueryReactor())
            {
                if (type == 0)
                {
                    dbClient.SetQuery("SELECT `id` FROM `user_relationships` WHERE `user_id` = '" + session.GetHabbo().Id + "' AND `target` = @target LIMIT 1");
                    dbClient.AddParameter("target", user);

                    dbClient.SetQuery("DELETE FROM `user_relationships` WHERE `user_id` = '" + session.GetHabbo().Id + "' AND `target` = @target LIMIT 1");
                    dbClient.AddParameter("target", user);
                    dbClient.RunQuery();

                    if (session.GetHabbo().Relationships.ContainsKey(user))
                    {
                        session.GetHabbo().Relationships.Remove(user);
                    }
                }
                else
                {
                    dbClient.SetQuery("SELECT `id` FROM `user_relationships` WHERE `user_id` = '" + session.GetHabbo().Id + "' AND `target` = @target LIMIT 1");
                    dbClient.AddParameter("target", user);
                    int id = dbClient.GetInteger();

                    if (id > 0)
                    {
                        dbClient.SetQuery("DELETE FROM `user_relationships` WHERE `user_id` = '" + session.GetHabbo().Id + "' AND `target` = @target LIMIT 1");
                        dbClient.AddParameter("target", user);
                        dbClient.RunQuery();

                        if (session.GetHabbo().Relationships.ContainsKey(id))
                        {
                            session.GetHabbo().Relationships.Remove(id);
                        }
                    }

                    dbClient.SetQuery("INSERT INTO `user_relationships` (`user_id`,`target`,`type`) VALUES ('" + session.GetHabbo().Id + "', @target, @type)");
                    dbClient.AddParameter("target", user);
                    dbClient.AddParameter("type", type);
                    int newId = Convert.ToInt32(dbClient.InsertQuery());

                    if (!session.GetHabbo().Relationships.ContainsKey(user))
                    {
                        session.GetHabbo().Relationships.Add(user, new Relationship(newId, user, type));
                    }
                }

                GameClient client = PlusEnvironment.GetGame().GetClientManager().GetClientByUserId(user);
                if (client != null)
                {
                    session.GetHabbo().GetMessenger().UpdateFriend(user, client, true);
                }
                else
                {
                    Habbo habbo = PlusEnvironment.GetHabboById(user);
                    if (habbo != null)
                    {
                        if (session.GetHabbo().GetMessenger().TryGetFriend(user, out MessengerBuddy buddy))
                        {
                            session.SendPacket(new FriendListUpdateComposer(session, buddy));
                        }
                    }
                }
            }
        }
Exemplo n.º 31
0
        public bool TryExecute(string[] parameters)
        {
            if (!int.TryParse(parameters[0], out int userId))
            {
                return(false);
            }

            GameClient client = PlusEnvironment.GetGame().GetClientManager().GetClientByUserId(userId);

            if (client == null || client.GetHabbo() == null)
            {
                return(false);
            }

            // Validate the currency type
            if (string.IsNullOrEmpty(Convert.ToString(parameters[1])))
            {
                return(false);
            }

            string currency = Convert.ToString(parameters[1]);

            switch (currency)
            {
            default:
                return(false);

            case "coins":
            case "credits":
            {
                int credits;
                using (IQueryAdapter dbClient = PlusEnvironment.GetDatabaseManager().GetQueryReactor())
                {
                    dbClient.SetQuery("SELECT `credits` FROM `users` WHERE `id` = @id LIMIT 1");
                    dbClient.AddParameter("id", userId);
                    credits = dbClient.GetInteger();
                }

                client.GetHabbo().Credits = credits;
                client.SendPacket(new CreditBalanceComposer(client.GetHabbo().Credits));
                break;
            }

            case "pixels":
            case "duckets":
            {
                int duckets;
                using (IQueryAdapter dbClient = PlusEnvironment.GetDatabaseManager().GetQueryReactor())
                {
                    dbClient.SetQuery("SELECT `activity_points` FROM `users` WHERE `id` = @id LIMIT 1");
                    dbClient.AddParameter("id", userId);
                    duckets = dbClient.GetInteger();
                }

                client.GetHabbo().Duckets = duckets;
                client.SendPacket(new HabboActivityPointNotificationComposer(client.GetHabbo().Duckets, duckets));
                break;
            }

            case "diamonds":
            {
                int diamonds;
                using (IQueryAdapter dbClient = PlusEnvironment.GetDatabaseManager().GetQueryReactor())
                {
                    dbClient.SetQuery("SELECT `vip_points` FROM `users` WHERE `id` = @id LIMIT 1");
                    dbClient.AddParameter("id", userId);
                    diamonds = dbClient.GetInteger();
                }

                client.GetHabbo().Diamonds = diamonds;
                client.SendPacket(new HabboActivityPointNotificationComposer(diamonds, 0, 5));
                break;
            }

            case "gotw":
            {
                int gotw;
                using (IQueryAdapter dbClient = PlusEnvironment.GetDatabaseManager().GetQueryReactor())
                {
                    dbClient.SetQuery("SELECT `gotw_points` FROM `users` WHERE `id` = @id LIMIT 1");
                    dbClient.AddParameter("id", userId);
                    gotw = dbClient.GetInteger();
                }

                client.GetHabbo().GOTWPoints = gotw;
                client.SendPacket(new HabboActivityPointNotificationComposer(gotw, 0, 103));
                break;
            }
            }
            return(true);
        }
Exemplo n.º 32
0
        public void Parse(GameClient session, ClientPacket packet)
        {
            int offerId = packet.PopInt();

            DataRow row;

            using (IQueryAdapter dbClient = PlusEnvironment.GetDatabaseManager().GetQueryReactor())
            {
                dbClient.SetQuery("SELECT `state`,`timestamp`,`total_price`,`extra_data`,`item_id`,`furni_id`,`user_id`,`limited_number`,`limited_stack` FROM `catalog_marketplace_offers` WHERE `offer_id` = @OfferId LIMIT 1");
                dbClient.AddParameter("OfferId", offerId);
                row = dbClient.GetRow();
            }

            if (row == null)
            {
                ReloadOffers(session);
                return;
            }

            if (Convert.ToString(row["state"]) == "2")
            {
                session.SendNotification("Oops, this offer is no longer available.");
                ReloadOffers(session);
                return;
            }

            if (PlusEnvironment.GetGame().GetCatalog().GetMarketplace().FormatTimestamp() > (Convert.ToDouble(row["timestamp"])))
            {
                session.SendNotification("Oops, this offer has expired..");
                ReloadOffers(session);
                return;
            }

            if (!PlusEnvironment.GetGame().GetItemManager().GetItem(Convert.ToInt32(row["item_id"]), out ItemData item))
            {
                session.SendNotification("Item isn't in the hotel anymore.");
                ReloadOffers(session);
                return;
            }
            else
            {
                if (Convert.ToInt32(row["user_id"]) == session.GetHabbo().Id)
                {
                    session.SendNotification("To prevent average boosting you cannot purchase your own marketplace offers.");
                    return;
                }

                if (Convert.ToInt32(row["total_price"]) > session.GetHabbo().Credits)
                {
                    session.SendNotification("Oops, you do not have enough credits for this.");
                    return;
                }

                session.GetHabbo().Credits -= Convert.ToInt32(row["total_price"]);
                session.SendPacket(new CreditBalanceComposer(session.GetHabbo().Credits));


                Item giveItem = ItemFactory.CreateSingleItem(item, session.GetHabbo(), Convert.ToString(row["extra_data"]), Convert.ToString(row["extra_data"]), Convert.ToInt32(row["furni_id"]), Convert.ToInt32(row["limited_number"]), Convert.ToInt32(row["limited_stack"]));
                if (giveItem != null)
                {
                    session.GetHabbo().GetInventoryComponent().TryAddItem(giveItem);
                    session.SendPacket(new FurniListNotificationComposer(giveItem.Id, 1));

                    session.SendPacket(new Outgoing.Catalog.PurchaseOKComposer());
                    session.SendPacket(new FurniListAddComposer(giveItem));
                    session.SendPacket(new FurniListUpdateComposer());
                }


                using (IQueryAdapter dbClient = PlusEnvironment.GetDatabaseManager().GetQueryReactor())
                {
                    dbClient.RunQuery("UPDATE `catalog_marketplace_offers` SET `state` = '2' WHERE `offer_id` = '" + offerId + "' LIMIT 1");

                    int id;
                    dbClient.SetQuery("SELECT `id` FROM `catalog_marketplace_data` WHERE `sprite` = " + item.SpriteId + " LIMIT 1;");
                    id = dbClient.GetInteger();

                    if (id > 0)
                    {
                        dbClient.RunQuery("UPDATE `catalog_marketplace_data` SET `sold` = `sold` + 1, `avgprice` = (avgprice + " + Convert.ToInt32(row["total_price"]) + ") WHERE `id` = " + id + " LIMIT 1;");
                    }
                    else
                    {
                        dbClient.RunQuery("INSERT INTO `catalog_marketplace_data` (`sprite`, `sold`, `avgprice`) VALUES ('" + item.SpriteId + "', '1', '" + Convert.ToInt32(row["total_price"]) + "')");
                    }


                    if (PlusEnvironment.GetGame().GetCatalog().GetMarketplace().MarketAverages.ContainsKey(item.SpriteId) && PlusEnvironment.GetGame().GetCatalog().GetMarketplace().MarketCounts.ContainsKey(item.SpriteId))
                    {
                        int num3 = PlusEnvironment.GetGame().GetCatalog().GetMarketplace().MarketCounts[item.SpriteId];
                        int num4 = (PlusEnvironment.GetGame().GetCatalog().GetMarketplace().MarketAverages[item.SpriteId] += Convert.ToInt32(row["total_price"]));

                        PlusEnvironment.GetGame().GetCatalog().GetMarketplace().MarketAverages.Remove(item.SpriteId);
                        PlusEnvironment.GetGame().GetCatalog().GetMarketplace().MarketAverages.Add(item.SpriteId, num4);
                        PlusEnvironment.GetGame().GetCatalog().GetMarketplace().MarketCounts.Remove(item.SpriteId);
                        PlusEnvironment.GetGame().GetCatalog().GetMarketplace().MarketCounts.Add(item.SpriteId, num3 + 1);
                    }
                    else
                    {
                        if (!PlusEnvironment.GetGame().GetCatalog().GetMarketplace().MarketAverages.ContainsKey(item.SpriteId))
                        {
                            PlusEnvironment.GetGame().GetCatalog().GetMarketplace().MarketAverages.Add(item.SpriteId, Convert.ToInt32(row["total_price"]));
                        }

                        if (!PlusEnvironment.GetGame().GetCatalog().GetMarketplace().MarketCounts.ContainsKey(item.SpriteId))
                        {
                            PlusEnvironment.GetGame().GetCatalog().GetMarketplace().MarketCounts.Add(item.SpriteId, 1);
                        }
                    }
                }
            }

            ReloadOffers(session);
        }