示例#1
0
 public override void DeleteFromDB(SQLTransaction trans)
 {
     DeleteFromDB(trans, GetGUID().GetCounter());
     base.DeleteFromDB(trans);
 }
示例#2
0
        void HandleTurnInPetition(TurnInPetition packet)
        {
            // Check if player really has the required petition charter
            Item item = GetPlayer().GetItemByGuid(packet.Item);

            if (!item)
            {
                return;
            }

            // Get petition data from db
            ObjectGuid ownerguid;
            string     name;

            PreparedStatement stmt = DB.Characters.GetPreparedStatement(CharStatements.SEL_PETITION);

            stmt.AddValue(0, packet.Item.GetCounter());
            SQLResult result = DB.Characters.Query(stmt);

            if (!result.IsEmpty())
            {
                ownerguid = ObjectGuid.Create(HighGuid.Player, result.Read <ulong>(0));
                name      = result.Read <string>(1);
            }
            else
            {
                Log.outError(LogFilter.Network, "Player {0} ({1}) tried to turn in petition ({2}) that is not present in the database", GetPlayer().GetName(), GetPlayer().GetGUID().ToString(), packet.Item.ToString());
                return;
            }

            // Only the petition owner can turn in the petition
            if (GetPlayer().GetGUID() != ownerguid)
            {
                return;
            }

            TurnInPetitionResult resultPacket = new TurnInPetitionResult();

            // Check if player is already in a guild
            if (GetPlayer().GetGuildId() != 0)
            {
                resultPacket.Result = PetitionTurns.AlreadyInGuild;
                GetPlayer().SendPacket(resultPacket);
                return;
            }

            // Check if guild name is already taken
            if (Global.GuildMgr.GetGuildByName(name))
            {
                Guild.SendCommandResult(this, GuildCommandType.CreateGuild, GuildCommandError.NameExists_S, name);
                return;
            }

            // Get petition signatures from db
            byte signatures;

            stmt = DB.Characters.GetPreparedStatement(CharStatements.SEL_PETITION_SIGNATURE);
            stmt.AddValue(0, packet.Item.GetCounter());
            result = DB.Characters.Query(stmt);

            if (!result.IsEmpty())
            {
                signatures = (byte)result.GetRowCount();
            }
            else
            {
                signatures = 0;
            }

            uint requiredSignatures = WorldConfig.GetUIntValue(WorldCfg.MinPetitionSigns);

            // Notify player if signatures are missing
            if (signatures < requiredSignatures)
            {
                resultPacket.Result = PetitionTurns.NeedMoreSignatures;
                SendPacket(resultPacket);
                return;
            }
            // Proceed with guild/arena team creation

            // Delete charter item
            GetPlayer().DestroyItem(item.GetBagSlot(), item.GetSlot(), true);

            // Create guild
            Guild guild = new Guild();

            if (!guild.Create(GetPlayer(), name))
            {
                return;
            }

            // Register guild and add guild master
            Global.GuildMgr.AddGuild(guild);

            Guild.SendCommandResult(this, GuildCommandType.CreateGuild, GuildCommandError.Success, name);

            // Add members from signatures
            for (byte i = 0; i < signatures; ++i)
            {
                guild.AddMember(ObjectGuid.Create(HighGuid.Player, result.Read <ulong>(0)));
                result.NextRow();
            }

            SQLTransaction trans = new SQLTransaction();

            stmt = DB.Characters.GetPreparedStatement(CharStatements.DEL_PETITION_BY_GUID);
            stmt.AddValue(0, packet.Item.GetCounter());
            trans.Append(stmt);

            stmt = DB.Characters.GetPreparedStatement(CharStatements.DEL_PETITION_SIGNATURE_BY_GUID);
            stmt.AddValue(0, packet.Item.GetCounter());
            trans.Append(stmt);

            DB.Characters.CommitTransaction(trans);

            // created
            Log.outDebug(LogFilter.Network, "Player {0} ({1}) turning in petition {2}", GetPlayer().GetName(), GetPlayer().GetGUID().ToString(), packet.Item.ToString());

            resultPacket.Result = PetitionTurns.Ok;
            SendPacket(resultPacket);
        }
示例#3
0
        static bool HandleSendMoneyCommand(StringArguments args, CommandHandler handler)
        {
            // format: name "subject text" "mail text" money

            Player     receiver;
            ObjectGuid receiverGuid;
            string     receiverName;

            if (!handler.ExtractPlayerTarget(args, out receiver, out receiverGuid, out receiverName))
            {
                return(false);
            }

            string tail1 = args.NextString("");

            if (string.IsNullOrEmpty(tail1))
            {
                return(false);
            }

            string subject = handler.ExtractQuotedArg(tail1);

            if (string.IsNullOrEmpty(subject))
            {
                return(false);
            }

            string tail2 = args.NextString("");

            if (string.IsNullOrEmpty(tail2))
            {
                return(false);
            }

            string text = handler.ExtractQuotedArg(tail2);

            if (string.IsNullOrEmpty(text))
            {
                return(false);
            }

            if (!long.TryParse(args.NextString(""), out long money))
            {
                money = 0;
            }

            if (money <= 0)
            {
                return(false);
            }

            // from console show not existed sender
            MailSender sender = new MailSender(MailMessageType.Normal, handler.GetSession() ? handler.GetSession().GetPlayer().GetGUID().GetCounter() : 0, MailStationery.Gm);

            SQLTransaction trans = new SQLTransaction();

            new MailDraft(subject, text)
            .AddMoney((uint)money)
            .SendMailTo(trans, new MailReceiver(receiver, receiverGuid.GetCounter()), sender);

            DB.Characters.CommitTransaction(trans);

            string nameLink = handler.PlayerLink(receiverName);

            handler.SendSysMessage(CypherStrings.MailSent, nameLink);
            return(true);
        }
示例#4
0
        void HandleBlackMarketBidOnItem(BlackMarketBidOnItem blackMarketBidOnItem)
        {
            if (!Global.BlackMarketMgr.IsEnabled())
            {
                return;
            }

            Player   player = GetPlayer();
            Creature unit   = player.GetNPCIfCanInteractWith(blackMarketBidOnItem.Guid, NPCFlags.BlackMarket, NPCFlags2.None);

            if (!unit)
            {
                Log.outDebug(LogFilter.Network, "WORLD: HandleBlackMarketBidOnItem - {0} not found or you can't interact with him.", blackMarketBidOnItem.Guid.ToString());
                return;
            }

            BlackMarketEntry entry = Global.BlackMarketMgr.GetAuctionByID(blackMarketBidOnItem.MarketID);

            if (entry == null)
            {
                Log.outDebug(LogFilter.Network, "WORLD: HandleBlackMarketBidOnItem - {0} (name: {1}) tried to bid on a nonexistent auction (MarketId: {2}).", player.GetGUID().ToString(), player.GetName(), blackMarketBidOnItem.MarketID);
                SendBlackMarketBidOnItemResult(BlackMarketError.ItemNotFound, blackMarketBidOnItem.MarketID, blackMarketBidOnItem.Item);
                return;
            }

            if (entry.GetBidder() == player.GetGUID().GetCounter())
            {
                Log.outDebug(LogFilter.Network, "WORLD: HandleBlackMarketBidOnItem - {0} (name: {1}) tried to place a bid on an item he already bid on. (MarketId: {2}).", player.GetGUID().ToString(), player.GetName(), blackMarketBidOnItem.MarketID);
                SendBlackMarketBidOnItemResult(BlackMarketError.AlreadyBid, blackMarketBidOnItem.MarketID, blackMarketBidOnItem.Item);
                return;
            }

            if (!entry.ValidateBid(blackMarketBidOnItem.BidAmount))
            {
                Log.outDebug(LogFilter.Network, "WORLD: HandleBlackMarketBidOnItem - {0} (name: {1}) tried to place an invalid bid. Amount: {2} (MarketId: {3}).", player.GetGUID().ToString(), player.GetName(), blackMarketBidOnItem.BidAmount, blackMarketBidOnItem.MarketID);
                SendBlackMarketBidOnItemResult(BlackMarketError.HigherBid, blackMarketBidOnItem.MarketID, blackMarketBidOnItem.Item);
                return;
            }

            if (!player.HasEnoughMoney(blackMarketBidOnItem.BidAmount))
            {
                Log.outDebug(LogFilter.Network, "WORLD: HandleBlackMarketBidOnItem - {0} (name: {1}) does not have enough money to place bid. (MarketId: {2}).", player.GetGUID().ToString(), player.GetName(), blackMarketBidOnItem.MarketID);
                SendBlackMarketBidOnItemResult(BlackMarketError.NotEnoughMoney, blackMarketBidOnItem.MarketID, blackMarketBidOnItem.Item);
                return;
            }

            if (entry.GetSecondsRemaining() <= 0)
            {
                Log.outDebug(LogFilter.Network, "WORLD: HandleBlackMarketBidOnItem - {0} (name: {1}) tried to bid on a completed auction. (MarketId: {2}).", player.GetGUID().ToString(), player.GetName(), blackMarketBidOnItem.MarketID);
                SendBlackMarketBidOnItemResult(BlackMarketError.DatabaseError, blackMarketBidOnItem.MarketID, blackMarketBidOnItem.Item);
                return;
            }

            SQLTransaction trans = new SQLTransaction();

            Global.BlackMarketMgr.SendAuctionOutbidMail(entry, trans);
            entry.PlaceBid(blackMarketBidOnItem.BidAmount, player, trans);

            DB.Characters.CommitTransaction(trans);

            SendBlackMarketBidOnItemResult(BlackMarketError.Ok, blackMarketBidOnItem.MarketID, blackMarketBidOnItem.Item);
        }
示例#5
0
        void HandlePetRename(PetRename packet)
        {
            ObjectGuid petguid    = packet.RenameData.PetGUID;
            bool       isdeclined = packet.RenameData.HasDeclinedNames;
            string     name       = packet.RenameData.NewName;

            Pet pet = ObjectAccessor.GetPet(GetPlayer(), petguid);

            // check it!
            if (!pet || !pet.IsPet() || pet.ToPet().GetPetType() != PetType.Hunter || !pet.HasPetFlag(UnitPetFlags.CanBeRenamed) ||
                pet.GetOwnerGUID() != GetPlayer().GetGUID() || pet.GetCharmInfo() == null)
            {
                return;
            }

            PetNameInvalidReason res = ObjectManager.CheckPetName(name);

            if (res != PetNameInvalidReason.Success)
            {
                SendPetNameInvalid(res, name, null);
                return;
            }

            if (Global.ObjectMgr.IsReservedName(name))
            {
                SendPetNameInvalid(PetNameInvalidReason.Reserved, name, null);
                return;
            }

            pet.SetName(name);
            pet.SetGroupUpdateFlag(GroupUpdatePetFlags.Name);
            pet.RemovePetFlag(UnitPetFlags.CanBeRenamed);

            PreparedStatement stmt;
            SQLTransaction    trans = new SQLTransaction();

            if (isdeclined)
            {
                stmt = DB.Characters.GetPreparedStatement(CharStatements.DEL_CHAR_PET_DECLINEDNAME);
                stmt.AddValue(0, pet.GetCharmInfo().GetPetNumber());
                trans.Append(stmt);

                stmt = DB.Characters.GetPreparedStatement(CharStatements.INS_CHAR_PET_DECLINEDNAME);
                stmt.AddValue(0, pet.GetCharmInfo().GetPetNumber());
                stmt.AddValue(1, GetPlayer().GetGUID().ToString());

                for (byte i = 0; i < SharedConst.MaxDeclinedNameCases; i++)
                {
                    stmt.AddValue(i + 1, packet.RenameData.DeclinedNames.name[i]);
                }

                trans.Append(stmt);
            }

            stmt = DB.Characters.GetPreparedStatement(CharStatements.UPD_CHAR_PET_NAME);
            stmt.AddValue(0, name);
            stmt.AddValue(1, GetPlayer().GetGUID().ToString());
            stmt.AddValue(2, pet.GetCharmInfo().GetPetNumber());
            trans.Append(stmt);

            DB.Characters.CommitTransaction(trans);

            pet.SetPetNameTimestamp((uint)Time.UnixTime); // cast can't be helped
        }
示例#6
0
 public void DeleteFromDB(SQLTransaction trans)
 {
     DeleteFromDB(GetOwnerGUID(), trans);
 }
示例#7
0
        //this function sends mail to old bidder
        public void SendAuctionOutbiddedMail(AuctionEntry auction, ulong newPrice, Player newBidder, SQLTransaction trans)
        {
            ObjectGuid oldBidder_guid = ObjectGuid.Create(HighGuid.Player, auction.bidder);
            Player     oldBidder      = Global.ObjAccessor.FindPlayer(oldBidder_guid);

            uint oldBidder_accId = 0;

            if (oldBidder == null)
            {
                oldBidder_accId = ObjectManager.GetPlayerAccountIdByGUID(oldBidder_guid);
            }

            Item item = GetAItem(auction.itemGUIDLow);

            // old bidder exist
            if (oldBidder || oldBidder_accId != 0)
            {
                if (oldBidder && item)
                {
                    oldBidder.GetSession().SendAuctionOutBidNotification(auction, item);
                }

                new MailDraft(auction.BuildAuctionMailSubject(MailAuctionAnswers.Outbidded), AuctionEntry.BuildAuctionMailBody(auction.owner, auction.bid, auction.buyout, auction.deposit, auction.GetAuctionCut()))
                .AddMoney(auction.bid)
                .SendMailTo(trans, new MailReceiver(oldBidder, auction.bidder), new MailSender(auction), MailCheckMask.Copied);
            }
        }
示例#8
0
        public void SendMailTo(SQLTransaction trans, MailReceiver receiver, MailSender sender, MailCheckMask checkMask = MailCheckMask.None, uint deliver_delay = 0)
        {
            Player pReceiver = receiver.GetPlayer();               // can be NULL
            Player pSender   = Global.ObjAccessor.FindPlayer(ObjectGuid.Create(HighGuid.Player, sender.GetSenderId()));

            if (pReceiver != null)
            {
                prepareItems(pReceiver, trans);                            // generate mail template items
            }
            uint mailId = Global.ObjectMgr.GenerateMailID();

            long deliver_time = Time.UnixTime + deliver_delay;

            //expire time if COD 3 days, if no COD 30 days, if auction sale pending 1 hour
            uint expire_delay;

            // auction mail without any items and money
            if (sender.GetMailMessageType() == MailMessageType.Auction && m_items.Empty() && m_money == 0)
            {
                expire_delay = WorldConfig.GetUIntValue(WorldCfg.MailDeliveryDelay);
            }
            // default case: expire time if COD 3 days, if no COD 30 days (or 90 days if sender is a game master)
            else
            if (m_COD != 0)
            {
                expire_delay = 3 * Time.Day;
            }
            else
            {
                expire_delay = (uint)(pSender != null && pSender.IsGameMaster() ? 90 * Time.Day : 30 * Time.Day);
            }

            long expire_time = deliver_time + expire_delay;

            // Add to DB
            byte index             = 0;
            PreparedStatement stmt = DB.Characters.GetPreparedStatement(CharStatements.INS_MAIL);

            stmt.AddValue(index, mailId);
            stmt.AddValue(++index, (byte)sender.GetMailMessageType());
            stmt.AddValue(++index, (sbyte)sender.GetStationery());
            stmt.AddValue(++index, GetMailTemplateId());
            stmt.AddValue(++index, sender.GetSenderId());
            stmt.AddValue(++index, receiver.GetPlayerGUIDLow());
            stmt.AddValue(++index, GetSubject());
            stmt.AddValue(++index, GetBody());
            stmt.AddValue(++index, !m_items.Empty());
            stmt.AddValue(++index, expire_time);
            stmt.AddValue(++index, deliver_time);
            stmt.AddValue(++index, m_money);
            stmt.AddValue(++index, m_COD);
            stmt.AddValue(++index, (byte)checkMask);
            trans.Append(stmt);

            foreach (var item in m_items.Values)
            {
                stmt = DB.Characters.GetPreparedStatement(CharStatements.INS_MAIL_ITEM);
                stmt.AddValue(0, mailId);
                stmt.AddValue(1, item.GetGUID().GetCounter());
                stmt.AddValue(2, receiver.GetPlayerGUIDLow());
                trans.Append(stmt);
            }

            // For online receiver update in game mail status and data
            if (pReceiver != null)
            {
                pReceiver.AddNewMailDeliverTime(deliver_time);

                if (pReceiver.IsMailsLoaded())
                {
                    Mail m = new Mail();
                    m.messageID      = mailId;
                    m.mailTemplateId = GetMailTemplateId();
                    m.subject        = GetSubject();
                    m.body           = GetBody();
                    m.money          = GetMoney();
                    m.COD            = GetCOD();

                    foreach (var item in m_items.Values)
                    {
                        m.AddItem(item.GetGUID().GetCounter(), item.GetEntry());
                    }

                    m.messageType  = sender.GetMailMessageType();
                    m.stationery   = sender.GetStationery();
                    m.sender       = sender.GetSenderId();
                    m.receiver     = receiver.GetPlayerGUIDLow();
                    m.expire_time  = expire_time;
                    m.deliver_time = deliver_time;
                    m.checkMask    = checkMask;
                    m.state        = MailState.Unchanged;

                    pReceiver.AddMail(m);                           // to insert new mail to beginning of maillist

                    if (!m_items.Empty())
                    {
                        foreach (var item in m_items.Values)
                        {
                            pReceiver.AddMItem(item);
                        }
                    }
                }
                else if (!m_items.Empty())
                {
                    deleteIncludedItems(null);
                }
            }
            else if (!m_items.Empty())
            {
                deleteIncludedItems(null);
            }
        }
示例#9
0
        public void SendReturnToSender(uint senderAcc, ulong senderGuid, ulong receiver_guid, SQLTransaction trans)
        {
            ObjectGuid receiverGuid = ObjectGuid.Create(HighGuid.Player, receiver_guid);
            Player     receiver     = Global.ObjAccessor.FindPlayer(receiverGuid);

            uint rc_account = 0;

            if (receiver == null)
            {
                rc_account = Global.CharacterCacheStorage.GetCharacterAccountIdByGuid(receiverGuid);
            }

            if (receiver == null && rc_account == 0)                            // sender not exist
            {
                deleteIncludedItems(trans, true);
                return;
            }

            // prepare mail and send in other case
            bool needItemDelay = false;

            if (!m_items.Empty())
            {
                // if item send to character at another account, then apply item delivery delay
                needItemDelay = senderAcc != rc_account;

                // set owner to new receiver (to prevent delete item with sender char deleting)
                foreach (var item in m_items.Values)
                {
                    item.SaveToDB(trans);                      // item not in inventory and can be save standalone
                    // owner in data will set at mail receive and item extracting
                    PreparedStatement stmt = DB.Characters.GetPreparedStatement(CharStatements.UPD_ITEM_OWNER);
                    stmt.AddValue(0, receiver_guid);
                    stmt.AddValue(1, item.GetGUID().GetCounter());
                    trans.Append(stmt);
                }
            }

            // If theres is an item, there is a one hour delivery delay.
            uint deliver_delay = needItemDelay ? WorldConfig.GetUIntValue(WorldCfg.MailDeliveryDelay) : 0;

            // will delete item or place to receiver mail list
            SendMailTo(trans, new MailReceiver(receiver, receiver_guid), new MailSender(MailMessageType.Normal, senderGuid), MailCheckMask.Returned, deliver_delay);
        }
示例#10
0
        public void SaveToDB(SQLTransaction trans)
        {
            PreparedStatement stmt;

            foreach (var pair in _pets)
            {
                switch (pair.Value.SaveInfo)
                {
                case BattlePetSaveInfo.New:
                    stmt = DB.Login.GetPreparedStatement(LoginStatements.INS_BATTLE_PETS);
                    stmt.AddValue(0, pair.Key);
                    stmt.AddValue(1, _owner.GetBattlenetAccountId());
                    stmt.AddValue(2, pair.Value.PacketInfo.Species);
                    stmt.AddValue(3, pair.Value.PacketInfo.Breed);
                    stmt.AddValue(4, pair.Value.PacketInfo.Level);
                    stmt.AddValue(5, pair.Value.PacketInfo.Exp);
                    stmt.AddValue(6, pair.Value.PacketInfo.Health);
                    stmt.AddValue(7, pair.Value.PacketInfo.Quality);
                    stmt.AddValue(8, pair.Value.PacketInfo.Flags);
                    stmt.AddValue(9, pair.Value.PacketInfo.Name);
                    trans.Append(stmt);
                    pair.Value.SaveInfo = BattlePetSaveInfo.Unchanged;
                    break;

                case BattlePetSaveInfo.Changed:
                    stmt = DB.Login.GetPreparedStatement(LoginStatements.UPD_BATTLE_PETS);
                    stmt.AddValue(0, pair.Value.PacketInfo.Level);
                    stmt.AddValue(1, pair.Value.PacketInfo.Exp);
                    stmt.AddValue(2, pair.Value.PacketInfo.Health);
                    stmt.AddValue(3, pair.Value.PacketInfo.Quality);
                    stmt.AddValue(4, pair.Value.PacketInfo.Flags);
                    stmt.AddValue(5, pair.Value.PacketInfo.Name);
                    stmt.AddValue(6, _owner.GetBattlenetAccountId());
                    stmt.AddValue(7, pair.Key);
                    trans.Append(stmt);
                    pair.Value.SaveInfo = BattlePetSaveInfo.Unchanged;
                    break;

                case BattlePetSaveInfo.Removed:
                    stmt = DB.Login.GetPreparedStatement(LoginStatements.DEL_BATTLE_PETS);
                    stmt.AddValue(0, _owner.GetBattlenetAccountId());
                    stmt.AddValue(1, pair.Key);
                    trans.Append(stmt);
                    _pets.Remove(pair.Key);
                    break;
                }
            }

            stmt = DB.Login.GetPreparedStatement(LoginStatements.DEL_BATTLE_PET_SLOTS);
            stmt.AddValue(0, _owner.GetBattlenetAccountId());
            trans.Append(stmt);

            foreach (var slot in _slots)
            {
                stmt = DB.Login.GetPreparedStatement(LoginStatements.INS_BATTLE_PET_SLOTS);
                stmt.AddValue(0, slot.Index);
                stmt.AddValue(1, _owner.GetBattlenetAccountId());
                stmt.AddValue(2, slot.Pet.Guid.GetCounter());
                stmt.AddValue(3, slot.Locked);
                trans.Append(stmt);
            }
        }
示例#11
0
 public void SendMailTo(SQLTransaction trans, Player receiver, MailSender sender, MailCheckMask checkMask = MailCheckMask.None, uint deliver_delay = 0)
 {
     SendMailTo(trans, new MailReceiver(receiver), sender, checkMask, deliver_delay);
 }
示例#12
0
        public AccountOpResult DeleteAccount(uint accountId)
        {
            // Check if accounts exists
            PreparedStatement stmt = DB.Login.GetPreparedStatement(LoginStatements.SEL_ACCOUNT_BY_ID);

            stmt.AddValue(0, accountId);
            SQLResult result = DB.Login.Query(stmt);

            if (result.IsEmpty())
            {
                return(AccountOpResult.NameNotExist);
            }

            // Obtain accounts characters
            stmt = DB.Characters.GetPreparedStatement(CharStatements.SEL_CHARS_BY_ACCOUNT_ID);
            stmt.AddValue(0, accountId);
            result = DB.Characters.Query(stmt);

            if (!result.IsEmpty())
            {
                do
                {
                    ObjectGuid guid = ObjectGuid.Create(HighGuid.Player, result.Read <ulong>(0));

                    // Kick if player is online
                    Player p = Global.ObjAccessor.FindPlayer(guid);
                    if (p)
                    {
                        WorldSession s = p.GetSession();
                        s.KickPlayer();                            // mark session to remove at next session list update
                        s.LogoutPlayer(false);                     // logout player without waiting next session list update
                    }

                    Player.DeleteFromDB(guid, accountId, false);       // no need to update realm characters
                } while (result.NextRow());
            }

            // table realm specific but common for all characters of account for realm
            stmt = DB.Characters.GetPreparedStatement(CharStatements.DEL_TUTORIALS);
            stmt.AddValue(0, accountId);
            DB.Characters.Execute(stmt);

            stmt = DB.Characters.GetPreparedStatement(CharStatements.DEL_ACCOUNT_DATA);
            stmt.AddValue(0, accountId);
            DB.Characters.Execute(stmt);

            stmt = DB.Characters.GetPreparedStatement(CharStatements.DEL_CHARACTER_BAN);
            stmt.AddValue(0, accountId);
            DB.Characters.Execute(stmt);

            SQLTransaction trans = new SQLTransaction();

            stmt = DB.Login.GetPreparedStatement(LoginStatements.DEL_ACCOUNT);
            stmt.AddValue(0, accountId);
            trans.Append(stmt);

            stmt = DB.Login.GetPreparedStatement(LoginStatements.DEL_ACCOUNT_ACCESS);
            stmt.AddValue(0, accountId);
            trans.Append(stmt);

            stmt = DB.Login.GetPreparedStatement(LoginStatements.DEL_REALM_CHARACTERS);
            stmt.AddValue(0, accountId);
            trans.Append(stmt);

            stmt = DB.Login.GetPreparedStatement(LoginStatements.DEL_ACCOUNT_BANNED);
            stmt.AddValue(0, accountId);
            trans.Append(stmt);

            stmt = DB.Login.GetPreparedStatement(LoginStatements.DEL_ACCOUNT_MUTED);
            stmt.AddValue(0, accountId);
            trans.Append(stmt);

            DB.Login.CommitTransaction(trans);

            return(AccountOpResult.Ok);
        }
 protected override void BeforeSave(SQLTransaction trans)
 {
     if (ContactType == null)
     {
         ContactType = BOContactType.Default;
     }
     base.BeforeSave(trans);
 }
示例#14
0
        public void HandleLoginRequest(HttpHeader request)
        {
            LogonData   loginForm   = Json.CreateObject <LogonData>(request.Content);
            LogonResult loginResult = new LogonResult();

            if (loginForm == null)
            {
                loginResult.AuthenticationState = "LOGIN";
                loginResult.ErrorCode           = "UNABLE_TO_DECODE";
                loginResult.ErrorMessage        = "There was an internal error while connecting to Battle.net. Please try again later.";
                SendResponse(HttpCode.BadRequest, loginResult);
                return;
            }

            string login    = "";
            string password = "";

            for (int i = 0; i < loginForm.Inputs.Count; ++i)
            {
                switch (loginForm.Inputs[i].Id)
                {
                case "account_name":
                    login = loginForm.Inputs[i].Value;
                    break;

                case "password":
                    password = loginForm.Inputs[i].Value;
                    break;
                }
            }

            PreparedStatement stmt = DB.Login.GetPreparedStatement(LoginStatements.SelBnetAuthentication);

            stmt.AddValue(0, login);

            SQLResult result = DB.Login.Query(stmt);

            if (!result.IsEmpty())
            {
                uint   accountId         = result.Read <uint>(0);
                string pass_hash         = result.Read <string>(1);
                uint   failedLogins      = result.Read <uint>(2);
                string loginTicket       = result.Read <string>(3);
                uint   loginTicketExpiry = result.Read <uint>(4);
                bool   isBanned          = result.Read <ulong>(5) != 0;

                if (CalculateShaPassHash(login.ToUpper(), password.ToUpper()) == pass_hash)
                {
                    if (loginTicket.IsEmpty() || loginTicketExpiry < Time.UnixTime)
                    {
                        byte[] ticket = new byte[0].GenerateRandomKey(20);
                        loginTicket = "TC-" + ticket.ToHexString();
                    }

                    stmt = DB.Login.GetPreparedStatement(LoginStatements.UpdBnetAuthentication);
                    stmt.AddValue(0, loginTicket);
                    stmt.AddValue(1, Time.UnixTime + 3600);
                    stmt.AddValue(2, accountId);

                    DB.Login.Execute(stmt);
                    loginResult.LoginTicket = loginTicket;
                }
                else if (!isBanned)
                {
                    uint maxWrongPassword = ConfigMgr.GetDefaultValue("WrongPass.MaxCount", 0u);

                    if (ConfigMgr.GetDefaultValue("WrongPass.Logging", false))
                    {
                        Log.outDebug(LogFilter.Network, $"[{request.Host}, Account {login}, Id {accountId}] Attempted to connect with wrong password!");
                    }

                    if (maxWrongPassword != 0)
                    {
                        SQLTransaction trans = new SQLTransaction();
                        stmt = DB.Login.GetPreparedStatement(LoginStatements.UpdBnetFailedLogins);
                        stmt.AddValue(0, accountId);
                        trans.Append(stmt);

                        ++failedLogins;

                        Log.outDebug(LogFilter.Network, $"MaxWrongPass : {maxWrongPassword}, failed_login : {accountId}");

                        if (failedLogins >= maxWrongPassword)
                        {
                            BanMode banType = ConfigMgr.GetDefaultValue("WrongPass.BanType", BanMode.IP);
                            int     banTime = ConfigMgr.GetDefaultValue("WrongPass.BanTime", 600);

                            if (banType == BanMode.Account)
                            {
                                stmt = DB.Login.GetPreparedStatement(LoginStatements.InsBnetAccountAutoBanned);
                                stmt.AddValue(0, accountId);
                            }
                            else
                            {
                                stmt = DB.Login.GetPreparedStatement(LoginStatements.InsIpAutoBanned);
                                stmt.AddValue(0, request.Host);
                            }

                            stmt.AddValue(1, banTime);
                            trans.Append(stmt);

                            stmt = DB.Login.GetPreparedStatement(LoginStatements.UpdBnetResetFailedLogins);
                            stmt.AddValue(0, accountId);
                            trans.Append(stmt);
                        }

                        DB.Login.CommitTransaction(trans);
                    }
                }

                loginResult.AuthenticationState = "DONE";
                SendResponse(HttpCode.Ok, loginResult);
            }
            else
            {
                loginResult.AuthenticationState = "LOGIN";
                loginResult.ErrorCode           = "UNABLE_TO_DECODE";
                loginResult.ErrorMessage        = "There was an internal error while connecting to Battle.net. Please try again later.";
                SendResponse(HttpCode.BadRequest, loginResult);
            }
        }
示例#15
0
        public void SaveToDB()
        {
            if (_criteriaProgress.Empty())
            {
                return;
            }

            DifficultyRecord difficultyEntry = CliDB.DifficultyStorage.LookupByKey(_map.GetDifficultyID());

            if (difficultyEntry == null || difficultyEntry.Flags.HasAnyFlag(DifficultyFlags.ChallengeMode)) // Map should have some sort of "CanSave" boolean that returns whether or not the map is savable. (Challenge modes cannot be saved for example)
            {
                return;
            }

            uint id = _map.GetInstanceId();

            if (id == 0)
            {
                Log.outDebug(LogFilter.Scenario, "Scenario.SaveToDB: Can not save scenario progress without an instance save. Map.GetInstanceId() did not return an instance save.");
                return;
            }

            SQLTransaction trans = new SQLTransaction();

            foreach (var iter in _criteriaProgress)
            {
                if (!iter.Value.Changed)
                {
                    continue;
                }

                Criteria criteria = Global.CriteriaMgr.GetCriteria(iter.Key);
                switch (criteria.Entry.Type)
                {
                // Blizzard only appears to store creature kills
                case CriteriaTypes.KillCreature:
                    break;

                default:
                    continue;
                }

                if (iter.Value.Counter != 0)
                {
                    PreparedStatement stmt = DB.Characters.GetPreparedStatement(CharStatements.DEL_SCENARIO_INSTANCE_CRITERIA);
                    stmt.AddValue(0, id);
                    stmt.AddValue(1, iter.Key);
                    trans.Append(stmt);

                    stmt = DB.Characters.GetPreparedStatement(CharStatements.INS_SCENARIO_INSTANCE_CRITERIA);
                    stmt.AddValue(0, id);
                    stmt.AddValue(1, iter.Key);
                    stmt.AddValue(2, iter.Value.Counter);
                    stmt.AddValue(3, (uint)iter.Value.Date);
                    trans.Append(stmt);
                }

                iter.Value.Changed = false;
            }

            DB.Characters.CommitTransaction(trans);
        }
示例#16
0
        public void ActivateTalentGroup(ChrSpecializationRecord spec)
        {
            if (GetActiveTalentGroup() == spec.OrderIndex)
            {
                return;
            }

            if (IsNonMeleeSpellCast(false))
            {
                InterruptNonMeleeSpells(false);
            }

            SQLTransaction trans = new SQLTransaction();

            _SaveActions(trans);
            DB.Characters.CommitTransaction(trans);

            // TO-DO: We need more research to know what happens with warlock's reagent
            Pet pet = GetPet();

            if (pet)
            {
                RemovePet(pet, PetSaveMode.NotInSlot);
            }

            ClearAllReactives();
            UnsummonAllTotems();
            ExitVehicle();
            RemoveAllControlled();

            // remove single target auras at other targets
            var scAuras = GetSingleCastAuras();

            foreach (var aura in scAuras)
            {
                if (aura.GetUnitOwner() != this)
                {
                    aura.Remove();
                }
            }

            // Let client clear his current Actions
            SendActionButtons(2);
            foreach (var talentInfo in CliDB.TalentStorage.Values)
            {
                // unlearn only talents for character class
                // some spell learned by one class as normal spells or know at creation but another class learn it as talent,
                // to prevent unexpected lost normal learned spell skip another class talents
                if (talentInfo.ClassID != (int)GetClass())
                {
                    continue;
                }

                if (talentInfo.SpellID == 0)
                {
                    continue;
                }

                SpellInfo spellInfo = Global.SpellMgr.GetSpellInfo(talentInfo.SpellID);
                if (spellInfo == null)
                {
                    continue;
                }

                RemoveSpell(talentInfo.SpellID, true);

                // search for spells that the talent teaches and unlearn them
                foreach (SpellEffectInfo effect in spellInfo.GetEffectsForDifficulty(Difficulty.None))
                {
                    if (effect != null && effect.TriggerSpell > 0 && effect.Effect == SpellEffectName.LearnSpell)
                    {
                        RemoveSpell(effect.TriggerSpell, true);
                    }
                }

                if (talentInfo.OverridesSpellID != 0)
                {
                    RemoveOverrideSpell(talentInfo.OverridesSpellID, talentInfo.SpellID);
                }
            }

            // Remove spec specific spells
            RemoveSpecializationSpells();

            foreach (uint glyphId in GetGlyphs(GetActiveTalentGroup()))
            {
                RemoveAurasDueToSpell(CliDB.GlyphPropertiesStorage.LookupByKey(glyphId).SpellID);
            }

            SetActiveTalentGroup(spec.OrderIndex);
            SetUInt32Value(PlayerFields.CurrentSpecId, spec.Id);
            if (GetPrimarySpecialization() == 0)
            {
                SetPrimarySpecialization(spec.Id);
            }

            foreach (var talentInfo in CliDB.TalentStorage.Values)
            {
                // learn only talents for character class
                if (talentInfo.ClassID != (int)GetClass())
                {
                    continue;
                }

                if (talentInfo.SpellID == 0)
                {
                    continue;
                }

                if (HasTalent(talentInfo.Id, GetActiveTalentGroup()))
                {
                    LearnSpell(talentInfo.SpellID, false);      // add the talent to the PlayerSpellMap
                    if (talentInfo.OverridesSpellID != 0)
                    {
                        AddOverrideSpell(talentInfo.OverridesSpellID, talentInfo.SpellID);
                    }
                }
            }

            LearnSpecializationSpells();

            if (CanUseMastery())
            {
                for (uint i = 0; i < PlayerConst.MaxMasterySpells; ++i)
                {
                    uint mastery = spec.MasterySpellID[i];
                    if (mastery != 0)
                    {
                        LearnSpell(mastery, false);
                    }
                }
            }

            InitTalentForLevel();

            PreparedStatement stmt = DB.Characters.GetPreparedStatement(CharStatements.SEL_CHARACTER_ACTIONS_SPEC);

            stmt.AddValue(0, GetGUID().GetCounter());
            stmt.AddValue(1, GetActiveTalentGroup());
            _LoadActions(DB.Characters.Query(stmt));

            SendActionButtons(1);

            UpdateDisplayPower();
            PowerType pw = GetPowerType();

            if (pw != PowerType.Mana)
            {
                SetPower(PowerType.Mana, 0); // Mana must be 0 even if it isn't the active power type.
            }
            SetPower(pw, 0);
            UpdateItemSetAuras(false);

            // update visible transmog
            for (byte i = EquipmentSlot.Start; i < EquipmentSlot.End; ++i)
            {
                Item equippedItem = GetItemByPos(InventorySlots.Bag0, i);
                if (equippedItem)
                {
                    SetVisibleItemSlot(i, equippedItem);
                }
            }

            foreach (uint glyphId in GetGlyphs(spec.OrderIndex))
            {
                CastSpell(this, CliDB.GlyphPropertiesStorage.LookupByKey(glyphId).SpellID, true);
            }

            ActiveGlyphs activeGlyphs = new ActiveGlyphs();

            foreach (uint glyphId in GetGlyphs(spec.OrderIndex))
            {
                List <uint> bindableSpells = Global.DB2Mgr.GetGlyphBindableSpells(glyphId);
                foreach (uint bindableSpell in bindableSpells)
                {
                    if (HasSpell(bindableSpell) && !m_overrideSpells.ContainsKey(bindableSpell))
                    {
                        activeGlyphs.Glyphs.Add(new GlyphBinding(bindableSpell, (ushort)glyphId));
                    }
                }
            }

            activeGlyphs.IsFullUpdate = true;
            SendPacket(activeGlyphs);

            var shapeshiftAuras = GetAuraEffectsByType(AuraType.ModShapeshift);

            foreach (AuraEffect aurEff in shapeshiftAuras)
            {
                aurEff.HandleShapeshiftBoosts(this, false);
                aurEff.HandleShapeshiftBoosts(this, true);
            }
        }
示例#17
0
        void HandleSendMail(SendMail packet)
        {
            if (packet.Info.Attachments.Count > SharedConst.MaxMailItems)                      // client limit
            {
                GetPlayer().SendMailResult(0, MailResponseType.Send, MailResponseResult.TooManyAttachments);
                return;
            }

            if (!CanOpenMailBox(packet.Info.Mailbox))
            {
                return;
            }

            if (string.IsNullOrEmpty(packet.Info.Target))
            {
                return;
            }

            Player player = GetPlayer();

            if (player.GetLevel() < WorldConfig.GetIntValue(WorldCfg.MailLevelReq))
            {
                SendNotification(CypherStrings.MailSenderReq, WorldConfig.GetIntValue(WorldCfg.MailLevelReq));
                return;
            }

            ObjectGuid receiverGuid = ObjectGuid.Empty;

            if (ObjectManager.NormalizePlayerName(ref packet.Info.Target))
            {
                receiverGuid = Global.CharacterCacheStorage.GetCharacterGuidByName(packet.Info.Target);
            }

            if (receiverGuid.IsEmpty())
            {
                Log.outInfo(LogFilter.Network, "Player {0} is sending mail to {1} (GUID: not existed!) with subject {2}" +
                            "and body {3} includes {4} items, {5} copper and {6} COD copper with StationeryID = {7}",
                            GetPlayerInfo(), packet.Info.Target, packet.Info.Subject, packet.Info.Body,
                            packet.Info.Attachments.Count, packet.Info.SendMoney, packet.Info.Cod, packet.Info.StationeryID);
                player.SendMailResult(0, MailResponseType.Send, MailResponseResult.RecipientNotFound);
                return;
            }

            if (packet.Info.SendMoney < 0)
            {
                GetPlayer().SendMailResult(0, MailResponseType.Send, MailResponseResult.InternalError);
                Log.outWarn(LogFilter.Server, "Player {0} attempted to send mail to {1} ({2}) with negative money value (SendMoney: {3})",
                            GetPlayerInfo(), packet.Info.Target, receiverGuid.ToString(), packet.Info.SendMoney);
                return;
            }

            if (packet.Info.Cod < 0)
            {
                GetPlayer().SendMailResult(0, MailResponseType.Send, MailResponseResult.InternalError);
                Log.outWarn(LogFilter.Server, "Player {0} attempted to send mail to {1} ({2}) with negative COD value (Cod: {3})",
                            GetPlayerInfo(), packet.Info.Target, receiverGuid.ToString(), packet.Info.Cod);
                return;
            }

            Log.outInfo(LogFilter.Network, "Player {0} is sending mail to {1} ({2}) with subject {3} and body {4}" +
                        "includes {5} items, {6} copper and {7} COD copper with StationeryID = {8}",
                        GetPlayerInfo(), packet.Info.Target, receiverGuid.ToString(), packet.Info.Subject,
                        packet.Info.Body, packet.Info.Attachments.Count, packet.Info.SendMoney, packet.Info.Cod, packet.Info.StationeryID);

            if (player.GetGUID() == receiverGuid)
            {
                player.SendMailResult(0, MailResponseType.Send, MailResponseResult.CannotSendToSelf);
                return;
            }

            uint cost = (uint)(!packet.Info.Attachments.Empty() ? 30 * packet.Info.Attachments.Count : 30);  // price hardcoded in client

            long reqmoney = cost + packet.Info.SendMoney;

            // Check for overflow
            if (reqmoney < packet.Info.SendMoney)
            {
                player.SendMailResult(0, MailResponseType.Send, MailResponseResult.NotEnoughMoney);
                return;
            }

            if (!player.HasEnoughMoney(reqmoney) && !player.IsGameMaster())
            {
                player.SendMailResult(0, MailResponseType.Send, MailResponseResult.NotEnoughMoney);
                return;
            }

            Player receiver = Global.ObjAccessor.FindPlayer(receiverGuid);

            Team receiverTeam          = 0;
            byte mailsCount            = 0;                       //do not allow to send to one player more than 100 mails
            byte receiverLevel         = 0;
            uint receiverAccountId     = 0;
            uint receiverBnetAccountId = 0;

            if (receiver)
            {
                receiverTeam          = receiver.GetTeam();
                mailsCount            = (byte)receiver.GetMails().Count;
                receiverLevel         = (byte)receiver.GetLevel();
                receiverAccountId     = receiver.GetSession().GetAccountId();
                receiverBnetAccountId = receiver.GetSession().GetBattlenetAccountId();
            }
            else
            {
                CharacterCacheEntry characterInfo = Global.CharacterCacheStorage.GetCharacterCacheByGuid(receiverGuid);
                if (characterInfo != null)
                {
                    receiverTeam      = Player.TeamForRace(characterInfo.RaceId);
                    receiverLevel     = characterInfo.Level;
                    receiverAccountId = characterInfo.AccountId;
                }

                PreparedStatement stmt = DB.Characters.GetPreparedStatement(CharStatements.SEL_MAIL_COUNT);
                stmt.AddValue(0, receiverGuid.GetCounter());

                SQLResult result = DB.Characters.Query(stmt);
                if (!result.IsEmpty())
                {
                    mailsCount = (byte)result.Read <ulong>(0);
                }

                receiverBnetAccountId = Global.BNetAccountMgr.GetIdByGameAccount(receiverAccountId);
            }

            // do not allow to have more than 100 mails in mailbox.. mails count is in opcode byte!!! - so max can be 255..
            if (mailsCount > 100)
            {
                player.SendMailResult(0, MailResponseType.Send, MailResponseResult.RecipientCapReached);
                return;
            }

            // test the receiver's Faction... or all items are account bound
            bool accountBound = !packet.Info.Attachments.Empty();

            foreach (var att in packet.Info.Attachments)
            {
                Item item = player.GetItemByGuid(att.ItemGUID);
                if (item)
                {
                    ItemTemplate itemProto = item.GetTemplate();
                    if (itemProto == null || !itemProto.GetFlags().HasAnyFlag(ItemFlags.IsBoundToAccount))
                    {
                        accountBound = false;
                        break;
                    }
                }
            }

            if (!accountBound && player.GetTeam() != receiverTeam && !HasPermission(RBACPermissions.TwoSideInteractionMail))
            {
                player.SendMailResult(0, MailResponseType.Send, MailResponseResult.NotYourTeam);
                return;
            }

            if (receiverLevel < WorldConfig.GetIntValue(WorldCfg.MailLevelReq))
            {
                SendNotification(CypherStrings.MailReceiverReq, WorldConfig.GetIntValue(WorldCfg.MailLevelReq));
                return;
            }

            List <Item> items = new List <Item>();

            foreach (var att in packet.Info.Attachments)
            {
                if (att.ItemGUID.IsEmpty())
                {
                    player.SendMailResult(0, MailResponseType.Send, MailResponseResult.MailAttachmentInvalid);
                    return;
                }

                Item item = player.GetItemByGuid(att.ItemGUID);

                // prevent sending bag with items (cheat: can be placed in bag after adding equipped empty bag to mail)
                if (!item)
                {
                    player.SendMailResult(0, MailResponseType.Send, MailResponseResult.MailAttachmentInvalid);
                    return;
                }

                if (!item.CanBeTraded(true))
                {
                    player.SendMailResult(0, MailResponseType.Send, MailResponseResult.EquipError, InventoryResult.MailBoundItem);
                    return;
                }

                if (item.IsBoundAccountWide() && item.IsSoulBound() && player.GetSession().GetAccountId() != receiverAccountId)
                {
                    if (!item.IsBattlenetAccountBound() || player.GetSession().GetBattlenetAccountId() == 0 || player.GetSession().GetBattlenetAccountId() != receiverBnetAccountId)
                    {
                        player.SendMailResult(0, MailResponseType.Send, MailResponseResult.EquipError, InventoryResult.NotSameAccount);
                        return;
                    }
                }

                if (item.GetTemplate().GetFlags().HasAnyFlag(ItemFlags.Conjured) || item.m_itemData.Expiration != 0)
                {
                    player.SendMailResult(0, MailResponseType.Send, MailResponseResult.EquipError, InventoryResult.MailBoundItem);
                    return;
                }

                if (packet.Info.Cod != 0 && item.HasItemFlag(ItemFieldFlags.Wrapped))
                {
                    player.SendMailResult(0, MailResponseType.Send, MailResponseResult.CantSendWrappedCod);
                    return;
                }

                if (item.IsNotEmptyBag())
                {
                    player.SendMailResult(0, MailResponseType.Send, MailResponseResult.EquipError, InventoryResult.DestroyNonemptyBag);
                    return;
                }

                items.Add(item);
            }

            player.SendMailResult(0, MailResponseType.Send, MailResponseResult.Ok);

            player.ModifyMoney(-reqmoney);
            player.UpdateCriteria(CriteriaTypes.GoldSpentForMail, cost);

            bool needItemDelay = false;

            MailDraft draft = new MailDraft(packet.Info.Subject, packet.Info.Body);

            SQLTransaction trans = new SQLTransaction();

            if (!packet.Info.Attachments.Empty() || packet.Info.SendMoney > 0)
            {
                bool log = HasPermission(RBACPermissions.LogGmTrade);
                if (!packet.Info.Attachments.Empty())
                {
                    foreach (var item in items)
                    {
                        if (log)
                        {
                            Log.outCommand(GetAccountId(), "GM {0} ({1}) (Account: {2}) mail item: {3} (Entry: {4} Count: {5}) to player: {6} ({7}) (Account: {8})",
                                           GetPlayerName(), GetPlayer().GetGUID().ToString(), GetAccountId(), item.GetTemplate().GetName(), item.GetEntry(), item.GetCount(),
                                           packet.Info.Target, receiverGuid.ToString(), receiverAccountId);
                        }

                        item.SetNotRefundable(GetPlayer()); // makes the item no longer refundable
                        player.MoveItemFromInventory(item.GetBagSlot(), item.GetSlot(), true);

                        item.DeleteFromInventoryDB(trans);     // deletes item from character's inventory
                        item.SetOwnerGUID(receiverGuid);
                        item.SetState(ItemUpdateState.Changed);
                        item.SaveToDB(trans);                  // recursive and not have transaction guard into self, item not in inventory and can be save standalone

                        draft.AddItem(item);
                    }

                    // if item send to character at another account, then apply item delivery delay
                    needItemDelay = player.GetSession().GetAccountId() != receiverAccountId;
                }

                if (log && packet.Info.SendMoney > 0)
                {
                    Log.outCommand(GetAccountId(), "GM {0} ({1}) (Account: {{2}) mail money: {3} to player: {4} ({5}) (Account: {6})",
                                   GetPlayerName(), GetPlayer().GetGUID().ToString(), GetAccountId(), packet.Info.SendMoney, packet.Info.Target, receiverGuid.ToString(), receiverAccountId);
                }
            }

            // If theres is an item, there is a one hour delivery delay if sent to another account's character.
            uint deliver_delay = needItemDelay ? WorldConfig.GetUIntValue(WorldCfg.MailDeliveryDelay) : 0;

            // Mail sent between guild members arrives instantly
            Guild guild = Global.GuildMgr.GetGuildById(player.GetGuildId());

            if (guild)
            {
                if (guild.IsMember(receiverGuid))
                {
                    deliver_delay = 0;
                }
            }

            // don't ask for COD if there are no items
            if (packet.Info.Attachments.Empty())
            {
                packet.Info.Cod = 0;
            }

            // will delete item or place to receiver mail list
            draft.AddMoney((ulong)packet.Info.SendMoney).AddCOD((uint)packet.Info.Cod).SendMailTo(trans, new MailReceiver(receiver, receiverGuid.GetCounter()), new MailSender(player), string.IsNullOrEmpty(packet.Info.Body) ? MailCheckMask.Copied : MailCheckMask.HasBody, deliver_delay);

            player.SaveInventoryAndGoldToDB(trans);
            DB.Characters.CommitTransaction(trans);
        }
示例#18
0
        public bool ResetTalents(bool noCost = false)
        {
            Global.ScriptMgr.OnPlayerTalentsReset(this, noCost);

            // not need after this call
            if (HasAtLoginFlag(AtLoginFlags.ResetTalents))
            {
                RemoveAtLoginFlag(AtLoginFlags.ResetTalents, true);
            }

            uint cost = 0;

            if (!noCost && !WorldConfig.GetBoolValue(WorldCfg.NoResetTalentCost))
            {
                cost = GetNextResetTalentsCost();

                if (!HasEnoughMoney(cost))
                {
                    SendBuyError(BuyResult.NotEnoughtMoney, null, 0);
                    return(false);
                }
            }

            RemovePet(null, PetSaveMode.NotInSlot, true);

            foreach (var talentInfo in CliDB.TalentStorage.Values)
            {
                // unlearn only talents for character class
                // some spell learned by one class as normal spells or know at creation but another class learn it as talent,
                // to prevent unexpected lost normal learned spell skip another class talents
                if (talentInfo.ClassID != (uint)GetClass())
                {
                    continue;
                }

                // skip non-existant talent ranks
                if (talentInfo.SpellID == 0)
                {
                    continue;
                }

                RemoveTalent(talentInfo);
            }

            SQLTransaction trans = new SQLTransaction();

            _SaveTalents(trans);
            _SaveSpells(trans);
            DB.Characters.CommitTransaction(trans);

            if (!noCost)
            {
                ModifyMoney(-cost);
                UpdateCriteria(CriteriaTypes.GoldSpentForTalents, cost);
                UpdateCriteria(CriteriaTypes.NumberOfTalentResets, 1);

                SetTalentResetCost(cost);
                SetTalentResetTime(Time.UnixTime);
            }

            return(true);
        }
示例#19
0
        void _ResetOrWarnAll(uint mapid, Difficulty difficulty, bool warn, long resetTime)
        {
            // global reset for all instances of the given map
            MapRecord mapEntry = CliDB.MapStorage.LookupByKey(mapid);

            if (!mapEntry.Instanceable())
            {
                return;
            }

            Log.outDebug(LogFilter.Misc, "InstanceSaveManager.ResetOrWarnAll: Processing map {0} ({1}) on difficulty {2} (warn? {3})", mapEntry.MapName[Global.WorldMgr.GetDefaultDbcLocale()], mapid, difficulty, warn);
            long now = Time.UnixTime;

            if (!warn)
            {
                // calculate the next reset time
                long next_reset = GetSubsequentResetTime(mapid, difficulty, resetTime);
                if (next_reset == 0)
                {
                    return;
                }

                // delete them from the DB, even if not loaded
                SQLTransaction trans = new SQLTransaction();

                PreparedStatement stmt = DB.Characters.GetPreparedStatement(CharStatements.DEL_EXPIRED_CHAR_INSTANCE_BY_MAP_DIFF);
                stmt.AddValue(0, mapid);
                stmt.AddValue(1, (byte)difficulty);
                trans.Append(stmt);

                stmt = DB.Characters.GetPreparedStatement(CharStatements.DEL_GROUP_INSTANCE_BY_MAP_DIFF);
                stmt.AddValue(0, mapid);
                stmt.AddValue(1, (byte)difficulty);
                trans.Append(stmt);

                stmt = DB.Characters.GetPreparedStatement(CharStatements.DEL_EXPIRED_INSTANCE_BY_MAP_DIFF);
                stmt.AddValue(0, mapid);
                stmt.AddValue(1, (byte)difficulty);
                trans.Append(stmt);

                stmt = DB.Characters.GetPreparedStatement(CharStatements.UPD_EXPIRE_CHAR_INSTANCE_BY_MAP_DIFF);
                stmt.AddValue(0, mapid);
                stmt.AddValue(1, (byte)difficulty);
                trans.Append(stmt);

                DB.Characters.CommitTransaction(trans);

                // promote loaded binds to instances of the given map
                foreach (var pair in m_instanceSaveById.ToList())
                {
                    if (pair.Value.GetMapId() == mapid && pair.Value.GetDifficultyID() == difficulty)
                    {
                        _ResetSave(pair);
                    }
                }

                SetResetTimeFor(mapid, difficulty, next_reset);
                ScheduleReset(true, next_reset - 3600, new InstResetEvent(1, mapid, difficulty, 0));

                // Update it in the DB
                stmt = DB.Characters.GetPreparedStatement(CharStatements.UPD_GLOBAL_INSTANCE_RESETTIME);
                stmt.AddValue(0, (uint)next_reset);
                stmt.AddValue(1, (ushort)mapid);
                stmt.AddValue(2, (byte)difficulty);

                DB.Characters.Execute(stmt);
            }

            // note: this isn't fast but it's meant to be executed very rarely
            Map  map      = Global.MapMgr.CreateBaseMap(mapid);    // _not_ include difficulty
            var  instMaps = ((MapInstanced)map).GetInstancedMaps();
            uint timeLeft;

            foreach (var pair in instMaps)
            {
                Map map2 = pair.Value;
                if (!map2.IsDungeon())
                {
                    continue;
                }

                if (warn)
                {
                    if (now >= resetTime)
                    {
                        timeLeft = 0;
                    }
                    else
                    {
                        timeLeft = (uint)(resetTime - now);
                    }

                    ((InstanceMap)map2).SendResetWarnings(timeLeft);
                }
                else
                {
                    ((InstanceMap)map2).Reset(InstanceResetMethod.Global);
                }
            }

            // @todo delete creature/gameobject respawn times even if the maps are not loaded
        }
示例#20
0
 public override void SaveToDB(SQLTransaction trans)
 {
     base.SaveToDB(trans);
 }
示例#21
0
        public void SendAuctionWonMail(AuctionEntry auction, SQLTransaction trans)
        {
            Item item = GetAItem(auction.itemGUIDLow);

            if (!item)
            {
                return;
            }

            uint       bidderAccId = 0;
            ObjectGuid bidderGuid  = ObjectGuid.Create(HighGuid.Player, auction.bidder);
            Player     bidder      = Global.ObjAccessor.FindPlayer(bidderGuid);
            // data for gm.log
            string bidderName = "";
            bool   logGmTrade = false;

            if (bidder)
            {
                bidderAccId = bidder.GetSession().GetAccountId();
                bidderName  = bidder.GetName();
                logGmTrade  = bidder.GetSession().HasPermission(RBACPermissions.LogGmTrade);
            }
            else
            {
                bidderAccId = ObjectManager.GetPlayerAccountIdByGUID(bidderGuid);
                logGmTrade  = Global.AccountMgr.HasPermission(bidderAccId, RBACPermissions.LogGmTrade, Global.WorldMgr.GetRealm().Id.Realm);

                if (logGmTrade && !ObjectManager.GetPlayerNameByGUID(bidderGuid, out bidderName))
                {
                    bidderName = Global.ObjectMgr.GetCypherString(CypherStrings.Unknown);
                }
            }

            if (logGmTrade)
            {
                ObjectGuid ownerGuid = ObjectGuid.Create(HighGuid.Player, auction.owner);
                string     ownerName;
                if (!ObjectManager.GetPlayerNameByGUID(ownerGuid, out ownerName))
                {
                    ownerName = Global.ObjectMgr.GetCypherString(CypherStrings.Unknown);
                }

                uint ownerAccId = ObjectManager.GetPlayerAccountIdByGUID(ownerGuid);

                Log.outCommand(bidderAccId, $"GM {bidderName} (Account: {bidderAccId}) won item in auction: {item.GetTemplate().GetName()} (Entry: {item.GetEntry()} Count: {item.GetCount()}) and pay money: {auction.bid}. Original owner {ownerName} (Account: {ownerAccId})");
            }

            // receiver exist
            if (bidder || bidderAccId != 0)
            {
                // set owner to bidder (to prevent delete item with sender char deleting)
                // owner in `data` will set at mail receive and item extracting
                PreparedStatement stmt = DB.Characters.GetPreparedStatement(CharStatements.UPD_ITEM_OWNER);
                stmt.AddValue(0, auction.bidder);
                stmt.AddValue(1, item.GetGUID().GetCounter());
                trans.Append(stmt);

                if (bidder)
                {
                    bidder.GetSession().SendAuctionWonNotification(auction, item);
                    // FIXME: for offline player need also
                    bidder.UpdateCriteria(CriteriaTypes.WonAuctions, 1);
                }

                new MailDraft(auction.BuildAuctionMailSubject(MailAuctionAnswers.Won), AuctionEntry.BuildAuctionMailBody(auction.owner, auction.bid, auction.buyout, 0, 0))
                .AddItem(item)
                .SendMailTo(trans, new MailReceiver(bidder, auction.bidder), new MailSender(auction), MailCheckMask.Copied);
            }
            else
            {
                // bidder doesn't exist, delete the item
                Global.AuctionMgr.RemoveAItem(auction.itemGUIDLow, true);
            }
        }
示例#22
0
        void HandleAuctionSellItem(AuctionSellItem packet)
        {
            foreach (var aitem in packet.Items)
            {
                if (aitem.Guid.IsEmpty() || aitem.UseCount == 0 || aitem.UseCount > 1000)
                {
                    return;
                }
            }

            if (packet.MinBid == 0 || packet.RunTime == 0)
            {
                return;
            }

            if (packet.MinBid > PlayerConst.MaxMoneyAmount || packet.BuyoutPrice > PlayerConst.MaxMoneyAmount)
            {
                Log.outDebug(LogFilter.Network, "WORLD: HandleAuctionSellItem - Player {0} ({1}) attempted to sell item with higher price than max gold amount.", GetPlayer().GetName(), GetPlayer().GetGUID().ToString());
                SendAuctionCommandResult(null, AuctionAction.SellItem, AuctionError.DatabaseError);
                return;
            }

            Creature creature = GetPlayer().GetNPCIfCanInteractWith(packet.Auctioneer, NPCFlags.Auctioneer, NPCFlags2.None);

            if (!creature)
            {
                Log.outDebug(LogFilter.Network, "WORLD: HandleAuctionSellItem - {0} not found or you can't interact with him.", packet.Auctioneer.ToString());
                return;
            }

            uint houseId = 0;
            AuctionHouseRecord auctionHouseEntry = Global.AuctionMgr.GetAuctionHouseEntry(creature.GetFaction(), ref houseId);

            if (auctionHouseEntry == null)
            {
                Log.outDebug(LogFilter.Network, "WORLD: HandleAuctionSellItem - {0} has wrong faction.", packet.Auctioneer.ToString());
                return;
            }

            packet.RunTime *= Time.Minute;
            switch (packet.RunTime)
            {
            case 1 * SharedConst.MinAuctionTime:
            case 2 * SharedConst.MinAuctionTime:
            case 4 * SharedConst.MinAuctionTime:
                break;

            default:
                return;
            }

            if (GetPlayer().HasUnitState(UnitState.Died))
            {
                GetPlayer().RemoveAurasByType(AuraType.FeignDeath);
            }

            uint finalCount = 0;

            Item[] items = new Item[packet.Items.Count];
            for (var i = 0; i < packet.Items.Count; ++i)
            {
                items[i] = GetPlayer().GetItemByGuid(packet.Items[i].Guid);
                if (!items[i])
                {
                    SendAuctionCommandResult(null, AuctionAction.SellItem, AuctionError.ItemNotFound);
                    return;
                }

                if (Global.AuctionMgr.GetAItem(items[i].GetGUID().GetCounter()) || !items[i].CanBeTraded() || items[i].IsNotEmptyBag() ||
                    items[i].GetTemplate().GetFlags().HasAnyFlag(ItemFlags.Conjured) || items[i].m_itemData.Expiration != 0 ||
                    items[i].GetCount() < packet.Items[i].UseCount)
                {
                    SendAuctionCommandResult(null, AuctionAction.SellItem, AuctionError.DatabaseError);
                    return;
                }

                finalCount += packet.Items[i].UseCount;
            }

            if (packet.Items.Empty())
            {
                SendAuctionCommandResult(null, AuctionAction.SellItem, AuctionError.DatabaseError);
                return;
            }

            if (finalCount == 0)
            {
                SendAuctionCommandResult(null, AuctionAction.SellItem, AuctionError.DatabaseError);
                return;
            }

            // check if there are 2 identical guids, in this case user is most likely cheating
            for (int i = 0; i < packet.Items.Count; ++i)
            {
                for (int j = i + 1; j < packet.Items.Count; ++j)
                {
                    if (packet.Items[i].Guid == packet.Items[j].Guid)
                    {
                        SendAuctionCommandResult(null, AuctionAction.SellItem, AuctionError.DatabaseError);
                        return;
                    }
                    if (items[i].GetEntry() != items[j].GetEntry())
                    {
                        SendAuctionCommandResult(null, AuctionAction.SellItem, AuctionError.ItemNotFound);
                        return;
                    }
                }
            }

            for (var i = 0; i < packet.Items.Count; ++i)
            {
                if (items[i].GetMaxStackCount() < finalCount)
                {
                    SendAuctionCommandResult(null, AuctionAction.SellItem, AuctionError.DatabaseError);
                    return;
                }
            }

            Item item = items[0];

            uint auctionTime = (uint)(packet.RunTime * WorldConfig.GetFloatValue(WorldCfg.RateAuctionTime));
            AuctionHouseObject auctionHouse = Global.AuctionMgr.GetAuctionsMap(creature.GetFaction());

            ulong deposit = Global.AuctionMgr.GetAuctionDeposit(auctionHouseEntry, packet.RunTime, item, finalCount);

            if (!GetPlayer().HasEnoughMoney(deposit))
            {
                SendAuctionCommandResult(null, AuctionAction.SellItem, AuctionError.NotEnoughtMoney);
                return;
            }

            AuctionEntry   AH = new AuctionEntry();
            SQLTransaction trans;

            if (WorldConfig.GetBoolValue(WorldCfg.AllowTwoSideInteractionAuction))
            {
                AH.auctioneer = 23442;     //@TODO - HARDCODED DB GUID, BAD BAD BAD
            }
            else
            {
                AH.auctioneer = creature.GetSpawnId();
            }

            // Required stack size of auction matches to current item stack size, just move item to auctionhouse
            if (packet.Items.Count == 1 && item.GetCount() == packet.Items[0].UseCount)
            {
                if (HasPermission(RBACPermissions.LogGmTrade))
                {
                    Log.outCommand(GetAccountId(), "GM {0} (Account: {1}) create auction: {2} (Entry: {3} Count: {4})",
                                   GetPlayerName(), GetAccountId(), item.GetTemplate().GetName(), item.GetEntry(), item.GetCount());
                }

                AH.Id                = Global.ObjectMgr.GenerateAuctionID();
                AH.itemGUIDLow       = item.GetGUID().GetCounter();
                AH.itemEntry         = item.GetEntry();
                AH.itemCount         = item.GetCount();
                AH.owner             = GetPlayer().GetGUID().GetCounter();
                AH.startbid          = (uint)packet.MinBid;
                AH.bidder            = 0;
                AH.bid               = 0;
                AH.buyout            = (uint)packet.BuyoutPrice;
                AH.expire_time       = Time.UnixTime + auctionTime;
                AH.deposit           = deposit;
                AH.etime             = packet.RunTime;
                AH.auctionHouseEntry = auctionHouseEntry;

                Log.outInfo(LogFilter.Network, "CMSG_AUCTION_SELL_ITEM: {0} {1} is selling item {2} {3} to auctioneer {4} with count {5} with initial bid {6} with buyout {7} and with time {8} (in sec) in auctionhouse {9}",
                            GetPlayer().GetGUID().ToString(), GetPlayer().GetName(), item.GetGUID().ToString(), item.GetTemplate().GetName(), AH.auctioneer, item.GetCount(), packet.MinBid, packet.BuyoutPrice, auctionTime, AH.GetHouseId());
                Global.AuctionMgr.AddAItem(item);
                auctionHouse.AddAuction(AH);

                GetPlayer().MoveItemFromInventory(item.GetBagSlot(), item.GetSlot(), true);

                trans = new SQLTransaction();
                item.DeleteFromInventoryDB(trans);
                item.SaveToDB(trans);
                AH.SaveToDB(trans);
                GetPlayer().SaveInventoryAndGoldToDB(trans);
                DB.Characters.CommitTransaction(trans);

                SendAuctionCommandResult(AH, AuctionAction.SellItem, AuctionError.Ok);

                GetPlayer().UpdateCriteria(CriteriaTypes.CreateAuction, 1);
            }
            else // Required stack size of auction does not match to current item stack size, clone item and set correct stack size
            {
                Item newItem = item.CloneItem(finalCount, GetPlayer());
                if (!newItem)
                {
                    Log.outError(LogFilter.Network, "CMSG_AuctionAction.SellItem: Could not create clone of item {0}", item.GetEntry());
                    SendAuctionCommandResult(null, AuctionAction.SellItem, AuctionError.DatabaseError);
                    return;
                }

                if (HasPermission(RBACPermissions.LogGmTrade))
                {
                    Log.outCommand(GetAccountId(), "GM {0} (Account: {1}) create auction: {2} (Entry: {3} Count: {4})",
                                   GetPlayerName(), GetAccountId(), newItem.GetTemplate().GetName(), newItem.GetEntry(), newItem.GetCount());
                }

                AH.Id                = Global.ObjectMgr.GenerateAuctionID();
                AH.itemGUIDLow       = newItem.GetGUID().GetCounter();
                AH.itemEntry         = newItem.GetEntry();
                AH.itemCount         = newItem.GetCount();
                AH.owner             = GetPlayer().GetGUID().GetCounter();
                AH.startbid          = (uint)packet.MinBid;
                AH.bidder            = 0;
                AH.bid               = 0;
                AH.buyout            = (uint)packet.BuyoutPrice;
                AH.expire_time       = Time.UnixTime + auctionTime;
                AH.deposit           = deposit;
                AH.etime             = packet.RunTime;
                AH.auctionHouseEntry = auctionHouseEntry;

                Log.outInfo(LogFilter.Network, "CMSG_AuctionAction.SellItem: {0} {1} is selling {2} {3} to auctioneer {4} with count {5} with initial bid {6} with buyout {7} and with time {8} (in sec) in auctionhouse {9}",
                            GetPlayer().GetGUID().ToString(), GetPlayer().GetName(), newItem.GetGUID().ToString(), newItem.GetTemplate().GetName(), AH.auctioneer, newItem.GetCount(), packet.MinBid, packet.BuyoutPrice, auctionTime, AH.GetHouseId());
                Global.AuctionMgr.AddAItem(newItem);
                auctionHouse.AddAuction(AH);

                for (var i = 0; i < packet.Items.Count; ++i)
                {
                    Item item2 = items[i];

                    // Item stack count equals required count, ready to delete item - cloned item will be used for auction
                    if (item2.GetCount() == packet.Items[i].UseCount)
                    {
                        GetPlayer().MoveItemFromInventory(item2.GetBagSlot(), item2.GetSlot(), true);

                        trans = new SQLTransaction();
                        item2.DeleteFromInventoryDB(trans);
                        item2.DeleteFromDB(trans);
                        DB.Characters.CommitTransaction(trans);
                    }
                    else // Item stack count is bigger than required count, update item stack count and save to database - cloned item will be used for auction
                    {
                        item2.SetCount(item2.GetCount() - packet.Items[i].UseCount);
                        item2.SetState(ItemUpdateState.Changed, GetPlayer());
                        GetPlayer().ItemRemovedQuestCheck(item2.GetEntry(), packet.Items[i].UseCount);
                        item2.SendUpdateToPlayer(GetPlayer());

                        trans = new SQLTransaction();
                        item2.SaveToDB(trans);
                        DB.Characters.CommitTransaction(trans);
                    }
                }

                trans = new SQLTransaction();
                newItem.SaveToDB(trans);
                AH.SaveToDB(trans);
                GetPlayer().SaveInventoryAndGoldToDB(trans);
                DB.Characters.CommitTransaction(trans);

                SendAuctionCommandResult(AH, AuctionAction.SellItem, AuctionError.Ok);

                GetPlayer().UpdateCriteria(CriteriaTypes.CreateAuction, 1);
            }

            GetPlayer().ModifyMoney(-(long)deposit);
        }
示例#23
0
        public void SaveToDB <T>(SQLTransaction trans) where T : WorldObject
        {
            PreparedStatement stmt;

            if (typeof(T) == typeof(Pet))
            {
                stmt = DB.Characters.GetPreparedStatement(CharStatements.DEL_PET_SPELL_COOLDOWNS);
                stmt.AddValue(0, _owner.GetCharmInfo().GetPetNumber());
                trans.Append(stmt);

                stmt = DB.Characters.GetPreparedStatement(CharStatements.DEL_PET_SPELL_CHARGES);
                stmt.AddValue(0, _owner.GetCharmInfo().GetPetNumber());
                trans.Append(stmt);

                byte index = 0;
                foreach (var pair in _spellCooldowns)
                {
                    if (!pair.Value.OnHold)
                    {
                        index = 0;
                        stmt  = DB.Characters.GetPreparedStatement(CharStatements.INS_PET_SPELL_COOLDOWN);
                        stmt.AddValue(index++, _owner.GetCharmInfo().GetPetNumber());
                        stmt.AddValue(index++, pair.Key);
                        stmt.AddValue(index++, (uint)Time.DateTimeToUnixTime(pair.Value.CooldownEnd));
                        stmt.AddValue(index++, pair.Value.CategoryId);
                        stmt.AddValue(index++, (uint)Time.DateTimeToUnixTime(pair.Value.CategoryEnd));
                        trans.Append(stmt);
                    }
                }

                foreach (var pair in _categoryCharges)
                {
                    index = 0;
                    stmt  = DB.Characters.GetPreparedStatement(CharStatements.INS_PET_SPELL_CHARGES);
                    stmt.AddValue(index++, _owner.GetCharmInfo().GetPetNumber());
                    stmt.AddValue(index++, pair.Key);
                    stmt.AddValue(index++, (uint)Time.DateTimeToUnixTime(pair.Value.RechargeStart));
                    stmt.AddValue(index++, (uint)Time.DateTimeToUnixTime(pair.Value.RechargeEnd));
                    trans.Append(stmt);
                }
            }
            else
            {
                stmt = DB.Characters.GetPreparedStatement(CharStatements.DEL_CHAR_SPELL_COOLDOWNS);
                stmt.AddValue(0, _owner.GetGUID().GetCounter());
                trans.Append(stmt);

                stmt = DB.Characters.GetPreparedStatement(CharStatements.DEL_CHAR_SPELL_CHARGES);
                stmt.AddValue(0, _owner.GetGUID().GetCounter());
                trans.Append(stmt);

                byte index = 0;
                foreach (var pair in _spellCooldowns)
                {
                    if (!pair.Value.OnHold)
                    {
                        index = 0;
                        stmt  = DB.Characters.GetPreparedStatement(CharStatements.INS_CHAR_SPELL_COOLDOWN);
                        stmt.AddValue(index++, _owner.GetGUID().GetCounter());
                        stmt.AddValue(index++, pair.Key);
                        stmt.AddValue(index++, pair.Value.ItemId);
                        stmt.AddValue(index++, (uint)Time.DateTimeToUnixTime(pair.Value.CooldownEnd));
                        stmt.AddValue(index++, pair.Value.CategoryId);
                        stmt.AddValue(index++, (uint)Time.DateTimeToUnixTime(pair.Value.CategoryEnd));
                        trans.Append(stmt);
                    }
                }

                foreach (var pair in _categoryCharges)
                {
                    index = 0;
                    stmt  = DB.Characters.GetPreparedStatement(CharStatements.INS_CHAR_SPELL_CHARGES);
                    stmt.AddValue(index++, _owner.GetGUID().GetCounter());
                    stmt.AddValue(index++, pair.Key);
                    stmt.AddValue(index++, (uint)Time.DateTimeToUnixTime(pair.Value.RechargeStart));
                    stmt.AddValue(index++, (uint)Time.DateTimeToUnixTime(pair.Value.RechargeEnd));
                    trans.Append(stmt);
                }
            }
        }
示例#24
0
        void HandleAuctionPlaceBid(AuctionPlaceBid packet)
        {
            if (packet.AuctionItemID == 0 || packet.BidAmount == 0)
            {
                return; // check for cheaters
            }
            Creature creature = GetPlayer().GetNPCIfCanInteractWith(packet.Auctioneer, NPCFlags.Auctioneer, NPCFlags2.None);

            if (!creature)
            {
                Log.outDebug(LogFilter.Network, "WORLD: HandleAuctionPlaceBid - {0} not found or you can't interact with him.", packet.Auctioneer.ToString());
                return;
            }

            // remove fake death
            if (GetPlayer().HasUnitState(UnitState.Died))
            {
                GetPlayer().RemoveAurasByType(AuraType.FeignDeath);
            }

            AuctionHouseObject auctionHouse = Global.AuctionMgr.GetAuctionsMap(creature.GetFaction());

            AuctionEntry auction = auctionHouse.GetAuction(packet.AuctionItemID);
            Player       player  = GetPlayer();

            if (auction == null || auction.owner == player.GetGUID().GetCounter())
            {
                //you cannot bid your own auction:
                SendAuctionCommandResult(null, AuctionAction.PlaceBid, AuctionError.BidOwn);
                return;
            }

            // impossible have online own another character (use this for speedup check in case online owner)
            ObjectGuid ownerGuid     = ObjectGuid.Create(HighGuid.Player, auction.owner);
            Player     auction_owner = Global.ObjAccessor.FindPlayer(ownerGuid);

            if (!auction_owner && Global.CharacterCacheStorage.GetCharacterAccountIdByGuid(ownerGuid) == player.GetSession().GetAccountId())
            {
                //you cannot bid your another character auction:
                SendAuctionCommandResult(null, AuctionAction.PlaceBid, AuctionError.BidOwn);
                return;
            }

            // cheating
            if (packet.BidAmount <= auction.bid || packet.BidAmount < auction.startbid)
            {
                return;
            }

            // price too low for next bid if not buyout
            if ((packet.BidAmount < auction.buyout || auction.buyout == 0) && packet.BidAmount < auction.bid + auction.GetAuctionOutBid())
            {
                // client already test it but just in case ...
                SendAuctionCommandResult(auction, AuctionAction.PlaceBid, AuctionError.HigherBid);
                return;
            }

            if (!player.HasEnoughMoney(packet.BidAmount))
            {
                // client already test it but just in case ...
                SendAuctionCommandResult(auction, AuctionAction.PlaceBid, AuctionError.NotEnoughtMoney);
                return;
            }

            SQLTransaction trans = new SQLTransaction();

            if (packet.BidAmount < auction.buyout || auction.buyout == 0)
            {
                if (auction.bidder > 0)
                {
                    if (auction.bidder == player.GetGUID().GetCounter())
                    {
                        player.ModifyMoney(-(long)(packet.BidAmount - auction.bid));
                    }
                    else
                    {
                        // mail to last bidder and return money
                        Global.AuctionMgr.SendAuctionOutbiddedMail(auction, packet.BidAmount, GetPlayer(), trans);
                        player.ModifyMoney(-(long)packet.BidAmount);
                    }
                }
                else
                {
                    player.ModifyMoney(-(long)packet.BidAmount);
                }

                auction.bidder = player.GetGUID().GetCounter();
                auction.bid    = (uint)packet.BidAmount;
                GetPlayer().UpdateCriteria(CriteriaTypes.HighestAuctionBid, packet.BidAmount);

                PreparedStatement stmt = DB.Characters.GetPreparedStatement(CharStatements.UPD_AUCTION_BID);
                stmt.AddValue(0, auction.bidder);
                stmt.AddValue(1, auction.bid);
                stmt.AddValue(2, auction.Id);
                trans.Append(stmt);

                SendAuctionCommandResult(auction, AuctionAction.PlaceBid, AuctionError.Ok);

                // Not sure if we must send this now.
                Player owner = Global.ObjAccessor.FindConnectedPlayer(ObjectGuid.Create(HighGuid.Player, auction.owner));
                Item   item  = Global.AuctionMgr.GetAItem(auction.itemGUIDLow);
                if (owner && item)
                {
                    owner.GetSession().SendAuctionOwnerBidNotification(auction, item);
                }
            }
            else
            {
                //buyout:
                if (player.GetGUID().GetCounter() == auction.bidder)
                {
                    player.ModifyMoney(-(long)(auction.buyout - auction.bid));
                }
                else
                {
                    player.ModifyMoney(-(long)auction.buyout);
                    if (auction.bidder != 0)                          //buyout for bidded auction ..
                    {
                        Global.AuctionMgr.SendAuctionOutbiddedMail(auction, auction.buyout, GetPlayer(), trans);
                    }
                }
                auction.bidder = player.GetGUID().GetCounter();
                auction.bid    = auction.buyout;
                GetPlayer().UpdateCriteria(CriteriaTypes.HighestAuctionBid, auction.buyout);

                SendAuctionCommandResult(auction, AuctionAction.PlaceBid, AuctionError.Ok);

                //- Mails must be under transaction control too to prevent data loss
                Global.AuctionMgr.SendAuctionSalePendingMail(auction, trans);
                Global.AuctionMgr.SendAuctionSuccessfulMail(auction, trans);
                Global.AuctionMgr.SendAuctionWonMail(auction, trans);

                auction.DeleteFromDB(trans);

                Global.AuctionMgr.RemoveAItem(auction.itemGUIDLow);
                auctionHouse.RemoveAuction(auction);
            }

            player.SaveInventoryAndGoldToDB(trans);
            DB.Characters.CommitTransaction(trans);
        }
示例#25
0
        void HandlePetitionBuy(PetitionBuy packet)
        {
            // prevent cheating
            Creature creature = GetPlayer().GetNPCIfCanInteractWith(packet.Unit, NPCFlags.Petitioner);

            if (!creature)
            {
                Log.outDebug(LogFilter.Network, "WORLD: HandlePetitionBuyOpcode - {0} not found or you can't interact with him.", packet.Unit.ToString());
                return;
            }

            // remove fake death
            if (GetPlayer().HasUnitState(UnitState.Died))
            {
                GetPlayer().RemoveAurasByType(AuraType.FeignDeath);
            }

            uint charterItemID = GuildConst.CharterItemId;
            int  cost          = WorldConfig.GetIntValue(WorldCfg.CharterCostGuild);

            // do not let if already in guild.
            if (GetPlayer().GetGuildId() != 0)
            {
                return;
            }

            if (Global.GuildMgr.GetGuildByName(packet.Title))
            {
                Guild.SendCommandResult(this, GuildCommandType.CreateGuild, GuildCommandError.NameExists_S, packet.Title);
                return;
            }

            if (Global.ObjectMgr.IsReservedName(packet.Title) || !ObjectManager.IsValidCharterName(packet.Title))
            {
                Guild.SendCommandResult(this, GuildCommandType.CreateGuild, GuildCommandError.NameInvalid, packet.Title);
                return;
            }

            ItemTemplate pProto = Global.ObjectMgr.GetItemTemplate(charterItemID);

            if (pProto == null)
            {
                GetPlayer().SendBuyError(BuyResult.CantFindItem, null, charterItemID);
                return;
            }

            if (!GetPlayer().HasEnoughMoney(cost))
            {                                                       //player hasn't got enough money
                GetPlayer().SendBuyError(BuyResult.NotEnoughtMoney, creature, charterItemID);
                return;
            }

            List <ItemPosCount> dest = new List <ItemPosCount>();
            InventoryResult     msg  = GetPlayer().CanStoreNewItem(ItemConst.NullBag, ItemConst.NullSlot, dest, charterItemID, pProto.GetBuyCount());

            if (msg != InventoryResult.Ok)
            {
                GetPlayer().SendEquipError(msg, null, null, charterItemID);
                return;
            }

            GetPlayer().ModifyMoney(-cost);
            Item charter = GetPlayer().StoreNewItem(dest, charterItemID, true);

            if (!charter)
            {
                return;
            }

            charter.SetUInt32Value(ItemFields.Enchantment, (uint)charter.GetGUID().GetCounter());
            // ITEM_FIELD_ENCHANTMENT_1_1 is guild/arenateam id
            // ITEM_FIELD_ENCHANTMENT_1_1+1 is current signatures count (showed on item)
            charter.SetState(ItemUpdateState.Changed, GetPlayer());
            GetPlayer().SendNewItem(charter, 1, true, false);

            // a petition is invalid, if both the owner and the type matches
            // we checked above, if this player is in an arenateam, so this must be
            // datacorruption
            PreparedStatement stmt = DB.Characters.GetPreparedStatement(CharStatements.SEL_PETITION_BY_OWNER);

            stmt.AddValue(0, GetPlayer().GetGUID().GetCounter());
            SQLResult result = DB.Characters.Query(stmt);

            StringBuilder ssInvalidPetitionGUIDs = new StringBuilder();

            if (!result.IsEmpty())
            {
                do
                {
                    ssInvalidPetitionGUIDs.AppendFormat("'{0}', ", result.Read <uint>(0));
                } while (result.NextRow());
            }

            // delete petitions with the same guid as this one
            ssInvalidPetitionGUIDs.AppendFormat("'{0}'", charter.GetGUID().GetCounter());

            Log.outDebug(LogFilter.Network, "Invalid petition GUIDs: {0}", ssInvalidPetitionGUIDs.ToString());
            SQLTransaction trans = new SQLTransaction();

            trans.Append("DELETE FROM petition WHERE petitionguid IN ({0})", ssInvalidPetitionGUIDs.ToString());
            trans.Append("DELETE FROM petition_sign WHERE petitionguid IN ({0})", ssInvalidPetitionGUIDs.ToString());

            stmt = DB.Characters.GetPreparedStatement(CharStatements.INS_PETITION);
            stmt.AddValue(0, GetPlayer().GetGUID().GetCounter());
            stmt.AddValue(1, charter.GetGUID().GetCounter());
            stmt.AddValue(2, packet.Title);
            trans.Append(stmt);

            DB.Characters.CommitTransaction(trans);
        }
示例#26
0
        void HandleAuctionRemoveItem(AuctionRemoveItem packet)
        {
            Creature creature = GetPlayer().GetNPCIfCanInteractWith(packet.Auctioneer, NPCFlags.Auctioneer, NPCFlags2.None);

            if (!creature)
            {
                Log.outDebug(LogFilter.Network, "WORLD: HandleAuctionRemoveItem - {0} not found or you can't interact with him.", packet.Auctioneer.ToString());
                return;
            }

            // remove fake death
            if (GetPlayer().HasUnitState(UnitState.Died))
            {
                GetPlayer().RemoveAurasByType(AuraType.FeignDeath);
            }

            AuctionHouseObject auctionHouse = Global.AuctionMgr.GetAuctionsMap(creature.GetFaction());

            AuctionEntry auction = auctionHouse.GetAuction((uint)packet.AuctionItemID);
            Player       player  = GetPlayer();

            SQLTransaction trans = new SQLTransaction();

            if (auction != null && auction.owner == player.GetGUID().GetCounter())
            {
                Item pItem = Global.AuctionMgr.GetAItem(auction.itemGUIDLow);
                if (pItem)
                {
                    if (auction.bidder > 0)                        // If we have a bidder, we have to send him the money he paid
                    {
                        ulong auctionCut = auction.GetAuctionCut();
                        if (!player.HasEnoughMoney(auctionCut))          //player doesn't have enough money, maybe message needed
                        {
                            return;
                        }
                        Global.AuctionMgr.SendAuctionCancelledToBidderMail(auction, trans);
                        player.ModifyMoney(-(long)auctionCut);
                    }

                    // item will deleted or added to received mail list
                    new MailDraft(auction.BuildAuctionMailSubject(MailAuctionAnswers.Canceled), AuctionEntry.BuildAuctionMailBody(0, 0, auction.buyout, auction.deposit, 0))
                    .AddItem(pItem)
                    .SendMailTo(trans, new MailReceiver(player), new MailSender(auction), MailCheckMask.Copied);
                }
                else
                {
                    Log.outError(LogFilter.Network, "Auction id: {0} got non existing item (item guid : {1})!", auction.Id, auction.itemGUIDLow);
                    SendAuctionCommandResult(null, AuctionAction.Cancel, AuctionError.DatabaseError);
                    return;
                }
            }
            else
            {
                SendAuctionCommandResult(null, AuctionAction.Cancel, AuctionError.DatabaseError);
                //this code isn't possible ... maybe there should be assert
                Log.outError(LogFilter.Network, "CHEATER: {0} tried to cancel auction (id: {1}) of another player or auction is null", player.GetGUID().ToString(), packet.AuctionItemID);
                return;
            }

            //inform player, that auction is removed
            SendAuctionCommandResult(auction, AuctionAction.Cancel, AuctionError.Ok);

            // Now remove the auction
            player.SaveInventoryAndGoldToDB(trans);
            auction.DeleteFromDB(trans);
            DB.Characters.CommitTransaction(trans);

            Global.AuctionMgr.RemoveAItem(auction.itemGUIDLow);
            auctionHouse.RemoveAuction(auction);
        }
示例#27
0
        void HandleWrapItem(WrapItem packet)
        {
            if (packet.Inv.Items.Count != 2)
            {
                Log.outError(LogFilter.Network, "HandleWrapItem - Invalid itemCount ({0})", packet.Inv.Items.Count);
                return;
            }

            // Gift
            byte giftContainerSlot = packet.Inv.Items[0].ContainerSlot;
            byte giftSlot          = packet.Inv.Items[0].Slot;
            // Item
            byte itemContainerSlot = packet.Inv.Items[1].ContainerSlot;
            byte itemSlot          = packet.Inv.Items[1].Slot;

            Item gift = GetPlayer().GetItemByPos(giftContainerSlot, giftSlot);

            if (!gift)
            {
                GetPlayer().SendEquipError(InventoryResult.ItemNotFound, gift);
                return;
            }

            if (!gift.GetTemplate().GetFlags().HasAnyFlag(ItemFlags.IsWrapper)) // cheating: non-wrapper wrapper
            {
                GetPlayer().SendEquipError(InventoryResult.ItemNotFound, gift);
                return;
            }

            Item item = GetPlayer().GetItemByPos(itemContainerSlot, itemSlot);

            if (!item)
            {
                GetPlayer().SendEquipError(InventoryResult.ItemNotFound, item);
                return;
            }

            if (item == gift) // not possable with pacjket from real client
            {
                GetPlayer().SendEquipError(InventoryResult.CantWrapWrapped, item);
                return;
            }

            if (item.IsEquipped())
            {
                GetPlayer().SendEquipError(InventoryResult.CantWrapEquipped, item);
                return;
            }

            if (!item.GetGiftCreator().IsEmpty()) // HasFlag(ITEM_FIELD_FLAGS, ITEM_FLAGS_WRAPPED);
            {
                GetPlayer().SendEquipError(InventoryResult.CantWrapWrapped, item);
                return;
            }

            if (item.IsBag())
            {
                GetPlayer().SendEquipError(InventoryResult.CantWrapBags, item);
                return;
            }

            if (item.IsSoulBound())
            {
                GetPlayer().SendEquipError(InventoryResult.CantWrapBound, item);
                return;
            }

            if (item.GetMaxStackCount() != 1)
            {
                GetPlayer().SendEquipError(InventoryResult.CantWrapStackable, item);
                return;
            }

            // maybe not correct check  (it is better than nothing)
            if (item.GetTemplate().GetMaxCount() > 0)
            {
                GetPlayer().SendEquipError(InventoryResult.CantWrapUnique, item);
                return;
            }

            SQLTransaction trans = new SQLTransaction();

            PreparedStatement stmt = DB.Characters.GetPreparedStatement(CharStatements.INS_CHAR_GIFT);

            stmt.AddValue(0, item.GetOwnerGUID().GetCounter());
            stmt.AddValue(1, item.GetGUID().GetCounter());
            stmt.AddValue(2, item.GetEntry());
            stmt.AddValue(3, (uint)item.m_itemData.DynamicFlags);
            trans.Append(stmt);

            item.SetEntry(gift.GetEntry());

            switch (item.GetEntry())
            {
            case 5042:
                item.SetEntry(5043);
                break;

            case 5048:
                item.SetEntry(5044);
                break;

            case 17303:
                item.SetEntry(17302);
                break;

            case 17304:
                item.SetEntry(17305);
                break;

            case 17307:
                item.SetEntry(17308);
                break;

            case 21830:
                item.SetEntry(21831);
                break;
            }

            item.SetGiftCreator(GetPlayer().GetGUID());
            item.SetItemFlags(ItemFieldFlags.Wrapped);
            item.SetState(ItemUpdateState.Changed, GetPlayer());

            if (item.GetState() == ItemUpdateState.New) // save new item, to have alway for `character_gifts` record in `item_instance`
            {
                // after save it will be impossible to remove the item from the queue
                Item.RemoveItemFromUpdateQueueOf(item, GetPlayer());
                item.SaveToDB(trans); // item gave inventory record unchanged and can be save standalone
            }
            DB.Characters.CommitTransaction(trans);

            uint count = 1;

            GetPlayer().DestroyItemCount(gift, ref count, true);
        }
示例#28
0
        public void SendAuctionWonMail(BlackMarketEntry entry, SQLTransaction trans)
        {
            // Mail already sent
            if (entry.GetMailSent())
            {
                return;
            }

            uint       bidderAccId;
            ObjectGuid bidderGuid = ObjectGuid.Create(HighGuid.Player, entry.GetBidder());
            Player     bidder     = Global.ObjAccessor.FindConnectedPlayer(bidderGuid);
            // data for gm.log
            string bidderName = "";
            bool   logGmTrade;

            if (bidder)
            {
                bidderAccId = bidder.GetSession().GetAccountId();
                bidderName  = bidder.GetName();
                logGmTrade  = bidder.GetSession().HasPermission(RBACPermissions.LogGmTrade);
            }
            else
            {
                bidderAccId = Global.CharacterCacheStorage.GetCharacterAccountIdByGuid(bidderGuid);
                if (bidderAccId == 0) // Account exists
                {
                    return;
                }

                logGmTrade = Global.AccountMgr.HasPermission(bidderAccId, RBACPermissions.LogGmTrade, Global.WorldMgr.GetRealmId().Realm);

                if (logGmTrade && !Global.CharacterCacheStorage.GetCharacterNameByGuid(bidderGuid, out bidderName))
                {
                    bidderName = Global.ObjectMgr.GetCypherString(CypherStrings.Unknown);
                }
            }

            // Create item
            BlackMarketTemplate templ = entry.GetTemplate();
            Item item = Item.CreateItem(templ.Item.ItemID, templ.Quantity, ItemContext.BlackMarket);

            if (!item)
            {
                return;
            }

            if (templ.Item.ItemBonus.HasValue)
            {
                foreach (uint bonusList in templ.Item.ItemBonus.Value.BonusListIDs)
                {
                    item.AddBonuses(bonusList);
                }
            }

            item.SetOwnerGUID(bidderGuid);

            item.SaveToDB(trans);

            // Log trade
            if (logGmTrade)
            {
                Log.outCommand(bidderAccId, "GM {0} (Account: {1}) won item in blackmarket auction: {2} (Entry: {3} Count: {4}) and payed gold : {5}.",
                               bidderName, bidderAccId, item.GetTemplate().GetName(), item.GetEntry(), item.GetCount(), entry.GetCurrentBid() / MoneyConstants.Gold);
            }

            if (bidder)
            {
                bidder.GetSession().SendBlackMarketWonNotification(entry, item);
            }

            new MailDraft(entry.BuildAuctionMailSubject(BMAHMailAuctionAnswers.Won), entry.BuildAuctionMailBody())
            .AddItem(item)
            .SendMailTo(trans, new MailReceiver(bidder, entry.GetBidder()), new MailSender(entry), MailCheckMask.Copied);

            entry.MailSent();
        }
示例#29
0
        static bool HandleSendItemsCommand(StringArguments args, CommandHandler handler)
        {
            // format: name "subject text" "mail text" item1[:count1] item2[:count2] ... item12[:count12]
            Player     receiver;
            ObjectGuid receiverGuid;
            string     receiverName;

            if (!handler.ExtractPlayerTarget(args, out receiver, out receiverGuid, out receiverName))
            {
                return(false);
            }

            string tail1 = args.NextString("");

            if (string.IsNullOrEmpty(tail1))
            {
                return(false);
            }

            string subject = handler.ExtractQuotedArg(tail1);

            if (string.IsNullOrEmpty(subject))
            {
                return(false);
            }

            string tail2 = args.NextString("");

            if (string.IsNullOrEmpty(tail2))
            {
                return(false);
            }

            string text = handler.ExtractQuotedArg(tail2);

            if (string.IsNullOrEmpty(text))
            {
                return(false);
            }

            // extract items
            List <KeyValuePair <uint, uint> > items = new List <KeyValuePair <uint, uint> >();

            // get all tail string
            StringArguments tail = new StringArguments(args.NextString(""));

            // get from tail next item str
            StringArguments itemStr;

            while (!(itemStr = new StringArguments(tail.NextString(" "))).Empty())
            {
                // parse item str
                string itemIdStr    = itemStr.NextString(":");
                string itemCountStr = itemStr.NextString(" ");

                if (!uint.TryParse(itemIdStr, out uint itemId) || itemId == 0)
                {
                    return(false);
                }

                ItemTemplate item_proto = Global.ObjectMgr.GetItemTemplate(itemId);
                if (item_proto == null)
                {
                    handler.SendSysMessage(CypherStrings.CommandItemidinvalid, itemId);
                    return(false);
                }

                uint itemCount = 0;
                if (string.IsNullOrEmpty(itemCountStr) || !uint.TryParse(itemCountStr, out itemCount))
                {
                    itemCount = 1;
                }

                if (itemCount < 1 || (item_proto.GetMaxCount() > 0 && itemCount > item_proto.GetMaxCount()))
                {
                    handler.SendSysMessage(CypherStrings.CommandInvalidItemCount, itemCount, itemId);
                    return(false);
                }

                while (itemCount > item_proto.GetMaxStackSize())
                {
                    items.Add(new KeyValuePair <uint, uint>(itemId, item_proto.GetMaxStackSize()));
                    itemCount -= item_proto.GetMaxStackSize();
                }

                items.Add(new KeyValuePair <uint, uint>(itemId, itemCount));

                if (items.Count > SharedConst.MaxMailItems)
                {
                    handler.SendSysMessage(CypherStrings.CommandMailItemsLimit, SharedConst.MaxMailItems);
                    return(false);
                }
            }

            // from console show not existed sender
            MailSender sender = new MailSender(MailMessageType.Normal, handler.GetSession() ? handler.GetSession().GetPlayer().GetGUID().GetCounter() : 0, MailStationery.Gm);

            // fill mail
            MailDraft draft = new MailDraft(subject, text);

            SQLTransaction trans = new SQLTransaction();

            foreach (var pair in items)
            {
                Item item = Item.CreateItem(pair.Key, pair.Value, handler.GetSession() ? handler.GetSession().GetPlayer() : null);
                if (item)
                {
                    item.SaveToDB(trans);                               // save for prevent lost at next mail load, if send fail then item will deleted
                    draft.AddItem(item);
                }
            }

            draft.SendMailTo(trans, new MailReceiver(receiver, receiverGuid.GetCounter()), sender);
            DB.Characters.CommitTransaction(trans);

            string nameLink = handler.PlayerLink(receiverName);

            handler.SendSysMessage(CypherStrings.MailSent, nameLink);
            return(true);
        }
示例#30
0
        void HandleMailTakeItem(MailTakeItem packet)
        {
            uint AttachID = packet.AttachID;

            if (!CanOpenMailBox(packet.Mailbox))
            {
                return;
            }

            Player player = GetPlayer();

            Mail m = player.GetMail(packet.MailID);

            if (m == null || m.state == MailState.Deleted || m.deliver_time > Time.UnixTime)
            {
                player.SendMailResult(packet.MailID, MailResponseType.ItemTaken, MailResponseResult.InternalError);
                return;
            }

            // verify that the mail has the item to avoid cheaters taking COD items without paying
            if (!m.items.Any(p => p.item_guid == AttachID))
            {
                player.SendMailResult(packet.MailID, MailResponseType.ItemTaken, MailResponseResult.InternalError);
                return;
            }

            // prevent cheating with skip client money check
            if (!player.HasEnoughMoney(m.COD))
            {
                player.SendMailResult(packet.MailID, MailResponseType.ItemTaken, MailResponseResult.NotEnoughMoney);
                return;
            }

            Item it = player.GetMItem(packet.AttachID);

            List <ItemPosCount> dest = new List <ItemPosCount>();
            InventoryResult     msg  = GetPlayer().CanStoreItem(ItemConst.NullBag, ItemConst.NullSlot, dest, it, false);

            if (msg == InventoryResult.Ok)
            {
                SQLTransaction trans = new SQLTransaction();
                m.RemoveItem(packet.AttachID);
                m.removedItems.Add(packet.AttachID);

                if (m.COD > 0)                                     //if there is COD, take COD money from player and send them to sender by mail
                {
                    ObjectGuid sender_guid = ObjectGuid.Create(HighGuid.Player, m.sender);
                    Player     receiver    = Global.ObjAccessor.FindPlayer(sender_guid);

                    uint sender_accId = 0;

                    if (HasPermission(RBACPermissions.LogGmTrade))
                    {
                        string sender_name;
                        if (receiver)
                        {
                            sender_accId = receiver.GetSession().GetAccountId();
                            sender_name  = receiver.GetName();
                        }
                        else
                        {
                            // can be calculated early
                            sender_accId = Global.CharacterCacheStorage.GetCharacterAccountIdByGuid(sender_guid);

                            if (!Global.CharacterCacheStorage.GetCharacterNameByGuid(sender_guid, out sender_name))
                            {
                                sender_name = Global.ObjectMgr.GetCypherString(CypherStrings.Unknown);
                            }
                        }
                        Log.outCommand(GetAccountId(), "GM {0} (Account: {1}) receiver mail item: {2} (Entry: {3} Count: {4}) and send COD money: {5} to player: {6} (Account: {7})",
                                       GetPlayerName(), GetAccountId(), it.GetTemplate().GetName(), it.GetEntry(), it.GetCount(), m.COD, sender_name, sender_accId);
                    }
                    else if (!receiver)
                    {
                        sender_accId = Global.CharacterCacheStorage.GetCharacterAccountIdByGuid(sender_guid);
                    }

                    // check player existence
                    if (receiver || sender_accId != 0)
                    {
                        new MailDraft(m.subject, "")
                        .AddMoney(m.COD)
                        .SendMailTo(trans, new MailReceiver(receiver, m.sender), new MailSender(MailMessageType.Normal, m.receiver), MailCheckMask.CodPayment);
                    }

                    player.ModifyMoney(-(long)m.COD);
                }
                m.COD   = 0;
                m.state = MailState.Changed;
                player.m_mailsUpdated = true;
                player.RemoveMItem(it.GetGUID().GetCounter());

                uint count = it.GetCount();                      // save counts before store and possible merge with deleting
                it.SetState(ItemUpdateState.Unchanged);          // need to set this state, otherwise item cannot be removed later, if neccessary
                player.MoveItemToInventory(dest, it, true);

                player.SaveInventoryAndGoldToDB(trans);
                player._SaveMail(trans);
                DB.Characters.CommitTransaction(trans);

                player.SendMailResult(packet.MailID, MailResponseType.ItemTaken, MailResponseResult.Ok, 0, packet.AttachID, count);
            }
            else
            {
                player.SendMailResult(packet.MailID, MailResponseType.ItemTaken, MailResponseResult.EquipError, msg);
            }
        }
示例#31
0
        public override void SaveToDB(SQLTransaction trans)
        {
            PreparedStatement stmt = DB.Characters.GetPreparedStatement(CharStatements.DEL_ITEM_INSTANCE_AZERITE);

            stmt.AddValue(0, GetGUID().GetCounter());
            trans.Append(stmt);

            stmt = DB.Characters.GetPreparedStatement(CharStatements.DEL_ITEM_INSTANCE_AZERITE_MILESTONE_POWER);
            stmt.AddValue(0, GetGUID().GetCounter());
            trans.Append(stmt);

            stmt = DB.Characters.GetPreparedStatement(CharStatements.DEL_ITEM_INSTANCE_AZERITE_UNLOCKED_ESSENCE);
            stmt.AddValue(0, GetGUID().GetCounter());
            trans.Append(stmt);

            switch (GetState())
            {
            case ItemUpdateState.New:
            case ItemUpdateState.Changed:
                stmt = DB.Characters.GetPreparedStatement(CharStatements.INS_ITEM_INSTANCE_AZERITE);
                stmt.AddValue(0, GetGUID().GetCounter());
                stmt.AddValue(1, m_azeriteItemData.Xp);
                stmt.AddValue(2, m_azeriteItemData.Level);
                stmt.AddValue(3, m_azeriteItemData.KnowledgeLevel);

                int specIndex = 0;
                for (; specIndex < m_azeriteItemData.SelectedEssences.Size(); ++specIndex)
                {
                    stmt.AddValue(4 + specIndex * 5, m_azeriteItemData.SelectedEssences[specIndex].SpecializationID);
                    for (int j = 0; j < SharedConst.MaxAzeriteEssenceSlot; ++j)
                    {
                        stmt.AddValue(5 + specIndex * 5 + j, m_azeriteItemData.SelectedEssences[specIndex].AzeriteEssenceID[j]);
                    }
                }
                for (; specIndex < 4; ++specIndex)
                {
                    stmt.AddValue(4 + specIndex * 5, 0);
                    for (int j = 0; j < SharedConst.MaxAzeriteEssenceSlot; ++j)
                    {
                        stmt.AddValue(5 + specIndex * 5 + j, 0);
                    }
                }

                trans.Append(stmt);

                foreach (uint azeriteItemMilestonePowerId in m_azeriteItemData.UnlockedEssenceMilestones)
                {
                    stmt = DB.Characters.GetPreparedStatement(CharStatements.INS_ITEM_INSTANCE_AZERITE_MILESTONE_POWER);
                    stmt.AddValue(0, GetGUID().GetCounter());
                    stmt.AddValue(1, azeriteItemMilestonePowerId);
                    trans.Append(stmt);
                }

                foreach (var azeriteEssence in m_azeriteItemData.UnlockedEssences)
                {
                    stmt = DB.Characters.GetPreparedStatement(CharStatements.INS_ITEM_INSTANCE_AZERITE_UNLOCKED_ESSENCE);
                    stmt.AddValue(0, GetGUID().GetCounter());
                    stmt.AddValue(1, azeriteEssence.AzeriteEssenceID);
                    stmt.AddValue(2, azeriteEssence.Rank);
                    trans.Append(stmt);
                }
                break;
            }

            base.SaveToDB(trans);
        }
 protected override void BeforeSave(SQLTransaction trans)
 {
     if (StateProvince == null)
         StateProvince = new BOStateProvince(1);
     base.BeforeSave(trans);
 }