示例#1
0
        public void RemoveFromQueue(ObjectGuid guid)
        {
            RemoveFromNewQueue(guid);
            RemoveFromCurrentQueue(guid);
            RemoveFromCompatibles(guid);

            string sguid = guid.ToString();

            var itDelete = QueueDataStore.LastOrDefault().Key;

            foreach (var key in QueueDataStore.Keys.ToList())
            {
                var data = QueueDataStore[key];
                if (key != guid)
                {
                    if (data.bestCompatible.Contains(sguid))
                    {
                        data.bestCompatible = "";
                        FindBestCompatibleInQueue(key, data);
                    }
                }
                else
                {
                    itDelete = key;
                }
            }

            if (!itDelete.IsEmpty())
            {
                QueueDataStore.Remove(itDelete);
            }
        }
示例#2
0
        public void SendTrainerList(ObjectGuid guid, uint trainerId)
        {
            Creature unit = GetPlayer().GetNPCIfCanInteractWith(guid, NPCFlags.Trainer);

            if (unit == null)
            {
                Log.outDebug(LogFilter.Network, $"WORLD: SendTrainerList - {guid.ToString()} not found or you can not interact with him.");
                return;
            }

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

            Trainer trainer = Global.ObjectMgr.GetTrainer(trainerId);

            if (trainer == null)
            {
                Log.outDebug(LogFilter.Network, $"WORLD: SendTrainerList - trainer spells not found for trainer {guid.ToString()} id {trainerId}");
                return;
            }

            _player.PlayerTalkClass.GetInteractionData().Reset();
            _player.PlayerTalkClass.GetInteractionData().SourceGuid = guid;
            _player.PlayerTalkClass.GetInteractionData().TrainerId  = trainerId;
            trainer.SendSpells(unit, _player, GetSessionDbLocaleIndex());
        }
示例#3
0
        void RemoveFromCompatibles(ObjectGuid guid)
        {
            string strGuid = guid.ToString();

            Log.outDebug(LogFilter.Lfg, "RemoveFromCompatibles: Removing [{0}]", guid);
            foreach (var itNext in CompatibleMapStore.ToList())
            {
                if (itNext.Key.Contains(strGuid))
                {
                    CompatibleMapStore.Remove(itNext.Key);
                }
            }
        }
        static bool HandleGameObjectDeleteCommand(StringArguments args, CommandHandler handler)
        {
            // number or [name] Shift-click form |color|Hgameobject:go_guid|h[name]|h|r
            string id = handler.ExtractKeyFromLink(args, "Hgameobject");

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

            if (!ulong.TryParse(id, out ulong guidLow) || guidLow == 0)
            {
                return(false);
            }

            Player player = handler.GetSession().GetPlayer();

            // force respawn to make sure we find something
            player.GetMap().RemoveRespawnTime(SpawnObjectType.GameObject, guidLow, true);
            GameObject obj = handler.GetObjectFromPlayerMapByDbGuid(guidLow);

            if (!obj)
            {
                handler.SendSysMessage(CypherStrings.CommandObjnotfound, guidLow);
                return(false);
            }

            ObjectGuid ownerGuid = obj.GetOwnerGUID();

            if (ownerGuid.IsEmpty())
            {
                Unit owner = Global.ObjAccessor.GetUnit(player, ownerGuid);
                if (!owner || !ownerGuid.IsPlayer())
                {
                    handler.SendSysMessage(CypherStrings.CommandDelobjrefercreature, ownerGuid.ToString(), obj.GetGUID().ToString());
                    return(false);
                }

                owner.RemoveGameObject(obj, false);
            }

            obj.SetRespawnTime(0);                                 // not save respawn time
            obj.Delete();
            obj.DeleteFromDB();

            handler.SendSysMessage(CypherStrings.CommandDelobjmessage, obj.GetGUID().ToString());

            return(true);
        }
示例#5
0
        public static void OnRemoveObject(ObjectGuid id)
        {
            string msg = id.ToString();

            try
            {
                IGameObject obj;
                if (sObjectsOfInterest.TryGetValue(id, out obj))
                {
                    msg = "Object Of Interest Deleted: " + GetName(obj) + " (ID=" + id + ")";

                    DebugLogCorrection(msg);

                    //throw new Exception();
                }
            }
            catch (Exception e)
            {
                Common.Exception(msg, e);
            }
        }
示例#6
0
        public override string ToString()
        {
            StringBuilder sb = new StringBuilder();

            if (AceSid != null)
            {
                sb.AppendLineEnv($"{nameof(AceSid)}: {AceSid.ToString()}");
            }

            if (AceType != null)
            {
                sb.AppendLineEnv($"{nameof(AceType)}: {AceType.ToString()}");
            }

            if (AceFlags != null && AceFlags.Any())
            {
                sb.AppendLineEnv($"{nameof(AceFlags)}: {string.Join(", ", AceFlags)}");
            }

            if (Rights != null && Rights.Any())
            {
                sb.AppendLineEnv($"{nameof(Rights)}:");
                for (int i = 0; i < Rights.Length; ++i)
                {
                    sb.AppendIndentEnv(Rights[i]);
                }
            }

            if (ObjectGuid != null)
            {
                sb.AppendLineEnv($"{nameof(ObjectGuid)}: {ObjectGuid.ToString()}");
            }

            if (InheritObjectGuid != null)
            {
                sb.AppendLineEnv($"{nameof(InheritObjectGuid)}: {InheritObjectGuid.ToString()}");
            }

            return(sb.ToString());
        }
示例#7
0
        public void SendListInventory(ObjectGuid vendorGuid)
        {
            Creature vendor = GetPlayer().GetNPCIfCanInteractWith(vendorGuid, NPCFlags.Vendor);

            if (vendor == null)
            {
                Log.outDebug(LogFilter.Network, "WORLD: SendListInventory - {0} not found or you can not interact with him.", vendorGuid.ToString());
                GetPlayer().SendSellError(SellResult.CantFindVendor, null, ObjectGuid.Empty);
                return;
            }

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

            // Stop the npc if moving
            if (vendor.HasUnitState(UnitState.Moving))
            {
                vendor.StopMoving();
            }

            VendorItemData vendorItems  = vendor.GetVendorItems();
            int            rawItemCount = vendorItems != null?vendorItems.GetItemCount() : 0;

            VendorInventory packet = new VendorInventory();

            packet.Vendor = vendor.GetGUID();

            float discountMod = GetPlayer().GetReputationPriceDiscount(vendor);
            byte  count       = 0;

            for (uint slot = 0; slot < rawItemCount; ++slot)
            {
                VendorItem vendorItem = vendorItems.GetItem(slot);
                if (vendorItem == null)
                {
                    continue;
                }

                VendorItemPkt item = new VendorItemPkt();

                PlayerConditionRecord playerCondition = CliDB.PlayerConditionStorage.LookupByKey(vendorItem.PlayerConditionId);
                if (playerCondition != null)
                {
                    if (!ConditionManager.IsPlayerMeetingCondition(_player, playerCondition))
                    {
                        item.PlayerConditionFailed = (int)playerCondition.Id;
                    }
                }

                if (vendorItem.Type == ItemVendorType.Item)
                {
                    ItemTemplate itemTemplate = Global.ObjectMgr.GetItemTemplate(vendorItem.item);
                    if (itemTemplate == null)
                    {
                        continue;
                    }

                    int leftInStock = vendorItem.maxcount == 0 ? -1 : (int)vendor.GetVendorItemCurrentCount(vendorItem);
                    if (!GetPlayer().IsGameMaster())
                    {
                        if (!Convert.ToBoolean(itemTemplate.GetAllowableClass() & GetPlayer().getClassMask()) && itemTemplate.GetBonding() == ItemBondingType.OnAcquire)
                        {
                            continue;
                        }

                        if ((itemTemplate.GetFlags2().HasAnyFlag(ItemFlags2.FactionHorde) && GetPlayer().GetTeam() == Team.Alliance) ||
                            (itemTemplate.GetFlags2().HasAnyFlag(ItemFlags2.FactionAlliance) && GetPlayer().GetTeam() == Team.Horde))
                        {
                            continue;
                        }

                        if (leftInStock == 0)
                        {
                            continue;
                        }
                    }

                    if (!Global.ConditionMgr.IsObjectMeetingVendorItemConditions(vendor.GetEntry(), vendorItem.item, _player, vendor))
                    {
                        Log.outDebug(LogFilter.Condition, "SendListInventory: conditions not met for creature entry {0} item {1}", vendor.GetEntry(), vendorItem.item);
                        continue;
                    }

                    int price = (int)(vendorItem.IsGoldRequired(itemTemplate) ? Math.Floor(itemTemplate.GetBuyPrice() * discountMod) : 0);

                    int priceMod = GetPlayer().GetTotalAuraModifier(AuraType.ModVendorItemsPrices);
                    if (priceMod != 0)
                    {
                        price -= MathFunctions.CalculatePct(price, priceMod);
                    }

                    item.MuID                = (int)slot + 1;
                    item.Durability          = (int)itemTemplate.MaxDurability;
                    item.ExtendedCostID      = (int)vendorItem.ExtendedCost;
                    item.Type                = (int)vendorItem.Type;
                    item.Quantity            = leftInStock;
                    item.StackCount          = (int)itemTemplate.GetBuyCount();
                    item.Price               = (ulong)price;
                    item.DoNotFilterOnVendor = vendorItem.IgnoreFiltering;

                    item.Item.ItemID = vendorItem.item;
                    if (!vendorItem.BonusListIDs.Empty())
                    {
                        item.Item.ItemBonus.HasValue           = true;
                        item.Item.ItemBonus.Value.BonusListIDs = vendorItem.BonusListIDs;
                    }

                    packet.Items.Add(item);
                }
                else if (vendorItem.Type == ItemVendorType.Currency)
                {
                    CurrencyTypesRecord currencyTemplate = CliDB.CurrencyTypesStorage.LookupByKey(vendorItem.item);
                    if (currencyTemplate == null)
                    {
                        continue;
                    }

                    if (vendorItem.ExtendedCost == 0)
                    {
                        continue;                             // there's no price defined for currencies, only extendedcost is used
                    }
                    item.MuID                = (int)slot + 1; // client expects counting to start at 1
                    item.ExtendedCostID      = (int)vendorItem.ExtendedCost;
                    item.Item.ItemID         = vendorItem.item;
                    item.Type                = (int)vendorItem.Type;
                    item.StackCount          = (int)vendorItem.maxcount;
                    item.DoNotFilterOnVendor = vendorItem.IgnoreFiltering;

                    packet.Items.Add(item);
                }
                else
                {
                    continue;
                }

                if (++count >= SharedConst.MaxVendorItems)
                {
                    break;
                }
            }

            SendPacket(packet);
        }
示例#8
0
        public bool AddMember(ObjectGuid playerGuid)
        {
            string playerName;
            Class  playerClass;

            // Check if arena team is full (Can't have more than type * 2 players)
            if (GetMembersSize() >= GetArenaType() * 2)
            {
                return(false);
            }

            // Get player name and class either from db or ObjectMgr
            CharacterInfo characterInfo;
            Player        player = Global.ObjAccessor.FindPlayer(playerGuid);

            if (player)
            {
                playerClass = player.GetClass();
                playerName  = player.GetName();
            }
            else if ((characterInfo = Global.WorldMgr.GetCharacterInfo(playerGuid)) != null)
            {
                playerName  = characterInfo.Name;
                playerClass = characterInfo.ClassID;
            }
            else
            {
                return(false);
            }

            // Check if player is already in a similar arena team
            if ((player && player.GetArenaTeamId(GetSlot()) != 0) || Player.GetArenaTeamIdFromDB(playerGuid, GetArenaType()) != 0)
            {
                Log.outDebug(LogFilter.Arena, "Arena: {0} {1} already has an arena team of type {2}", playerGuid.ToString(), playerName, GetArenaType());
                return(false);
            }

            // Set player's personal rating
            uint personalRating = 0;

            if (WorldConfig.GetIntValue(WorldCfg.ArenaStartPersonalRating) > 0)
            {
                personalRating = WorldConfig.GetUIntValue(WorldCfg.ArenaStartPersonalRating);
            }
            else if (GetRating() >= 1000)
            {
                personalRating = 1000;
            }

            // Try to get player's match maker rating from db and fall back to config setting if not found
            PreparedStatement stmt = DB.Characters.GetPreparedStatement(CharStatements.SEL_MATCH_MAKER_RATING);

            stmt.AddValue(0, playerGuid.GetCounter());
            stmt.AddValue(1, GetSlot());
            SQLResult result = DB.Characters.Query(stmt);

            uint matchMakerRating;

            if (!result.IsEmpty())
            {
                matchMakerRating = result.Read <ushort>(0);
            }
            else
            {
                matchMakerRating = WorldConfig.GetUIntValue(WorldCfg.ArenaStartMatchmakerRating);
            }

            // Remove all player signatures from other petitions
            // This will prevent player from joining too many arena teams and corrupt arena team data integrity
            //Player.RemovePetitionsAndSigns(playerGuid, GetArenaType());

            // Feed data to the struct
            ArenaTeamMember newMember = new ArenaTeamMember();

            newMember.Name             = playerName;
            newMember.Guid             = playerGuid;
            newMember.Class            = (byte)playerClass;
            newMember.SeasonGames      = 0;
            newMember.WeekGames        = 0;
            newMember.SeasonWins       = 0;
            newMember.WeekWins         = 0;
            newMember.PersonalRating   = (ushort)(uint)0;
            newMember.MatchMakerRating = (ushort)matchMakerRating;

            Members.Add(newMember);

            // Save player's arena team membership to db
            stmt = DB.Characters.GetPreparedStatement(CharStatements.INS_ARENA_TEAM_MEMBER);
            stmt.AddValue(0, teamId);
            stmt.AddValue(1, playerGuid.GetCounter());
            DB.Characters.Execute(stmt);

            // Inform player if online
            if (player)
            {
                player.SetInArenaTeam(teamId, GetSlot(), GetArenaType());
                player.SetArenaTeamIdInvited(0);

                // Hide promote/remove buttons
                if (CaptainGuid != playerGuid)
                {
                    player.SetArenaTeamInfoField(GetSlot(), ArenaTeamInfoType.Member, 1);
                }
            }

            Log.outDebug(LogFilter.Arena, "Player: {0} [{1}] joined arena team type: {2} [Id: {3}, Name: {4}].", playerName, playerGuid.ToString(), GetArenaType(), GetId(), GetName());

            return(true);
        }
示例#9
0
        void HandlePetAction(PetAction packet)
        {
            ObjectGuid guid1 = packet.PetGUID;         //pet guid
            ObjectGuid guid2 = packet.TargetGUID;      //tag guid

            uint         spellid = UnitActionBarEntry.UNIT_ACTION_BUTTON_ACTION(packet.Action);
            ActiveStates flag    = (ActiveStates)UnitActionBarEntry.UNIT_ACTION_BUTTON_TYPE(packet.Action);          //delete = 0x07 CastSpell = C1

            // used also for charmed creature
            Unit pet = Global.ObjAccessor.GetUnit(GetPlayer(), guid1);

            if (!pet)
            {
                Log.outError(LogFilter.Network, "HandlePetAction: {0} doesn't exist for {1}", guid1.ToString(), GetPlayer().GetGUID().ToString());
                return;
            }

            if (pet != GetPlayer().GetFirstControlled())
            {
                Log.outError(LogFilter.Network, "HandlePetAction: {0} does not belong to {1}", guid1.ToString(), GetPlayer().GetGUID().ToString());
                return;
            }

            if (!pet.IsAlive())
            {
                SpellInfo spell = (flag == ActiveStates.Enabled || flag == ActiveStates.Passive) ? Global.SpellMgr.GetSpellInfo(spellid) : null;
                if (spell == null)
                {
                    return;
                }
                if (!spell.HasAttribute(SpellAttr0.CastableWhileDead))
                {
                    return;
                }
            }

            // @todo allow control charmed player?
            if (pet.IsTypeId(TypeId.Player) && !(flag == ActiveStates.Command && spellid == (uint)CommandStates.Attack))
            {
                return;
            }

            if (GetPlayer().m_Controlled.Count == 1)
            {
                HandlePetActionHelper(pet, guid1, spellid, flag, guid2, packet.ActionPosition.X, packet.ActionPosition.Y, packet.ActionPosition.Z);
            }
            else
            {
                //If a pet is dismissed, m_Controlled will change
                List <Unit> controlled = new List <Unit>();
                foreach (var unit in GetPlayer().m_Controlled)
                {
                    if (unit.GetEntry() == pet.GetEntry() && unit.IsAlive())
                    {
                        controlled.Add(unit);
                    }
                }

                foreach (var unit in controlled)
                {
                    HandlePetActionHelper(unit, guid1, spellid, flag, guid2, packet.ActionPosition.X, packet.ActionPosition.Y, packet.ActionPosition.Z);
                }
            }
        }
示例#10
0
        void HandleLfgSetRoles(DFSetRoles dfSetRoles)
        {
            ObjectGuid guid  = GetPlayer().GetGUID();
            Group      group = GetPlayer().GetGroup();

            if (!group)
            {
                Log.outDebug(LogFilter.Lfg, "CMSG_DF_SET_ROLES {0} Not in group",
                             GetPlayerInfo());
                return;
            }
            ObjectGuid gguid = group.GetGUID();

            Log.outDebug(LogFilter.Lfg, "CMSG_DF_SET_ROLES: Group {0}, Player {1}, Roles: {2}", gguid.ToString(), GetPlayerInfo(), dfSetRoles.RolesDesired);
            Global.LFGMgr.UpdateRoleCheck(gguid, guid, dfSetRoles.RolesDesired);
        }
示例#11
0
 bool CheckStableMaster(ObjectGuid guid)
 {
     // spell case or GM
     if (guid == GetPlayer().GetGUID())
     {
         if (!GetPlayer().IsGameMaster() && !GetPlayer().HasAuraType(AuraType.OpenStable))
         {
             Log.outDebug(LogFilter.Network, "{0} attempt open stable in cheating way.", guid.ToString());
             return(false);
         }
     }
     // stable master case
     else
     {
         if (!GetPlayer().GetNPCIfCanInteractWith(guid, NPCFlags.StableMaster))
         {
             Log.outDebug(LogFilter.Network, "Stablemaster {0} not found or you can't interact with him.", guid.ToString());
             return(false);
         }
     }
     return(true);
 }
示例#12
0
        void HandlePetSetAction(PetSetAction packet)
        {
            ObjectGuid petguid = packet.PetGUID;
            Unit       pet     = Global.ObjAccessor.GetUnit(GetPlayer(), petguid);

            if (!pet || pet != GetPlayer().GetFirstControlled())
            {
                Log.outError(LogFilter.Network, "HandlePetSetAction: Unknown {0} or pet owner {1}", petguid.ToString(), GetPlayer().GetGUID().ToString());
                return;
            }

            CharmInfo charmInfo = pet.GetCharmInfo();

            if (charmInfo == null)
            {
                Log.outError(LogFilter.Network, "WorldSession.HandlePetSetAction: {0} is considered pet-like but doesn't have a charminfo!", pet.GetGUID().ToString());
                return;
            }

            uint position   = packet.Index;
            uint actionData = packet.Action;

            uint         spell_id  = UnitActionBarEntry.UNIT_ACTION_BUTTON_ACTION(actionData);
            ActiveStates act_state = (ActiveStates)UnitActionBarEntry.UNIT_ACTION_BUTTON_TYPE(actionData);

            Log.outDebug(LogFilter.Network, "Player {0} has changed pet spell action. Position: {1}, Spell: {2}, State: {3}", GetPlayer().GetName(), position, spell_id, act_state);


            //if it's act for spell (en/disable/cast) and there is a spell given (0 = remove spell) which pet doesn't know, don't add
            if (!((act_state == ActiveStates.Enabled || act_state == ActiveStates.Disabled || act_state == ActiveStates.Passive) && spell_id != 0 && !pet.HasSpell(spell_id)))
            {
                SpellInfo spellInfo = Global.SpellMgr.GetSpellInfo(spell_id);
                if (spellInfo != null)
                {
                    //sign for autocast
                    if (act_state == ActiveStates.Enabled)
                    {
                        if (pet.GetTypeId() == TypeId.Unit && pet.IsPet())
                        {
                            ((Pet)pet).ToggleAutocast(spellInfo, true);
                        }
                        else
                        {
                            foreach (var unit in GetPlayer().m_Controlled)
                            {
                                if (unit.GetEntry() == pet.GetEntry())
                                {
                                    unit.GetCharmInfo().ToggleCreatureAutocast(spellInfo, true);
                                }
                            }
                        }
                    }
                    //sign for no/turn off autocast
                    else if (act_state == ActiveStates.Disabled)
                    {
                        if (pet.GetTypeId() == TypeId.Unit && pet.IsPet())
                        {
                            pet.ToPet().ToggleAutocast(spellInfo, false);
                        }
                        else
                        {
                            foreach (var unit in GetPlayer().m_Controlled)
                            {
                                if (unit.GetEntry() == pet.GetEntry())
                                {
                                    unit.GetCharmInfo().ToggleCreatureAutocast(spellInfo, false);
                                }
                            }
                        }
                    }
                }

                charmInfo.SetActionBar((byte)position, spell_id, act_state);
            }
        }
示例#13
0
        static bool HandleGameObjectDeleteCommand(StringArguments args, CommandHandler handler)
        {
            // number or [name] Shift-click form |color|Hgameobject:go_guid|h[name]|h|r
            string id = handler.ExtractKeyFromLink(args, "Hgameobject");

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

            if (!ulong.TryParse(id, out ulong spawnId) || spawnId == 0)
            {
                return(false);
            }

            GameObject obj = handler.GetObjectFromPlayerMapByDbGuid(spawnId);

            if (obj != null)
            {
                Player     player    = handler.GetSession().GetPlayer();
                ObjectGuid ownerGuid = obj.GetOwnerGUID();
                if (!ownerGuid.IsEmpty())
                {
                    Unit owner = Global.ObjAccessor.GetUnit(player, ownerGuid);
                    if (!owner || !ownerGuid.IsPlayer())
                    {
                        handler.SendSysMessage(CypherStrings.CommandDelobjrefercreature, ownerGuid.ToString(), obj.GetGUID().ToString());
                        return(false);
                    }

                    owner.RemoveGameObject(obj, false);
                }
            }

            if (GameObject.DeleteFromDB(spawnId))
            {
                handler.SendSysMessage(CypherStrings.CommandDelobjmessage, spawnId);
                return(true);
            }

            handler.SendSysMessage(CypherStrings.CommandObjnotfound, obj.GetGUID().ToString());
            return(false);
        }
示例#14
0
        public void SendTaxiStatus(ObjectGuid guid)
        {
            // cheating checks
            Player   player = GetPlayer();
            Creature unit   = ObjectAccessor.GetCreature(player, guid);

            if (!unit || unit.IsHostileTo(player) || !unit.HasNpcFlag(NPCFlags.FlightMaster))
            {
                Log.outDebug(LogFilter.Network, "WorldSession.SendTaxiStatus - {0} not found.", guid.ToString());
                return;
            }

            // find taxi node
            uint nearest = Global.ObjectMgr.GetNearestTaxiNode(unit.GetPositionX(), unit.GetPositionY(), unit.GetPositionZ(), unit.GetMapId(), player.GetTeam());

            TaxiNodeStatusPkt data = new();

            data.Unit = guid;

            if (nearest == 0)
            {
                data.Status = TaxiNodeStatus.None;
            }
            else if (unit.GetReactionTo(player) >= ReputationRank.Neutral)
            {
                data.Status = player.m_taxi.IsTaximaskNodeKnown(nearest) ? TaxiNodeStatus.Learned : TaxiNodeStatus.Unlearned;
            }
            else
            {
                data.Status = TaxiNodeStatus.NotEligible;
            }

            SendPacket(data);
        }
示例#15
0
        void SendTrainerList(ObjectGuid guid, string title, uint index = 0)
        {
            Creature unit = GetPlayer().GetNPCIfCanInteractWith(guid, NPCFlags.Trainer);

            if (unit == null)
            {
                Log.outDebug(LogFilter.Network, "WORLD: SendTrainerList - {0} not found or you can not interact with him.", guid.ToString());
                return;
            }

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

            TrainerSpellData trainer_spells = unit.GetTrainerSpells();

            if (trainer_spells == null)
            {
                Log.outDebug(LogFilter.Network, "WORLD: SendTrainerList - Training spells not found for {0}", guid.ToString());
                return;
            }

            TrainerList packet = new TrainerList();

            packet.TrainerGUID = guid;
            packet.TrainerType = (int)trainer_spells.trainerType;
            packet.Greeting    = title;

            // reputation discount
            float fDiscountMod = GetPlayer().GetReputationPriceDiscount(unit);

            foreach (var tSpell in trainer_spells.spellList.Values)
            {
                if (index != 0 && tSpell.Index != index)
                {
                    continue;
                }

                bool valid = true;
                for (var i = 0; i < SharedConst.MaxTrainerspellAbilityReqs; i++)
                {
                    if (tSpell.ReqAbility[i] == 0)
                    {
                        continue;
                    }

                    if (!GetPlayer().IsSpellFitByClassAndRace(tSpell.ReqAbility[i]))
                    {
                        valid = false;
                        break;
                    }
                }

                if (!valid)
                {
                    continue;
                }

                TrainerSpellState state = GetPlayer().GetTrainerSpellState(tSpell);

                TrainerListSpell spell = new TrainerListSpell();
                spell.SpellID      = (int)tSpell.SpellID;
                spell.MoneyCost    = (int)Math.Floor(tSpell.MoneyCost * fDiscountMod);
                spell.ReqSkillLine = (int)tSpell.ReqSkillLine;
                spell.ReqSkillRank = (int)tSpell.ReqSkillRank;
                spell.ReqLevel     = (byte)tSpell.ReqLevel;
                spell.Usable       = (state == TrainerSpellState.GreenDisabled ? TrainerSpellState.Green : state);

                byte maxReq = 0;
                for (var i = 0; i < SharedConst.MaxTrainerspellAbilityReqs; ++i)
                {
                    if (tSpell.ReqAbility[i] == 0)
                    {
                        continue;
                    }

                    uint prevSpellId = Global.SpellMgr.GetPrevSpellInChain(tSpell.ReqAbility[i]);
                    if (prevSpellId != 0)
                    {
                        spell.ReqAbility[maxReq] = (int)prevSpellId;
                        ++maxReq;
                    }

                    if (maxReq == 2)
                    {
                        break;
                    }

                    var spellsRequired = Global.SpellMgr.GetSpellsRequiredForSpellBounds(tSpell.ReqAbility[i]);
                    for (var c = 0; c < spellsRequired.Count && maxReq < SharedConst.MaxTrainerspellAbilityReqs; ++c)
                    {
                        spell.ReqAbility[maxReq] = (int)spellsRequired[c];
                        ++maxReq;
                    }

                    if (maxReq == 2)
                    {
                        break;
                    }
                }

                packet.Spells.Add(spell);
            }

            SendPacket(packet);
        }
示例#16
0
        void FindBestCompatibleInQueue(ObjectGuid guid, LfgQueueData data)
        {
            Log.outDebug(LogFilter.Lfg, "FindBestCompatibleInQueue: {0}", guid);

            foreach (var pair in CompatibleMapStore)
            {
                if (pair.Value.compatibility == LfgCompatibility.WithLessPlayers && pair.Key.Contains(guid.ToString()))
                {
                    UpdateBestCompatibleInQueue(guid, data, pair.Key, pair.Value.roles);
                }
            }
        }
示例#17
0
        public void SendTaxiStatus(ObjectGuid guid)
        {
            // cheating checks
            Creature unit = ObjectAccessor.GetCreature(GetPlayer(), guid);

            if (unit == null)
            {
                Log.outDebug(LogFilter.Network, "WorldSession.SendTaxiStatus - {0} not found.", guid.ToString());
                return;
            }

            uint curloc = Global.ObjectMgr.GetNearestTaxiNode(unit.GetPositionX(), unit.GetPositionY(), unit.GetPositionZ(), unit.GetMapId(), GetPlayer().GetTeam());

            TaxiNodeStatusPkt data = new TaxiNodeStatusPkt();

            data.Unit = guid;

            if (curloc == 0)
            {
                data.Status = TaxiNodeStatus.None;
            }
            else if (unit.GetReactionTo(GetPlayer()) >= ReputationRank.Neutral)
            {
                data.Status = GetPlayer().m_taxi.IsTaximaskNodeKnown(curloc) ? TaxiNodeStatus.Learned : TaxiNodeStatus.Unlearned;
            }
            else
            {
                data.Status = TaxiNodeStatus.NotEligible;
            }

            SendPacket(data);
        }
示例#18
0
        /// todo get rid of this many variables passed in function.
        public void Start(bool isActiveAttacker = true, bool run = false, ObjectGuid playerGUID = default, Quest quest = null, bool instantRespawn = false, bool canLoopPath = false, bool resetWaypoints = true)
        {
            if (me.GetVictim())
            {
                Log.outError(LogFilter.Server, "TSCR ERROR: EscortAI (script: {0}, creature entry: {1}) attempts to Start while in combat", me.GetScriptName(), me.GetEntry());
                return;
            }

            if (HasEscortState(EscortState.Escorting))
            {
                Log.outError(LogFilter.Scripts, "EscortAI (script: {0}, creature entry: {1}) attempts to Start while already escorting", me.GetScriptName(), me.GetEntry());
                return;
            }

            if (!ScriptWP && resetWaypoints)
            {
                if (!WaypointList.Empty())
                {
                    WaypointList.Clear();
                }
                FillPointMovementListForCreature();
            }


            if (WaypointList.Empty())
            {
                Log.outError(LogFilter.Scripts, $"EscortAI (script: {me.GetScriptName()}, creature entry: {me.GetEntry()}) starts with 0 waypoints (possible missing entry in script_waypoint. Quest: {(quest != null ? quest.Id : 0)}).");
                return;
            }

            //set variables
            m_bIsActiveAttacker = isActiveAttacker;
            m_bIsRunning        = run;

            m_uiPlayerGUID    = playerGUID;
            m_pQuestForEscort = quest;

            m_bCanInstantRespawn = instantRespawn;
            m_bCanReturnToStart  = canLoopPath;

            if (m_bCanReturnToStart && m_bCanInstantRespawn)
            {
                Log.outDebug(LogFilter.Scripts, "EscortAI is set to return home after waypoint end and instant respawn at waypoint end. Creature will never despawn.");
            }

            if (me.GetMotionMaster().GetCurrentMovementGeneratorType() == MovementGeneratorType.Waypoint)
            {
                me.GetMotionMaster().MovementExpired();
                me.GetMotionMaster().MoveIdle();
                Log.outDebug(LogFilter.Scripts, "EscortAI start with WAYPOINT_MOTION_TYPE, changed to MoveIdle.");
            }

            //disable npcflags
            me.SetNpcFlags(NPCFlags.None);
            me.SetNpcFlags2(NPCFlags2.None);
            if (me.HasUnitFlag(UnitFlags.ImmuneToNpc))
            {
                HasImmuneToNPCFlags = true;
                me.RemoveUnitFlag(UnitFlags.ImmuneToNpc);
            }

            Log.outDebug(LogFilter.Scripts, $"EscortAI started. ActiveAttacker = {m_bIsActiveAttacker}, Run = {m_bIsRunning}, PlayerGUID = {m_uiPlayerGUID.ToString()}");

            CurrentWPIndex = 0;

            //Set initial speed
            if (m_bIsRunning)
            {
                me.SetWalk(false);
            }
            else
            {
                me.SetWalk(true);
            }

            AddEscortState(EscortState.Escorting);
        }
示例#19
0
        public override void OnLogin(Player player)
        {
            if (!Global.LFGMgr.isOptionEnabled(LfgOptions.EnableDungeonFinder | LfgOptions.EnableRaidBrowser))
            {
                return;
            }

            // Temporal: Trying to determine when group data and LFG data gets desynched
            ObjectGuid guid  = player.GetGUID();
            ObjectGuid gguid = Global.LFGMgr.GetGroup(guid);

            Group group = player.GetGroup();

            if (group)
            {
                ObjectGuid gguid2 = group.GetGUID();
                if (gguid != gguid2)
                {
                    Log.outError(LogFilter.Lfg, "{0} on group {1} but LFG has group {2} saved... Fixing.", player.GetSession().GetPlayerInfo(), gguid2.ToString(), gguid.ToString());
                    Global.LFGMgr.SetupGroupMember(guid, group.GetGUID());
                }
            }

            Global.LFGMgr.SetTeam(player.GetGUID(), player.GetTeam());
            /// @todo - Restore LfgPlayerData and send proper status to player if it was in a group
        }
示例#20
0
        static bool HandleListItemCommand(StringArguments args, CommandHandler handler)
        {
            if (args.Empty())
            {
                return(false);
            }

            string id = handler.ExtractKeyFromLink(args, "Hitem");

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

            if (!uint.TryParse(id, out uint itemId) || itemId == 0)
            {
                handler.SendSysMessage(CypherStrings.CommandItemidinvalid, itemId);
                return(false);
            }

            ItemTemplate itemTemplate = Global.ObjectMgr.GetItemTemplate(itemId);

            if (itemTemplate == null)
            {
                handler.SendSysMessage(CypherStrings.CommandItemidinvalid, itemId);
                return(false);
            }

            if (!uint.TryParse(args.NextString(), out uint count))
            {
                count = 10;
            }

            if (count == 0)
            {
                return(false);
            }

            // inventory case
            uint inventoryCount = 0;

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

            stmt.AddValue(0, itemId);
            SQLResult result = DB.Characters.Query(stmt);

            if (!result.IsEmpty())
            {
                inventoryCount = result.Read <uint>(0);
            }

            stmt = DB.Characters.GetPreparedStatement(CharStatements.SEL_CHAR_INVENTORY_ITEM_BY_ENTRY);
            stmt.AddValue(0, itemId);
            stmt.AddValue(1, count);
            result = DB.Characters.Query(stmt);

            if (!result.IsEmpty())
            {
                do
                {
                    ObjectGuid itemGuid       = ObjectGuid.Create(HighGuid.Item, result.Read <ulong>(0));
                    uint       itemBag        = result.Read <uint>(1);
                    byte       itemSlot       = result.Read <byte>(2);
                    ObjectGuid ownerGuid      = ObjectGuid.Create(HighGuid.Player, result.Read <ulong>(3));
                    uint       ownerAccountId = result.Read <uint>(4);
                    string     ownerName      = result.Read <string>(5);

                    string itemPos;
                    if (Player.IsEquipmentPos((byte)itemBag, itemSlot))
                    {
                        itemPos = "[equipped]";
                    }
                    else if (Player.IsInventoryPos((byte)itemBag, itemSlot))
                    {
                        itemPos = "[in inventory]";
                    }
                    else if (Player.IsBankPos((byte)itemBag, itemSlot))
                    {
                        itemPos = "[in bank]";
                    }
                    else
                    {
                        itemPos = "";
                    }

                    handler.SendSysMessage(CypherStrings.ItemlistSlot, itemGuid.ToString(), ownerName, ownerGuid.ToString(), ownerAccountId, itemPos);

                    count--;
                }while (result.NextRow());
            }

            // mail case
            uint mailCount = 0;

            stmt = DB.Characters.GetPreparedStatement(CharStatements.SEL_MAIL_COUNT_ITEM);
            stmt.AddValue(0, itemId);
            result = DB.Characters.Query(stmt);

            if (!result.IsEmpty())
            {
                mailCount = result.Read <uint>(0);
            }

            if (count > 0)
            {
                stmt = DB.Characters.GetPreparedStatement(CharStatements.SEL_MAIL_ITEMS_BY_ENTRY);
                stmt.AddValue(0, itemId);
                stmt.AddValue(1, count);
                result = DB.Characters.Query(stmt);
            }
            else
            {
                result = null;
            }

            if (result != null && !result.IsEmpty())
            {
                do
                {
                    ulong  itemGuid            = result.Read <ulong>(0);
                    ulong  itemSender          = result.Read <ulong>(1);
                    ulong  itemReceiver        = result.Read <ulong>(2);
                    uint   itemSenderAccountId = result.Read <uint>(3);
                    string itemSenderName      = result.Read <string>(4);
                    uint   itemReceiverAccount = result.Read <uint>(5);
                    string itemReceiverName    = result.Read <string>(6);

                    string itemPos = "[in mail]";

                    handler.SendSysMessage(CypherStrings.ItemlistMail, itemGuid, itemSenderName, itemSender, itemSenderAccountId, itemReceiverName, itemReceiver, itemReceiverAccount, itemPos);

                    count--;
                }while (result.NextRow());
            }

            // auction case
            uint auctionCount = 0;

            stmt = DB.Characters.GetPreparedStatement(CharStatements.SEL_AUCTIONHOUSE_COUNT_ITEM);
            stmt.AddValue(0, itemId);
            result = DB.Characters.Query(stmt);

            if (!result.IsEmpty())
            {
                auctionCount = result.Read <uint>(0);
            }

            if (count > 0)
            {
                stmt = DB.Characters.GetPreparedStatement(CharStatements.SEL_AUCTIONHOUSE_ITEM_BY_ENTRY);
                stmt.AddValue(0, itemId);
                stmt.AddValue(1, count);
                result = DB.Characters.Query(stmt);
            }
            else
            {
                result = null;
            }

            if (result != null && !result.IsEmpty())
            {
                do
                {
                    ObjectGuid itemGuid       = ObjectGuid.Create(HighGuid.Item, result.Read <ulong>(0));
                    ObjectGuid owner          = ObjectGuid.Create(HighGuid.Player, result.Read <ulong>(1));
                    uint       ownerAccountId = result.Read <uint>(2);
                    string     ownerName      = result.Read <string>(3);

                    string itemPos = "[in auction]";

                    handler.SendSysMessage(CypherStrings.ItemlistAuction, itemGuid.ToString(), ownerName, owner.ToString(), ownerAccountId, itemPos);
                }while (result.NextRow());
            }

            // guild bank case
            uint guildCount = 0;

            stmt = DB.Characters.GetPreparedStatement(CharStatements.SEL_GUILD_BANK_COUNT_ITEM);
            stmt.AddValue(0, itemId);
            result = DB.Characters.Query(stmt);

            if (!result.IsEmpty())
            {
                guildCount = result.Read <uint>(0);
            }

            stmt = DB.Characters.GetPreparedStatement(CharStatements.SEL_GUILD_BANK_ITEM_BY_ENTRY);
            stmt.AddValue(0, itemId);
            stmt.AddValue(1, count);
            result = DB.Characters.Query(stmt);

            if (!result.IsEmpty())
            {
                do
                {
                    ObjectGuid itemGuid  = ObjectGuid.Create(HighGuid.Item, result.Read <ulong>(0));
                    ObjectGuid guildGuid = ObjectGuid.Create(HighGuid.Guild, result.Read <ulong>(1));
                    string     guildName = result.Read <string>(2);

                    string itemPos = "[in guild bank]";

                    handler.SendSysMessage(CypherStrings.ItemlistGuild, itemGuid.ToString(), guildName, guildGuid.ToString(), itemPos);

                    count--;
                }while (result.NextRow());
            }

            if (inventoryCount + mailCount + auctionCount + guildCount == 0)
            {
                handler.SendSysMessage(CypherStrings.CommandNoitemfound);
                return(false);
            }

            handler.SendSysMessage(CypherStrings.CommandListitemmessage, itemId, inventoryCount + mailCount + auctionCount + guildCount, inventoryCount, mailCount, auctionCount, guildCount);
            return(true);
        }
示例#21
0
        public void SendQuestGiverQuestListMessage(ObjectGuid guid)
        {
            QuestGiverQuestListMessage questList = new QuestGiverQuestListMessage();

            questList.QuestGiverGUID = guid;

            QuestGreeting questGreeting = Global.ObjectMgr.GetQuestGreeting(guid);

            if (questGreeting != null)
            {
                questList.GreetEmoteDelay = questGreeting.greetEmoteDelay;
                questList.GreetEmoteType  = questGreeting.greetEmoteType;
                questList.Greeting        = questGreeting.greeting;
            }
            else
            {
                Log.outError(LogFilter.Server, "Guid: {0} - No quest greeting found.", guid.ToString());
            }

            for (var i = 0; i < _questMenu.GetMenuItemCount(); ++i)
            {
                QuestMenuItem questMenuItem = _questMenu.GetItem(i);

                uint  questID = questMenuItem.QuestId;
                Quest quest   = Global.ObjectMgr.GetQuestTemplate(questID);
                if (quest != null)
                {
                    string title = quest.LogTitle;

                    LocaleConstant locale = _session.GetSessionDbLocaleIndex();
                    if (locale != LocaleConstant.enUS)
                    {
                        QuestTemplateLocale localeData = Global.ObjectMgr.GetQuestLocale(quest.Id);
                        if (localeData != null)
                        {
                            ObjectManager.GetLocaleString(localeData.LogTitle, locale, ref title);
                        }
                    }

                    GossipText text = new GossipText();
                    text.QuestID      = questID;
                    text.QuestType    = questMenuItem.QuestIcon;
                    text.QuestLevel   = (uint)quest.Level;
                    text.QuestFlags   = (uint)quest.Flags;
                    text.QuestFlagsEx = (uint)quest.FlagsEx;
                    text.Repeatable   = false; // NYI
                    text.QuestTitle   = title;
                    questList.QuestDataText.Add(text);
                }
            }

            _session.SendPacket(questList);
        }
示例#22
0
        public bool ExecuteCommandInTable(ICollection <ChatCommand> table, string text, string fullcmd)
        {
            StringArguments args = new(text);
            string          cmd  = args.NextString();

            foreach (var command in table)
            {
                if (!HasStringAbbr(command.Name, cmd))
                {
                    continue;
                }

                bool match = false;
                if (command.Name.Length > cmd.Length)
                {
                    foreach (var command2 in table)
                    {
                        if (!HasStringAbbr(command2.Name, cmd))
                        {
                            continue;
                        }

                        if (command2.Name.Equals(cmd))
                        {
                            match = true;
                            break;
                        }
                    }
                }
                if (match)
                {
                    continue;
                }

                if (!command.ChildCommands.Empty())
                {
                    string arg = args.NextString("");
                    if (!ExecuteCommandInTable(command.ChildCommands, arg, fullcmd))
                    {
                        if (_session != null && !_session.HasPermission(RBACPermissions.CommandsNotifyCommandNotFoundError))
                        {
                            return(false);
                        }

                        if (!arg.IsEmpty())
                        {
                            SendSysMessage(CypherStrings.NoSubcmd);
                        }
                        else
                        {
                            SendSysMessage(CypherStrings.CmdSyntax);
                        }

                        ShowHelpForCommand(command.ChildCommands, arg);
                    }

                    return(true);
                }

                // must be available and have handler
                if (!command.HasHandler() || !IsAvailable(command))
                {
                    continue;
                }

                _sentErrorMessage = false;
                if (command.Invoke(this, new StringArguments(!command.Name.IsEmpty() ? args.NextString("") : text)))
                {
                    if (GetSession() == null) // ignore console
                    {
                        return(true);
                    }

                    Player player = GetPlayer();
                    if (!Global.AccountMgr.IsPlayerAccount(GetSession().GetSecurity()))
                    {
                        ObjectGuid guid     = player.GetTarget();
                        uint       areaId   = player.GetAreaId();
                        string     areaName = "Unknown";
                        string     zoneName = "Unknown";

                        AreaTableRecord area = CliDB.AreaTableStorage.LookupByKey(areaId);
                        if (area != null)
                        {
                            var locale = GetSessionDbcLocale();
                            areaName = area.AreaName[locale];
                            AreaTableRecord zone = CliDB.AreaTableStorage.LookupByKey(area.ParentAreaID);
                            if (zone != null)
                            {
                                zoneName = zone.AreaName[locale];
                            }
                        }

                        Log.outCommand(GetSession().GetAccountId(), "Command: {0} [Player: {1} ({2}) (Account: {3}) Postion: {4} Map: {5} ({6}) Area: {7} ({8}) Zone: {9} Selected: {10} ({11})]",
                                       fullcmd, player.GetName(), player.GetGUID().ToString(), GetSession().GetAccountId(), player.GetPosition(), player.GetMapId(),
                                       player.GetMap() ? player.GetMap().GetMapName() : "Unknown", areaId, areaName, zoneName, (player.GetSelectedUnit()) ? player.GetSelectedUnit().GetName() : "", guid.ToString());
                    }
                }
                else if (!HasSentErrorMessage())
                {
                    if (!command.Help.IsEmpty())
                    {
                        SendSysMessage(command.Help);
                    }
                    else
                    {
                        SendSysMessage(CypherStrings.CmdSyntax);
                    }
                }

                return(true);
            }

            return(false);
        }
示例#23
0
        /// todo get rid of this many variables passed in function.
        public void Start(bool isActiveAttacker = true, bool run = false, ObjectGuid playerGUID = default(ObjectGuid), Quest quest = null, bool instantRespawn = false, bool canLoopPath = false, bool resetWaypoints = true)
        {
            if (me.GetVictim())
            {
                Log.outError(LogFilter.Server, "TSCR ERROR: EscortAI (script: {0}, creature entry: {1}) attempts to Start while in combat", me.GetScriptName(), me.GetEntry());
                return;
            }

            if (HasEscortState(eEscortState.Escorting))
            {
                Log.outError(LogFilter.Scripts, "EscortAI (script: {0}, creature entry: {1}) attempts to Start while already escorting", me.GetScriptName(), me.GetEntry());
                return;
            }

            //set variables
            m_bIsActiveAttacker = isActiveAttacker;
            m_bIsRunning        = run;

            m_uiPlayerGUID    = playerGUID;
            m_pQuestForEscort = quest;

            m_bCanInstantRespawn = instantRespawn;
            m_bCanReturnToStart  = canLoopPath;

            if (!ScriptWP && resetWaypoints) // sd2 never adds wp in script, but tc does
            {
                FillPointMovementListForCreature();
            }

            if (m_bCanReturnToStart && m_bCanInstantRespawn)
            {
                Log.outDebug(LogFilter.Scripts, "EscortAI is set to return home after waypoint end and instant respawn at waypoint end. Creature will never despawn.");
            }

            if (me.GetMotionMaster().GetCurrentMovementGeneratorType() == MovementGeneratorType.Waypoint)
            {
                me.StopMoving();
                me.GetMotionMaster().Clear(false);
                me.GetMotionMaster().MoveIdle();
                Log.outDebug(LogFilter.Scripts, "EscortAI start with WAYPOINT_MOTION_TYPE, changed to MoveIdle.");
            }

            //disable npcflags
            me.SetUInt64Value(UnitFields.NpcFlags, (ulong)NPCFlags.None);
            if (me.HasFlag(UnitFields.Flags, UnitFlags.ImmuneToNpc))
            {
                HasImmuneToNPCFlags = true;
                me.RemoveFlag(UnitFields.Flags, UnitFlags.ImmuneToNpc);
            }

            Log.outDebug(LogFilter.Scripts, $"EscortAI started. ActiveAttacker = {m_bIsActiveAttacker}, Run = {m_bIsRunning}, PlayerGUID = {m_uiPlayerGUID.ToString()}");

            //Set initial speed
            if (m_bIsRunning)
            {
                me.SetWalk(false);
            }
            else
            {
                me.SetWalk(true);
            }

            m_bStarted = false;

            AddEscortState(eEscortState.Escorting);
        }
示例#24
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);
        }
示例#25
0
        public void SendPetitionQuery(ObjectGuid petitionGUID)
        {
            ObjectGuid ownerGUID = ObjectGuid.Empty;
            string     title     = "NO_NAME_FOR_GUID";

            QueryPetitionResponse responsePacket = new QueryPetitionResponse();

            responsePacket.PetitionID = (uint)petitionGUID.GetCounter();  // PetitionID (in Trinity always same as GUID_LOPART(petition guid))

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

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

            if (!result.IsEmpty())
            {
                ownerGUID = ObjectGuid.Create(HighGuid.Player, result.Read <ulong>(0));
                title     = result.Read <string>(1);
            }
            else
            {
                Log.outDebug(LogFilter.Network, "CMSG_PETITION_Select failed for petition ({0})", petitionGUID.ToString());
                return;
            }

            int reqSignatures = WorldConfig.GetIntValue(WorldCfg.MinPetitionSigns);

            PetitionInfo petitionInfo = new PetitionInfo();

            petitionInfo.PetitionID    = (int)petitionGUID.GetCounter();
            petitionInfo.Petitioner    = ownerGUID;
            petitionInfo.MinSignatures = reqSignatures;
            petitionInfo.MaxSignatures = reqSignatures;
            petitionInfo.Title         = title;

            responsePacket.Allow = true;
            responsePacket.Info  = petitionInfo;

            SendPacket(responsePacket);
        }
示例#26
0
        public void SendPetitionShowList(ObjectGuid guid)
        {
            Creature creature = GetPlayer().GetNPCIfCanInteractWith(guid, NPCFlags.Petitioner, NPCFlags2.None);

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

            WorldPacket data = new WorldPacket(ServerOpcodes.PetitionShowList);

            data.WritePackedGuid(guid);                                           // npc guid

            ServerPetitionShowList packet = new ServerPetitionShowList();

            packet.Unit  = guid;
            packet.Price = WorldConfig.GetUIntValue(WorldCfg.CharterCostGuild);
            SendPacket(packet);
        }
示例#27
0
        public void StartFollow(Player player, uint factionForFollower = 0, Quest quest = null)
        {
            if (me.GetVictim())
            {
                Log.outDebug(LogFilter.Scripts, "FollowerAI attempt to StartFollow while in combat.");
                return;
            }

            if (HasFollowState(FollowState.Inprogress))
            {
                Log.outError(LogFilter.Scenario, "FollowerAI attempt to StartFollow while already following.");
                return;
            }

            //set variables
            _leaderGUID = player.GetGUID();

            if (factionForFollower != 0)
            {
                me.SetFaction(factionForFollower);
            }

            _questForFollow = quest;

            me.GetMotionMaster().Clear(MovementGeneratorPriority.Normal);
            me.PauseMovement();

            me.SetNpcFlags(NPCFlags.None);
            me.SetNpcFlags2(NPCFlags2.None);

            AddFollowState(FollowState.Inprogress);

            me.GetMotionMaster().MoveFollow(player, SharedConst.PetFollowDist, SharedConst.PetFollowAngle);

            Log.outDebug(LogFilter.Scripts, "FollowerAI start follow {0} ({1})", player.GetName(), _leaderGUID.ToString());
        }