public SimulationWindow(WorldConfig config, bool shouldSave = true)
        {
            InitializeComponent();
            this.ViewModel = new DynamicConfigViewModel();

            // We use another thread for physics
            this.PhysicsTimer = new Timer(1000.0 / PHYSICS_PER_SECOND);
            this.PhysicsTimer.AutoReset = true;
            this.PhysicsTimer.Elapsed += CalculatePhysics;
            this.PhysicsTimer.Enabled = true;

            this.DrawTimer = new DispatcherTimer(TimeSpan.FromMilliseconds(1000.0 / FRAMES_PER_SECOND), DispatcherPriority.Send, DoDraw, this.Dispatcher);

            SetWorldConfig(config, shouldSave);
        }
Example #2
0
    public WorldConfig GetLevelConfig(int level)
    {
        WorldConfig wc = new WorldConfig {
            Width = WorldSize,
            Height = WorldSize,
            CoinCount = 10,
            TimeBoostCount = 2,
            BlueDoor = false
        };
        switch (level) {
        case 1:
            wc.GoalTip = true;
            wc.Width = 6;
            wc.Height = 4;
            wc.TimeBoostCount = 0;
            wc.CoinCount = 0;
            break;
        case 2:
            wc.CoinTip= true;
            wc.Width = 5;
            wc.Height = 5;
            wc.TimeBoostCount = 0;
            wc.CoinCount = 5;
            break;
        case 3:
            wc.TimeBoostTip = true;
            wc.Width = 8;
            wc.Height = 8;
            break;
        case 4:
            wc.SwitchTip = true;
            wc.BlueDoor = true;
            break;
        case 5:
            wc.Width = 15;
            wc.Height = 5;
            break;
        }

        return wc;
    }
        public void SetWorldConfig(WorldConfig config, bool save = false)
        {
            config.Width = Math.Max(Math.Abs(config.Width), MIN_WORLD_WIDTH);
            config.Height = Math.Max(Math.Abs(config.Height), MIN_WORLD_HEIGHT);

            this.Config = config;

            Canvas.Width = Config.Width;
            Canvas.Height = Config.Height;
            Canvas.Children.Clear();

            if ( save )
                MapManager.GetInstance().SaveGame(config);

            this.ViewModel.Gravity = Config.Gravity;

            this.World = new World(Config.Width, Config.Height, ViewModel.Gravity);

            foreach (MovingCircleConfig c in config.Objects) {
                AddCircle(new MovingCircle(c.Radius, c.Mass, c.BounceFactor, c.Position - new Vector(c.Radius, c.Radius), c.Speed));
            }
        }
Example #4
0
        public bool CheckInstanceValidity(bool isLogin)
        {
            // game masters' instances are always valid
            if (IsGameMaster())
            {
                return(true);
            }

            // non-instances are always valid
            Map map = GetMap();

            if (!map || !map.IsDungeon())
            {
                return(true);
            }

            // raid instances require the player to be in a raid group to be valid
            if (map.IsRaid() && !WorldConfig.GetBoolValue(WorldCfg.InstanceIgnoreRaid) && (map.GetEntry().Expansion() >= (Expansion)WorldConfig.GetIntValue(WorldCfg.Expansion)))
            {
                if (!GetGroup() || !GetGroup().IsRaidGroup())
                {
                    return(false);
                }
            }

            Group group = GetGroup();

            if (group)
            {
                // check if player's group is bound to this instance
                InstanceBind bind = group.GetBoundInstance(map.GetDifficultyID(), map.GetId());
                if (bind == null || bind.save == null || bind.save.GetInstanceId() != map.GetInstanceId())
                {
                    return(false);
                }

                var players = map.GetPlayers();
                if (!players.Empty())
                {
                    foreach (var otherPlayer in players)
                    {
                        if (otherPlayer.IsGameMaster())
                        {
                            continue;
                        }
                        if (!otherPlayer.m_InstanceValid) // ignore players that currently have a homebind timer active
                        {
                            continue;
                        }
                        if (group != otherPlayer.GetGroup())
                        {
                            return(false);
                        }
                    }
                }
            }
            else
            {
                // instance is invalid if we are not grouped and there are other players
                if (map.GetPlayersCountExceptGMs() > 1)
                {
                    return(false);
                }

                // check if the player is bound to this instance
                InstanceBind bind = GetBoundInstance(map.GetId(), map.GetDifficultyID());
                if (bind == null || bind.save == null || bind.save.GetInstanceId() != map.GetInstanceId())
                {
                    return(false);
                }
            }

            return(true);
        }
Example #5
0
        public void UpdateZone(uint newZone, uint newArea)
        {
            if (!IsInWorld)
            {
                return;
            }

            uint oldZone = m_zoneUpdateId;

            m_zoneUpdateId    = newZone;
            m_zoneUpdateTimer = 1 * Time.InMilliseconds;

            GetMap().UpdatePlayerZoneStats(oldZone, newZone);

            // call leave script hooks immedately (before updating flags)
            if (oldZone != newZone)
            {
                Global.OutdoorPvPMgr.HandlePlayerLeaveZone(this, m_zoneUpdateId);
                Global.BattleFieldMgr.HandlePlayerLeaveZone(this, m_zoneUpdateId);
            }

            // group update
            if (GetGroup())
            {
                SetGroupUpdateFlag(GroupUpdateFlags.Full);

                Pet pet = GetPet();
                if (pet)
                {
                    pet.SetGroupUpdateFlag(GroupUpdatePetFlags.Full);
                }
            }

            // zone changed, so area changed as well, update it
            UpdateArea(newArea);

            AreaTableRecord zone = CliDB.AreaTableStorage.LookupByKey(newZone);

            if (zone == null)
            {
                return;
            }

            if (WorldConfig.GetBoolValue(WorldCfg.Weather))
            {
                GetMap().GetOrGenerateZoneDefaultWeather(newZone);
            }

            GetMap().SendZoneDynamicInfo(newZone, this);

            UpdateHostileAreaState(zone);

            if (zone.Flags[0].HasAnyFlag(AreaFlags.Capital))                     // Is in a capital city
            {
                if (!pvpInfo.IsInHostileArea || zone.IsSanctuary())
                {
                    _restMgr.SetRestFlag(RestFlag.City);
                }
                pvpInfo.IsInNoPvPArea = true;
            }
            else
            {
                _restMgr.RemoveRestFlag(RestFlag.City);
            }

            UpdatePvPState();

            // remove items with area/map limitations (delete only for alive player to allow back in ghost mode)
            // if player resurrected at teleport this will be applied in resurrect code
            if (IsAlive())
            {
                DestroyZoneLimitedItem(true, newZone);
            }

            // check some item equip limitations (in result lost CanTitanGrip at talent reset, for example)
            AutoUnequipOffhandIfNeed();

            // recent client version not send leave/join channel packets for built-in local channels
            UpdateLocalChannels(newZone);

            UpdateZoneDependentAuras(newZone);

            // call enter script hooks after everyting else has processed
            Global.ScriptMgr.OnPlayerUpdateZone(this, newZone, newArea);
            if (oldZone != newZone)
            {
                Global.OutdoorPvPMgr.HandlePlayerEnterZone(this, newZone);
                Global.BattleFieldMgr.HandlePlayerEnterZone(this, newZone);
                SendInitWorldStates(newZone, newArea);              // only if really enters to new zone, not just area change, works strange...
                Guild guild = GetGuild();
                if (guild)
                {
                    guild.UpdateMemberData(this, GuildMemberData.ZoneId, newZone);
                }
            }
        }
Example #6
0
        public void DuelComplete(DuelCompleteType type)
        {
            // duel not requested
            if (duel == null)
            {
                return;
            }

            // Check if DuelComplete() has been called already up in the stack and in that case don't do anything else here
            if (duel.isCompleted || duel.opponent.duel.isCompleted)
            {
                return;
            }

            duel.isCompleted = true;
            duel.opponent.duel.isCompleted = true;

            Log.outDebug(LogFilter.Player, "Duel Complete {0} {1}", GetName(), duel.opponent.GetName());

            DuelComplete duelCompleted = new DuelComplete();

            duelCompleted.Started = type != DuelCompleteType.Interrupted;
            SendPacket(duelCompleted);

            if (duel.opponent.GetSession() != null)
            {
                duel.opponent.SendPacket(duelCompleted);
            }

            if (type != DuelCompleteType.Interrupted)
            {
                DuelWinner duelWinner = new DuelWinner();
                duelWinner.BeatenName = (type == DuelCompleteType.Won ? duel.opponent.GetName() : GetName());
                duelWinner.WinnerName = (type == DuelCompleteType.Won ? GetName() : duel.opponent.GetName());
                duelWinner.BeatenVirtualRealmAddress = Global.WorldMgr.GetVirtualRealmAddress();
                duelWinner.WinnerVirtualRealmAddress = Global.WorldMgr.GetVirtualRealmAddress();
                duelWinner.Fled = type != DuelCompleteType.Won;

                SendMessageToSet(duelWinner, true);
            }

            duel.opponent.DisablePvpRules();
            DisablePvpRules();

            Global.ScriptMgr.OnPlayerDuelEnd(duel.opponent, this, type);

            switch (type)
            {
            case DuelCompleteType.Fled:
                // if initiator and opponent are on the same team
                // or initiator and opponent are not PvP enabled, forcibly stop attacking
                if (duel.initiator.GetTeam() == duel.opponent.GetTeam())
                {
                    duel.initiator.AttackStop();
                    duel.opponent.AttackStop();
                }
                else
                {
                    if (!duel.initiator.IsPvP())
                    {
                        duel.initiator.AttackStop();
                    }
                    if (!duel.opponent.IsPvP())
                    {
                        duel.opponent.AttackStop();
                    }
                }
                break;

            case DuelCompleteType.Won:
                UpdateCriteria(CriteriaTypes.LoseDuel, 1);
                duel.opponent.UpdateCriteria(CriteriaTypes.WinDuel, 1);

                // Credit for quest Death's Challenge
                if (GetClass() == Class.Deathknight && duel.opponent.GetQuestStatus(12733) == QuestStatus.Incomplete)
                {
                    duel.opponent.CastSpell(duel.opponent, 52994, true);
                }

                // Honor points after duel (the winner) - ImpConfig
                int amount = WorldConfig.GetIntValue(WorldCfg.HonorAfterDuel);
                if (amount != 0)
                {
                    duel.opponent.RewardHonor(null, 1, amount);
                }

                break;

            default:
                break;
            }

            // Victory emote spell
            if (type != DuelCompleteType.Interrupted)
            {
                duel.opponent.CastSpell(duel.opponent, 52852, true);
            }

            //Remove Duel Flag object
            GameObject obj = GetMap().GetGameObject(m_playerData.DuelArbiter);

            if (obj)
            {
                duel.initiator.RemoveGameObject(obj, true);
            }

            //remove auras
            var itsAuras = duel.opponent.GetAppliedAuras();

            foreach (var pair in itsAuras)
            {
                Aura aura = pair.Value.GetBase();
                if (!pair.Value.IsPositive() && aura.GetCasterGUID() == GetGUID() && aura.GetApplyTime() >= duel.startTime)
                {
                    duel.opponent.RemoveAura(pair);
                }
            }

            var myAuras = GetAppliedAuras();

            foreach (var pair in myAuras)
            {
                Aura aura = pair.Value.GetBase();
                if (!pair.Value.IsPositive() && aura.GetCasterGUID() == duel.opponent.GetGUID() && aura.GetApplyTime() >= duel.startTime)
                {
                    RemoveAura(pair);
                }
            }

            // cleanup combo points
            ClearComboPoints();
            duel.opponent.ClearComboPoints();

            //cleanups
            SetDuelArbiter(ObjectGuid.Empty);
            SetDuelTeam(0);
            duel.opponent.SetDuelArbiter(ObjectGuid.Empty);
            duel.opponent.SetDuelTeam(0);

            duel.opponent.duel = null;
            duel = null;
        }
Example #7
0
        public void LoadWardenChecks()
        {
            // Check if Warden is enabled by config before loading anything
            if (!WorldConfig.GetBoolValue(WorldCfg.WardenEnabled))
            {
                Log.outInfo(LogFilter.Warden, "Warden disabled, loading checks skipped.");
                return;
            }

            //                              0    1     2     3        4       5      6      7
            SQLResult result = DB.World.Query("SELECT id, type, data, result, address, length, str, comment FROM warden_checks ORDER BY id ASC");

            if (result.IsEmpty())
            {
                Log.outInfo(LogFilter.ServerLoading, "Loaded 0 Warden checks. DB table `warden_checks` is empty!");
                return;
            }

            uint count = 0;

            do
            {
                ushort          id          = result.Read <ushort>(0);
                WardenCheckType checkType   = (WardenCheckType)result.Read <byte>(1);
                string          data        = result.Read <string>(2);
                string          checkResult = result.Read <string>(3);
                uint            address     = result.Read <uint>(4);
                byte            length      = result.Read <byte>(5);
                string          str         = result.Read <string>(6);
                string          comment     = result.Read <string>(7);

                WardenCheck wardenCheck = new WardenCheck();
                wardenCheck.Type    = checkType;
                wardenCheck.CheckId = id;

                // Initialize action with default action from config
                wardenCheck.Action = (WardenActions)WorldConfig.GetIntValue(WorldCfg.WardenClientFailAction);

                if (checkType == WardenCheckType.PageA || checkType == WardenCheckType.PageB || checkType == WardenCheckType.Driver)
                {
                    wardenCheck.Data = new BigInteger(data.ToByteArray());
                    int len = data.Length / 2;

                    if (wardenCheck.Data.ToByteArray().Length < len)
                    {
                        byte[] temp = wardenCheck.Data.ToByteArray();
                        Array.Reverse(temp);
                        wardenCheck.Data = new BigInteger(temp);
                    }
                }

                if (checkType == WardenCheckType.Memory || checkType == WardenCheckType.Module)
                {
                    MemChecksIdPool.Add(id);
                }
                else
                {
                    OtherChecksIdPool.Add(id);
                }

                if (checkType == WardenCheckType.Memory || checkType == WardenCheckType.PageA || checkType == WardenCheckType.PageB || checkType == WardenCheckType.Proc)
                {
                    wardenCheck.Address = address;
                    wardenCheck.Length  = length;
                }

                // PROC_CHECK support missing
                if (checkType == WardenCheckType.Memory || checkType == WardenCheckType.MPQ || checkType == WardenCheckType.LuaStr || checkType == WardenCheckType.Driver || checkType == WardenCheckType.Module)
                {
                    wardenCheck.Str = str;
                }

                CheckStore[id] = wardenCheck;

                if (checkType == WardenCheckType.MPQ || checkType == WardenCheckType.Memory)
                {
                    BigInteger Result = new BigInteger(checkResult.ToByteArray());
                    int        len    = checkResult.Length / 2;
                    if (Result.ToByteArray().Length < len)
                    {
                        byte[] temp = Result.ToByteArray();
                        Array.Reverse(temp);
                        Result = new BigInteger(temp);
                    }
                    CheckResultStore[id] = Result;
                }

                if (comment.IsEmpty())
                {
                    wardenCheck.Comment = "Undocumented Check";
                }
                else
                {
                    wardenCheck.Comment = comment;
                }

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

            Log.outInfo(LogFilter.ServerLoading, "Loaded {0} warden checks.", count);
        }
Example #8
0
        public static void reset(GameObject game_object, TerrainConfig terrain_config, WorldConfig world_config)
        {
            terrain_parent = game_object;
            TerrainService.terrain_config = terrain_config;
            TerrainService.world_config   = world_config;
            terrain_collection            = TerrainCollectionFactory.create(terrain_config, world_config.world_size);
            TerrainEntityRepository.reset(world_config.world_name);

            texture = ConfigData.instantiate_texture2D(
                StrOpe.i + "/Resources/" + terrain_config.texture_filepath,
                terrain_config.detail_resolution,
                terrain_config.detail_resolution
                );
        }
Example #9
0
            static bool HandleAccountSetAddonCommand(StringArguments args, CommandHandler handler)
            {
                if (args.Empty())
                {
                    return(false);
                }

                // Get the command line arguments
                string account = args.NextString();
                string exp     = args.NextString();

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

                string accountName;
                uint   accountId;

                if (string.IsNullOrEmpty(exp))
                {
                    Player player = handler.GetSelectedPlayer();
                    if (!player)
                    {
                        return(false);
                    }

                    accountId = player.GetSession().GetAccountId();
                    Global.AccountMgr.GetName(accountId, out accountName);
                    exp = account;
                }
                else
                {
                    // Convert Account name to Upper Format
                    accountName = account.ToUpper();

                    accountId = Global.AccountMgr.GetId(accountName);
                    if (accountId == 0)
                    {
                        handler.SendSysMessage(CypherStrings.AccountNotExist, accountName);
                        return(false);
                    }
                }

                // Let set addon state only for lesser (strong) security level
                // or to self account
                if (handler.GetSession() != null && handler.GetSession().GetAccountId() != accountId &&
                    handler.HasLowerSecurityAccount(null, accountId, true))
                {
                    return(false);
                }

                if (!byte.TryParse(exp, out byte expansion))
                {
                    return(false);
                }

                if (expansion > WorldConfig.GetIntValue(WorldCfg.Expansion))
                {
                    return(false);
                }

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

                stmt.AddValue(0, expansion);
                stmt.AddValue(1, accountId);

                DB.Login.Execute(stmt);

                handler.SendSysMessage(CypherStrings.AccountSetaddon, accountName, accountId, expansion);
                return(true);
            }
Example #10
0
        public override bool DoUpdate(T owner, uint time_diff)
        {
            if (!reftarget.isValid() || !target.IsInWorld)
                return false;

            if (owner == null || !owner.IsAlive())
                return false;

            if (owner.HasUnitState(UnitState.NotMove))
            {
                _clearUnitStateMove(owner);
                return true;
            }

            // prevent movement while casting spells with cast time or channel time
            if (owner.IsMovementPreventedByCasting())
            {
                if (!owner.isStopped())
                    owner.StopMoving();
                return true;
            }

            // prevent crash after creature killed pet
            if (_lostTarget(owner))
            {
                _clearUnitStateMove(owner);
                return true;
            }

            bool targetMoved = false;
            recheckDistance.Update((int)time_diff);
            if (recheckDistance.Passed())
            {
                recheckDistance.Reset(100);
                //More distance let have better performance, less distance let have more sensitive reaction at target move.
                float allowed_dist = 0.0f;// owner.GetCombatReach() + WorldConfig.GetFloatValue(WorldCfg.RateTargetPosRecalculationRange);

                if (owner.IsPet() && (owner.GetCharmerOrOwnerGUID() == target.GetGUID()))
                    allowed_dist = 1.0f; // pet following owner
                else
                    allowed_dist = owner.GetCombatReach() + WorldConfig.GetFloatValue(WorldCfg.RateTargetPosRecalculationRange);

                Vector3 dest = owner.moveSpline.FinalDestination();
                if (owner.moveSpline.onTransport)
                {
                    float o = 0;
                    ITransport transport = owner.GetDirectTransport();
                    if (transport != null)
                        transport.CalculatePassengerPosition(ref dest.X, ref dest.Y, ref dest.Z, ref o);
                }

                // First check distance
                if (owner.IsTypeId(TypeId.Unit) && (owner.ToCreature().CanFly() || owner.ToCreature().CanSwim()))
                    targetMoved = !target.IsWithinDist3d(dest.X, dest.Y, dest.Z, allowed_dist);
                else
                    targetMoved = !target.IsWithinDist2d(dest.X, dest.Y, allowed_dist);


                // then, if the target is in range, check also Line of Sight.
                if (!targetMoved)
                    targetMoved = !target.IsWithinLOSInMap(owner);
            }

            if (recalculateTravel || targetMoved)
                _setTargetLocation(owner, targetMoved);

            if (owner.moveSpline.Finalized())
            {
                MovementInform(owner);
                if (angle == 0.0f && !owner.HasInArc(0.01f, target))
                    owner.SetInFront(target);

                if (!targetReached)
                {
                    targetReached = true;
                    _reachTarget(owner);
                }
            }

            return true;
        }
        void LoadResetTimes()
        {
            long now   = Time.UnixTime;
            long today = (now / Time.Day) * Time.Day;

            // NOTE: Use DirectPExecute for tables that will be queried later

            // get the current reset times for normal instances (these may need to be updated)
            // these are only kept in memory for InstanceSaves that are loaded later
            // resettime = 0 in the DB for raid/heroic instances so those are skipped
            Dictionary <uint, Tuple <uint, long> > instResetTime = new Dictionary <uint, Tuple <uint, long> >();

            // index instance ids by map/difficulty pairs for fast reset warning send
            MultiMap <uint, uint> mapDiffResetInstances = new MultiMap <uint, uint>();

            SQLResult result = DB.Characters.Query("SELECT id, map, difficulty, resettime FROM instance ORDER BY id ASC");

            if (!result.IsEmpty())
            {
                do
                {
                    uint instanceId = result.Read <uint>(0);

                    // Mark instance id as being used
                    Global.MapMgr.RegisterInstanceId(instanceId);
                    long resettime = result.Read <long>(3);
                    if (resettime != 0)
                    {
                        uint mapid      = result.Read <ushort>(1);
                        uint difficulty = result.Read <byte>(2);

                        instResetTime[instanceId] = Tuple.Create(MathFunctions.MakePair32(mapid, difficulty), resettime);
                        mapDiffResetInstances.Add(MathFunctions.MakePair32(mapid, difficulty), instanceId);
                    }
                }while (result.NextRow());

                // schedule the reset times
                foreach (var pair in instResetTime)
                {
                    if (pair.Value.Item2 > now)
                    {
                        ScheduleReset(true, pair.Value.Item2, new InstResetEvent(0, MathFunctions.Pair32_LoPart(pair.Value.Item1), (Difficulty)MathFunctions.Pair32_HiPart(pair.Value.Item1), pair.Key));
                    }
                }
            }

            // load the global respawn times for raid/heroic instances
            uint diff = (uint)(WorldConfig.GetIntValue(WorldCfg.InstanceResetTimeHour) * Time.Hour);

            result = DB.Characters.Query("SELECT mapid, difficulty, resettime FROM instance_reset");
            if (!result.IsEmpty())
            {
                do
                {
                    uint       mapid        = result.Read <ushort>(0);
                    Difficulty difficulty   = (Difficulty)result.Read <byte>(1);
                    long       oldresettime = result.Read <long>(2);

                    MapDifficultyRecord mapDiff = Global.DB2Mgr.GetMapDifficultyData(mapid, difficulty);
                    if (mapDiff == null)
                    {
                        Log.outError(LogFilter.Server, "InstanceSaveManager.LoadResetTimes: invalid mapid({0})/difficulty({1}) pair in instance_reset!", mapid, difficulty);
                        PreparedStatement stmt = DB.Characters.GetPreparedStatement(CharStatements.DEL_GLOBAL_INSTANCE_RESETTIME);
                        stmt.AddValue(0, mapid);
                        stmt.AddValue(1, (byte)difficulty);
                        DB.Characters.DirectExecute(stmt);
                        continue;
                    }

                    // update the reset time if the hour in the configs changes
                    long newresettime = (oldresettime / Time.Day) * Time.Day + diff;
                    if (oldresettime != newresettime)
                    {
                        PreparedStatement stmt = DB.Characters.GetPreparedStatement(CharStatements.UPD_GLOBAL_INSTANCE_RESETTIME);
                        stmt.AddValue(0, newresettime);
                        stmt.AddValue(1, mapid);
                        stmt.AddValue(2, (byte)difficulty);
                        DB.Characters.DirectExecute(stmt);
                    }

                    InitializeResetTimeFor(mapid, difficulty, newresettime);
                } while (result.NextRow());
            }

            // calculate new global reset times for expired instances and those that have never been reset yet
            // add the global reset times to the priority queue
            foreach (var mapDifficultyPair in Global.DB2Mgr.GetMapDifficulties())
            {
                uint mapid = mapDifficultyPair.Key;

                foreach (var difficultyPair in mapDifficultyPair.Value)
                {
                    Difficulty          difficulty = (Difficulty)difficultyPair.Key;
                    MapDifficultyRecord mapDiff    = difficultyPair.Value;
                    if (mapDiff.GetRaidDuration() == 0)
                    {
                        continue;
                    }

                    // the reset_delay must be at least one day
                    uint period = (uint)(((mapDiff.GetRaidDuration() * WorldConfig.GetFloatValue(WorldCfg.RateInstanceResetTime)) / Time.Day) * Time.Day);
                    if (period < Time.Day)
                    {
                        period = Time.Day;
                    }

                    long t = GetResetTimeFor(mapid, difficulty);
                    if (t == 0)
                    {
                        // initialize the reset time
                        t = today + period + diff;

                        PreparedStatement stmt = DB.Characters.GetPreparedStatement(CharStatements.INS_GLOBAL_INSTANCE_RESETTIME);
                        stmt.AddValue(0, mapid);
                        stmt.AddValue(1, (byte)difficulty);
                        stmt.AddValue(2, t);
                        DB.Characters.DirectExecute(stmt);
                    }

                    if (t < now)
                    {
                        // assume that expired instances have already been cleaned
                        // calculate the next reset time
                        t  = (t / Time.Day) * Time.Day;
                        t += ((today - t) / period + 1) * period + diff;

                        PreparedStatement stmt = DB.Characters.GetPreparedStatement(CharStatements.UPD_GLOBAL_INSTANCE_RESETTIME);
                        stmt.AddValue(0, t);
                        stmt.AddValue(1, mapid);
                        stmt.AddValue(2, (byte)difficulty);
                        DB.Characters.DirectExecute(stmt);
                    }

                    InitializeResetTimeFor(mapid, difficulty, t);

                    // schedule the global reset/warning
                    byte type;
                    for (type = 1; type < 4; ++type)
                    {
                        if (t - ResetTimeDelay[type - 1] > now)
                        {
                            break;
                        }
                    }

                    ScheduleReset(true, t - ResetTimeDelay[type - 1], new InstResetEvent(type, mapid, difficulty, 0));

                    var range = mapDiffResetInstances.LookupByKey(MathFunctions.MakePair32(mapid, (uint)difficulty));
                    foreach (var id in range)
                    {
                        ScheduleReset(true, t - ResetTimeDelay[type - 1], new InstResetEvent(type, mapid, difficulty, id));
                    }
                }
            }
        }
Example #12
0
        void HandleWho(WhoRequestPkt whoRequest)
        {
            WhoRequest request = whoRequest.Request;

            // zones count, client limit = 10 (2.0.10)
            // can't be received from real client or broken packet
            if (whoRequest.Areas.Count > 10)
            {
                return;
            }

            // user entered strings count, client limit=4 (checked on 2.0.10)
            // can't be received from real client or broken packet
            if (request.Words.Count > 4)
            {
                return;
            }

            // @todo: handle following packet values
            // VirtualRealmNames
            // ShowEnemies
            // ShowArenaPlayers
            // ExactName
            // ServerInfo

            request.Words.ForEach(p => p = p.ToLower());

            request.Name  = request.Name.ToLower();
            request.Guild = request.Guild.ToLower();

            // client send in case not set max level value 100 but we support 255 max level,
            // update it to show GMs with characters after 100 level
            if (whoRequest.Request.MaxLevel >= 100)
            {
                whoRequest.Request.MaxLevel = 255;
            }

            var team = GetPlayer().GetTeam();

            uint gmLevelInWhoList = WorldConfig.GetUIntValue(WorldCfg.GmLevelInWhoList);

            WhoResponsePkt           response = new WhoResponsePkt();
            List <WhoListPlayerInfo> whoList  = Global.WhoListStorageMgr.GetWhoList();

            foreach (WhoListPlayerInfo target in whoList)
            {
                // player can see member of other team only if CONFIG_ALLOW_TWO_SIDE_WHO_LIST
                if (target.Team != team && !HasPermission(RBACPermissions.TwoSideWhoList))
                {
                    continue;
                }

                // player can see MODERATOR, GAME MASTER, ADMINISTRATOR only if CONFIG_GM_IN_WHO_LIST
                if (target.Security > (AccountTypes)gmLevelInWhoList && !HasPermission(RBACPermissions.WhoSeeAllSecLevels))
                {
                    continue;
                }

                // check if target is globally visible for player
                if (_player.GetGUID() != target.Guid && !target.IsVisible)
                {
                    if (Global.AccountMgr.IsPlayerAccount(_player.GetSession().GetSecurity()) || target.Security > _player.GetSession().GetSecurity())
                    {
                        continue;
                    }
                }

                // check if target's level is in level range
                uint lvl = target.Level;
                if (lvl < request.MinLevel || lvl > request.MaxLevel)
                {
                    continue;
                }

                // check if class matches classmask
                if (!Convert.ToBoolean(request.ClassFilter & (1 << target.Class)))
                {
                    continue;
                }

                // check if race matches racemask
                if (!Convert.ToBoolean(request.RaceFilter & (1 << target.Race)))
                {
                    continue;
                }

                if (!whoRequest.Areas.Empty())
                {
                    if (whoRequest.Areas.Contains((int)target.ZoneId))
                    {
                        continue;
                    }
                }

                string wTargetName = target.PlayerName.ToLower();
                if (!(request.Name.IsEmpty() || wTargetName.Equals(request.Name)))
                {
                    continue;
                }

                string wTargetGuildName = target.GuildName.ToLower();
                if (!request.Guild.IsEmpty() && !wTargetGuildName.Equals(request.Guild))
                {
                    continue;
                }

                if (!request.Words.Empty())
                {
                    string          aname     = "";
                    AreaTableRecord areaEntry = CliDB.AreaTableStorage.LookupByKey(target.ZoneId);
                    if (areaEntry != null)
                    {
                        aname = areaEntry.AreaName[GetSessionDbcLocale()].ToLower();
                    }

                    bool show = false;
                    for (int i = 0; i < request.Words.Count; ++i)
                    {
                        if (!string.IsNullOrEmpty(request.Words[i]))
                        {
                            if (wTargetName.Equals(request.Words[i]) ||
                                wTargetGuildName.Equals(request.Words[i]) ||
                                aname.Equals(request.Words[i]))
                            {
                                show = true;
                                break;
                            }
                        }
                    }

                    if (!show)
                    {
                        continue;
                    }
                }

                WhoEntry whoEntry = new WhoEntry();
                if (!whoEntry.PlayerData.Initialize(target.Guid, null))
                {
                    continue;
                }

                if (!target.GuildGuid.IsEmpty())
                {
                    whoEntry.GuildGUID = target.GuildGuid;
                    whoEntry.GuildVirtualRealmAddress = Global.WorldMgr.GetVirtualRealmAddress();
                    whoEntry.GuildName = target.GuildName;
                }

                whoEntry.AreaID = (int)target.ZoneId;
                whoEntry.IsGM   = target.IsGamemaster;

                response.Response.Add(whoEntry);

                // 50 is maximum player count sent to client
                if (response.Response.Count >= 50)
                {
                    break;
                }
            }

            SendPacket(response);
        }
Example #13
0
 public bool IsAutoComplete()
 {
     return(!WorldConfig.GetBoolValue(WorldCfg.QuestIgnoreAutoComplete) && Type == QuestType.AutoComplete);
 }
Example #14
0
 public bool IsAutoAccept()
 {
     return(!WorldConfig.GetBoolValue(WorldCfg.QuestIgnoreAutoAccept) && HasFlag(QuestFlags.AutoAccept));
 }
Example #15
0
        public bool RewardHonor(Unit victim, uint groupsize, int honor = -1, bool pvptoken = false)
        {
            // do not reward honor in arenas, but enable onkill spellproc
            if (InArena())
            {
                if (!victim || victim == this || !victim.IsTypeId(TypeId.Player))
                {
                    return(false);
                }

                if (GetBGTeam() == victim.ToPlayer().GetBGTeam())
                {
                    return(false);
                }

                return(true);
            }

            // 'Inactive' this aura prevents the player from gaining honor points and BattlegroundTokenizer
            if (HasAura(BattlegroundConst.SpellAuraPlayerInactive))
            {
                return(false);
            }

            ObjectGuid victim_guid = ObjectGuid.Empty;
            uint       victim_rank = 0;

            // need call before fields update to have chance move yesterday data to appropriate fields before today data change.
            UpdateHonorFields();

            // do not reward honor in arenas, but return true to enable onkill spellproc
            if (InBattleground() && GetBattleground() && GetBattleground().IsArena())
            {
                return(true);
            }

            // Promote to float for calculations
            float honor_f = honor;

            if (honor_f <= 0)
            {
                if (!victim || victim == this || victim.HasAuraType(AuraType.NoPvpCredit))
                {
                    return(false);
                }

                victim_guid = victim.GetGUID();
                Player plrVictim = victim.ToPlayer();
                if (plrVictim)
                {
                    if (GetTeam() == plrVictim.GetTeam() && !Global.WorldMgr.IsFFAPvPRealm())
                    {
                        return(false);
                    }

                    byte k_level = (byte)GetLevel();
                    byte k_grey  = (byte)Formulas.GetGrayLevel(k_level);
                    byte v_level = (byte)victim.GetLevelForTarget(this);

                    if (v_level <= k_grey)
                    {
                        return(false);
                    }

                    // PLAYER_CHOSEN_TITLE VALUES DESCRIPTION
                    //  [0]      Just name
                    //  [1..14]  Alliance honor titles and player name
                    //  [15..28] Horde honor titles and player name
                    //  [29..38] Other title and player name
                    //  [39+]    Nothing
                    // this is all wrong, should be going off PvpTitle, not PlayerTitle
                    uint victim_title = plrVictim.m_playerData.PlayerTitle;
                    // Get Killer titles, CharTitlesEntry.bit_index
                    // Ranks:
                    //  title[1..14]  . rank[5..18]
                    //  title[15..28] . rank[5..18]
                    //  title[other]  . 0
                    if (victim_title == 0)
                    {
                        victim_guid.Clear();                        // Don't show HK: <rank> message, only log.
                    }
                    else if (victim_title < 15)
                    {
                        victim_rank = victim_title + 4;
                    }
                    else if (victim_title < 29)
                    {
                        victim_rank = victim_title - 14 + 4;
                    }
                    else
                    {
                        victim_guid.Clear();                        // Don't show HK: <rank> message, only log.
                    }
                    honor_f = (float)Math.Ceiling(Formulas.HKHonorAtLevelF(k_level) * (v_level - k_grey) / (k_level - k_grey));

                    // count the number of playerkills in one day
                    ApplyModUpdateFieldValue(m_values.ModifyValue(m_activePlayerData).ModifyValue(m_activePlayerData.TodayHonorableKills), (ushort)1, true);
                    // and those in a lifetime
                    ApplyModUpdateFieldValue(m_values.ModifyValue(m_activePlayerData).ModifyValue(m_activePlayerData.LifetimeHonorableKills), 1u, true);
                    UpdateCriteria(CriteriaTypes.EarnHonorableKill);
                    UpdateCriteria(CriteriaTypes.HkClass, (uint)victim.GetClass());
                    UpdateCriteria(CriteriaTypes.HkRace, (uint)victim.GetRace());
                    UpdateCriteria(CriteriaTypes.HonorableKillAtArea, GetAreaId());
                    UpdateCriteria(CriteriaTypes.HonorableKill, 1, 0, 0, victim);
                }
                else
                {
                    if (!victim.ToCreature().IsRacialLeader())
                    {
                        return(false);
                    }

                    honor_f     = 100.0f;                           // ??? need more info
                    victim_rank = 19;                               // HK: Leader
                }
            }

            if (victim != null)
            {
                if (groupsize > 1)
                {
                    honor_f /= groupsize;
                }

                // apply honor multiplier from aura (not stacking-get highest)
                MathFunctions.AddPct(ref honor_f, GetMaxPositiveAuraModifier(AuraType.ModHonorGainPct));
                honor_f += _restMgr.GetRestBonusFor(RestTypes.Honor, (uint)honor_f);
            }

            honor_f *= WorldConfig.GetFloatValue(WorldCfg.RateHonor);
            // Back to int now
            honor = (int)honor_f;
            // honor - for show honor points in log
            // victim_guid - for show victim name in log
            // victim_rank [1..4]  HK: <dishonored rank>
            // victim_rank [5..19] HK: <alliance\horde rank>
            // victim_rank [0, 20+] HK: <>
            PvPCredit data = new PvPCredit();

            data.Honor         = honor;
            data.OriginalHonor = honor;
            data.Target        = victim_guid;
            data.Rank          = victim_rank;

            SendPacket(data);

            AddHonorXP((uint)honor);

            if (InBattleground() && honor > 0)
            {
                Battleground bg = GetBattleground();
                if (bg != null)
                {
                    bg.UpdatePlayerScore(this, ScoreType.BonusHonor, (uint)honor, false); //false: prevent looping
                }
            }

            if (WorldConfig.GetBoolValue(WorldCfg.PvpTokenEnable) && pvptoken)
            {
                if (!victim || victim == this || victim.HasAuraType(AuraType.NoPvpCredit))
                {
                    return(true);
                }

                if (victim.IsTypeId(TypeId.Player))
                {
                    // Check if allowed to receive it in current map
                    int MapType = WorldConfig.GetIntValue(WorldCfg.PvpTokenMapType);
                    if ((MapType == 1 && !InBattleground() && !IsFFAPvP()) ||
                        (MapType == 2 && !IsFFAPvP()) ||
                        (MapType == 3 && !InBattleground()))
                    {
                        return(true);
                    }

                    uint itemId = WorldConfig.GetUIntValue(WorldCfg.PvpTokenId);
                    uint count  = WorldConfig.GetUIntValue(WorldCfg.PvpTokenCount);

                    if (AddItem(itemId, count))
                    {
                        SendSysMessage("You have been awarded a token for slaying another player.");
                    }
                }
            }

            return(true);
        }
Example #16
0
    public void GenerateWorld(WorldConfig config)
    {
        MaxPoint = new Point2D (config.Width, config.Height);
        MinPoint = new Point2D (); // (0,0)

        CurrentMode = Mode.Newest;

        InitializeGrid (config.Width, config.Height);

        ClearMazeObjects ();

        GenerateGrid ();

        CreateRoomGameObjects ();

        CreateGoal (config.GoalTip);

        CreateCoins (config.CoinCount, config.CoinTip);

        CreateTimeBoosts (config.TimeBoostCount, config.TimeBoostTip);

        if (config.BlueDoor) {
            CreateBlueDoor (config.SwitchTip);
        }
    }
Example #17
0
        void HandleChat(ChatMsg type, Language lang, string msg, string target = "")
        {
            Player sender = GetPlayer();

            if (lang == Language.Universal && type != ChatMsg.Emote)
            {
                Log.outError(LogFilter.Network, "CMSG_MESSAGECHAT: Possible hacking-attempt: {0} tried to send a message in universal language", GetPlayerInfo());
                SendNotification(CypherStrings.UnknownLanguage);
                return;
            }

            // prevent talking at unknown language (cheating)
            var languageData = Global.LanguageMgr.GetLanguageDescById(lang);

            if (languageData.Empty())
            {
                SendNotification(CypherStrings.UnknownLanguage);
                return;
            }

            if (!languageData.Any(langDesc => langDesc.SkillId == 0 || sender.HasSkill((SkillType)langDesc.SkillId)))
            {
                // also check SPELL_AURA_COMPREHEND_LANGUAGE (client offers option to speak in that language)
                if (!sender.HasAuraTypeWithMiscvalue(AuraType.ComprehendLanguage, (int)lang))
                {
                    SendNotification(CypherStrings.NotLearnedLanguage);
                    return;
                }
            }

            // send in universal language if player in .gm on mode (ignore spell effects)
            if (sender.IsGameMaster())
            {
                lang = Language.Universal;
            }
            else
            {
                // send in universal language in two side iteration allowed mode
                if (HasPermission(RBACPermissions.TwoSideInteractionChat))
                {
                    lang = Language.Universal;
                }
                else
                {
                    switch (type)
                    {
                    case ChatMsg.Party:
                    case ChatMsg.Raid:
                    case ChatMsg.RaidWarning:
                        // allow two side chat at group channel if two side group allowed
                        if (WorldConfig.GetBoolValue(WorldCfg.AllowTwoSideInteractionGroup))
                        {
                            lang = Language.Universal;
                        }
                        break;

                    case ChatMsg.Guild:
                    case ChatMsg.Officer:
                        // allow two side chat at guild channel if two side guild allowed
                        if (WorldConfig.GetBoolValue(WorldCfg.AllowTwoSideInteractionGuild))
                        {
                            lang = Language.Universal;
                        }
                        break;
                    }
                }
                // but overwrite it by SPELL_AURA_MOD_LANGUAGE auras (only single case used)
                var ModLangAuras = sender.GetAuraEffectsByType(AuraType.ModLanguage);
                if (!ModLangAuras.Empty())
                {
                    lang = (Language)ModLangAuras.FirstOrDefault().GetMiscValue();
                }
            }

            if (!CanSpeak())
            {
                string timeStr = Time.secsToTimeString((ulong)(m_muteTime - GameTime.GetGameTime()));
                SendNotification(CypherStrings.WaitBeforeSpeaking, timeStr);
                return;
            }

            if (sender.HasAura(1852) && type != ChatMsg.Whisper)
            {
                SendNotification(Global.ObjectMgr.GetCypherString(CypherStrings.GmSilence), sender.GetName());
                return;
            }

            if (string.IsNullOrEmpty(msg))
            {
                return;
            }

            if (new CommandHandler(this).ParseCommand(msg))
            {
                return;
            }

            switch (type)
            {
            case ChatMsg.Say:
                // Prevent cheating
                if (!sender.IsAlive())
                {
                    return;
                }

                if (sender.GetLevel() < WorldConfig.GetIntValue(WorldCfg.ChatSayLevelReq))
                {
                    SendNotification(Global.ObjectMgr.GetCypherString(CypherStrings.SayReq), WorldConfig.GetIntValue(WorldCfg.ChatSayLevelReq));
                    return;
                }

                sender.Say(msg, lang);
                break;

            case ChatMsg.Emote:
                // Prevent cheating
                if (!sender.IsAlive())
                {
                    return;
                }

                if (sender.GetLevel() < WorldConfig.GetIntValue(WorldCfg.ChatEmoteLevelReq))
                {
                    SendNotification(Global.ObjectMgr.GetCypherString(CypherStrings.SayReq), WorldConfig.GetIntValue(WorldCfg.ChatEmoteLevelReq));
                    return;
                }

                sender.TextEmote(msg);
                break;

            case ChatMsg.Yell:
                // Prevent cheating
                if (!sender.IsAlive())
                {
                    return;
                }

                if (sender.GetLevel() < WorldConfig.GetIntValue(WorldCfg.ChatYellLevelReq))
                {
                    SendNotification(Global.ObjectMgr.GetCypherString(CypherStrings.SayReq), WorldConfig.GetIntValue(WorldCfg.ChatYellLevelReq));
                    return;
                }

                sender.Yell(msg, lang);
                break;

            case ChatMsg.Whisper:
                // @todo implement cross realm whispers (someday)
                ExtendedPlayerName extName = ObjectManager.ExtractExtendedPlayerName(target);

                if (!ObjectManager.NormalizePlayerName(ref extName.Name))
                {
                    SendChatPlayerNotfoundNotice(target);
                    break;
                }

                Player receiver = Global.ObjAccessor.FindPlayerByName(extName.Name);
                if (!receiver || (lang != Language.Addon && !receiver.IsAcceptWhispers() && receiver.GetSession().HasPermission(RBACPermissions.CanFilterWhispers) && !receiver.IsInWhisperWhiteList(sender.GetGUID())))
                {
                    SendChatPlayerNotfoundNotice(target);
                    return;
                }
                if (!sender.IsGameMaster() && sender.GetLevel() < WorldConfig.GetIntValue(WorldCfg.ChatWhisperLevelReq) && !receiver.IsInWhisperWhiteList(sender.GetGUID()))
                {
                    SendNotification(Global.ObjectMgr.GetCypherString(CypherStrings.WhisperReq), WorldConfig.GetIntValue(WorldCfg.ChatWhisperLevelReq));
                    return;
                }

                if (GetPlayer().GetTeam() != receiver.GetTeam() && !HasPermission(RBACPermissions.TwoSideInteractionChat) && !receiver.IsInWhisperWhiteList(sender.GetGUID()))
                {
                    SendChatPlayerNotfoundNotice(target);
                    return;
                }

                if (GetPlayer().HasAura(1852) && !receiver.IsGameMaster())
                {
                    SendNotification(Global.ObjectMgr.GetCypherString(CypherStrings.GmSilence), GetPlayer().GetName());
                    return;
                }

                if (receiver.GetLevel() < WorldConfig.GetIntValue(WorldCfg.ChatWhisperLevelReq) ||
                    (HasPermission(RBACPermissions.CanFilterWhispers) && !sender.IsAcceptWhispers() && !sender.IsInWhisperWhiteList(receiver.GetGUID())))
                {
                    sender.AddWhisperWhiteList(receiver.GetGUID());
                }

                GetPlayer().Whisper(msg, lang, receiver);
                break;

            case ChatMsg.Party:
            {
                // if player is in Battleground, he cannot say to Battlegroundmembers by /p
                Group group = GetPlayer().GetOriginalGroup();
                if (!group)
                {
                    group = GetPlayer().GetGroup();
                    if (!group || group.IsBGGroup())
                    {
                        return;
                    }
                }

                if (group.IsLeader(GetPlayer().GetGUID()))
                {
                    type = ChatMsg.PartyLeader;
                }

                Global.ScriptMgr.OnPlayerChat(GetPlayer(), type, lang, msg, group);

                ChatPkt data = new();
                data.Initialize(type, lang, sender, null, msg);
                group.BroadcastPacket(data, false, group.GetMemberGroup(GetPlayer().GetGUID()));
            }
            break;

            case ChatMsg.Guild:
                if (GetPlayer().GetGuildId() != 0)
                {
                    Guild guild = Global.GuildMgr.GetGuildById(GetPlayer().GetGuildId());
                    if (guild)
                    {
                        Global.ScriptMgr.OnPlayerChat(GetPlayer(), type, lang, msg, guild);

                        guild.BroadcastToGuild(this, false, msg, lang == Language.Addon ? Language.Addon : Language.Universal);
                    }
                }
                break;

            case ChatMsg.Officer:
                if (GetPlayer().GetGuildId() != 0)
                {
                    Guild guild = Global.GuildMgr.GetGuildById(GetPlayer().GetGuildId());
                    if (guild)
                    {
                        Global.ScriptMgr.OnPlayerChat(GetPlayer(), type, lang, msg, guild);

                        guild.BroadcastToGuild(this, true, msg, lang == Language.Addon ? Language.Addon : Language.Universal);
                    }
                }
                break;

            case ChatMsg.Raid:
            {
                Group group = GetPlayer().GetGroup();
                if (!group || !group.IsRaidGroup() || group.IsBGGroup())
                {
                    return;
                }

                if (group.IsLeader(GetPlayer().GetGUID()))
                {
                    type = ChatMsg.RaidLeader;
                }

                Global.ScriptMgr.OnPlayerChat(GetPlayer(), type, lang, msg, group);

                ChatPkt data = new();
                data.Initialize(type, lang, sender, null, msg);
                group.BroadcastPacket(data, false);
            }
            break;

            case ChatMsg.RaidWarning:
            {
                Group group = GetPlayer().GetGroup();
                if (!group || !(group.IsRaidGroup() || WorldConfig.GetBoolValue(WorldCfg.ChatPartyRaidWarnings)) || !(group.IsLeader(GetPlayer().GetGUID()) || group.IsAssistant(GetPlayer().GetGUID())) || group.IsBGGroup())
                {
                    return;
                }

                Global.ScriptMgr.OnPlayerChat(GetPlayer(), type, lang, msg, group);

                ChatPkt data = new();
                //in Battleground, raid warning is sent only to players in Battleground - code is ok
                data.Initialize(ChatMsg.RaidWarning, lang, sender, null, msg);
                group.BroadcastPacket(data, false);
            }
            break;

            case ChatMsg.Channel:
                if (!HasPermission(RBACPermissions.SkipCheckChatChannelReq))
                {
                    if (GetPlayer().GetLevel() < WorldConfig.GetIntValue(WorldCfg.ChatChannelLevelReq))
                    {
                        SendNotification(Global.ObjectMgr.GetCypherString(CypherStrings.ChannelReq), WorldConfig.GetIntValue(WorldCfg.ChatChannelLevelReq));
                        return;
                    }
                }
                Channel chn = ChannelManager.GetChannelForPlayerByNamePart(target, sender);
                if (chn != null)
                {
                    Global.ScriptMgr.OnPlayerChat(GetPlayer(), type, lang, msg, chn);
                    chn.Say(GetPlayer().GetGUID(), msg, lang);
                }
                break;

            case ChatMsg.InstanceChat:
            {
                Group group = GetPlayer().GetGroup();
                if (!group)
                {
                    return;
                }

                if (group.IsLeader(GetPlayer().GetGUID()))
                {
                    type = ChatMsg.InstanceChatLeader;
                }

                Global.ScriptMgr.OnPlayerChat(GetPlayer(), type, lang, msg, group);

                ChatPkt packet = new();
                packet.Initialize(type, lang, sender, null, msg);
                group.BroadcastPacket(packet, false);
                break;
            }

            default:
                Log.outError(LogFilter.ChatSystem, "CHAT: unknown message type {0}, lang: {1}", type, lang);
                break;
            }
        }
Example #18
0
        static bool HandleAccountPasswordCommand(StringArguments args, CommandHandler handler)
        {
            // If no args are given at all, we can return false right away.
            if (args.Empty())
            {
                handler.SendSysMessage(CypherStrings.CmdSyntax);
                return(false);
            }

            // First, we check config. What security type (sec type) is it ? Depending on it, the command branches out
            uint pwConfig = WorldConfig.GetUIntValue(WorldCfg.AccPasschangesec); // 0 - PW_NONE, 1 - PW_EMAIL, 2 - PW_RBAC

            // Command is supposed to be: .account password [$oldpassword] [$newpassword] [$newpasswordconfirmation] [$emailconfirmation]
            string oldPassword          = args.NextString(); // This extracts [$oldpassword]
            string newPassword          = args.NextString(); // This extracts [$newpassword]
            string passwordConfirmation = args.NextString(); // This extracts [$newpasswordconfirmation]
            string emailConfirmation    = args.NextString(); // This defines the emailConfirmation variable, which is optional depending on sec type.

            //Is any of those variables missing for any reason ? We return false.
            if (string.IsNullOrEmpty(oldPassword) || string.IsNullOrEmpty(newPassword) ||
                string.IsNullOrEmpty(passwordConfirmation))
            {
                handler.SendSysMessage(CypherStrings.CmdSyntax);

                return(false);
            }

            // We compare the old, saved password to the entered old password - no chance for the unauthorized.
            if (!Global.AccountMgr.CheckPassword(handler.GetSession().GetAccountId(), oldPassword))
            {
                handler.SendSysMessage(CypherStrings.CommandWrongoldpassword);

                Log.outInfo(LogFilter.Player, "Account: {0} (IP: {1}) Character:[{2}] (GUID: {3}) Tried to change password, but the provided old password is wrong.",
                            handler.GetSession().GetAccountId(), handler.GetSession().GetRemoteAddress(),
                            handler.GetSession().GetPlayer().GetName(), handler.GetSession().GetPlayer().GetGUID().ToString());
                return(false);
            }
            // This compares the old, current email to the entered email - however, only...
            if ((pwConfig == 1 || (pwConfig == 2 && handler.GetSession().HasPermission(RBACPermissions.EmailConfirmForPassChange))) && // ...if either PW_EMAIL or PW_RBAC with the Permission is active...
                !Global.AccountMgr.CheckEmail(handler.GetSession().GetAccountId(), emailConfirmation))    // ... and returns false if the comparison fails.
            {
                handler.SendSysMessage(CypherStrings.CommandWrongemail);

                Log.outInfo(LogFilter.Player, "Account: {0} (IP: {1}) Character:[{2}] (GUID: {3}) Tried to change password, but the entered email [{4}] is wrong.",
                            handler.GetSession().GetAccountId(), handler.GetSession().GetRemoteAddress(),
                            handler.GetSession().GetPlayer().GetName(), handler.GetSession().GetPlayer().GetGUID().ToString(),
                            emailConfirmation);
                return(false);
            }

            // Making sure that newly entered password is correctly entered.
            if (newPassword != passwordConfirmation)
            {
                handler.SendSysMessage(CypherStrings.NewPasswordsNotMatch);
                return(false);
            }

            // Changes password and prints result.
            AccountOpResult result = Global.AccountMgr.ChangePassword(handler.GetSession().GetAccountId(), newPassword);

            switch (result)
            {
            case AccountOpResult.Ok:
                handler.SendSysMessage(CypherStrings.CommandPassword);
                Log.outInfo(LogFilter.Player, "Account: {0} (IP: {1}) Character:[{2}] (GUID: {3}) Changed Password.",
                            handler.GetSession().GetAccountId(), handler.GetSession().GetRemoteAddress(),
                            handler.GetSession().GetPlayer().GetName(), handler.GetSession().GetPlayer().GetGUID().ToString());
                break;

            case AccountOpResult.PassTooLong:
                handler.SendSysMessage(CypherStrings.PasswordTooLong);
                return(false);

            default:
                handler.SendSysMessage(CypherStrings.CommandNotchangepassword);
                return(false);
            }

            return(true);
        }
Example #19
0
        void HandleChatAddon(ChatMsg type, string prefix, string text, bool isLogged, string target = "")
        {
            Player sender = GetPlayer();

            if (string.IsNullOrEmpty(prefix) || prefix.Length > 16)
            {
                return;
            }

            // Disabled addon channel?
            if (!WorldConfig.GetBoolValue(WorldCfg.AddonChannel))
            {
                return;
            }

            if (prefix == AddonChannelCommandHandler.PREFIX && new AddonChannelCommandHandler(this).ParseCommand(text))
            {
                return;
            }

            switch (type)
            {
            case ChatMsg.Guild:
            case ChatMsg.Officer:
                if (sender.GetGuildId() != 0)
                {
                    Guild guild = Global.GuildMgr.GetGuildById(sender.GetGuildId());
                    if (guild)
                    {
                        guild.BroadcastAddonToGuild(this, type == ChatMsg.Officer, text, prefix, isLogged);
                    }
                }
                break;

            case ChatMsg.Whisper:
                // @todo implement cross realm whispers (someday)
                ExtendedPlayerName extName = ObjectManager.ExtractExtendedPlayerName(target);

                if (!ObjectManager.NormalizePlayerName(ref extName.Name))
                {
                    break;
                }

                Player receiver = Global.ObjAccessor.FindPlayerByName(extName.Name);
                if (!receiver)
                {
                    break;
                }

                sender.WhisperAddon(text, prefix, isLogged, receiver);
                break;

            // Messages sent to "RAID" while in a party will get delivered to "PARTY"
            case ChatMsg.Party:
            case ChatMsg.Raid:
            case ChatMsg.InstanceChat:
            {
                Group group    = null;
                int   subGroup = -1;
                if (type != ChatMsg.InstanceChat)
                {
                    group = sender.GetOriginalGroup();
                }

                if (!group)
                {
                    group = sender.GetGroup();
                    if (!group)
                    {
                        break;
                    }

                    if (type == ChatMsg.Party)
                    {
                        subGroup = sender.GetSubGroup();
                    }
                }

                ChatPkt data = new();
                data.Initialize(type, isLogged ? Language.AddonLogged : Language.Addon, sender, null, text, 0, "", Locale.enUS, prefix);
                group.BroadcastAddonMessagePacket(data, prefix, true, subGroup, sender.GetGUID());
                break;
            }

            case ChatMsg.Channel:
                Channel chn = ChannelManager.GetChannelForPlayerByNamePart(target, sender);
                if (chn != null)
                {
                    chn.AddonSay(sender.GetGUID(), prefix, text, isLogged);
                }
                break;

            default:
                Log.outError(LogFilter.Server, "HandleAddonMessagechat: unknown addon message type {0}", type);
                break;
            }
        }
Example #20
0
        void HandlePartyInvite(PartyInviteClient packet)
        {
            Player player = Global.ObjAccessor.FindPlayerByName(packet.TargetName);

            // no player
            if (!player)
            {
                SendPartyResult(PartyOperation.Invite, packet.TargetName, PartyResult.BadPlayerNameS);
                return;
            }

            // player trying to invite himself (most likely cheating)
            if (player == GetPlayer())
            {
                SendPartyResult(PartyOperation.Invite, player.GetName(), PartyResult.BadPlayerNameS);
                return;
            }

            // restrict invite to GMs
            if (!WorldConfig.GetBoolValue(WorldCfg.AllowGmGroup) && !GetPlayer().IsGameMaster() && player.IsGameMaster())
            {
                SendPartyResult(PartyOperation.Invite, player.GetName(), PartyResult.BadPlayerNameS);
                return;
            }

            // can't group with
            if (!GetPlayer().IsGameMaster() && !WorldConfig.GetBoolValue(WorldCfg.AllowTwoSideInteractionGroup) && GetPlayer().GetTeam() != player.GetTeam())
            {
                SendPartyResult(PartyOperation.Invite, player.GetName(), PartyResult.PlayerWrongFaction);
                return;
            }
            if (GetPlayer().GetInstanceId() != 0 && player.GetInstanceId() != 0 && GetPlayer().GetInstanceId() != player.GetInstanceId() && GetPlayer().GetMapId() == player.GetMapId())
            {
                SendPartyResult(PartyOperation.Invite, player.GetName(), PartyResult.TargetNotInInstanceS);
                return;
            }
            // just ignore us
            if (player.GetInstanceId() != 0 && player.GetDungeonDifficultyID() != GetPlayer().GetDungeonDifficultyID())
            {
                SendPartyResult(PartyOperation.Invite, player.GetName(), PartyResult.IgnoringYouS);
                return;
            }

            if (player.GetSocial().HasIgnore(GetPlayer().GetGUID()))
            {
                SendPartyResult(PartyOperation.Invite, player.GetName(), PartyResult.IgnoringYouS);
                return;
            }

            if (!player.GetSocial().HasFriend(GetPlayer().GetGUID()) && GetPlayer().GetLevel() < WorldConfig.GetIntValue(WorldCfg.PartyLevelReq))
            {
                SendPartyResult(PartyOperation.Invite, player.GetName(), PartyResult.InviteRestricted);
                return;
            }

            Group group = GetPlayer().GetGroup();

            if (group && group.IsBGGroup())
            {
                group = GetPlayer().GetOriginalGroup();
            }

            Group group2 = player.GetGroup();

            if (group2 && group2.IsBGGroup())
            {
                group2 = player.GetOriginalGroup();
            }

            PartyInvite partyInvite;

            // player already in another group or invited
            if (group2 || player.GetGroupInvite())
            {
                SendPartyResult(PartyOperation.Invite, player.GetName(), PartyResult.AlreadyInGroupS);

                if (group2)
                {
                    // tell the player that they were invited but it failed as they were already in a group
                    partyInvite = new PartyInvite();
                    partyInvite.Initialize(GetPlayer(), packet.ProposedRoles, false);
                    player.SendPacket(partyInvite);
                }

                return;
            }

            if (group)
            {
                // not have permissions for invite
                if (!group.IsLeader(GetPlayer().GetGUID()) && !group.IsAssistant(GetPlayer().GetGUID()))
                {
                    SendPartyResult(PartyOperation.Invite, "", PartyResult.NotLeader);
                    return;
                }
                // not have place
                if (group.IsFull())
                {
                    SendPartyResult(PartyOperation.Invite, "", PartyResult.GroupFull);
                    return;
                }
            }

            // ok, but group not exist, start a new group
            // but don't create and save the group to the DB until
            // at least one person joins
            if (!group)
            {
                group = new Group();
                // new group: if can't add then delete
                if (!group.AddLeaderInvite(GetPlayer()))
                {
                    return;
                }

                if (!group.AddInvite(player))
                {
                    group.RemoveAllInvites();
                    return;
                }
            }
            else
            {
                // already existed group: if can't add then just leave
                if (!group.AddInvite(player))
                {
                    return;
                }
            }

            partyInvite = new PartyInvite();
            partyInvite.Initialize(GetPlayer(), packet.ProposedRoles, true);
            player.SendPacket(partyInvite);

            SendPartyResult(PartyOperation.Invite, player.GetName(), PartyResult.Ok);
        }
Example #21
0
        void HandleTextEmote(CTextEmote packet)
        {
            if (!GetPlayer().IsAlive())
            {
                return;
            }

            if (!CanSpeak())
            {
                string timeStr = Time.secsToTimeString((ulong)(m_muteTime - GameTime.GetGameTime()));
                SendNotification(CypherStrings.WaitBeforeSpeaking, timeStr);
                return;
            }

            Global.ScriptMgr.OnPlayerTextEmote(GetPlayer(), (uint)packet.SoundIndex, (uint)packet.EmoteID, packet.Target);

            EmotesTextRecord em = CliDB.EmotesTextStorage.LookupByKey(packet.EmoteID);

            if (em == null)
            {
                return;
            }

            Emote emoteAnim = (Emote)em.EmoteId;

            switch (emoteAnim)
            {
            case Emote.StateSleep:
            case Emote.StateSit:
            case Emote.StateKneel:
            case Emote.OneshotNone:
                break;

            case Emote.StateDance:
            case Emote.StateRead:
                GetPlayer().SetEmoteState(emoteAnim);
                break;

            default:
                // Only allow text-emotes for "dead" entities (feign death included)
                if (GetPlayer().HasUnitState(UnitState.Died))
                {
                    break;
                }
                GetPlayer().HandleEmoteCommand(emoteAnim, packet.SpellVisualKitIDs);
                break;
            }

            STextEmote textEmote = new();

            textEmote.SourceGUID        = GetPlayer().GetGUID();
            textEmote.SourceAccountGUID = GetAccountGUID();
            textEmote.TargetGUID        = packet.Target;
            textEmote.EmoteID           = packet.EmoteID;
            textEmote.SoundIndex        = packet.SoundIndex;
            GetPlayer().SendMessageToSetInRange(textEmote, WorldConfig.GetFloatValue(WorldCfg.ListenRangeTextemote), true);

            Unit unit = Global.ObjAccessor.GetUnit(GetPlayer(), packet.Target);

            GetPlayer().UpdateCriteria(CriteriaTypes.DoEmote, (uint)packet.EmoteID, 0, 0, unit);

            // Send scripted event call
            if (unit)
            {
                Creature creature = unit.ToCreature();
                if (creature)
                {
                    creature.GetAI().ReceiveEmote(GetPlayer(), (TextEmotes)packet.EmoteID);
                }
            }

            if (emoteAnim != Emote.OneshotNone)
            {
                _player.RemoveAurasWithInterruptFlags(SpellAuraInterruptFlags.Anim);
            }
        }
Example #22
0
            public CharacterInfo(SQLFields fields)
            {
                //         0                1                2                3                 4                  5                6                7
                // "SELECT characters.guid, characters.name, characters.race, characters.class, characters.gender, characters.skin, characters.face, characters.hairStyle, "
                //  8                     9                       10                         11                         12                         13
                // "characters.hairColor, characters.facialStyle, characters.customDisplay1, characters.customDisplay2, characters.customDisplay3, characters.level, "
                //  14               15              16                     17                     18
                // "characters.zone, characters.map, characters.position_x, characters.position_y, characters.position_z, "
                //  19                    20                      21                   22                   23                     24                   25
                // "guild_member.guildid, characters.playerFlags, characters.at_login, character_pet.entry, character_pet.modelid, character_pet.level, characters.equipmentCache, "
                //  26                     27               28                      29                            30                         31
                // "character_banned.guid, characters.slot, characters.logout_time, characters.activeTalentGroup, characters.lastLoginBuild, character_declinedname.genitive"

                Guid             = ObjectGuid.Create(HighGuid.Player, fields.Read <ulong>(0));
                Name             = fields.Read <string>(1);
                RaceId           = fields.Read <byte>(2);
                ClassId          = (Class)fields.Read <byte>(3);
                SexId            = fields.Read <byte>(4);
                SkinId           = fields.Read <byte>(5);
                FaceId           = fields.Read <byte>(6);
                HairStyle        = fields.Read <byte>(7);
                HairColor        = fields.Read <byte>(8);
                FacialHair       = fields.Read <byte>(9);
                CustomDisplay[0] = fields.Read <byte>(10);
                CustomDisplay[1] = fields.Read <byte>(11);
                CustomDisplay[2] = fields.Read <byte>(12);
                ExperienceLevel  = fields.Read <byte>(13);
                ZoneId           = fields.Read <uint>(14);
                MapId            = fields.Read <uint>(15);
                PreloadPos       = new Vector3(fields.Read <float>(16), fields.Read <float>(17), fields.Read <float>(18));

                ulong guildId = fields.Read <ulong>(19);

                if (guildId != 0)
                {
                    GuildGuid = ObjectGuid.Create(HighGuid.Guild, guildId);
                }

                PlayerFlags  playerFlags  = (PlayerFlags)fields.Read <uint>(20);
                AtLoginFlags atLoginFlags = (AtLoginFlags)fields.Read <ushort>(21);

                if (atLoginFlags.HasAnyFlag(AtLoginFlags.Resurrect))
                {
                    playerFlags &= ~PlayerFlags.Ghost;
                }

                if (playerFlags.HasAnyFlag(PlayerFlags.Ghost))
                {
                    Flags |= CharacterFlags.Ghost;
                }

                if (atLoginFlags.HasAnyFlag(AtLoginFlags.Rename))
                {
                    Flags |= CharacterFlags.Rename;
                }

                if (fields.Read <uint>(26) != 0)
                {
                    Flags |= CharacterFlags.LockedByBilling;
                }

                if (WorldConfig.GetBoolValue(WorldCfg.DeclinedNamesUsed) && !string.IsNullOrEmpty(fields.Read <string>(31)))
                {
                    Flags |= CharacterFlags.Declined;
                }

                if (atLoginFlags.HasAnyFlag(AtLoginFlags.Customize))
                {
                    Flags2 = CharacterCustomizeFlags.Customize;
                }
                else if (atLoginFlags.HasAnyFlag(AtLoginFlags.ChangeFaction))
                {
                    Flags2 = CharacterCustomizeFlags.Faction;
                }
                else if (atLoginFlags.HasAnyFlag(AtLoginFlags.ChangeRace))
                {
                    Flags2 = CharacterCustomizeFlags.Race;
                }

                Flags3     = 0;
                Flags4     = 0;
                FirstLogin = atLoginFlags.HasAnyFlag(AtLoginFlags.FirstLogin);

                // show pet at selection character in character list only for non-ghost character
                if (!playerFlags.HasAnyFlag(PlayerFlags.Ghost) && (ClassId == Class.Warlock || ClassId == Class.Hunter || ClassId == Class.Deathknight))
                {
                    CreatureTemplate creatureInfo = Global.ObjectMgr.GetCreatureTemplate(fields.Read <uint>(22));
                    if (creatureInfo != null)
                    {
                        PetCreatureDisplayId = fields.Read <uint>(23);
                        PetExperienceLevel   = fields.Read <ushort>(24);
                        PetCreatureFamilyId  = (uint)creatureInfo.Family;
                    }
                }

                BoostInProgress  = false;
                ProfessionIds[0] = 0;
                ProfessionIds[1] = 0;

                StringArguments equipment = new StringArguments(fields.Read <string>(25));

                ListPosition   = fields.Read <byte>(27);
                LastPlayedTime = fields.Read <uint>(28);

                var spec = Global.DB2Mgr.GetChrSpecializationByIndex(ClassId, fields.Read <byte>(29));

                if (spec != null)
                {
                    SpecID = (ushort)spec.Id;
                }

                LastLoginVersion = fields.Read <uint>(30);

                for (byte slot = 0; slot < InventorySlots.BagEnd; ++slot)
                {
                    VisualItems[slot].InvType          = (byte)equipment.NextUInt32();
                    VisualItems[slot].DisplayId        = equipment.NextUInt32();
                    VisualItems[slot].DisplayEnchantId = equipment.NextUInt32();
                    VisualItems[slot].Subclass         = (byte)equipment.NextUInt32();
                }
            }
Example #23
0
        //call this method to send mail to auction owner, when auction is successful, it does not clear ram
        public void SendAuctionSuccessfulMail(AuctionEntry auction, SQLTransaction trans)
        {
            ObjectGuid owner_guid  = ObjectGuid.Create(HighGuid.Player, auction.owner);
            Player     owner       = Global.ObjAccessor.FindPlayer(owner_guid);
            uint       owner_accId = ObjectManager.GetPlayerAccountIdByGUID(owner_guid);
            Item       item        = GetAItem(auction.itemGUIDLow);

            // owner exist
            if (owner || owner_accId != 0)
            {
                ulong profit = auction.bid + auction.deposit - auction.GetAuctionCut();

                //FIXME: what do if owner offline
                if (owner && item)
                {
                    owner.UpdateCriteria(CriteriaTypes.GoldEarnedByAuctions, profit);
                    owner.UpdateCriteria(CriteriaTypes.HighestAuctionSold, auction.bid);
                    // send auction owner notification, bidder must be current!
                    owner.GetSession().SendAuctionClosedNotification(auction, WorldConfig.GetIntValue(WorldCfg.MailDeliveryDelay), true, item);
                }

                new MailDraft(auction.BuildAuctionMailSubject(MailAuctionAnswers.Successful), AuctionEntry.BuildAuctionMailBody(auction.bidder, auction.bid, auction.buyout, auction.deposit, auction.GetAuctionCut()))
                .AddMoney(profit)
                .SendMailTo(trans, new MailReceiver(owner, auction.owner), new MailSender(auction), MailCheckMask.Copied, WorldConfig.GetUIntValue(WorldCfg.MailDeliveryDelay));
            }
        }
Example #24
0
        static bool HandleResetLevelCommand(StringArguments args, CommandHandler handler)
        {
            Player target;

            if (!handler.ExtractPlayerTarget(args, out target))
            {
                return(false);
            }

            if (!HandleResetStatsOrLevelHelper(target))
            {
                return(false);
            }

            byte oldLevel = (byte)target.GetLevel();

            // set starting level
            uint startLevel = (uint)(target.GetClass() != Class.Deathknight ? WorldConfig.GetIntValue(WorldCfg.StartPlayerLevel) : WorldConfig.GetIntValue(WorldCfg.StartDeathKnightPlayerLevel));

            target._ApplyAllLevelScaleItemMods(false);
            target.SetLevel(startLevel);
            target.InitRunes();
            target.InitStatsForLevel(true);
            target.InitTaxiNodesForLevel();
            target.InitTalentForLevel();
            target.SetXP(0);

            target._ApplyAllLevelScaleItemMods(true);

            // reset level for pet
            Pet pet = target.GetPet();

            if (pet)
            {
                pet.SynchronizeLevelWithOwner();
            }

            Global.ScriptMgr.OnPlayerLevelChanged(target, oldLevel);

            return(true);
        }
Example #25
0
        public ulong GetAuctionDeposit(AuctionHouseRecord entry, uint time, Item pItem, uint count)
        {
            uint MSV = pItem.GetTemplate().GetSellPrice();

            if (MSV <= 0)
            {
                return(AH_MINIMUM_DEPOSIT * (uint)WorldConfig.GetFloatValue(WorldCfg.RateAuctionDeposit));
            }

            float multiplier = MathFunctions.CalculatePct((float)entry.DepositRate, 3);
            uint  timeHr     = (((time / 60) / 60) / 12);
            ulong deposit    = (ulong)(((multiplier * MSV * count / 3) * timeHr * 3) * WorldConfig.GetFloatValue(WorldCfg.RateAuctionDeposit));

            Log.outDebug(LogFilter.Auctionhouse, $"MSV:        {MSV}");
            Log.outDebug(LogFilter.Auctionhouse, $"Items:      {count}");
            Log.outDebug(LogFilter.Auctionhouse, $"Multiplier: {multiplier}");
            Log.outDebug(LogFilter.Auctionhouse, $"Deposit:    {deposit}");

            if (deposit < AH_MINIMUM_DEPOSIT * WorldConfig.GetFloatValue(WorldCfg.RateAuctionDeposit))
            {
                return(AH_MINIMUM_DEPOSIT * (uint)WorldConfig.GetFloatValue(WorldCfg.RateAuctionDeposit));
            }
            else
            {
                return(deposit);
            }
        }
Example #26
0
 // Return wether server allow two side groups or not
 public bool ServerAllowsTwoSideGroups()
 {
     return(WorldConfig.GetBoolValue(WorldCfg.AllowTwoSideInteractionGroup));
 }
Example #27
0
        public ulong GetAuctionCut()
        {
            long cut = (long)(MathFunctions.CalculatePct(bid, auctionHouseEntry.ConsignmentRate) * WorldConfig.GetFloatValue(WorldCfg.RateAuctionCut));

            return((ulong)Math.Max(cut, 0));
        }
Example #28
0
        public bool Satisfy(AccessRequirement ar, uint target_map, bool report = false)
        {
            if (!IsGameMaster())
            {
                byte LevelMin = 0;
                byte LevelMax = 0;
                uint failedMapDifficultyXCondition = 0;
                uint missingItem        = 0;
                uint missingQuest       = 0;
                uint missingAchievement = 0;

                MapRecord mapEntry = CliDB.MapStorage.LookupByKey(target_map);
                if (mapEntry == null)
                {
                    return(false);
                }

                Difficulty          target_difficulty = GetDifficultyID(mapEntry);
                MapDifficultyRecord mapDiff           = Global.DB2Mgr.GetDownscaledMapDifficultyData(target_map, ref target_difficulty);
                if (!WorldConfig.GetBoolValue(WorldCfg.InstanceIgnoreLevel))
                {
                    var mapDifficultyConditions = Global.DB2Mgr.GetMapDifficultyConditions(mapDiff.Id);
                    foreach (var pair in mapDifficultyConditions)
                    {
                        if (!ConditionManager.IsPlayerMeetingCondition(this, pair.Item2))
                        {
                            failedMapDifficultyXCondition = pair.Item1;
                            break;
                        }
                    }
                }

                if (ar != null)
                {
                    if (!WorldConfig.GetBoolValue(WorldCfg.InstanceIgnoreLevel))
                    {
                        if (ar.levelMin != 0 && GetLevel() < ar.levelMin)
                        {
                            LevelMin = ar.levelMin;
                        }
                        if (ar.levelMax != 0 && GetLevel() > ar.levelMax)
                        {
                            LevelMax = ar.levelMax;
                        }
                    }

                    if (ar.item != 0)
                    {
                        if (!HasItemCount(ar.item) &&
                            (ar.item2 == 0 || !HasItemCount(ar.item2)))
                        {
                            missingItem = ar.item;
                        }
                    }
                    else if (ar.item2 != 0 && !HasItemCount(ar.item2))
                    {
                        missingItem = ar.item2;
                    }

                    if (Global.DisableMgr.IsDisabledFor(DisableType.Map, target_map, this))
                    {
                        GetSession().SendNotification("{0}", Global.ObjectMgr.GetCypherString(CypherStrings.InstanceClosed));
                        return(false);
                    }

                    if (GetTeam() == Team.Alliance && ar.quest_A != 0 && !GetQuestRewardStatus(ar.quest_A))
                    {
                        missingQuest = ar.quest_A;
                    }
                    else if (GetTeam() == Team.Horde && ar.quest_H != 0 && !GetQuestRewardStatus(ar.quest_H))
                    {
                        missingQuest = ar.quest_H;
                    }

                    Player     leader     = this;
                    ObjectGuid leaderGuid = GetGroup() != null?GetGroup().GetLeaderGUID() : GetGUID();

                    if (leaderGuid != GetGUID())
                    {
                        leader = Global.ObjAccessor.FindPlayer(leaderGuid);
                    }

                    if (ar.achievement != 0)
                    {
                        if (leader == null || !leader.HasAchieved(ar.achievement))
                        {
                            missingAchievement = ar.achievement;
                        }
                    }
                }

                if (LevelMin != 0 || LevelMax != 0 || failedMapDifficultyXCondition != 0 || missingItem != 0 || missingQuest != 0 || missingAchievement != 0)
                {
                    if (report)
                    {
                        if (missingQuest != 0 && !string.IsNullOrEmpty(ar.questFailedText))
                        {
                            SendSysMessage("{0}", ar.questFailedText);
                        }
                        else if (mapDiff.Message[Global.WorldMgr.GetDefaultDbcLocale()][0] != '\0' || failedMapDifficultyXCondition != 0) // if (missingAchievement) covered by this case
                        {
                            SendTransferAborted(target_map, TransferAbortReason.Difficulty, (byte)target_difficulty, failedMapDifficultyXCondition);
                        }
                        else if (missingItem != 0)
                        {
                            GetSession().SendNotification(Global.ObjectMgr.GetCypherString(CypherStrings.LevelMinrequiredAndItem), LevelMin, Global.ObjectMgr.GetItemTemplate(missingItem).GetName());
                        }
                        else if (LevelMin != 0)
                        {
                            GetSession().SendNotification(Global.ObjectMgr.GetCypherString(CypherStrings.LevelMinrequired), LevelMin);
                        }
                    }
                    return(false);
                }
            }
            return(true);
        }
Example #29
0
        static bool HandleCharacterChangeAccountCommand(StringArguments args, CommandHandler handler)
        {
            string playerNameStr;
            string accountName;

            handler.ExtractOptFirstArg(args, out playerNameStr, out accountName);
            if (accountName.IsEmpty())
            {
                return(false);
            }

            ObjectGuid targetGuid;
            string     targetName;

            if (!handler.ExtractPlayerTarget(new StringArguments(playerNameStr), out _, out targetGuid, out targetName))
            {
                return(false);
            }

            CharacterCacheEntry characterInfo = Global.CharacterCacheStorage.GetCharacterCacheByGuid(targetGuid);

            if (characterInfo == null)
            {
                handler.SendSysMessage(CypherStrings.PlayerNotFound);
                return(false);
            }

            uint oldAccountId = characterInfo.AccountId;
            uint newAccountId = oldAccountId;

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

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

            if (!result.IsEmpty())
            {
                newAccountId = result.Read <uint>(0);
            }
            else
            {
                handler.SendSysMessage(CypherStrings.AccountNotExist, accountName);
                return(false);
            }

            // nothing to do :)
            if (newAccountId == oldAccountId)
            {
                return(true);
            }

            uint charCount = Global.AccountMgr.GetCharactersCount(newAccountId);

            if (charCount != 0)
            {
                if (charCount >= WorldConfig.GetIntValue(WorldCfg.CharactersPerRealm))
                {
                    handler.SendSysMessage(CypherStrings.AccountCharacterListFull, accountName, newAccountId);
                    return(false);
                }
            }

            stmt = DB.Characters.GetPreparedStatement(CharStatements.UPD_ACCOUNT_BY_GUID);
            stmt.AddValue(0, newAccountId);
            stmt.AddValue(1, targetGuid.GetCounter());
            DB.Characters.DirectExecute(stmt);

            Global.WorldMgr.UpdateRealmCharCount(oldAccountId);
            Global.WorldMgr.UpdateRealmCharCount(newAccountId);

            Global.CharacterCacheStorage.UpdateCharacterAccountId(targetGuid, newAccountId);

            handler.SendSysMessage(CypherStrings.ChangeAccountSuccess, targetName, accountName);

            string       logString = $"changed ownership of player {targetName} ({targetGuid}) from account {oldAccountId} to account {newAccountId}";
            WorldSession session   = handler.GetSession();

            if (session != null)
            {
                Player player = session.GetPlayer();
                if (player != null)
                {
                    Log.outCommand(session.GetAccountId(), $"GM {player.GetName()} (Account: {session.GetAccountId()}) {logString}");
                }
            }
            else
            {
                Log.outCommand(0, $"{handler.GetCypherString(CypherStrings.Console)} {logString}");
            }
            return(true);
        }
Example #30
0
        public void SendQuestGiverQuestDetails(Quest quest, ObjectGuid npcGUID, bool autoLaunched, bool displayPopup)
        {
            QuestGiverQuestDetails packet = new QuestGiverQuestDetails();

            packet.QuestTitle         = quest.LogTitle;
            packet.LogDescription     = quest.LogDescription;
            packet.DescriptionText    = quest.QuestDescription;
            packet.PortraitGiverText  = quest.PortraitGiverText;
            packet.PortraitGiverName  = quest.PortraitGiverName;
            packet.PortraitTurnInText = quest.PortraitTurnInText;
            packet.PortraitTurnInName = quest.PortraitTurnInName;

            LocaleConstant locale = _session.GetSessionDbLocaleIndex();

            if (locale != LocaleConstant.enUS)
            {
                QuestTemplateLocale localeData = Global.ObjectMgr.GetQuestLocale(quest.Id);
                if (localeData != null)
                {
                    ObjectManager.GetLocaleString(localeData.LogTitle, locale, ref packet.QuestTitle);
                    ObjectManager.GetLocaleString(localeData.LogDescription, locale, ref packet.LogDescription);
                    ObjectManager.GetLocaleString(localeData.QuestDescription, locale, ref packet.DescriptionText);
                    ObjectManager.GetLocaleString(localeData.PortraitGiverText, locale, ref packet.PortraitGiverText);
                    ObjectManager.GetLocaleString(localeData.PortraitGiverName, locale, ref packet.PortraitGiverName);
                    ObjectManager.GetLocaleString(localeData.PortraitTurnInText, locale, ref packet.PortraitTurnInText);
                    ObjectManager.GetLocaleString(localeData.PortraitTurnInName, locale, ref packet.PortraitTurnInName);
                }
            }

            packet.QuestGiverGUID        = npcGUID;
            packet.InformUnit            = _session.GetPlayer().GetDivider();
            packet.QuestID               = quest.Id;
            packet.PortraitGiver         = quest.QuestGiverPortrait;
            packet.PortraitGiverMount    = quest.QuestGiverPortraitMount;
            packet.PortraitTurnIn        = quest.QuestTurnInPortrait;
            packet.AutoLaunched          = autoLaunched;
            packet.DisplayPopup          = displayPopup;
            packet.QuestFlags[0]         = (uint)(quest.Flags & (WorldConfig.GetBoolValue(WorldCfg.QuestIgnoreAutoAccept) ? ~QuestFlags.AutoAccept : ~QuestFlags.None));
            packet.QuestFlags[1]         = (uint)quest.FlagsEx;
            packet.SuggestedPartyMembers = quest.SuggestedPlayers;

            // RewardSpell can teach multiple spells in trigger spell effects. But not all effects must be SPELL_EFFECT_LEARN_SPELL. See example spell 33950
            if (quest.RewardSpell != 0)
            {
                SpellInfo spellInfo = Global.SpellMgr.GetSpellInfo(quest.RewardSpell);
                if (spellInfo.HasEffect(SpellEffectName.LearnSpell))
                {
                    var effects = spellInfo.GetEffectsForDifficulty(Difficulty.None);
                    foreach (var spellEffectInfo in effects)
                    {
                        if (spellEffectInfo.IsEffect(SpellEffectName.LearnSpell))
                        {
                            packet.LearnSpells.Add(spellEffectInfo.TriggerSpell);
                        }
                    }
                }
            }

            quest.BuildQuestRewards(packet.Rewards, _session.GetPlayer());

            for (int i = 0; i < SharedConst.QuestEmoteCount; ++i)
            {
                var emote = new QuestDescEmote(quest.DetailsEmote[i], quest.DetailsEmoteDelay[i]);
                packet.DescEmotes.Add(emote);
            }

            var objs = quest.Objectives;

            for (int i = 0; i < objs.Count; ++i)
            {
                var obj = new QuestObjectiveSimple();
                obj.ID       = objs[i].ID;
                obj.ObjectID = objs[i].ObjectID;
                obj.Amount   = objs[i].Amount;
                obj.Type     = (byte)objs[i].Type;
                packet.Objectives.Add(obj);
            }

            _session.SendPacket(packet);
        }
Example #31
0
        static bool HandleBanHelper(BanMode mode, StringArguments args, CommandHandler handler)
        {
            if (args.Empty())
            {
                return(false);
            }

            string nameOrIP = args.NextString();

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

            string durationStr = args.NextString();

            if (!uint.TryParse(durationStr, out uint duration))
            {
                return(false);
            }

            string reasonStr = args.NextString("");

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

            switch (mode)
            {
            case BanMode.Character:
                if (!ObjectManager.NormalizePlayerName(ref nameOrIP))
                {
                    handler.SendSysMessage(CypherStrings.PlayerNotFound);
                    return(false);
                }
                break;

            case BanMode.IP:
                if (!IPAddress.TryParse(nameOrIP, out _))
                {
                    return(false);
                }
                break;
            }

            string author = handler.GetSession() ? handler.GetSession().GetPlayerName() : "Server";

            switch (Global.WorldMgr.BanAccount(mode, nameOrIP, durationStr, reasonStr, author))
            {
            case BanReturn.Success:
                if (duration > 0)
                {
                    if (WorldConfig.GetBoolValue(WorldCfg.ShowBanInWorld))
                    {
                        Global.WorldMgr.SendWorldText(CypherStrings.BanAccountYoubannedmessageWorld, author, nameOrIP, Time.secsToTimeString(Time.TimeStringToSecs(durationStr)), reasonStr);
                    }
                    else
                    {
                        handler.SendSysMessage(CypherStrings.BanYoubanned, nameOrIP, Time.secsToTimeString(Time.TimeStringToSecs(durationStr), true), reasonStr);
                    }
                }
                else
                {
                    if (WorldConfig.GetBoolValue(WorldCfg.ShowBanInWorld))
                    {
                        Global.WorldMgr.SendWorldText(CypherStrings.BanAccountYoupermbannedmessageWorld, author, nameOrIP, reasonStr);
                    }
                    else
                    {
                        handler.SendSysMessage(CypherStrings.BanYoupermbanned, nameOrIP, reasonStr);
                    }
                }
                break;

            case BanReturn.SyntaxError:
                return(false);

            case BanReturn.Notfound:
                switch (mode)
                {
                default:
                    handler.SendSysMessage(CypherStrings.BanNotfound, "account", nameOrIP);
                    break;

                case BanMode.Character:
                    handler.SendSysMessage(CypherStrings.BanNotfound, "character", nameOrIP);
                    break;

                case BanMode.IP:
                    handler.SendSysMessage(CypherStrings.BanNotfound, "ip", nameOrIP);
                    break;
                }
                return(false);

            case BanReturn.Exists:
                handler.SendSysMessage(CypherStrings.BanExists);
                break;
            }

            return(true);
        }
Example #32
0
        void HandleInitiateTrade(InitiateTrade initiateTrade)
        {
            if (GetPlayer().GetTradeData() != null)
            {
                return;
            }

            TradeStatusPkt info = new();

            if (!GetPlayer().IsAlive())
            {
                info.Status = TradeStatus.Dead;
                SendTradeStatus(info);
                return;
            }

            if (GetPlayer().HasUnitState(UnitState.Stunned))
            {
                info.Status = TradeStatus.Stunned;
                SendTradeStatus(info);
                return;
            }

            if (IsLogingOut())
            {
                info.Status = TradeStatus.LoggingOut;
                SendTradeStatus(info);
                return;
            }

            if (GetPlayer().IsInFlight())
            {
                info.Status = TradeStatus.TooFarAway;
                SendTradeStatus(info);
                return;
            }

            if (GetPlayer().GetLevel() < WorldConfig.GetIntValue(WorldCfg.TradeLevelReq))
            {
                SendNotification(Global.ObjectMgr.GetCypherString(CypherStrings.TradeReq), WorldConfig.GetIntValue(WorldCfg.TradeLevelReq));
                info.Status = TradeStatus.Failed;
                SendTradeStatus(info);
                return;
            }


            Player pOther = Global.ObjAccessor.FindPlayer(initiateTrade.Guid);

            if (!pOther)
            {
                info.Status = TradeStatus.NoTarget;
                SendTradeStatus(info);
                return;
            }

            if (pOther == GetPlayer() || pOther.GetTradeData() != null)
            {
                info.Status = TradeStatus.PlayerBusy;
                SendTradeStatus(info);
                return;
            }

            if (!pOther.IsAlive())
            {
                info.Status = TradeStatus.TargetDead;
                SendTradeStatus(info);
                return;
            }

            if (pOther.IsInFlight())
            {
                info.Status = TradeStatus.TooFarAway;
                SendTradeStatus(info);
                return;
            }

            if (pOther.HasUnitState(UnitState.Stunned))
            {
                info.Status = TradeStatus.TargetStunned;
                SendTradeStatus(info);
                return;
            }

            if (pOther.GetSession().IsLogingOut())
            {
                info.Status = TradeStatus.TargetLoggingOut;
                SendTradeStatus(info);
                return;
            }

            if (pOther.GetSocial().HasIgnore(GetPlayer().GetGUID(), GetPlayer().GetSession().GetAccountGUID()))
            {
                info.Status = TradeStatus.PlayerIgnored;
                SendTradeStatus(info);
                return;
            }

            if ((pOther.GetTeam() != GetPlayer().GetTeam() ||
                 pOther.HasPlayerFlagEx(PlayerFlagsEx.MercenaryMode) ||
                 GetPlayer().HasPlayerFlagEx(PlayerFlagsEx.MercenaryMode)) &&
                (!WorldConfig.GetBoolValue(WorldCfg.AllowTwoSideTrade) &&
                 !HasPermission(RBACPermissions.AllowTwoSideTrade)))
            {
                info.Status = TradeStatus.WrongFaction;
                SendTradeStatus(info);
                return;
            }

            if (!pOther.IsWithinDistInMap(GetPlayer(), 11.11f, false))
            {
                info.Status = TradeStatus.TooFarAway;
                SendTradeStatus(info);
                return;
            }

            if (pOther.GetLevel() < WorldConfig.GetIntValue(WorldCfg.TradeLevelReq))
            {
                SendNotification(Global.ObjectMgr.GetCypherString(CypherStrings.TradeOtherReq), WorldConfig.GetIntValue(WorldCfg.TradeLevelReq));
                info.Status = TradeStatus.Failed;
                SendTradeStatus(info);
                return;
            }

            // OK start trade
            GetPlayer().SetTradeData(new TradeData(GetPlayer(), pOther));
            pOther.SetTradeData(new TradeData(pOther, GetPlayer()));

            info.Status  = TradeStatus.Proposed;
            info.Partner = GetPlayer().GetGUID();
            pOther.GetSession().SendTradeStatus(info);
        }
Example #33
0
        static bool HandleBanCharacterCommand(StringArguments args, CommandHandler handler)
        {
            if (args.Empty())
            {
                return(false);
            }

            string name = args.NextString();

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

            string durationStr = args.NextString();

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

            if (!uint.TryParse(durationStr, out uint duration))
            {
                return(false);
            }

            string reasonStr = args.NextString("");

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

            if (!ObjectManager.NormalizePlayerName(ref name))
            {
                handler.SendSysMessage(CypherStrings.PlayerNotFound);
                return(false);
            }

            string author = handler.GetSession() != null?handler.GetSession().GetPlayerName() : "Server";

            switch (Global.WorldMgr.BanCharacter(name, durationStr, reasonStr, author))
            {
            case BanReturn.Success:
            {
                if (duration > 0)
                {
                    if (WorldConfig.GetBoolValue(WorldCfg.ShowBanInWorld))
                    {
                        Global.WorldMgr.SendWorldText(CypherStrings.BanCharacterYoubannedmessageWorld, author, name, Time.secsToTimeString(Time.TimeStringToSecs(durationStr), true), reasonStr);
                    }
                    else
                    {
                        handler.SendSysMessage(CypherStrings.BanYoubanned, name, Time.secsToTimeString(Time.TimeStringToSecs(durationStr), true), reasonStr);
                    }
                }
                else
                {
                    if (WorldConfig.GetBoolValue(WorldCfg.ShowBanInWorld))
                    {
                        Global.WorldMgr.SendWorldText(CypherStrings.BanCharacterYoupermbannedmessageWorld, author, name, reasonStr);
                    }
                    else
                    {
                        handler.SendSysMessage(CypherStrings.BanYoupermbanned, name, reasonStr);
                    }
                }
                break;
            }

            case BanReturn.Notfound:
            {
                handler.SendSysMessage(CypherStrings.BanNotfound, "character", name);
                return(false);
            }

            default:
                break;
            }

            return(true);
        }
 public void SaveGame(WorldConfig game)
 {
     _SavedGames.Add(game);
 }
Example #35
0
 public bool IsEnabled()
 {
     return(WorldConfig.GetBoolValue(WorldCfg.BlackmarketEnabled));
 }