Ejemplo n.º 1
0
        public SQLResult Select(string sql, params object[] args)
        {
            SQLResult retData = new SQLResult();

            StringBuilder sqlString = new StringBuilder();
            // Fix for floating point problems on some languages
            sqlString.AppendFormat(CultureInfo.GetCultureInfo("en-US").NumberFormat, sql);

            MySqlCommand sqlCommand = new MySqlCommand(sqlString.ToString(), Connection);
            
            try
            {
                List<MySqlParameter> mParams = new List<MySqlParameter>(args.Length);

                foreach (var a in args)
                    mParams.Add(new MySqlParameter("", a));

                sqlCommand.Parameters.AddRange(mParams.ToArray());
                SqlData = sqlCommand.ExecuteReader(CommandBehavior.Default);
                retData.Load(SqlData);
                retData.Count = retData.Rows.Count;
                SqlData.Close();
            }
            catch (MySqlException ex)
            {
                LogConsole.Show(LogType.ERROR, "{0}", ex.Message);
            }

            return retData;
        }
Ejemplo n.º 2
0
 public GridCreator(SQLResult p_sqlResult, DataGrid dgDataGrid1)
 {
     dgDataGrid = dgDataGrid1;
     sqlResult = p_sqlResult;
     ReadTypes();
     CreateNewType();
     ReadXML();
     ////why not work
     dynamic dEntries;
     dEntries = entries;
     dgDataGrid.ItemsSource = dEntries;
 }
Ejemplo n.º 3
0
        public SQLResult Select(string sql, params object[] args)
        {
            SQLResult retData = new SQLResult();

            StringBuilder sqlString = new StringBuilder();
            // Fix for floating point problems on some languages
            sqlString.AppendFormat(CultureInfo.GetCultureInfo("en-US").NumberFormat, sql, args);

            MySqlCommand sqlCommand = new MySqlCommand(sqlString.ToString(), Connection);

            try
            {
                SqlData = sqlCommand.ExecuteReader(CommandBehavior.Default);
                retData.Load(SqlData);
                retData.Count = retData.Rows.Count;
                SqlData.Close();
            }
            catch (MySqlException ex)
            {
                Log.Message(LogType.ERROR, "{0}", ex.Message);
            }

            return retData;
        }
Ejemplo n.º 4
0
        public void LoadAreaTriggerTemplates()
        {
            uint oldMSTime = Time.GetMSTime();
            MultiMap <uint, Vector2>           verticesByAreaTrigger       = new MultiMap <uint, Vector2>();
            MultiMap <uint, Vector2>           verticesTargetByAreaTrigger = new MultiMap <uint, Vector2>();
            MultiMap <uint, Vector3>           splinesBySpellMisc          = new MultiMap <uint, Vector3>();
            MultiMap <uint, AreaTriggerAction> actionsByAreaTrigger        = new MultiMap <uint, AreaTriggerAction>();

            //                                                       0              1           2            3
            SQLResult templateActions = DB.World.Query("SELECT AreaTriggerId, ActionType, ActionParam, TargetType FROM `areatrigger_template_actions`");

            if (!templateActions.IsEmpty())
            {
                do
                {
                    uint areaTriggerId = templateActions.Read <uint>(0);

                    AreaTriggerAction action;
                    action.Param      = templateActions.Read <uint>(2);
                    action.ActionType = (AreaTriggerActionTypes)templateActions.Read <uint>(1);
                    action.TargetType = (AreaTriggerActionUserTypes)templateActions.Read <uint>(3);

                    if (action.ActionType >= AreaTriggerActionTypes.Max)
                    {
                        Log.outError(LogFilter.Sql, "Table `areatrigger_template_actions` has invalid ActionType ({0}) for AreaTriggerId {1} and Param {2}", action.ActionType, areaTriggerId, action.Param);
                        continue;
                    }

                    if (action.TargetType >= AreaTriggerActionUserTypes.Max)
                    {
                        Log.outError(LogFilter.Sql, "Table `areatrigger_template_actions` has invalid TargetType ({0}) for AreaTriggerId {1} and Param {2}", action.TargetType, areaTriggerId, action.Param);
                        continue;
                    }

                    actionsByAreaTrigger.Add(areaTriggerId, action);
                }while (templateActions.NextRow());
            }
            else
            {
                Log.outInfo(LogFilter.ServerLoading, "Loaded 0 AreaTrigger templates actions. DB table `areatrigger_template_actions` is empty.");
            }

            //                                           0              1    2         3         4               5
            SQLResult vertices = DB.World.Query("SELECT AreaTriggerId, Idx, VerticeX, VerticeY, VerticeTargetX, VerticeTargetY FROM `areatrigger_template_polygon_vertices` ORDER BY `AreaTriggerId`, `Idx`");

            if (!vertices.IsEmpty())
            {
                do
                {
                    uint areaTriggerId = vertices.Read <uint>(0);

                    verticesByAreaTrigger.Add(areaTriggerId, new Vector2(vertices.Read <float>(2), vertices.Read <float>(3)));

                    if (!vertices.IsNull(4) && !vertices.IsNull(5))
                    {
                        verticesTargetByAreaTrigger.Add(areaTriggerId, new Vector2(vertices.Read <float>(4), vertices.Read <float>(5)));
                    }
                    else if (vertices.IsNull(4) != vertices.IsNull(5))
                    {
                        Log.outError(LogFilter.Sql, "Table `areatrigger_template_polygon_vertices` has listed invalid target vertices (AreaTrigger: {0}, Index: {1}).", areaTriggerId, vertices.Read <uint>(1));
                    }
                }while (vertices.NextRow());
            }
            else
            {
                Log.outInfo(LogFilter.ServerLoading, "Loaded 0 AreaTrigger templates polygon vertices. DB table `areatrigger_template_polygon_vertices` is empty.");
            }

            //                                         0            1  2  3
            SQLResult splines = DB.World.Query("SELECT SpellMiscId, X, Y, Z FROM `spell_areatrigger_splines` ORDER BY `SpellMiscId`, `Idx`");

            if (!splines.IsEmpty())
            {
                do
                {
                    uint spellMiscId = splines.Read <uint>(0);

                    Vector3 spline = new Vector3(splines.Read <float>(1), splines.Read <float>(2), splines.Read <float>(3));

                    splinesBySpellMisc.Add(spellMiscId, spline);
                }while (splines.NextRow());
            }
            else
            {
                Log.outInfo(LogFilter.ServerLoading, "Loaded 0 AreaTrigger templates splines. DB table `spell_areatrigger_splines` is empty.");
            }

            //                                                      0   1     2      3      4      5      6      7      8      9
            SQLResult templates = DB.World.Query("SELECT Id, Type, Flags, Data0, Data1, Data2, Data3, Data4, Data5, ScriptName FROM `areatrigger_template`");

            if (!templates.IsEmpty())
            {
                do
                {
                    AreaTriggerTemplate areaTriggerTemplate = new AreaTriggerTemplate();
                    areaTriggerTemplate.Id = templates.Read <uint>(0);
                    AreaTriggerTypes type = (AreaTriggerTypes)templates.Read <byte>(1);

                    if (type >= AreaTriggerTypes.Max)
                    {
                        Log.outError(LogFilter.Sql, "Table `areatrigger_template` has listed areatrigger (Id: {0}) with invalid type {1}.", areaTriggerTemplate.Id, type);
                        continue;
                    }

                    areaTriggerTemplate.TriggerType = type;
                    areaTriggerTemplate.Flags       = (AreaTriggerFlags)templates.Read <uint>(2);

                    unsafe
                    {
                        fixed(float *b = areaTriggerTemplate.DefaultDatas.Data)
                        {
                            for (byte i = 0; i < SharedConst.MaxAreatriggerEntityData; ++i)
                            {
                                b[i] = templates.Read <float>(3 + i);
                            }
                        }
                    }

                    areaTriggerTemplate.ScriptId              = Global.ObjectMgr.GetScriptId(templates.Read <string>(9));
                    areaTriggerTemplate.PolygonVertices       = verticesByAreaTrigger[areaTriggerTemplate.Id];
                    areaTriggerTemplate.PolygonVerticesTarget = verticesTargetByAreaTrigger[areaTriggerTemplate.Id];
                    areaTriggerTemplate.Actions = actionsByAreaTrigger[areaTriggerTemplate.Id];

                    areaTriggerTemplate.InitMaxSearchRadius();
                    _areaTriggerTemplateStore[areaTriggerTemplate.Id] = areaTriggerTemplate;
                }while (templates.NextRow());
            }

            //                                                                  0            1              2            3             4             5              6                  7             8
            SQLResult areatriggerSpellMiscs = DB.World.Query("SELECT SpellMiscId, AreaTriggerId, MoveCurveId, ScaleCurveId, MorphCurveId, FacingCurveId, DecalPropertiesId, TimeToTarget, TimeToTargetScale FROM `spell_areatrigger`");

            if (!areatriggerSpellMiscs.IsEmpty())
            {
                do
                {
                    AreaTriggerMiscTemplate miscTemplate = new AreaTriggerMiscTemplate();
                    miscTemplate.MiscId = areatriggerSpellMiscs.Read <uint>(0);

                    uint areatriggerId = areatriggerSpellMiscs.Read <uint>(1);
                    miscTemplate.Template = GetAreaTriggerTemplate(areatriggerId);

                    if (miscTemplate.Template == null)
                    {
                        Log.outError(LogFilter.Sql, "Table `spell_areatrigger` reference invalid AreaTriggerId {0} for miscId {1}", areatriggerId, miscTemplate.MiscId);
                        continue;
                    }

                    Func <uint, uint> ValidateAndSetCurve = value =>
                    {
                        if (value != 0 && !CliDB.CurveStorage.ContainsKey(value))
                        {
                            Log.outError(LogFilter.Sql, "Table `spell_areatrigger` has listed areatrigger (MiscId: {0}, Id: {1}) with invalid Curve ({2}), set to 0!", miscTemplate.MiscId, areatriggerId, value);
                            return(0);
                        }
                        return(value);
                    };

                    miscTemplate.MoveCurveId   = ValidateAndSetCurve(areatriggerSpellMiscs.Read <uint>(2));
                    miscTemplate.ScaleCurveId  = ValidateAndSetCurve(areatriggerSpellMiscs.Read <uint>(3));
                    miscTemplate.MorphCurveId  = ValidateAndSetCurve(areatriggerSpellMiscs.Read <uint>(4));
                    miscTemplate.FacingCurveId = ValidateAndSetCurve(areatriggerSpellMiscs.Read <uint>(5));

                    miscTemplate.DecalPropertiesId = areatriggerSpellMiscs.Read <uint>(6);

                    miscTemplate.TimeToTarget      = areatriggerSpellMiscs.Read <uint>(7);
                    miscTemplate.TimeToTargetScale = areatriggerSpellMiscs.Read <uint>(8);

                    miscTemplate.SplinePoints = splinesBySpellMisc[miscTemplate.MiscId];

                    _areaTriggerTemplateSpellMisc[miscTemplate.MiscId] = miscTemplate;
                }while (areatriggerSpellMiscs.NextRow());
            }
            else
            {
                Log.outInfo(LogFilter.ServerLoading, "Loaded 0 Spell AreaTrigger templates. DB table `spell_areatrigger` is empty.");
            }

            Log.outInfo(LogFilter.ServerLoading, "Loaded {0} spell areatrigger templates in {1} ms.", _areaTriggerTemplateStore.Count, Time.GetMSTimeDiffToNow(oldMSTime));
        }
Ejemplo n.º 5
0
        public void LoadConversationTemplates()
        {
            _conversationLineTemplateStorage.Clear();
            _conversationTemplateStorage.Clear();

            Dictionary <uint, ConversationActor[]> actorsByConversation     = new();
            Dictionary <uint, ulong[]>             actorGuidsByConversation = new();

            SQLResult lineTemplates = DB.World.Query("SELECT Id, UiCameraID, ActorIdx, Flags FROM conversation_line_template");

            if (!lineTemplates.IsEmpty())
            {
                uint oldMSTime = Time.GetMSTime();

                do
                {
                    uint id = lineTemplates.Read <uint>(0);

                    if (!CliDB.ConversationLineStorage.ContainsKey(id))
                    {
                        Log.outError(LogFilter.Sql, "Table `conversation_line_template` has template for non existing ConversationLine (ID: {0}), skipped", id);
                        continue;
                    }

                    ConversationLineTemplate conversationLine = new();
                    conversationLine.Id         = id;
                    conversationLine.UiCameraID = lineTemplates.Read <uint>(1);
                    conversationLine.ActorIdx   = lineTemplates.Read <byte>(2);
                    conversationLine.Flags      = lineTemplates.Read <byte>(3);

                    _conversationLineTemplateStorage[id] = conversationLine;
                }while (lineTemplates.NextRow());

                Log.outInfo(LogFilter.ServerLoading, "Loaded {0} Conversation line templates in {1} ms", _conversationLineTemplateStorage.Count, Time.GetMSTimeDiffToNow(oldMSTime));
            }
            else
            {
                Log.outInfo(LogFilter.ServerLoading, "Loaded 0 Conversation line templates. DB table `conversation_line_template` is empty.");
            }

            SQLResult actorResult = DB.World.Query("SELECT ConversationId, ConversationActorId, ConversationActorGuid, Idx, CreatureId, CreatureDisplayInfoId FROM conversation_actors");

            if (!actorResult.IsEmpty())
            {
                uint oldMSTime = Time.GetMSTime();
                uint count     = 0;

                do
                {
                    uint   conversationId        = actorResult.Read <uint>(0);
                    uint   actorId               = actorResult.Read <uint>(1);
                    ulong  actorGuid             = actorResult.Read <ulong>(2);
                    ushort idx                   = actorResult.Read <ushort>(3);
                    uint   creatureId            = actorResult.Read <uint>(4);
                    uint   creatureDisplayInfoId = actorResult.Read <uint>(5);

                    if (creatureId != 0 && actorGuid != 0)
                    {
                        Log.outError(LogFilter.Sql, $"Table `conversation_actors` references both actor (ID: {actorId}) and actorGuid (GUID: {actorGuid}) for Conversation {conversationId}, skipped.");
                        continue;
                    }

                    if (creatureId != 0)
                    {
                        if (creatureDisplayInfoId != 0)
                        {
                            ConversationActor conversationActor = new();
                            conversationActor.ActorId               = actorId;
                            conversationActor.CreatureId            = creatureId;
                            conversationActor.CreatureDisplayInfoId = creatureDisplayInfoId;

                            if (!actorsByConversation.ContainsKey(conversationId))
                            {
                                actorsByConversation[conversationId] = new ConversationActor[idx + 1];
                            }

                            ConversationActor[] actors = actorsByConversation[conversationId];
                            if (actors.Length <= idx)
                            {
                                Array.Resize(ref actors, idx + 1);
                            }

                            actors[idx] = conversationActor;
                            ++count;
                        }
                        else
                        {
                            Log.outError(LogFilter.Sql, $"Table `conversation_actors` references an actor (CreatureId: {creatureId}) without CreatureDisplayInfoId for Conversation {conversationId}, skipped");
                        }
                    }
                    else if (actorGuid != 0)
                    {
                        CreatureData creData = Global.ObjectMgr.GetCreatureData(actorGuid);
                        if (creData != null)
                        {
                            if (!actorGuidsByConversation.ContainsKey(conversationId))
                            {
                                actorGuidsByConversation[conversationId] = new ulong[idx + 1];
                            }

                            var guids = actorGuidsByConversation[conversationId];
                            if (guids.Length <= idx)
                            {
                                Array.Resize(ref guids, idx + 1);
                            }

                            guids[idx] = actorGuid;
                            ++count;
                        }
                        else
                        {
                            Log.outError(LogFilter.Sql, $"Table `conversation_actors` references an invalid creature guid (GUID: {actorGuid}) for Conversation {conversationId}, skipped");
                        }
                    }
                }while (actorResult.NextRow());

                Log.outInfo(LogFilter.ServerLoading, "Loaded {0} Conversation actors in {1} ms", count, Time.GetMSTimeDiffToNow(oldMSTime));
            }
            else
            {
                Log.outInfo(LogFilter.ServerLoading, "Loaded 0 Conversation actors. DB table `conversation_actors` is empty.");
            }

            SQLResult templateResult = DB.World.Query("SELECT Id, FirstLineId, TextureKitId, ScriptName FROM conversation_template");

            if (!templateResult.IsEmpty())
            {
                uint oldMSTime = Time.GetMSTime();

                do
                {
                    ConversationTemplate conversationTemplate = new();
                    conversationTemplate.Id           = templateResult.Read <uint>(0);
                    conversationTemplate.FirstLineId  = templateResult.Read <uint>(1);
                    conversationTemplate.TextureKitId = templateResult.Read <uint>(2);
                    conversationTemplate.ScriptId     = Global.ObjectMgr.GetScriptId(templateResult.Read <string>(3));

                    conversationTemplate.Actors     = actorsByConversation.TryGetValue(conversationTemplate.Id, out var actors) ? actors.ToList() : null;
                    conversationTemplate.ActorGuids = actorGuidsByConversation.TryGetValue(conversationTemplate.Id, out var actorGuids) ? actorGuids.ToList() : null;

                    ConversationLineRecord currentConversationLine = CliDB.ConversationLineStorage.LookupByKey(conversationTemplate.FirstLineId);
                    if (currentConversationLine == null)
                    {
                        Log.outError(LogFilter.Sql, "Table `conversation_template` references an invalid line (ID: {0}) for Conversation {1}, skipped", conversationTemplate.FirstLineId, conversationTemplate.Id);
                    }

                    while (currentConversationLine != null)
                    {
                        ConversationLineTemplate conversationLineTemplate = _conversationLineTemplateStorage.LookupByKey(currentConversationLine.Id);
                        if (conversationLineTemplate != null)
                        {
                            conversationTemplate.Lines.Add(conversationLineTemplate);
                        }
                        else
                        {
                            Log.outError(LogFilter.Sql, "Table `conversation_line_template` has missing template for line (ID: {0}) in Conversation {1}, skipped", currentConversationLine.Id, conversationTemplate.Id);
                        }

                        if (currentConversationLine.NextConversationLineID == 0)
                        {
                            break;
                        }

                        currentConversationLine = CliDB.ConversationLineStorage.LookupByKey(currentConversationLine.NextConversationLineID);
                    }

                    _conversationTemplateStorage[conversationTemplate.Id] = conversationTemplate;
                }while (templateResult.NextRow());

                Log.outInfo(LogFilter.ServerLoading, "Loaded {0} Conversation templates in {1} ms", _conversationTemplateStorage.Count, Time.GetMSTimeDiffToNow(oldMSTime));
            }
            else
            {
                Log.outInfo(LogFilter.ServerLoading, "Loaded 0 Conversation templates. DB table `conversation_template` is empty.");
            }
        }
Ejemplo n.º 6
0
        static bool HandleLfgGroupInfoCommand(StringArguments args, CommandHandler handler)
        {
            if (args.Empty())
            {
                return(false);
            }

            Player     playerTarget = null;
            ObjectGuid guidTarget;
            string     nameTarget;

            ObjectGuid parseGUID = ObjectGuid.Create(HighGuid.Player, args.NextUInt64());

            if (Global.CharacterCacheStorage.GetCharacterNameByGuid(parseGUID, out nameTarget))
            {
                playerTarget = Global.ObjAccessor.FindPlayer(parseGUID);
                guidTarget   = parseGUID;
            }
            else if (!handler.ExtractPlayerTarget(args, out playerTarget, out guidTarget, out nameTarget))
            {
                return(false);
            }

            Group groupTarget = null;

            if (playerTarget)
            {
                groupTarget = playerTarget.GetGroup();
            }
            else
            {
                PreparedStatement stmt = DB.Characters.GetPreparedStatement(CharStatements.SEL_GROUP_MEMBER);
                stmt.AddValue(0, guidTarget.GetCounter());
                SQLResult resultGroup = DB.Characters.Query(stmt);
                if (!resultGroup.IsEmpty())
                {
                    groupTarget = Global.GroupMgr.GetGroupByDbStoreId(resultGroup.Read <uint>(0));
                }
            }

            if (!groupTarget)
            {
                handler.SendSysMessage(CypherStrings.LfgNotInGroup, nameTarget);
                return(false);
            }

            ObjectGuid guid = groupTarget.GetGUID();

            handler.SendSysMessage(CypherStrings.LfgGroupInfo, groupTarget.IsLFGGroup(), Global.LFGMgr.GetState(guid), Global.LFGMgr.GetDungeon(guid));

            foreach (var slot in groupTarget.GetMemberSlots())
            {
                Player p = Global.ObjAccessor.FindPlayer(slot.guid);
                if (p)
                {
                    GetPlayerInfo(handler, p);
                }
                else
                {
                    handler.SendSysMessage("{0} is offline.", slot.name);
                }
            }

            return(true);
        }
Ejemplo n.º 7
0
        public SQLResult Query(string json)
        {
            SQLResult sqlResult = new SQLResult();

            try
            {
                dynamic data      = JsonConvert.DeserializeObject(json);
                string  operation = data.operation;

                _logger.LogInformation("operation:" + operation);
                _logger.LogInformation("json:" + json);

                var connectionString = Configuration["SQLConnection"];

                using (SqlConnection sqlConnection = new SqlConnection(connectionString))
                {
                    sqlConnection.Open();
                    var commandText = "[dbo].[SQL_REST_API]";

                    using (SqlCommand sqlCommand = new SqlCommand(commandText, sqlConnection))
                    {
                        sqlCommand.CommandType = System.Data.CommandType.StoredProcedure;

                        SqlParameter sqlParameter = sqlCommand.Parameters.Add("@json", System.Data.SqlDbType.VarChar, -1);
                        sqlParameter.Value = json;

                        // Execute the command and log the # rows affected.
                        if (operation == "select")
                        {
                            string        rowData = "";
                            SqlDataReader reader  = sqlCommand.ExecuteReader();
                            sqlResult.Data = new List <string>();
                            while (reader.Read())
                            {
                                rowData = "";
                                // _logger.LogInformation("reader.FieldCount: " + reader.FieldCount.ToString());
                                for (int i = 0; i < reader.FieldCount; i++)
                                {
                                    rowData += ("\"" + reader.GetName(i) + "\" : \"" + reader[i].ToString() + "\",");
                                }
                                sqlResult.Data.Add("{" + rowData.Substring(0, rowData.Length - 1) + "}");
                            }
                            _logger.LogInformation("SELECT executed");
                        }
                        else
                        {
                            sqlCommand.ExecuteNonQueryAsync();
                            _logger.LogInformation("INSERT/UPDATE/DELETE executed");
                        }
                    }
                } // sqlConnection


                sqlResult.Result = true;
                return(sqlResult);
            }
            catch (Exception ex)
            {
                _logger.LogError("Error: " + ex.ToString());
                sqlResult.Result       = false;
                sqlResult.ErrorMessage = ex.ToString();
                return(sqlResult);
            } // try
        }     // get
Ejemplo n.º 8
0
        public void LoadBattlegroundTemplates()
        {
            uint oldMSTime = Time.GetMSTime();

            _BattlegroundMapTemplates.Clear();
            _BattlegroundTemplates.Clear();

            //                                         0   1                  2                  3       4       5                 6               7            8       9
            SQLResult result = DB.World.Query("SELECT ID, MinPlayersPerTeam, MaxPlayersPerTeam, MinLvl, MaxLvl, AllianceStartLoc, HordeStartLoc, StartMaxDist, Weight, ScriptName FROM battleground_template");

            if (result.IsEmpty())
            {
                Log.outError(LogFilter.ServerLoading, "Loaded 0 Battlegrounds. DB table `Battleground_template` is empty.");
                return;
            }

            uint count = 0;

            do
            {
                BattlegroundTypeId bgTypeId = (BattlegroundTypeId)result.Read <uint>(0);
                if (Global.DisableMgr.IsDisabledFor(DisableType.Battleground, (uint)bgTypeId, null))
                {
                    continue;
                }

                // can be overwrite by values from DB
                BattlemasterListRecord bl = CliDB.BattlemasterListStorage.LookupByKey(bgTypeId);
                if (bl == null)
                {
                    Log.outError(LogFilter.Battleground, "Battleground ID {0} not found in BattlemasterList.dbc. Battleground not created.", bgTypeId);
                    continue;
                }

                BattlegroundTemplate bgTemplate = new BattlegroundTemplate();
                bgTemplate.Id = bgTypeId;
                bgTemplate.MinPlayersPerTeam = result.Read <ushort>(1);
                bgTemplate.MaxPlayersPerTeam = result.Read <ushort>(2);
                bgTemplate.MinLevel          = result.Read <byte>(3);
                bgTemplate.MaxLevel          = result.Read <byte>(4);
                float dist = result.Read <float>(7);
                bgTemplate.StartMaxDist = dist * dist;
                bgTemplate.Weight       = result.Read <byte>(8);

                bgTemplate.scriptId          = Global.ObjectMgr.GetScriptId(result.Read <string>(9));
                bgTemplate.BattlemasterEntry = bl;

                if (bgTemplate.MaxPlayersPerTeam == 0 || bgTemplate.MinPlayersPerTeam > bgTemplate.MaxPlayersPerTeam)
                {
                    Log.outError(LogFilter.Sql, "Table `Battleground_template` for Id {0} has bad values for MinPlayersPerTeam ({1}) and MaxPlayersPerTeam({2})",
                                 bgTemplate.Id, bgTemplate.MinPlayersPerTeam, bgTemplate.MaxPlayersPerTeam);
                    continue;
                }

                if (bgTemplate.MinLevel == 0 || bgTemplate.MaxLevel == 0 || bgTemplate.MinLevel > bgTemplate.MaxLevel)
                {
                    Log.outError(LogFilter.Sql, "Table `Battleground_template` for Id {0} has bad values for LevelMin ({1}) and LevelMax({2})",
                                 bgTemplate.Id, bgTemplate.MinLevel, bgTemplate.MaxLevel);
                    continue;
                }

                if (bgTemplate.Id != BattlegroundTypeId.AA && bgTemplate.Id != BattlegroundTypeId.RB)
                {
                    uint startId = result.Read <uint>(5);
                    if (CliDB.WorldSafeLocsStorage.ContainsKey(startId))
                    {
                        WorldSafeLocsRecord start = CliDB.WorldSafeLocsStorage.LookupByKey(startId);
                        bgTemplate.StartLocation[TeamId.Alliance] = new Position(start.Loc.X, start.Loc.Y, start.Loc.Z, (start.Facing + MathFunctions.PI) / 180);
                    }
                    else
                    {
                        Log.outError(LogFilter.Sql, "Table `Battleground_template` for Id {0} has a non-existed WorldSafeLocs.dbc id {1} in field `AllianceStartLoc`. BG not created.", bgTemplate.Id, startId);
                        continue;
                    }

                    startId = result.Read <uint>(6);
                    if (CliDB.WorldSafeLocsStorage.ContainsKey(startId))
                    {
                        WorldSafeLocsRecord start = CliDB.WorldSafeLocsStorage.LookupByKey(startId);
                        bgTemplate.StartLocation[TeamId.Horde] = new Position(start.Loc.X, start.Loc.Y, start.Loc.Z, result.Read <float>(8));
                    }
                    else
                    {
                        Log.outError(LogFilter.Sql, "Table `Battleground_template` for Id {0} has a non-existed WorldSafeLocs.dbc id {1} in field `HordeStartLoc`. BG not created.", bgTemplate.Id, startId);
                        continue;
                    }
                }

                if (!CreateBattleground(bgTemplate))
                {
                    continue;
                }

                _BattlegroundTemplates[bgTypeId] = bgTemplate;

                if (bgTemplate.BattlemasterEntry.MapId[1] == -1) // in this case we have only one mapId
                {
                    _BattlegroundMapTemplates[(uint)bgTemplate.BattlemasterEntry.MapId[0]] = _BattlegroundTemplates[bgTypeId];
                }

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

            Log.outInfo(LogFilter.ServerLoading, "Loaded {0} Battlegrounds in {1} ms", count, Time.GetMSTimeDiffToNow(oldMSTime));
        }
Ejemplo n.º 9
0
 private void DelDoorWorker_DoWork(object sender, DoWorkEventArgs e)
 {
     result = bUS_Door.DeleteDoor(door.Id);
 }
Ejemplo n.º 10
0
        public SQLResult Select(string sql, params object[] args)
        {
            SQLResult retData = new SQLResult();
            StringBuilder sqlString = new StringBuilder();
            // Fix for floating point problems on some languages
            sqlString.AppendFormat(new CultureInfo("en-US").NumberFormat, sql, args);

            IDbCommand sqlCommand = Connection.CreateCommand();
            sqlCommand.CommandText = sqlString.ToString();

            try
            {
                if (Connection.State == ConnectionState.Closed)
                    Connection.Open();

                SqlData = sqlCommand.ExecuteReader();
                retData.DataReader = SqlData;
                retData.FieldCount = SqlData.FieldCount;

                Connection.Close();
            }
            catch (Exception ex)
            {
                Log.Message(LogType.ERROR, "{0}", ex.Message);
            }

            return retData;
        }
Ejemplo n.º 11
0
        public void LoadBattlegroundTemplates()
        {
            uint oldMSTime = Time.GetMSTime();

            //                                         0   1                 2              3             4       5
            SQLResult result = DB.World.Query("SELECT ID, AllianceStartLoc, HordeStartLoc, StartMaxDist, Weight, ScriptName FROM battleground_template");

            if (result.IsEmpty())
            {
                Log.outInfo(LogFilter.ServerLoading, "Loaded 0 Battlegrounds. DB table `Battleground_template` is empty.");
                return;
            }

            uint count = 0;

            do
            {
                BattlegroundTypeId bgTypeId = (BattlegroundTypeId)result.Read <uint>(0);
                if (Global.DisableMgr.IsDisabledFor(DisableType.Battleground, (uint)bgTypeId, null))
                {
                    continue;
                }

                // can be overwrite by values from DB
                BattlemasterListRecord bl = CliDB.BattlemasterListStorage.LookupByKey(bgTypeId);
                if (bl == null)
                {
                    Log.outError(LogFilter.Battleground, "Battleground ID {0} not found in BattlemasterList.dbc. Battleground not created.", bgTypeId);
                    continue;
                }

                BattlegroundTemplate bgTemplate = new();
                bgTemplate.Id = bgTypeId;
                float dist = result.Read <float>(3);
                bgTemplate.MaxStartDistSq = dist * dist;
                bgTemplate.Weight         = result.Read <byte>(4);

                bgTemplate.ScriptId          = Global.ObjectMgr.GetScriptId(result.Read <string>(5));
                bgTemplate.BattlemasterEntry = bl;

                if (bgTemplate.Id != BattlegroundTypeId.AA && bgTemplate.Id != BattlegroundTypeId.RB && bgTemplate.Id != BattlegroundTypeId.RandomEpic)
                {
                    uint startId             = result.Read <uint>(1);
                    WorldSafeLocsEntry start = Global.ObjectMgr.GetWorldSafeLoc(startId);
                    if (start != null)
                    {
                        bgTemplate.StartLocation[TeamId.Alliance] = start;
                    }
                    else if (bgTemplate.StartLocation[TeamId.Alliance] != null) // reload case
                    {
                        Log.outError(LogFilter.Sql, $"Table `battleground_template` for id {bgTemplate.Id} contains a non-existing WorldSafeLocs.dbc id {startId} in field `AllianceStartLoc`. Ignoring.");
                    }
                    else
                    {
                        Log.outError(LogFilter.Sql, $"Table `Battleground_template` for Id {bgTemplate.Id} has a non-existed WorldSafeLocs.dbc id {startId} in field `AllianceStartLoc`. BG not created.");
                        continue;
                    }

                    startId = result.Read <uint>(2);
                    start   = Global.ObjectMgr.GetWorldSafeLoc(startId);
                    if (start != null)
                    {
                        bgTemplate.StartLocation[TeamId.Horde] = start;
                    }
                    else if (bgTemplate.StartLocation[TeamId.Horde] != null) // reload case
                    {
                        Log.outError(LogFilter.Sql, $"Table `battleground_template` for id {bgTemplate.Id} contains a non-existing WorldSafeLocs.dbc id {startId} in field `HordeStartLoc`. Ignoring.");
                    }
                    else
                    {
                        Log.outError(LogFilter.Sql, $"Table `Battleground_template` for Id {bgTemplate.Id} has a non-existed WorldSafeLocs.dbc id {startId} in field `HordeStartLoc`. BG not created.");
                        continue;
                    }
                }

                if (!CreateBattleground(bgTemplate))
                {
                    Log.outError(LogFilter.Battleground, $"Could not create battleground template class ({bgTemplate.Id})!");
                    continue;
                }

                _battlegroundTemplates[bgTypeId] = bgTemplate;

                if (bgTemplate.BattlemasterEntry.MapId[1] == -1) // in this case we have only one mapId
                {
                    _battlegroundMapTemplates[(uint)bgTemplate.BattlemasterEntry.MapId[0]] = _battlegroundTemplates[bgTypeId];
                }

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

            Log.outInfo(LogFilter.ServerLoading, "Loaded {0} Battlegrounds in {1} ms", count, Time.GetMSTimeDiffToNow(oldMSTime));
        }
Ejemplo n.º 12
0
        public void HandleLoginRequest(HttpHeader request)
        {
            LogonData   loginForm   = Json.CreateObject <LogonData>(request.Content);
            LogonResult loginResult = new LogonResult();

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

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

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

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

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

            stmt.AddValue(0, login);

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

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

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

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

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

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

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

                        ++failedLogins;

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

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

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

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

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

                        DB.Login.CommitTransaction(trans);
                    }
                }

                loginResult.AuthenticationState = "DONE";
                SendResponse(HttpCode.Ok, loginResult);
            }
            else
            {
                loginResult.AuthenticationState = "LOGIN";
                loginResult.ErrorCode           = "UNABLE_TO_DECODE";
                loginResult.ErrorMessage        = "There was an internal error while connecting to Battle.net. Please try again later.";
                SendResponse(HttpCode.BadRequest, loginResult);
            }
        }
Ejemplo n.º 13
0
        static bool HandleGoCreatureCommand(StringArguments args, CommandHandler handler)
        {
            if (args.Empty())
            {
                return(false);
            }

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

            // "id" or number or [name] Shift-click form |color|Hcreature_entry:creature_id|h[name]|h|r
            string param1 = handler.extractKeyFromLink(args, "Hcreature");

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

            string whereClause = "";

            // User wants to teleport to the NPC's template entry
            if (param1.Equals("id"))
            {
                // Get the "creature_template.entry"
                // number or [name] Shift-click form |color|Hcreature_entry:creature_id|h[name]|h|r
                string idStr = handler.extractKeyFromLink(args, "Hcreature_entry");
                if (string.IsNullOrEmpty(idStr))
                {
                    return(false);
                }

                if (!int.TryParse(idStr, out int entry) || entry == 0)
                {
                    return(false);
                }

                whereClause += "WHERE id = '" + entry + '\'';
            }
            else
            {
                // Number is invalid - maybe the user specified the mob's name
                if (!ulong.TryParse(param1, out ulong guidLow) || guidLow == 0)
                {
                    string name = param1;
                    whereClause += ", creature_template WHERE creature.id = creature_template.entry AND creature_template.name LIKE '" + name + '\'';
                }
                else
                {
                    whereClause += "WHERE guid = '" + guidLow + '\'';
                }
            }

            SQLResult result = DB.World.Query("SELECT position_x, position_y, position_z, orientation, map FROM creature {0}", whereClause);

            if (result.IsEmpty())
            {
                handler.SendSysMessage(CypherStrings.CommandGocreatnotfound);
                return(false);
            }
            if (result.GetRowCount() > 1)
            {
                handler.SendSysMessage(CypherStrings.CommandGocreatmultiple);
            }

            float x     = result.Read <float>(0);
            float y     = result.Read <float>(1);
            float z     = result.Read <float>(2);
            float o     = result.Read <float>(3);
            uint  mapId = result.Read <ushort>(4);

            if (!GridDefines.IsValidMapCoord(mapId, x, y, z, o) || Global.ObjectMgr.IsTransportMap(mapId))
            {
                handler.SendSysMessage(CypherStrings.InvalidTargetCoord, x, y, mapId);
                return(false);
            }

            // stop flight if need
            if (player.IsInFlight())
            {
                player.GetMotionMaster().MovementExpired();
                player.CleanupAfterTaxiFlight();
            }
            // save only in non-flight case
            else
            {
                player.SaveRecallPosition();
            }

            player.TeleportTo(mapId, x, y, z, o);

            return(true);
        }
Ejemplo n.º 14
0
        public SQLResult Select(MySqlConnection connection, bool openConnection, bool closeConnection, string sql, params object[] args)
        {
            if (openConnection == true)
            {
                connection.Open();
            }

            StringBuilder sqlString = new StringBuilder();
            sqlString.AppendFormat(CultureInfo.GetCultureInfo("en-US").NumberFormat, sql);

            try
            {
                using (var sqlCommand = new MySqlCommand(sqlString.ToString(), connection))
                {
                    var mParams = new List<MySqlParameter>(args.Length);

                    foreach (var a in args)
                    {
                        mParams.Add(new MySqlParameter("", a));
                    }

                    sqlCommand.Parameters.AddRange(mParams.ToArray());

                    using (var SqlData = sqlCommand.ExecuteReader(CommandBehavior.Default))
                    {
                        using (var retData = new SQLResult())
                        {
                            retData.Load(SqlData);
                            retData.Count = retData.Rows.Count;

                            return retData;
                        }
                    }
                }
            }
            catch (MySqlException ex)
            {
                Console.WriteLine(ex.Message);
            }
            finally
            {
                if (closeConnection == true)
                {
                    connection.Close();
                }
            }

            return null;
        }
Ejemplo n.º 15
0
        public static void HandleAuthResponse(ref PacketReader packet, ref WorldClass session)
        {
            BitUnpack BitUnpack = new BitUnpack(packet);

            packet.Skip(54);

            int addonSize = packet.Read <int>();

            packet.Skip(addonSize);

            uint   nameLength  = BitUnpack.GetBits <uint>(12);
            string accountName = packet.ReadString(nameLength);

            SQLResult result = DB.Realms.Select("SELECT * FROM accounts WHERE name = ?", accountName);

            if (result.Count == 0)
            {
                session.clientSocket.Close();
            }
            else
            {
                session.Account = new Account()
                {
                    Id         = result.Read <int>(0, "id"),
                    Name       = result.Read <String>(0, "name"),
                    Password   = result.Read <String>(0, "password"),
                    SessionKey = result.Read <String>(0, "sessionkey"),
                    Expansion  = result.Read <byte>(0, "expansion"),
                    GMLevel    = result.Read <byte>(0, "gmlevel"),
                    IP         = result.Read <String>(0, "ip"),
                    Language   = result.Read <String>(0, "language")
                }
            };

            string K = session.Account.SessionKey;

            byte[] kBytes = new byte[K.Length / 2];

            for (int i = 0; i < K.Length; i += 2)
            {
                kBytes[i / 2] = Convert.ToByte(K.Substring(i, 2), 16);
            }

            session.Crypt.Initialize(kBytes);

            uint      realmId          = WorldConfig.RealmId;
            SQLResult realmClassResult = DB.Realms.Select("SELECT class, expansion FROM realm_classes WHERE realmId = ?", realmId);
            SQLResult realmRaceResult  = DB.Realms.Select("SELECT race, expansion FROM realm_races WHERE realmId = ?", realmId);

            bool HasAccountData = true;
            bool IsInQueue      = false;

            PacketWriter authResponse = new PacketWriter(ServerMessage.AuthResponse);
            BitPack      BitPack      = new BitPack(authResponse);

            authResponse.WriteUInt8((byte)AuthCodes.AUTH_OK);

            BitPack.Write(IsInQueue);
            BitPack.Write(HasAccountData);

            if (HasAccountData)
            {
                BitPack.Write(0, 21);                              // Activate character template windows/button
                BitPack.Write(realmRaceResult.Count, 23);          // Activation count for races

                //if (HasCharacterTemplate)
                //Write bits for char templates...

                BitPack.Write(0);                                  // Unknown, 5.0.4
                BitPack.Write(realmClassResult.Count, 23);         // Activation count for classes
                BitPack.Write(0);                                  // Unknown, 5.1.0
            }

            if (IsInQueue)
            {
                BitPack.Write(1);                                  // Unknown
                BitPack.Flush();

                authResponse.WriteUInt32(0);
            }

            BitPack.Flush();

            if (HasAccountData)
            {
                for (int c = 0; c < realmClassResult.Count; c++)
                {
                    authResponse.WriteUInt8(realmClassResult.Read <byte>(c, "class"));
                    authResponse.WriteUInt8(realmClassResult.Read <byte>(c, "expansion"));
                }

                //if (HasCharacterTemplate)
                //Write data for char templates...

                for (int r = 0; r < realmRaceResult.Count; r++)
                {
                    authResponse.WriteUInt8(realmRaceResult.Read <byte>(r, "expansion"));
                    authResponse.WriteUInt8(realmRaceResult.Read <byte>(r, "race"));
                }

                authResponse.WriteUInt8(session.Account.Expansion);
                authResponse.WriteUInt8(session.Account.Expansion);
                authResponse.WriteUInt8(0);
                authResponse.WriteUInt32(0);
                authResponse.WriteUInt32(0);
                authResponse.WriteUInt32(0);
            }

            session.Send(ref authResponse);

            MiscHandler.HandleCacheVersion(ref session);
            TutorialHandler.HandleTutorialFlags(ref session);
        }
    }
Ejemplo n.º 16
0
    void UpdateRealms(object source, ElapsedEventArgs e)
    {
        PreparedStatement            stmt           = DB.Login.GetPreparedStatement(LoginStatements.SEL_REALMLIST);
        SQLResult                    result         = DB.Login.Query(stmt);
        Dictionary <RealmId, string> existingRealms = new();

        foreach (var p in _realms)
        {
            existingRealms[p.Key] = p.Value.Name;
        }

        _realms.Clear();

        // Circle through results and add them to the realm map
        if (!result.IsEmpty())
        {
            do
            {
                var  realm   = new Realm();
                uint realmId = result.Read <uint>(0);
                realm.Name            = result.Read <string>(1);
                realm.ExternalAddress = IPAddress.Parse(result.Read <string>(2));
                realm.LocalAddress    = IPAddress.Parse(result.Read <string>(3));
                realm.LocalSubnetMask = IPAddress.Parse(result.Read <string>(4));
                realm.Port            = result.Read <ushort>(5);
                RealmType realmType = (RealmType)result.Read <byte>(6);
                if (realmType == RealmType.FFAPVP)
                {
                    realmType = RealmType.PVP;
                }
                if (realmType >= RealmType.MaxType)
                {
                    realmType = RealmType.Normal;
                }

                realm.Type     = (byte)realmType;
                realm.Flags    = (RealmFlags)result.Read <byte>(7);
                realm.Timezone = result.Read <byte>(8);
                AccountTypes allowedSecurityLevel = (AccountTypes)result.Read <byte>(9);
                realm.AllowedSecurityLevel = (allowedSecurityLevel <= AccountTypes.Administrator ? allowedSecurityLevel : AccountTypes.Administrator);
                realm.PopulationLevel      = result.Read <float>(10);
                realm.Build = result.Read <uint>(11);
                byte region      = result.Read <byte>(12);
                byte battlegroup = result.Read <byte>(13);

                realm.Id = new RealmId(region, battlegroup, realmId);

                UpdateRealm(realm);

                var subRegion = new RealmId(region, battlegroup, 0).GetAddressString();
                if (!_subRegions.Contains(subRegion))
                {
                    _subRegions.Add(subRegion);
                }

                if (!existingRealms.ContainsKey(realm.Id))
                {
                    Log.outInfo(LogFilter.Realmlist, "Added realm \"{0}\" at {1}:{2}", realm.Name, realm.ExternalAddress.ToString(), realm.Port);
                }
                else
                {
                    Log.outDebug(LogFilter.Realmlist, "Updating realm \"{0}\" at {1}:{2}", realm.Name, realm.ExternalAddress.ToString(), realm.Port);
                }

                existingRealms.Remove(realm.Id);
            }while (result.NextRow());
        }

        foreach (var pair in existingRealms)
        {
            Log.outInfo(LogFilter.Realmlist, "Removed realm \"{0}\".", pair.Value);
        }
    }
Ejemplo n.º 17
0
        static bool HandleWpEventCommand(StringArguments args, CommandHandler handler)
        {
            if (args.Empty())
            {
                return(false);
            }

            string            show = args.NextString();
            PreparedStatement stmt;

            // Check
            if ((show != "add") && (show != "mod") && (show != "del") && (show != "listid"))
            {
                return(false);
            }

            string arg_id = args.NextString();
            uint   id;

            if (show == "add")
            {
                if (!uint.TryParse(arg_id, out id))
                {
                    id = 0;
                }

                if (id != 0)
                {
                    stmt = DB.World.GetPreparedStatement(WorldStatements.SEL_WAYPOINT_SCRIPT_ID_BY_GUID);
                    stmt.AddValue(0, id);
                    SQLResult result = DB.World.Query(stmt);

                    if (result.IsEmpty())
                    {
                        stmt = DB.World.GetPreparedStatement(WorldStatements.INS_WAYPOINT_SCRIPT);
                        stmt.AddValue(0, id);
                        DB.World.Execute(stmt);

                        handler.SendSysMessage("|cff00ff00Wp Event: New waypoint event added: {0}|r", "", id);
                    }
                    else
                    {
                        handler.SendSysMessage("|cff00ff00Wp Event: You have choosed an existing waypoint script guid: {0}|r", id);
                    }
                }
                else
                {
                    stmt = DB.World.GetPreparedStatement(WorldStatements.SEL_WAYPOINT_SCRIPTS_MAX_ID);
                    SQLResult result = DB.World.Query(stmt);
                    id = result.Read <uint>(0);

                    stmt = DB.World.GetPreparedStatement(WorldStatements.INS_WAYPOINT_SCRIPT);
                    stmt.AddValue(0, id + 1);
                    DB.World.Execute(stmt);

                    handler.SendSysMessage("|cff00ff00Wp Event: New waypoint event added: |r|cff00ffff{0}|r", id + 1);
                }

                return(true);
            }

            if (show == "listid")
            {
                if (string.IsNullOrEmpty(arg_id))
                {
                    handler.SendSysMessage("|cff33ffffWp Event: You must provide waypoint script id.|r");
                    return(true);
                }

                if (!uint.TryParse(arg_id, out id))
                {
                    return(false);
                }

                uint   a2, a3, a4, a5, a6;
                float  a8, a9, a10, a11;
                string a7;

                stmt = DB.World.GetPreparedStatement(WorldStatements.SEL_WAYPOINT_SCRIPT_BY_ID);
                stmt.AddValue(0, id);
                SQLResult result = DB.World.Query(stmt);

                if (result.IsEmpty())
                {
                    handler.SendSysMessage("|cff33ffffWp Event: No waypoint scripts found on id: {0}|r", id);
                    return(true);
                }

                do
                {
                    a2  = result.Read <uint>(0);
                    a3  = result.Read <uint>(1);
                    a4  = result.Read <uint>(2);
                    a5  = result.Read <uint>(3);
                    a6  = result.Read <uint>(4);
                    a7  = result.Read <string>(5);
                    a8  = result.Read <float>(6);
                    a9  = result.Read <float>(7);
                    a10 = result.Read <float>(8);
                    a11 = result.Read <float>(9);

                    handler.SendSysMessage("|cffff33ffid:|r|cff00ffff {0}|r|cff00ff00, guid: |r|cff00ffff{1}|r|cff00ff00, delay: |r|cff00ffff{2}|r|cff00ff00, command: |r|cff00ffff{3}|r|cff00ff00," +
                                           "datalong: |r|cff00ffff{4}|r|cff00ff00, datalong2: |r|cff00ffff{5}|r|cff00ff00, datatext: |r|cff00ffff{6}|r|cff00ff00, posx: |r|cff00ffff{7}|r|cff00ff00, " +
                                           "posy: |r|cff00ffff{8}|r|cff00ff00, posz: |r|cff00ffff{9}|r|cff00ff00, orientation: |r|cff00ffff{10}|r", id, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11);
                }while (result.NextRow());
            }

            if (show == "del")
            {
                if (arg_id.IsEmpty())
                {
                    handler.SendSysMessage("|cffff33ffERROR: Waypoint script guid not present.|r");
                    return(true);
                }

                if (!uint.TryParse(arg_id, out id))
                {
                    return(false);
                }

                stmt = DB.World.GetPreparedStatement(WorldStatements.SEL_WAYPOINT_SCRIPT_ID_BY_GUID);
                stmt.AddValue(0, id);
                SQLResult result = DB.World.Query(stmt);

                if (!result.IsEmpty())
                {
                    stmt = DB.World.GetPreparedStatement(WorldStatements.DEL_WAYPOINT_SCRIPT);
                    stmt.AddValue(0, id);
                    DB.World.Execute(stmt);

                    handler.SendSysMessage("|cff00ff00{0}{1}|r", "Wp Event: Waypoint script removed: ", id);
                }
                else
                {
                    handler.SendSysMessage("|cffff33ffWp Event: ERROR: you have selected a non existing script: {0}|r", id);
                }

                return(true);
            }

            if (show == "mod")
            {
                if (string.IsNullOrEmpty(arg_id))
                {
                    handler.SendSysMessage("|cffff33ffERROR: Waypoint script guid not present.|r");
                    return(true);
                }

                if (!uint.TryParse(arg_id, out id) || id == 0)
                {
                    handler.SendSysMessage("|cffff33ffERROR: No valid waypoint script id not present.|r");
                    return(true);
                }

                string arg_string = args.NextString();
                if (string.IsNullOrEmpty(arg_string))
                {
                    handler.SendSysMessage("|cffff33ffERROR: No argument present.|r");
                    return(true);
                }

                if ((arg_string != "setid") && (arg_string != "delay") && (arg_string != "command") &&
                    (arg_string != "datalong") && (arg_string != "datalong2") && (arg_string != "dataint") && (arg_string != "posx") &&
                    (arg_string != "posy") && (arg_string != "posz") && (arg_string != "orientation"))
                {
                    handler.SendSysMessage("|cffff33ffERROR: No valid argument present.|r");
                    return(true);
                }

                string arg_3 = args.NextString();
                if (string.IsNullOrEmpty(arg_3))
                {
                    handler.SendSysMessage("|cffff33ffERROR: No additional argument present.|r");
                    return(true);
                }

                if (arg_string == "setid")
                {
                    if (!uint.TryParse(arg_3, out uint newid))
                    {
                        return(false);
                    }
                    handler.SendSysMessage("|cff00ff00Wp Event: Waypoint script guid: {0}|r|cff00ffff id changed: |r|cff00ff00{1}|r", newid, id);

                    stmt = DB.World.GetPreparedStatement(WorldStatements.UPD_WAYPOINT_SCRIPT_ID);
                    stmt.AddValue(0, newid);
                    stmt.AddValue(1, id);

                    DB.World.Execute(stmt);

                    return(true);
                }
                else
                {
                    stmt = DB.World.GetPreparedStatement(WorldStatements.SEL_WAYPOINT_SCRIPT_ID_BY_GUID);
                    stmt.AddValue(0, id);
                    SQLResult result = DB.World.Query(stmt);

                    if (result.IsEmpty())
                    {
                        handler.SendSysMessage("|cffff33ffERROR: You have selected an non existing waypoint script guid.|r");
                        return(true);
                    }

                    if (arg_string == "posx")
                    {
                        if (!float.TryParse(arg_3, out float arg3))
                        {
                            return(false);
                        }

                        stmt = DB.World.GetPreparedStatement(WorldStatements.UPD_WAYPOINT_SCRIPT_X);
                        stmt.AddValue(0, arg3);
                        stmt.AddValue(1, id);
                        DB.World.Execute(stmt);

                        handler.SendSysMessage("|cff00ff00Waypoint script:|r|cff00ffff {0}|r|cff00ff00 position_x updated.|r", id);
                        return(true);
                    }
                    else if (arg_string == "posy")
                    {
                        if (!float.TryParse(arg_3, out float arg3))
                        {
                            return(false);
                        }

                        stmt = DB.World.GetPreparedStatement(WorldStatements.UPD_WAYPOINT_SCRIPT_Y);
                        stmt.AddValue(0, arg3);
                        stmt.AddValue(1, id);
                        DB.World.Execute(stmt);

                        handler.SendSysMessage("|cff00ff00Waypoint script: {0} position_y updated.|r", id);
                        return(true);
                    }
                    else if (arg_string == "posz")
                    {
                        if (!float.TryParse(arg_3, out float arg3))
                        {
                            return(false);
                        }

                        stmt = DB.World.GetPreparedStatement(WorldStatements.UPD_WAYPOINT_SCRIPT_Z);
                        stmt.AddValue(0, arg3);
                        stmt.AddValue(1, id);
                        DB.World.Execute(stmt);

                        handler.SendSysMessage("|cff00ff00Waypoint script: |r|cff00ffff{0}|r|cff00ff00 position_z updated.|r", id);
                        return(true);
                    }
                    else if (arg_string == "orientation")
                    {
                        if (!float.TryParse(arg_3, out float arg3))
                        {
                            return(false);
                        }

                        stmt = DB.World.GetPreparedStatement(WorldStatements.UPD_WAYPOINT_SCRIPT_O);
                        stmt.AddValue(0, arg3);
                        stmt.AddValue(1, id);
                        DB.World.Execute(stmt);

                        handler.SendSysMessage("|cff00ff00Waypoint script: |r|cff00ffff{0}|r|cff00ff00 orientation updated.|r", id);
                        return(true);
                    }
                    else if (arg_string == "dataint")
                    {
                        if (!uint.TryParse(arg_3, out uint arg3))
                        {
                            return(false);
                        }

                        DB.World.Execute("UPDATE waypoint_scripts SET {0}='{1}' WHERE guid='{2}'", arg_string, arg3, id); // Query can't be a prepared statement

                        handler.SendSysMessage("|cff00ff00Waypoint script: |r|cff00ffff{0}|r|cff00ff00 dataint updated.|r", id);
                        return(true);
                    }
                    else
                    {
                        DB.World.Execute("UPDATE waypoint_scripts SET {0}='{1}' WHERE guid='{2}'", arg_string, arg_string, id); // Query can't be a prepared statement
                    }
                }
                handler.SendSysMessage("|cff00ff00Waypoint script:|r|cff00ffff{0}:|r|cff00ff00 {1} updated.|r", id, arg_string);
            }
            return(true);
        }
Ejemplo n.º 18
0
        public void LoadData(WDCHeader header, BitSet availableDb2Locales, HotfixStatements preparedStatement, HotfixStatements preparedStatementLocale)
        {
            _header    = header;
            _tableName = typeof(T).Name;

            SQLResult result = DB.Hotfix.Query(DB.Hotfix.GetPreparedStatement(preparedStatement));

            if (!result.IsEmpty())
            {
                do
                {
                    var obj = new T();

                    int dbIndex = 0;
                    var fields  = typeof(T).GetFields();
                    foreach (var f in typeof(T).GetFields())
                    {
                        Type type = f.FieldType;

                        if (type.IsArray)
                        {
                            Type arrayElementType = type.GetElementType();
                            if (arrayElementType.IsEnum)
                            {
                                arrayElementType = arrayElementType.GetEnumUnderlyingType();
                            }

                            Array array = (Array)f.GetValue(obj);
                            switch (Type.GetTypeCode(arrayElementType))
                            {
                            case TypeCode.SByte:
                                f.SetValue(obj, ReadArray <sbyte>(result, dbIndex, array.Length));
                                break;

                            case TypeCode.Byte:
                                f.SetValue(obj, ReadArray <byte>(result, dbIndex, array.Length));
                                break;

                            case TypeCode.Int16:
                                f.SetValue(obj, ReadArray <short>(result, dbIndex, array.Length));
                                break;

                            case TypeCode.UInt16:
                                f.SetValue(obj, ReadArray <ushort>(result, dbIndex, array.Length));
                                break;

                            case TypeCode.Int32:
                                f.SetValue(obj, ReadArray <int>(result, dbIndex, array.Length));
                                break;

                            case TypeCode.UInt32:
                                f.SetValue(obj, ReadArray <uint>(result, dbIndex, array.Length));
                                break;

                            case TypeCode.Int64:
                                f.SetValue(obj, ReadArray <long>(result, dbIndex, array.Length));
                                break;

                            case TypeCode.UInt64:
                                f.SetValue(obj, ReadArray <ulong>(result, dbIndex, array.Length));
                                break;

                            case TypeCode.Single:
                                f.SetValue(obj, ReadArray <float>(result, dbIndex, array.Length));
                                break;

                            case TypeCode.String:
                                f.SetValue(obj, ReadArray <string>(result, dbIndex, array.Length));
                                break;

                            case TypeCode.Object:
                                if (arrayElementType == typeof(Vector3))
                                {
                                    float[] values = ReadArray <float>(result, dbIndex, array.Length * 3);

                                    Vector3[] vectors = new Vector3[array.Length];
                                    for (var i = 0; i < array.Length; ++i)
                                    {
                                        vectors[i] = new Vector3(values[(i * 3)..(3 + (i * 3))]);
Ejemplo n.º 19
0
        static bool HandleWpAddCommand(StringArguments args, CommandHandler handler)
        {
            // optional
            string path_number = null;
            uint   pathid;

            if (!args.Empty())
            {
                path_number = args.NextString();
            }

            uint     point  = 0;
            Creature target = handler.GetSelectedCreature();

            PreparedStatement stmt;

            if (string.IsNullOrEmpty(path_number))
            {
                if (target)
                {
                    pathid = target.GetWaypointPath();
                }
                else
                {
                    stmt = DB.World.GetPreparedStatement(WorldStatements.SEL_WAYPOINT_DATA_MAX_ID);
                    SQLResult result1 = DB.World.Query(stmt);

                    uint maxpathid = result1.Read <uint>(0);
                    pathid = maxpathid + 1;
                    handler.SendSysMessage("|cff00ff00New path started.|r");
                }
            }
            else
            {
                if (!uint.TryParse(path_number, out pathid))
                {
                    return(false);
                }
            }

            // path_id . ID of the Path
            // point   . number of the waypoint (if not 0)

            if (pathid == 0)
            {
                handler.SendSysMessage("|cffff33ffCurrent creature haven't loaded path.|r");
                return(true);
            }

            stmt = DB.World.GetPreparedStatement(WorldStatements.SEL_WAYPOINT_DATA_MAX_POINT);
            stmt.AddValue(0, pathid);
            SQLResult result = DB.World.Query(stmt);

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

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

            stmt = DB.World.GetPreparedStatement(WorldStatements.INS_WAYPOINT_DATA);
            stmt.AddValue(0, pathid);
            stmt.AddValue(1, point + 1);
            stmt.AddValue(2, player.GetPositionX());
            stmt.AddValue(3, player.GetPositionY());
            stmt.AddValue(4, player.GetPositionZ());
            stmt.AddValue(5, player.GetOrientation());

            DB.World.Execute(stmt);

            handler.SendSysMessage("|cff00ff00PathID: |r|cff00ffff{0} |r|cff00ff00: Waypoint |r|cff00ffff{1}|r|cff00ff00 created.|r", pathid, point + 1);
            return(true);
        }
Ejemplo n.º 20
0
        public void LoadCreatureData()
        {
            Log.Message(LogType.DB, "Loading creatures...");

            SQLResult result = DB.World.Select("SELECT cs.Id FROM creature_stats cs LEFT JOIN creature_data cd ON cs.Id = cd.Id WHERE cd.Id IS NULL");

            if (result.Count != 0)
            {
                var missingIds = result.ReadAllValuesFromField("Id");
                DB.World.ExecuteBigQuery("creature_data", "Id", 1, result.Count, missingIds);

                Log.Message(LogType.DB, "Added {0} default data definition for creatures.", missingIds.Length);
            }

            result = DB.World.Select("SELECT * FROM creature_stats cs RIGHT JOIN creature_data cd ON cs.Id = cd.Id WHERE cs.Id IS NOT NULL");

            Parallel.For(0, result.Count, r =>
            {
                CreatureStats Stats = new CreatureStats
                {
                    Id                = result.Read <Int32>(r, "Id"),
                    Name              = result.Read <String>(r, "Name"),
                    SubName           = result.Read <String>(r, "SubName"),
                    IconName          = result.Read <String>(r, "IconName"),
                    Type              = result.Read <Int32>(r, "Type"),
                    Family            = result.Read <Int32>(r, "Family"),
                    Rank              = result.Read <Int32>(r, "Rank"),
                    HealthModifier    = result.Read <Single>(r, "HealthModifier"),
                    PowerModifier     = result.Read <Single>(r, "PowerModifier"),
                    RacialLeader      = result.Read <Byte>(r, "RacialLeader"),
                    MovementInfoId    = result.Read <Int32>(r, "MovementInfoId"),
                    ExpansionRequired = result.Read <Int32>(r, "ExpansionRequired")
                };

                for (int i = 0; i < Stats.Flag.Capacity; i++)
                {
                    Stats.Flag.Add(result.Read <Int32>(r, "Flag", i));
                }

                for (int i = 0; i < Stats.QuestKillNpcId.Capacity; i++)
                {
                    Stats.QuestKillNpcId.Add(result.Read <Int32>(r, "QuestKillNpcId", i));
                }

                for (int i = 0; i < Stats.DisplayInfoId.Capacity; i++)
                {
                    Stats.DisplayInfoId.Add(result.Read <Int32>(r, "DisplayInfoId", i));
                }

                for (int i = 0; i < Stats.QuestItemId.Capacity; i++)
                {
                    var questItem = result.Read <Int32>(r, "QuestItemId", i);

                    if (questItem != 0)
                    {
                        Stats.QuestItemId.Add(questItem);
                    }
                }

                Add(new Creature
                {
                    Data = new CreatureData
                    {
                        Health     = result.Read <Int32>(r, "Health"),
                        Level      = result.Read <Byte>(r, "Level"),
                        Class      = result.Read <Byte>(r, "Class"),
                        Faction    = result.Read <Int32>(r, "Faction"),
                        Scale      = result.Read <Int32>(r, "Scale"),
                        UnitFlags  = result.Read <Int32>(r, "UnitFlags"),
                        UnitFlags2 = result.Read <Int32>(r, "UnitFlags2"),
                        NpcFlags   = result.Read <Int32>(r, "NpcFlags")
                    },

                    Stats = Stats,
                });
            });

            Log.Message(LogType.DB, "Loaded {0} creatures.", Creatures.Count);
            Log.Message();
        }
Ejemplo n.º 21
0
        static bool HandleWpLoadCommand(StringArguments args, CommandHandler handler)
        {
            if (args.Empty())
            {
                return(false);
            }

            // optional
            string path_number = args.NextString();

            uint     pathid;
            Creature target = handler.GetSelectedCreature();

            // Did player provide a path_id?
            if (string.IsNullOrEmpty(path_number))
            {
                return(false);
            }

            if (!target)
            {
                handler.SendSysMessage(CypherStrings.SelectCreature);
                return(false);
            }

            if (target.GetEntry() == 1)
            {
                handler.SendSysMessage("|cffff33ffYou want to load path to a waypoint? Aren't you?|r");
                return(false);
            }

            if (!uint.TryParse(path_number, out pathid) || pathid == 0)
            {
                handler.SendSysMessage("|cffff33ffNo valid path number provided.|r");
                return(true);
            }

            ulong guidLow = target.GetSpawnId();

            PreparedStatement stmt = DB.World.GetPreparedStatement(WorldStatements.SEL_CREATURE_ADDON_BY_GUID);

            stmt.AddValue(0, guidLow);
            SQLResult result = DB.World.Query(stmt);

            if (!result.IsEmpty())
            {
                stmt = DB.World.GetPreparedStatement(WorldStatements.UPD_CREATURE_ADDON_PATH);
                stmt.AddValue(0, pathid);
                stmt.AddValue(1, guidLow);
            }
            else
            {
                stmt = DB.World.GetPreparedStatement(WorldStatements.INS_CREATURE_ADDON);
                stmt.AddValue(0, guidLow);
                stmt.AddValue(1, pathid);
            }

            DB.World.Execute(stmt);

            stmt = DB.World.GetPreparedStatement(WorldStatements.UPD_CREATURE_MOVEMENT_TYPE);
            stmt.AddValue(0, (byte)MovementGeneratorType.Waypoint);
            stmt.AddValue(1, guidLow);

            DB.World.Execute(stmt);

            target.LoadPath(pathid);
            target.SetDefaultMovementType(MovementGeneratorType.Waypoint);
            target.GetMotionMaster().Initialize();
            target.Say("Path loaded.", Language.Universal);

            return(true);
        }
Ejemplo n.º 22
0
 private void DelRightWorker_DoWork(object sender, DoWorkEventArgs e)
 {
     result = bUS_Right.DeleteRight(userRight.Id);
 }
Ejemplo n.º 23
0
        static bool HandleWpModifyCommand(StringArguments args, CommandHandler handler)
        {
            if (args.Empty())
            {
                return(false);
            }

            // first arg: add del text emote spell waittime move
            string show = args.NextString();

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

            // Check
            // Remember: "show" must also be the name of a column!
            if ((show != "delay") && (show != "action") && (show != "action_chance") &&
                (show != "move_flag") && (show != "del") && (show != "move"))
            {
                return(false);
            }

            // Did user provide a GUID
            // or did the user select a creature?
            // . variable lowguid is filled with the GUID of the NPC
            uint     pathid;
            uint     point;
            Creature target = handler.GetSelectedCreature();

            // User did select a visual waypoint?
            if (!target || target.GetEntry() != 1)
            {
                handler.SendSysMessage("|cffff33ffERROR: You must select a waypoint.|r");
                return(false);
            }

            // Check the creature
            PreparedStatement stmt = DB.World.GetPreparedStatement(WorldStatements.SEL_WAYPOINT_DATA_BY_WPGUID);

            stmt.AddValue(0, target.GetSpawnId());
            SQLResult result = DB.World.Query(stmt);

            if (result.IsEmpty())
            {
                handler.SendSysMessage(CypherStrings.WaypointNotfoundsearch, target.GetGUID().ToString());
                // Select waypoint number from database
                // Since we compare float values, we have to deal with
                // some difficulties.
                // Here we search for all waypoints that only differ in one from 1 thousand
                // See also: http://dev.mysql.com/doc/refman/5.0/en/problems-with-float.html
                string maxDiff = "0.01";

                stmt = DB.World.GetPreparedStatement(WorldStatements.SEL_WAYPOINT_DATA_BY_POS);
                stmt.AddValue(0, target.GetPositionX());
                stmt.AddValue(1, maxDiff);
                stmt.AddValue(2, target.GetPositionY());
                stmt.AddValue(3, maxDiff);
                stmt.AddValue(4, target.GetPositionZ());
                stmt.AddValue(5, maxDiff);
                result = DB.World.Query(stmt);

                if (result.IsEmpty())
                {
                    handler.SendSysMessage(CypherStrings.WaypointNotfounddbproblem, target.GetGUID().ToString());
                    return(true);
                }
            }

            do
            {
                pathid = result.Read <uint>(0);
                point  = result.Read <uint>(1);
            }while (result.NextRow());

            // We have the waypoint number and the GUID of the "master npc"
            // Text is enclosed in "<>", all other arguments not
            string arg_str = args.NextString();

            // Check for argument
            if (show != "del" && show != "move" && arg_str == null)
            {
                handler.SendSysMessage(CypherStrings.WaypointArgumentreq, show);
                return(false);
            }

            if (show == "del")
            {
                handler.SendSysMessage("|cff00ff00DEBUG: wp modify del, PathID: |r|cff00ffff{0}|r", pathid);

                if (Creature.DeleteFromDB(target.GetSpawnId()))
                {
                    stmt = DB.World.GetPreparedStatement(WorldStatements.DEL_WAYPOINT_DATA);
                    stmt.AddValue(0, pathid);
                    stmt.AddValue(1, point);
                    DB.World.Execute(stmt);

                    stmt = DB.World.GetPreparedStatement(WorldStatements.UPD_WAYPOINT_DATA_POINT);
                    stmt.AddValue(0, pathid);
                    stmt.AddValue(1, point);
                    DB.World.Execute(stmt);

                    handler.SendSysMessage(CypherStrings.WaypointRemoved);
                    return(true);
                }
                else
                {
                    handler.SendSysMessage(CypherStrings.WaypointNotremoved);
                    return(false);
                }
            }                                                       // del

            if (show == "move")
            {
                handler.SendSysMessage("|cff00ff00DEBUG: wp move, PathID: |r|cff00ffff{0}|r", pathid);

                Player chr = handler.GetSession().GetPlayer();
                Map    map = chr.GetMap();
                // What to do:
                // Move the visual spawnpoint
                // Respawn the owner of the waypoints
                if (!Creature.DeleteFromDB(target.GetSpawnId()))
                {
                    handler.SendSysMessage(CypherStrings.WaypointVpNotcreated, 1);
                    return(false);
                }

                // re-create
                Creature creature = Creature.CreateCreature(1, map, chr.GetPosition());
                if (!creature)
                {
                    handler.SendSysMessage(CypherStrings.WaypointVpNotcreated, 1);
                    return(false);
                }

                PhasingHandler.InheritPhaseShift(creature, chr);
                creature.SaveToDB(map.GetId(), new List <Difficulty>()
                {
                    map.GetDifficultyID()
                });

                ulong dbGuid = creature.GetSpawnId();

                // current "wpCreature" variable is deleted and created fresh new, otherwise old values might trigger asserts or cause undefined behavior
                creature.CleanupsBeforeDelete();
                creature.Dispose();

                // To call _LoadGoods(); _LoadQuests(); CreateTrainerSpells();
                creature = Creature.CreateCreatureFromDB(dbGuid, map, true, true);
                if (!creature)
                {
                    handler.SendSysMessage(CypherStrings.WaypointVpNotcreated, 1);
                    return(false);
                }

                stmt = DB.World.GetPreparedStatement(WorldStatements.UPD_WAYPOINT_DATA_POSITION);
                stmt.AddValue(0, chr.GetPositionX());
                stmt.AddValue(1, chr.GetPositionY());
                stmt.AddValue(2, chr.GetPositionZ());
                stmt.AddValue(3, chr.GetOrientation());
                stmt.AddValue(4, pathid);
                stmt.AddValue(5, point);
                DB.World.Execute(stmt);

                handler.SendSysMessage(CypherStrings.WaypointChanged);

                return(true);
            }                                                     // move

            if (string.IsNullOrEmpty(arg_str))
            {
                // show_str check for present in list of correct values, no sql injection possible
                DB.World.Execute("UPDATE waypoint_data SET {0}=null WHERE id='{1}' AND point='{2}'", show, pathid, point); // Query can't be a prepared statement
            }
            else
            {
                // show_str check for present in list of correct values, no sql injection possible
                DB.World.Execute("UPDATE waypoint_data SET {0}='{1}' WHERE id='{2}' AND point='{3}'", show, arg_str, pathid, point); // Query can't be a prepared statement
            }

            handler.SendSysMessage(CypherStrings.WaypointChangedNo, show);
            return(true);
        }
Ejemplo n.º 24
0
        public void LoadGuilds()
        {
            Log.outInfo(LogFilter.ServerLoading, "Loading Guilds Definitions...");
            {
                uint oldMSTime = Time.GetMSTime();

                //          0          1       2             3              4              5              6
                SQLResult result = DB.Characters.Query("SELECT g.guildid, g.name, g.leaderguid, g.EmblemStyle, g.EmblemColor, g.BorderStyle, g.BorderColor, " +
                                                       //   7                  8       9       10            11          12
                                                       "g.BackgroundColor, g.info, g.motd, g.createdate, g.BankMoney, COUNT(gbt.guildid) " +
                                                       "FROM guild g LEFT JOIN guild_bank_tab gbt ON g.guildid = gbt.guildid GROUP BY g.guildid ORDER BY g.guildid ASC");

                if (result.IsEmpty())
                {
                    Log.outError(LogFilter.Guild, "Loaded 0 guild definitions. DB table `guild` is empty.");
                    return;
                }

                uint count = 0;
                do
                {
                    Guild guild = new Guild();

                    if (!guild.LoadFromDB(result.GetFields()))
                    {
                        continue;
                    }

                    AddGuild(guild);
                    count++;
                } while (result.NextRow());
                Log.outInfo(LogFilter.ServerLoading, "Loaded {0} guild definitions in {1} ms", count, Time.GetMSTimeDiffToNow(oldMSTime));
            }

            Log.outInfo(LogFilter.ServerLoading, "Loading guild ranks...");
            {
                uint oldMSTime = Time.GetMSTime();

                // Delete orphaned guild rank entries before loading the valid ones
                DB.Characters.DirectExecute("DELETE gr FROM guild_rank gr LEFT JOIN guild g ON gr.guildId = g.guildId WHERE g.guildId IS NULL");

                //                                                   0    1      2       3                4
                SQLResult result = DB.Characters.Query("SELECT guildid, rid, rname, rights, BankMoneyPerDay FROM guild_rank ORDER BY guildid ASC, rid ASC");

                if (result.IsEmpty())
                {
                    Log.outInfo(LogFilter.ServerLoading, "Loaded 0 guild ranks. DB table `guild_rank` is empty.");
                }
                else
                {
                    uint count = 0;
                    do
                    {
                        uint  guildId = result.Read <uint>(0);
                        Guild guild   = GetGuildById(guildId);
                        if (guild)
                        {
                            guild.LoadRankFromDB(result.GetFields());
                        }

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

                    Log.outInfo(LogFilter.ServerLoading, "Loaded {0} guild ranks in {1} ms", count, Time.GetMSTimeDiffToNow(oldMSTime));
                }
            }

            // 3. Load all guild members
            Log.outInfo(LogFilter.ServerLoading, "Loading guild members...");
            {
                uint oldMSTime = Time.GetMSTime();

                // Delete orphaned guild member entries before loading the valid ones
                DB.Characters.DirectExecute("DELETE gm FROM guild_member gm LEFT JOIN guild g ON gm.guildId = g.guildId WHERE g.guildId IS NULL");
                DB.Characters.DirectExecute("DELETE gm FROM guild_member_withdraw gm LEFT JOIN guild_member g ON gm.guid = g.guid WHERE g.guid IS NULL");

                //           0           1        2     3      4        5       6       7       8       9       10
                SQLResult result = DB.Characters.Query("SELECT gm.guildid, gm.guid, rank, pnote, offnote, w.tab0, w.tab1, w.tab2, w.tab3, w.tab4, w.tab5, " +
                                                       //   11      12      13       14      15       16       17      18         19         20
                                                       "w.tab6, w.tab7, w.money, c.name, c.level, c.class, c.gender, c.zone, c.account, c.logout_time " +
                                                       "FROM guild_member gm LEFT JOIN guild_member_withdraw w ON gm.guid = w.guid " +
                                                       "LEFT JOIN characters c ON c.guid = gm.guid ORDER BY gm.guildid ASC");

                if (result.IsEmpty())
                {
                    Log.outInfo(LogFilter.ServerLoading, "Loaded 0 guild members. DB table `guild_member` is empty.");
                }
                else
                {
                    uint count = 0;

                    do
                    {
                        uint  guildId = result.Read <uint>(0);
                        Guild guild   = GetGuildById(guildId);
                        if (guild)
                        {
                            guild.LoadMemberFromDB(result.GetFields());
                        }

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

                    Log.outInfo(LogFilter.ServerLoading, "Loaded {0} guild members in {1} ms", count, Time.GetMSTimeDiffToNow(oldMSTime));
                }
            }

            // 4. Load all guild bank tab rights
            Log.outInfo(LogFilter.ServerLoading, "Loading bank tab rights...");
            {
                uint oldMSTime = Time.GetMSTime();

                // Delete orphaned guild bank right entries before loading the valid ones
                DB.Characters.DirectExecute("DELETE gbr FROM guild_bank_right gbr LEFT JOIN guild g ON gbr.guildId = g.guildId WHERE g.guildId IS NULL");

                //      0        1      2    3        4
                SQLResult result = DB.Characters.Query("SELECT guildid, TabId, rid, gbright, SlotPerDay FROM guild_bank_right ORDER BY guildid ASC, TabId ASC");

                if (result.IsEmpty())
                {
                    Log.outInfo(LogFilter.ServerLoading, "Loaded 0 guild bank tab rights. DB table `guild_bank_right` is empty.");
                }
                else
                {
                    uint count = 0;
                    do
                    {
                        uint  guildId = result.Read <uint>(0);
                        Guild guild   = GetGuildById(guildId);
                        if (guild)
                        {
                            guild.LoadBankRightFromDB(result.GetFields());
                        }

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

                    Log.outInfo(LogFilter.ServerLoading, "Loaded {0} bank tab rights in {1} ms", count, Time.GetMSTimeDiffToNow(oldMSTime));
                }
            }

            // 5. Load all event logs
            Log.outInfo(LogFilter.ServerLoading, "Loading guild event logs...");
            {
                uint oldMSTime = Time.GetMSTime();

                DB.Characters.DirectExecute("DELETE FROM guild_eventlog WHERE LogGuid > {0}", GuildConst.EventLogMaxRecords);

                //          0        1        2          3            4            5        6
                SQLResult result = DB.Characters.Query("SELECT guildid, LogGuid, EventType, PlayerGuid1, PlayerGuid2, NewRank, TimeStamp FROM guild_eventlog ORDER BY TimeStamp DESC, LogGuid DESC");

                if (result.IsEmpty())
                {
                    Log.outInfo(LogFilter.ServerLoading, "Loaded 0 guild event logs. DB table `guild_eventlog` is empty.");
                }
                else
                {
                    uint count = 0;
                    do
                    {
                        uint  guildId = result.Read <uint>(0);
                        Guild guild   = GetGuildById(guildId);
                        if (guild)
                        {
                            guild.LoadEventLogFromDB(result.GetFields());
                        }

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

                    Log.outInfo(LogFilter.ServerLoading, "Loaded {0} guild event logs in {1} ms", count, Time.GetMSTimeDiffToNow(oldMSTime));
                }
            }

            // 6. Load all bank event logs
            Log.outInfo(LogFilter.ServerLoading, "Loading guild bank event logs...");
            {
                uint oldMSTime = Time.GetMSTime();

                // Remove log entries that exceed the number of allowed entries per guild
                DB.Characters.DirectExecute("DELETE FROM guild_bank_eventlog WHERE LogGuid > {0}", GuildConst.BankLogMaxRecords);

                //          0        1      2        3          4           5            6               7          8
                SQLResult result = DB.Characters.Query("SELECT guildid, TabId, LogGuid, EventType, PlayerGuid, ItemOrMoney, ItemStackCount, DestTabId, TimeStamp FROM guild_bank_eventlog ORDER BY TimeStamp DESC, LogGuid DESC");

                if (result.IsEmpty())
                {
                    Log.outInfo(LogFilter.ServerLoading, "Loaded 0 guild bank event logs. DB table `guild_bank_eventlog` is empty.");
                }
                else
                {
                    uint count = 0;
                    do
                    {
                        uint  guildId = result.Read <uint>(0);
                        Guild guild   = GetGuildById(guildId);
                        if (guild)
                        {
                            guild.LoadBankEventLogFromDB(result.GetFields());
                        }

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

                    Log.outInfo(LogFilter.ServerLoading, "Loaded {0} guild bank event logs in {1} ms", count, Time.GetMSTimeDiffToNow(oldMSTime));
                }
            }

            // 7. Load all news event logs
            Log.outInfo(LogFilter.ServerLoading, "Loading Guild News...");
            {
                uint oldMSTime = Time.GetMSTime();

                DB.Characters.DirectExecute("DELETE FROM guild_newslog WHERE LogGuid > {0}", GuildConst.NewsLogMaxRecords);

                //      0        1        2          3           4      5      6
                SQLResult result = DB.Characters.Query("SELECT guildid, LogGuid, EventType, PlayerGuid, Flags, Value, Timestamp FROM guild_newslog ORDER BY TimeStamp DESC, LogGuid DESC");

                if (result.IsEmpty())
                {
                    Log.outInfo(LogFilter.ServerLoading, "Loaded 0 guild event logs. DB table `guild_newslog` is empty.");
                }
                else
                {
                    uint count = 0;
                    do
                    {
                        uint  guildId = result.Read <uint>(0);
                        Guild guild   = GetGuildById(guildId);
                        if (guild)
                        {
                            guild.LoadGuildNewsLogFromDB(result.GetFields());
                        }

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

                    Log.outInfo(LogFilter.ServerLoading, "Loaded {0} guild new logs in {1} ms", count, Time.GetMSTimeDiffToNow(oldMSTime));
                }
            }

            // 8. Load all guild bank tabs
            Log.outInfo(LogFilter.ServerLoading, "Loading guild bank tabs...");
            {
                uint oldMSTime = Time.GetMSTime();

                // Delete orphaned guild bank tab entries before loading the valid ones
                DB.Characters.DirectExecute("DELETE gbt FROM guild_bank_tab gbt LEFT JOIN guild g ON gbt.guildId = g.guildId WHERE g.guildId IS NULL");

                //         0        1      2        3        4
                SQLResult result = DB.Characters.Query("SELECT guildid, TabId, TabName, TabIcon, TabText FROM guild_bank_tab ORDER BY guildid ASC, TabId ASC");

                if (result.IsEmpty())
                {
                    Log.outInfo(LogFilter.ServerLoading, "Loaded 0 guild bank tabs. DB table `guild_bank_tab` is empty.");
                }
                else
                {
                    uint count = 0;
                    do
                    {
                        uint  guildId = result.Read <uint>(0);
                        Guild guild   = GetGuildById(guildId);
                        if (guild)
                        {
                            guild.LoadBankTabFromDB(result.GetFields());
                        }

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

                    Log.outInfo(LogFilter.ServerLoading, "Loaded {0} guild bank tabs in {1} ms", count, Time.GetMSTimeDiffToNow(oldMSTime));
                }
            }

            // 9. Fill all guild bank tabs
            Log.outInfo(LogFilter.ServerLoading, "Filling bank tabs with items...");
            {
                uint oldMSTime = Time.GetMSTime();

                // Delete orphan guild bank items
                DB.Characters.DirectExecute("DELETE gbi FROM guild_bank_item gbi LEFT JOIN guild g ON gbi.guildId = g.guildId WHERE g.guildId IS NULL");

                SQLResult result = DB.Characters.Query(DB.Characters.GetPreparedStatement(CharStatements.SEL_GUILD_BANK_ITEMS));
                if (result.IsEmpty())
                {
                    Log.outInfo(LogFilter.ServerLoading, "Loaded 0 guild bank tab items. DB table `guild_bank_item` or `item_instance` is empty.");
                }
                else
                {
                    uint count = 0;
                    do
                    {
                        ulong guildId = result.Read <ulong>(45);
                        Guild guild   = GetGuildById(guildId);
                        if (guild)
                        {
                            guild.LoadBankItemFromDB(result.GetFields());
                        }

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

                    Log.outInfo(LogFilter.ServerLoading, "Loaded {0} guild bank tab items in {1} ms", count, Time.GetMSTimeDiffToNow(oldMSTime));
                }
            }

            // 10. Load guild achievements
            Log.outInfo(LogFilter.ServerLoading, "Loading guild achievements...");
            {
                uint oldMSTime = Time.GetMSTime();

                foreach (var pair in GuildStore)
                {
                    PreparedStatement stmt = DB.Characters.GetPreparedStatement(CharStatements.SEL_GUILD_ACHIEVEMENT);
                    stmt.AddValue(0, pair.Key);
                    SQLResult achievementResult = DB.Characters.Query(stmt);

                    stmt = DB.Characters.GetPreparedStatement(CharStatements.SEL_GUILD_ACHIEVEMENT_CRITERIA);
                    stmt.AddValue(0, pair.Key);
                    SQLResult criteriaResult = DB.Characters.Query(stmt);

                    pair.Value.GetAchievementMgr().LoadFromDB(achievementResult, criteriaResult);
                }

                Log.outInfo(LogFilter.ServerLoading, "Loaded guild achievements and criterias in {0} ms", Time.GetMSTimeDiffToNow(oldMSTime));
            }

            // 11. Validate loaded guild data
            Log.outInfo(LogFilter.Server, "Validating data of loaded guilds...");
            {
                uint oldMSTime = Time.GetMSTime();

                foreach (var guild in GuildStore.ToList())
                {
                    if (!guild.Value.Validate())
                    {
                        GuildStore.Remove(guild.Key);
                    }
                }

                Log.outInfo(LogFilter.ServerLoading, "Validated data of loaded guilds in {0} ms", Time.GetMSTimeDiffToNow(oldMSTime));
            }
        }
Ejemplo n.º 25
0
        static bool HandleWpShowCommand(StringArguments args, CommandHandler handler)
        {
            if (args.Empty())
            {
                return(false);
            }

            // first arg: on, off, first, last
            string show = args.NextString();

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

            // second arg: GUID (optional, if a creature is selected)
            string guid_str = args.NextString();

            uint     pathid;
            Creature target = handler.GetSelectedCreature();

            // Did player provide a PathID?

            if (string.IsNullOrEmpty(guid_str))
            {
                // No PathID provided
                // . Player must have selected a creature

                if (!target)
                {
                    handler.SendSysMessage(CypherStrings.SelectCreature);
                    return(false);
                }

                pathid = target.GetWaypointPath();
            }
            else
            {
                // PathID provided
                // Warn if player also selected a creature
                // . Creature selection is ignored <-
                if (target)
                {
                    handler.SendSysMessage(CypherStrings.WaypointCreatselected);
                }

                if (!uint.TryParse(guid_str, out pathid))
                {
                    return(false);
                }
            }

            // Show info for the selected waypoint
            if (show == "info")
            {
                // Check if the user did specify a visual waypoint
                if (!target || target.GetEntry() != 1)
                {
                    handler.SendSysMessage(CypherStrings.WaypointVpSelect);
                    return(false);
                }

                PreparedStatement stmt = DB.World.GetPreparedStatement(WorldStatements.SEL_WAYPOINT_DATA_ALL_BY_WPGUID);
                stmt.AddValue(0, target.GetSpawnId());
                SQLResult result = DB.World.Query(stmt);

                if (result.IsEmpty())
                {
                    handler.SendSysMessage(CypherStrings.WaypointNotfounddbproblem, target.GetSpawnId());
                    return(true);
                }

                handler.SendSysMessage("|cff00ffffDEBUG: wp show info:|r");
                do
                {
                    pathid = result.Read <uint>(0);
                    uint point     = result.Read <uint>(1);
                    uint delay     = result.Read <uint>(2);
                    uint flag      = result.Read <uint>(3);
                    uint ev_id     = result.Read <uint>(4);
                    uint ev_chance = result.Read <uint>(5);

                    handler.SendSysMessage("|cff00ff00Show info: for current point: |r|cff00ffff{0}|r|cff00ff00, Path ID: |r|cff00ffff{1}|r", point, pathid);
                    handler.SendSysMessage("|cff00ff00Show info: delay: |r|cff00ffff{0}|r", delay);
                    handler.SendSysMessage("|cff00ff00Show info: Move flag: |r|cff00ffff{0}|r", flag);
                    handler.SendSysMessage("|cff00ff00Show info: Waypoint event: |r|cff00ffff{0}|r", ev_id);
                    handler.SendSysMessage("|cff00ff00Show info: Event chance: |r|cff00ffff{0}|r", ev_chance);
                }while (result.NextRow());

                return(true);
            }

            if (show == "on")
            {
                PreparedStatement stmt = DB.World.GetPreparedStatement(WorldStatements.SEL_WAYPOINT_DATA_POS_BY_ID);
                stmt.AddValue(0, pathid);
                SQLResult result = DB.World.Query(stmt);

                if (result.IsEmpty())
                {
                    handler.SendSysMessage("|cffff33ffPath no found.|r");
                    return(false);
                }

                handler.SendSysMessage("|cff00ff00DEBUG: wp on, PathID: |cff00ffff{0}|r", pathid);

                // Delete all visuals for this NPC
                stmt = DB.World.GetPreparedStatement(WorldStatements.SEL_WAYPOINT_DATA_WPGUID_BY_ID);
                stmt.AddValue(0, pathid);
                SQLResult result2 = DB.World.Query(stmt);

                if (!result2.IsEmpty())
                {
                    bool hasError = false;
                    do
                    {
                        ulong wpguid = result2.Read <ulong>(0);

                        if (!Creature.DeleteFromDB(wpguid))
                        {
                            handler.SendSysMessage(CypherStrings.WaypointNotremoved, wpguid);
                            hasError = true;
                        }
                    }while (result2.NextRow());

                    if (hasError)
                    {
                        handler.SendSysMessage(CypherStrings.WaypointToofar1);
                        handler.SendSysMessage(CypherStrings.WaypointToofar2);
                        handler.SendSysMessage(CypherStrings.WaypointToofar3);
                    }
                }

                do
                {
                    uint  point = result.Read <uint>(0);
                    float x     = result.Read <float>(1);
                    float y     = result.Read <float>(2);
                    float z     = result.Read <float>(3);
                    float o     = result.Read <float>(4);

                    uint id = 1;

                    Player chr = handler.GetSession().GetPlayer();
                    Map    map = chr.GetMap();

                    Creature creature = Creature.CreateCreature(id, map, new Position(x, y, z, o));
                    if (!creature)
                    {
                        handler.SendSysMessage(CypherStrings.WaypointVpNotcreated, id);
                        return(false);
                    }

                    PhasingHandler.InheritPhaseShift(creature, chr);
                    creature.SaveToDB(map.GetId(), new List <Difficulty>()
                    {
                        map.GetDifficultyID()
                    });

                    ulong dbGuid = creature.GetSpawnId();

                    // current "wpCreature" variable is deleted and created fresh new, otherwise old values might trigger asserts or cause undefined behavior
                    creature.CleanupsBeforeDelete();
                    creature.Dispose();

                    // To call _LoadGoods(); _LoadQuests(); CreateTrainerSpells();
                    creature = Creature.CreateCreatureFromDB(dbGuid, map, true, true);
                    if (!creature)
                    {
                        handler.SendSysMessage(CypherStrings.WaypointVpNotcreated, id);
                        return(false);
                    }

                    if (target)
                    {
                        creature.SetDisplayId(target.GetDisplayId());
                        creature.SetObjectScale(0.5f);
                        creature.SetLevel(Math.Min(point, SharedConst.StrongMaxLevel));
                    }

                    // Set "wpguid" column to the visual waypoint
                    stmt = DB.World.GetPreparedStatement(WorldStatements.UPD_WAYPOINT_DATA_WPGUID);
                    stmt.AddValue(0, creature.GetSpawnId());
                    stmt.AddValue(1, pathid);
                    stmt.AddValue(2, point);
                    DB.World.Execute(stmt);
                }while (result.NextRow());

                handler.SendSysMessage("|cff00ff00Showing the current creature's path.|r");
                return(true);
            }

            if (show == "first")
            {
                handler.SendSysMessage("|cff00ff00DEBUG: wp first, pathid: {0}|r", pathid);

                PreparedStatement stmt = DB.World.GetPreparedStatement(WorldStatements.SEL_WAYPOINT_DATA_POS_FIRST_BY_ID);
                stmt.AddValue(0, pathid);
                SQLResult result = DB.World.Query(stmt);

                if (result.IsEmpty())
                {
                    handler.SendSysMessage(CypherStrings.WaypointNotfound, pathid);
                    return(false);
                }

                float x = result.Read <float>(0);
                float y = result.Read <float>(1);
                float z = result.Read <float>(2);
                float o = result.Read <float>(3);

                Player chr = handler.GetSession().GetPlayer();
                Map    map = chr.GetMap();

                Creature creature = Creature.CreateCreature(1, map, new Position(x, y, z, 0));
                if (!creature)
                {
                    handler.SendSysMessage(CypherStrings.WaypointVpNotcreated, 1);
                    return(false);
                }

                PhasingHandler.InheritPhaseShift(creature, chr);
                creature.SaveToDB(map.GetId(), new List <Difficulty>()
                {
                    map.GetDifficultyID()
                });

                ulong dbGuid = creature.GetSpawnId();

                // current "creature" variable is deleted and created fresh new, otherwise old values might trigger asserts or cause undefined behavior
                creature.CleanupsBeforeDelete();
                creature.Dispose();

                creature = Creature.CreateCreatureFromDB(dbGuid, map, true, true);
                if (!creature)
                {
                    handler.SendSysMessage(CypherStrings.WaypointVpNotcreated, 1);
                    return(false);
                }

                if (target)
                {
                    creature.SetDisplayId(target.GetDisplayId());
                    creature.SetObjectScale(0.5f);
                }

                return(true);
            }

            if (show == "last")
            {
                handler.SendSysMessage("|cff00ff00DEBUG: wp last, PathID: |r|cff00ffff{0}|r", pathid);

                PreparedStatement stmt = DB.World.GetPreparedStatement(WorldStatements.SEL_WAYPOINT_DATA_POS_LAST_BY_ID);
                stmt.AddValue(0, pathid);
                SQLResult result = DB.World.Query(stmt);

                if (result.IsEmpty())
                {
                    handler.SendSysMessage(CypherStrings.WaypointNotfoundlast, pathid);
                    return(false);
                }

                float x = result.Read <float>(0);
                float y = result.Read <float>(1);
                float z = result.Read <float>(2);
                float o = result.Read <float>(3);

                Player   chr = handler.GetSession().GetPlayer();
                Map      map = chr.GetMap();
                Position pos = new(x, y, z, o);

                Creature creature = Creature.CreateCreature(1, map, pos);
                if (!creature)
                {
                    handler.SendSysMessage(CypherStrings.WaypointNotcreated, 1);
                    return(false);
                }

                PhasingHandler.InheritPhaseShift(creature, chr);
                creature.SaveToDB(map.GetId(), new List <Difficulty>()
                {
                    map.GetDifficultyID()
                });

                ulong dbGuid = creature.GetSpawnId();

                // current "creature" variable is deleted and created fresh new, otherwise old values might trigger asserts or cause undefined behavior
                creature.CleanupsBeforeDelete();
                creature.Dispose();

                creature = Creature.CreateCreatureFromDB(dbGuid, map, true, true);
                if (!creature)
                {
                    handler.SendSysMessage(CypherStrings.WaypointNotcreated, 1);
                    return(false);
                }

                if (target)
                {
                    creature.SetDisplayId(target.GetDisplayId());
                    creature.SetObjectScale(0.5f);
                }

                return(true);
            }

            if (show == "off")
            {
                PreparedStatement stmt = DB.World.GetPreparedStatement(WorldStatements.SEL_CREATURE_BY_ID);
                stmt.AddValue(0, 1);
                SQLResult result = DB.World.Query(stmt);

                if (result.IsEmpty())
                {
                    handler.SendSysMessage(CypherStrings.WaypointVpNotfound);
                    return(false);
                }
                bool hasError = false;
                do
                {
                    ulong lowguid = result.Read <ulong>(0);

                    if (!Creature.DeleteFromDB(lowguid))
                    {
                        handler.SendSysMessage(CypherStrings.WaypointNotremoved, lowguid);
                        hasError = true;
                    }
                }while (result.NextRow());
                // set "wpguid" column to "empty" - no visual waypoint spawned
                stmt = DB.World.GetPreparedStatement(WorldStatements.UPD_WAYPOINT_DATA_ALL_WPGUID);

                DB.World.Execute(stmt);
                //DB.World.PExecute("UPDATE creature_movement SET wpguid = '0' WHERE wpguid <> '0'");

                if (hasError)
                {
                    handler.SendSysMessage(CypherStrings.WaypointToofar1);
                    handler.SendSysMessage(CypherStrings.WaypointToofar2);
                    handler.SendSysMessage(CypherStrings.WaypointToofar3);
                }

                handler.SendSysMessage(CypherStrings.WaypointVpAllremoved);
                return(true);
            }

            handler.SendSysMessage("|cffff33ffDEBUG: wpshow - no valid command found|r");
            return(true);
        }
Ejemplo n.º 26
0
        void HandleAuthSessionCallback(AuthSession authSession, SQLResult result)
        {
            // Stop if the account is not found
            if (result.IsEmpty())
            {
                Log.outError(LogFilter.Network, "HandleAuthSession: Sent Auth Response (unknown account).");
                CloseSocket();
                return;
            }

            RealmBuildInfo buildInfo = Global.RealmMgr.GetBuildInfo(Global.WorldMgr.GetRealm().Build);

            if (buildInfo == null)
            {
                SendAuthResponseError(BattlenetRpcErrorCode.BadVersion);
                Log.outError(LogFilter.Network, $"WorldSocket.HandleAuthSessionCallback: Missing auth seed for realm build {Global.WorldMgr.GetRealm().Build} ({GetRemoteIpAddress()}).");
                CloseSocket();
                return;
            }

            AccountInfo account = new AccountInfo(result.GetFields());

            // For hook purposes, we get Remoteaddress at this point.
            string address = GetRemoteIpAddress().ToString();

            Sha256 digestKeyHash = new Sha256();

            digestKeyHash.Process(account.game.SessionKey, account.game.SessionKey.Length);
            if (account.game.OS == "Wn64")
            {
                digestKeyHash.Finish(buildInfo.Win64AuthSeed);
            }
            else if (account.game.OS == "Mc64")
            {
                digestKeyHash.Finish(buildInfo.Mac64AuthSeed);
            }
            else
            {
                Log.outError(LogFilter.Network, "WorldSocket.HandleAuthSession: Authentication failed for account: {0} ('{1}') address: {2}", account.game.Id, authSession.RealmJoinTicket, address);
                CloseSocket();
                return;
            }

            HmacSha256 hmac = new HmacSha256(digestKeyHash.Digest);

            hmac.Process(authSession.LocalChallenge, authSession.LocalChallenge.Count);
            hmac.Process(_serverChallenge, 16);
            hmac.Finish(AuthCheckSeed, 16);

            // Check that Key and account name are the same on client and server
            if (!hmac.Digest.Compare(authSession.Digest))
            {
                Log.outError(LogFilter.Network, "WorldSocket.HandleAuthSession: Authentication failed for account: {0} ('{1}') address: {2}", account.game.Id, authSession.RealmJoinTicket, address);
                CloseSocket();
                return;
            }

            Sha256 keyData = new Sha256();

            keyData.Finish(account.game.SessionKey);

            HmacSha256 sessionKeyHmac = new HmacSha256(keyData.Digest);

            sessionKeyHmac.Process(_serverChallenge, 16);
            sessionKeyHmac.Process(authSession.LocalChallenge, authSession.LocalChallenge.Count);
            sessionKeyHmac.Finish(SessionKeySeed, 16);

            _sessionKey = new byte[40];
            var sessionKeyGenerator = new SessionKeyGenerator(sessionKeyHmac.Digest, 32);

            sessionKeyGenerator.Generate(_sessionKey, 40);

            HmacSha256 encryptKeyGen = new HmacSha256(_sessionKey);

            encryptKeyGen.Process(authSession.LocalChallenge, authSession.LocalChallenge.Count);
            encryptKeyGen.Process(_serverChallenge, 16);
            encryptKeyGen.Finish(EncryptionKeySeed, 16);

            // only first 16 bytes of the hmac are used
            Buffer.BlockCopy(encryptKeyGen.Digest, 0, _encryptKey, 0, 16);

            // As we don't know if attempted login process by ip works, we update last_attempt_ip right away
            PreparedStatement stmt = DB.Login.GetPreparedStatement(LoginStatements.UPD_LAST_ATTEMPT_IP);

            stmt.AddValue(0, address);
            stmt.AddValue(1, authSession.RealmJoinTicket);

            DB.Login.Execute(stmt);
            // This also allows to check for possible "hack" attempts on account

            stmt = DB.Login.GetPreparedStatement(LoginStatements.UPD_ACCOUNT_INFO_CONTINUED_SESSION);
            stmt.AddValue(0, _sessionKey);
            stmt.AddValue(1, account.game.Id);
            DB.Login.Execute(stmt);

            // First reject the connection if packet contains invalid data or realm state doesn't allow logging in
            if (Global.WorldMgr.IsClosed())
            {
                SendAuthResponseError(BattlenetRpcErrorCode.Denied);
                Log.outError(LogFilter.Network, "WorldSocket.HandleAuthSession: World closed, denying client ({0}).", GetRemoteIpAddress());
                CloseSocket();
                return;
            }

            if (authSession.RealmID != Global.WorldMgr.GetRealm().Id.Index)
            {
                SendAuthResponseError(BattlenetRpcErrorCode.Denied);
                Log.outError(LogFilter.Network, "WorldSocket.HandleAuthSession: Client {0} requested connecting with realm id {1} but this realm has id {2} set in config.",
                             GetRemoteIpAddress().ToString(), authSession.RealmID, Global.WorldMgr.GetRealm().Id.Index);
                CloseSocket();
                return;
            }

            // Must be done before WorldSession is created
            bool wardenActive = WorldConfig.GetBoolValue(WorldCfg.WardenEnabled);

            if (wardenActive && account.game.OS != "Win" && account.game.OS != "Wn64" && account.game.OS != "Mc64")
            {
                SendAuthResponseError(BattlenetRpcErrorCode.Denied);
                Log.outError(LogFilter.Network, "WorldSocket.HandleAuthSession: Client {0} attempted to log in using invalid client OS ({1}).", address, account.game.OS);
                CloseSocket();
                return;
            }

            //Re-check ip locking (same check as in auth).
            if (account.battleNet.IsLockedToIP) // if ip is locked
            {
                if (account.battleNet.LastIP != address)
                {
                    SendAuthResponseError(BattlenetRpcErrorCode.RiskAccountLocked);
                    Log.outDebug(LogFilter.Network, "HandleAuthSession: Sent Auth Response (Account IP differs).");
                    CloseSocket();
                    return;
                }
            }
            else if (!account.battleNet.LockCountry.IsEmpty() && account.battleNet.LockCountry != "00" && !_ipCountry.IsEmpty())
            {
                if (account.battleNet.LockCountry != _ipCountry)
                {
                    SendAuthResponseError(BattlenetRpcErrorCode.RiskAccountLocked);
                    Log.outDebug(LogFilter.Network, "WorldSocket.HandleAuthSession: Sent Auth Response (Account country differs. Original country: {0}, new country: {1}).", account.battleNet.LockCountry, _ipCountry);
                    CloseSocket();
                    return;
                }
            }

            long mutetime = account.game.MuteTime;

            //! Negative mutetime indicates amount of seconds to be muted effective on next login - which is now.
            if (mutetime < 0)
            {
                mutetime = Time.UnixTime + mutetime;

                stmt = DB.Login.GetPreparedStatement(LoginStatements.UPD_MUTE_TIME_LOGIN);
                stmt.AddValue(0, mutetime);
                stmt.AddValue(1, account.game.Id);
                DB.Login.Execute(stmt);
            }

            if (account.IsBanned()) // if account banned
            {
                SendAuthResponseError(BattlenetRpcErrorCode.GameAccountBanned);
                Log.outError(LogFilter.Network, "WorldSocket:HandleAuthSession: Sent Auth Response (Account banned).");
                CloseSocket();
                return;
            }

            // Check locked state for server
            AccountTypes allowedAccountType = Global.WorldMgr.GetPlayerSecurityLimit();

            if (allowedAccountType > AccountTypes.Player && account.game.Security < allowedAccountType)
            {
                SendAuthResponseError(BattlenetRpcErrorCode.ServerIsPrivate);
                Log.outInfo(LogFilter.Network, "WorldSocket:HandleAuthSession: User tries to login but his security level is not enough");
                CloseSocket();
                return;
            }

            Log.outDebug(LogFilter.Network, "WorldSocket:HandleAuthSession: Client '{0}' authenticated successfully from {1}.", authSession.RealmJoinTicket, address);

            // Update the last_ip in the database
            stmt = DB.Login.GetPreparedStatement(LoginStatements.UPD_LAST_IP);
            stmt.AddValue(0, address);
            stmt.AddValue(1, authSession.RealmJoinTicket);
            DB.Login.Execute(stmt);

            _worldSession = new WorldSession(account.game.Id, authSession.RealmJoinTicket, account.battleNet.Id, this, account.game.Security, (Expansion)account.game.Expansion,
                                             mutetime, account.game.OS, account.battleNet.Locale, account.game.Recruiter, account.game.IsRectuiter);

            // Initialize Warden system only if it is enabled by config
            //if (wardenActive)
            //_worldSession.InitWarden(_sessionKey);

            _queryProcessor.AddCallback(_worldSession.LoadPermissionsAsync().WithCallback(LoadSessionPermissionsCallback));
            AsyncRead();
        }
Ejemplo n.º 27
0
        public void LoadRBAC()
        {
            ClearRBAC();

            Log.outDebug(LogFilter.Rbac, "AccountMgr:LoadRBAC");
            uint oldMSTime = Time.GetMSTime();
            uint count1    = 0;
            uint count2    = 0;
            uint count3    = 0;

            Log.outDebug(LogFilter.Rbac, "AccountMgr:LoadRBAC: Loading permissions");
            SQLResult result = DB.Login.Query("SELECT id, name FROM rbac_permissions");

            if (result.IsEmpty())
            {
                Log.outInfo(LogFilter.ServerLoading, "Loaded 0 account permission definitions. DB table `rbac_permissions` is empty.");
                return;
            }

            do
            {
                uint id = result.Read <uint>(0);
                _permissions[id] = new RBACPermission(id, result.Read <string>(1));
                ++count1;
            }while (result.NextRow());

            Log.outDebug(LogFilter.Rbac, "AccountMgr:LoadRBAC: Loading linked permissions");
            result = DB.Login.Query("SELECT id, linkedId FROM rbac_linked_permissions ORDER BY id ASC");
            if (result.IsEmpty())
            {
                Log.outInfo(LogFilter.ServerLoading, "Loaded 0 linked permissions. DB table `rbac_linked_permissions` is empty.");
                return;
            }

            uint           permissionId = 0;
            RBACPermission permission   = null;

            do
            {
                uint newId = result.Read <uint>(0);
                if (permissionId != newId)
                {
                    permissionId = newId;
                    permission   = _permissions[newId];
                }

                uint linkedPermissionId = result.Read <uint>(1);
                if (linkedPermissionId == permissionId)
                {
                    Log.outError(LogFilter.Sql, "RBAC Permission {0} has itself as linked permission. Ignored", permissionId);
                    continue;
                }
                permission.AddLinkedPermission(linkedPermissionId);
                ++count2;
            }while (result.NextRow());

            Log.outDebug(LogFilter.Rbac, "AccountMgr:LoadRBAC: Loading default permissions");
            result = DB.Login.Query("SELECT secId, permissionId FROM rbac_default_permissions ORDER BY secId ASC");
            if (result.IsEmpty())
            {
                Log.outInfo(LogFilter.ServerLoading, "Loaded 0 default permission definitions. DB table `rbac_default_permissions` is empty.");
                return;
            }

            uint secId = 255;

            do
            {
                uint newId = result.Read <uint>(0);
                if (secId != newId)
                {
                    secId = newId;
                }

                _defaultPermissions.Add((byte)secId, result.Read <uint>(1));
                ++count3;
            }while (result.NextRow());

            Log.outInfo(LogFilter.ServerLoading, "Loaded {0} permission definitions, {1} linked permissions and {2} default permissions in {3} ms", count1, count2, count3, Time.GetMSTimeDiffToNow(oldMSTime));
        }
Ejemplo n.º 28
0
        public void SpawnContinentTransports()
        {
            if (_transportTemplates.Empty())
            {
                return;
            }

            uint oldMSTime = Time.GetMSTime();

            SQLResult result = DB.World.Query("SELECT guid, entry, phaseUseFlags, phaseid, phasegroup FROM transports");

            uint count = 0;

            if (!result.IsEmpty())
            {
                do
                {
                    ulong guid  = result.Read <ulong>(0);
                    uint  entry = result.Read <uint>(1);
                    PhaseUseFlagsValues phaseUseFlags = (PhaseUseFlagsValues)result.Read <byte>(2);
                    uint phaseId      = result.Read <uint>(3);
                    uint phaseGroupId = result.Read <uint>(4);

                    if (Convert.ToBoolean(phaseUseFlags & ~PhaseUseFlagsValues.All))
                    {
                        Log.outError(LogFilter.Sql, $"Table `transports` have transport (GUID: {guid} Entry: {entry}) with unknown `phaseUseFlags` set, removed unknown value.");
                        phaseUseFlags &= PhaseUseFlagsValues.All;
                    }

                    if (phaseUseFlags.HasAnyFlag(PhaseUseFlagsValues.AlwaysVisible) && phaseUseFlags.HasAnyFlag(PhaseUseFlagsValues.Inverse))
                    {
                        Log.outError(LogFilter.Sql, $"Table `transports` have transport (GUID: {guid} Entry: {entry}) has both `phaseUseFlags` PHASE_USE_FLAGS_ALWAYS_VISIBLE and PHASE_USE_FLAGS_INVERSE," +
                                     " removing PHASE_USE_FLAGS_INVERSE.");
                        phaseUseFlags &= ~PhaseUseFlagsValues.Inverse;
                    }

                    if (phaseGroupId != 0 && phaseId != 0)
                    {
                        Log.outError(LogFilter.Sql, $"Table `transports` have transport (GUID: {guid} Entry: {entry}) with both `phaseid` and `phasegroup` set, `phasegroup` set to 0");
                        phaseGroupId = 0;
                    }

                    if (phaseId != 0)
                    {
                        if (!CliDB.PhaseStorage.ContainsKey(phaseId))
                        {
                            Log.outError(LogFilter.Sql, $"Table `transports` have transport (GUID: {guid} Entry: {entry}) with `phaseid` {phaseId} does not exist, set to 0");
                            phaseId = 0;
                        }
                    }

                    if (phaseGroupId != 0)
                    {
                        if (Global.DB2Mgr.GetPhasesForGroup(phaseGroupId).Empty())
                        {
                            Log.outError(LogFilter.Sql, $"Table `transports` have transport (GUID: {guid} Entry: {entry}) with `phaseGroup` {phaseGroupId} does not exist, set to 0");
                            phaseGroupId = 0;
                        }
                    }

                    TransportTemplate tInfo = GetTransportTemplate(entry);
                    if (tInfo != null)
                    {
                        if (!tInfo.inInstance)
                        {
                            if (CreateTransport(entry, guid, null, phaseUseFlags, phaseId, phaseGroupId))
                            {
                                ++count;
                            }
                        }
                    }
                } while (result.NextRow());
            }

            Log.outInfo(LogFilter.ServerLoading, "Spawned {0} continent transports in {1} ms", count, Time.GetMSTimeDiffToNow(oldMSTime));
        }
Ejemplo n.º 29
0
        public AccountOpResult DeleteAccount(uint accountId)
        {
            // Check if accounts exists
            PreparedStatement stmt = DB.Login.GetPreparedStatement(LoginStatements.SEL_ACCOUNT_BY_ID);

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

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

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

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

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

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

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

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

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

            SQLTransaction trans = new SQLTransaction();

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

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

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

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

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

            DB.Login.CommitTransaction(trans);

            return(AccountOpResult.Ok);
        }
Ejemplo n.º 30
0
        void HandleCalendarInvite(CalendarInvitePkt calendarInvite)
        {
            ObjectGuid playerGuid = GetPlayer().GetGUID();

            ObjectGuid inviteeGuid    = ObjectGuid.Empty;
            Team       inviteeTeam    = 0;
            ulong      inviteeGuildId = 0;

            if (!ObjectManager.NormalizePlayerName(ref calendarInvite.Name))
            {
                return;
            }

            Player player = Global.ObjAccessor.FindPlayerByName(calendarInvite.Name);

            if (player)
            {
                // Invitee is online
                inviteeGuid    = player.GetGUID();
                inviteeTeam    = player.GetTeam();
                inviteeGuildId = player.GetGuildId();
            }
            else
            {
                // Invitee offline, get data from database
                ObjectGuid guid = Global.CharacterCacheStorage.GetCharacterGuidByName(calendarInvite.Name);
                if (!guid.IsEmpty())
                {
                    CharacterCacheEntry characterInfo = Global.CharacterCacheStorage.GetCharacterCacheByGuid(guid);
                    if (characterInfo != null)
                    {
                        inviteeGuid    = guid;
                        inviteeTeam    = Player.TeamForRace(characterInfo.RaceId);
                        inviteeGuildId = characterInfo.GuildId;
                    }
                }
            }

            if (inviteeGuid.IsEmpty())
            {
                Global.CalendarMgr.SendCalendarCommandResult(playerGuid, CalendarError.PlayerNotFound);
                return;
            }

            if (GetPlayer().GetTeam() != inviteeTeam && !WorldConfig.GetBoolValue(WorldCfg.AllowTwoSideInteractionCalendar))
            {
                Global.CalendarMgr.SendCalendarCommandResult(playerGuid, CalendarError.NotAllied);
                return;
            }

            SQLResult result1 = DB.Characters.Query("SELECT flags FROM character_social WHERE guid = {0} AND friend = {1}", inviteeGuid, playerGuid);

            if (!result1.IsEmpty())
            {
                if (Convert.ToBoolean(result1.Read <byte>(0) & (byte)SocialFlag.Ignored))
                {
                    Global.CalendarMgr.SendCalendarCommandResult(playerGuid, CalendarError.IgnoringYouS, calendarInvite.Name);
                    return;
                }
            }

            if (!calendarInvite.Creating)
            {
                CalendarEvent calendarEvent = Global.CalendarMgr.GetEvent(calendarInvite.EventID);
                if (calendarEvent != null)
                {
                    if (calendarEvent.IsGuildEvent() && calendarEvent.GuildId == inviteeGuildId)
                    {
                        // we can't invite guild members to guild events
                        Global.CalendarMgr.SendCalendarCommandResult(playerGuid, CalendarError.NoGuildInvites);
                        return;
                    }

                    CalendarInvite invite = new(Global.CalendarMgr.GetFreeInviteId(), calendarInvite.EventID, inviteeGuid, playerGuid, SharedConst.CalendarDefaultResponseTime, CalendarInviteStatus.Invited, CalendarModerationRank.Player, "");
                    Global.CalendarMgr.AddInvite(calendarEvent, invite);
                }
                else
                {
                    Global.CalendarMgr.SendCalendarCommandResult(playerGuid, CalendarError.EventInvalid);
                }
            }
            else
            {
                if (calendarInvite.IsSignUp && inviteeGuildId == GetPlayer().GetGuildId())
                {
                    Global.CalendarMgr.SendCalendarCommandResult(playerGuid, CalendarError.NoGuildInvites);
                    return;
                }

                CalendarInvite invite = new(calendarInvite.EventID, 0, inviteeGuid, playerGuid, SharedConst.CalendarDefaultResponseTime, CalendarInviteStatus.Invited, CalendarModerationRank.Player, "");
                Global.CalendarMgr.SendCalendarEventInvite(invite);
            }
        }
Ejemplo n.º 31
0
        public void LoadFromDB()
        {
            uint count = 0;

            _maxEventId  = 0;
            _maxInviteId = 0;

            //                                              0        1      2      3            4          5          6     7      8
            SQLResult result = DB.Characters.Query("SELECT EventID, Owner, Title, Description, EventType, TextureID, Date, Flags, LockDate FROM calendar_events");

            if (!result.IsEmpty())
            {
                do
                {
                    ulong             eventID     = result.Read <ulong>(0);
                    ObjectGuid        ownerGUID   = ObjectGuid.Create(HighGuid.Player, result.Read <ulong>(1));
                    string            title       = result.Read <string>(2);
                    string            description = result.Read <string>(3);
                    CalendarEventType type        = (CalendarEventType)result.Read <byte>(4);
                    int           textureID       = result.Read <int>(5);
                    uint          date            = result.Read <uint>(6);
                    CalendarFlags flags           = (CalendarFlags)result.Read <uint>(7);
                    uint          lockDate        = result.Read <uint>(8);
                    ulong         guildID         = 0;

                    if (flags.HasAnyFlag(CalendarFlags.GuildEvent) || flags.HasAnyFlag(CalendarFlags.WithoutInvites))
                    {
                        guildID = Global.CharacterCacheStorage.GetCharacterGuildIdByGuid(ownerGUID);
                    }

                    CalendarEvent calendarEvent = new CalendarEvent(eventID, ownerGUID, guildID, type, textureID, date, flags, title, description, lockDate);
                    _events.Add(calendarEvent);

                    _maxEventId = Math.Max(_maxEventId, eventID);

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

            Log.outInfo(LogFilter.ServerLoading, "Loaded {0} calendar events", count);
            count = 0;

            //                                    0         1        2        3       4       5             6               7
            result = DB.Characters.Query("SELECT InviteID, EventID, Invitee, Sender, Status, ResponseTime, ModerationRank, Note FROM calendar_invites");
            if (!result.IsEmpty())
            {
                do
                {
                    ulong                inviteId   = result.Read <ulong>(0);
                    ulong                eventId    = result.Read <ulong>(1);
                    ObjectGuid           invitee    = ObjectGuid.Create(HighGuid.Player, result.Read <ulong>(2));
                    ObjectGuid           senderGUID = ObjectGuid.Create(HighGuid.Player, result.Read <ulong>(3));
                    CalendarInviteStatus status     = (CalendarInviteStatus)result.Read <byte>(4);
                    uint responseTime           = result.Read <uint>(5);
                    CalendarModerationRank rank = (CalendarModerationRank)result.Read <byte>(6);
                    string note = result.Read <string>(7);

                    CalendarInvite invite = new CalendarInvite(inviteId, eventId, invitee, senderGUID, responseTime, status, rank, note);
                    _invites.Add(eventId, invite);

                    _maxInviteId = Math.Max(_maxInviteId, inviteId);

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

            Log.outInfo(LogFilter.ServerLoading, "Loaded {0} calendar invites", count);

            for (ulong i = 1; i < _maxEventId; ++i)
            {
                if (GetEvent(i) == null)
                {
                    _freeEventIds.Add(i);
                }
            }

            for (ulong i = 1; i < _maxInviteId; ++i)
            {
                if (GetInvite(i) == null)
                {
                    _freeInviteIds.Add(i);
                }
            }
        }
Ejemplo n.º 32
0
        public void LoadFromDB(SQLResult result)
        {
            // Set initial reputations (so everything is nifty before DB data load)
            Initialize();

            if (!result.IsEmpty())
            {
                do
                {
                    var factionEntry = CliDB.FactionStorage.LookupByKey(result.Read <uint>(0));
                    if (factionEntry != null && factionEntry.CanHaveReputation())
                    {
                        var faction = _factions.LookupByKey((uint)factionEntry.ReputationIndex);
                        if (faction == null)
                        {
                            continue;
                        }
                        // update standing to current
                        faction.Standing = result.Read <int>(1);

                        // update counters
                        int            BaseRep  = GetBaseReputation(factionEntry);
                        ReputationRank old_rank = ReputationToRank(BaseRep);
                        ReputationRank new_rank = ReputationToRank(BaseRep + faction.Standing);
                        UpdateRankCounters(old_rank, new_rank);

                        FactionFlags dbFactionFlags = (FactionFlags)result.Read <uint>(2);

                        if (Convert.ToBoolean(dbFactionFlags & FactionFlags.Visible))
                        {
                            SetVisible(faction);                    // have internal checks for forced invisibility
                        }
                        if (Convert.ToBoolean(dbFactionFlags & FactionFlags.Inactive))
                        {
                            SetInactive(faction, true);                             // have internal checks for visibility requirement
                        }
                        if (Convert.ToBoolean(dbFactionFlags & FactionFlags.AtWar)) // DB at war
                        {
                            SetAtWar(faction, true);                                // have internal checks for FACTION_FLAG_PEACE_FORCED
                        }
                        else                                                        // DB not at war
                        {
                            // allow remove if visible (and then not FACTION_FLAG_INVISIBLE_FORCED or FACTION_FLAG_HIDDEN)
                            if (Convert.ToBoolean(faction.Flags & FactionFlags.Visible))
                            {
                                SetAtWar(faction, false);            // have internal checks for FACTION_FLAG_PEACE_FORCED
                            }
                        }

                        // set atWar for hostile
                        if (GetRank(factionEntry) <= ReputationRank.Hostile)
                        {
                            SetAtWar(faction, true);
                        }

                        // reset changed flag if values similar to saved in DB
                        if (faction.Flags == dbFactionFlags)
                        {
                            faction.needSend = false;
                            faction.needSave = false;
                        }
                    }
                } while (result.NextRow());
            }
        }
Ejemplo n.º 33
0
        static bool HandleGroupListCommand(StringArguments args, CommandHandler handler)
        {
            // Get ALL the variables!
            Player     playerTarget;
            ObjectGuid guidTarget;
            string     nameTarget;
            string     zoneName    = "";
            string     onlineState = "";

            // Parse the guid to uint32...
            ObjectGuid parseGUID = ObjectGuid.Create(HighGuid.Player, args.NextUInt64());

            // ... and try to extract a player out of it.
            if (Global.CharacterCacheStorage.GetCharacterNameByGuid(parseGUID, out nameTarget))
            {
                playerTarget = Global.ObjAccessor.FindPlayer(parseGUID);
                guidTarget   = parseGUID;
            }
            // If not, we return false and end right away.
            else if (!handler.ExtractPlayerTarget(args, out playerTarget, out guidTarget, out nameTarget))
            {
                return(false);
            }

            // Next, we need a group. So we define a group variable.
            Group groupTarget = null;

            // We try to extract a group from an online player.
            if (playerTarget)
            {
                groupTarget = playerTarget.GetGroup();
            }

            // If not, we extract it from the SQL.
            if (!groupTarget)
            {
                PreparedStatement stmt = DB.Characters.GetPreparedStatement(CharStatements.SEL_GROUP_MEMBER);
                stmt.AddValue(0, guidTarget.GetCounter());
                SQLResult resultGroup = DB.Characters.Query(stmt);
                if (!resultGroup.IsEmpty())
                {
                    groupTarget = Global.GroupMgr.GetGroupByDbStoreId(resultGroup.Read <uint>(0));
                }
            }

            // If both fails, players simply has no party. Return false.
            if (!groupTarget)
            {
                handler.SendSysMessage(CypherStrings.GroupNotInGroup, nameTarget);
                return(false);
            }

            // We get the group members after successfully detecting a group.
            var members = groupTarget.GetMemberSlots();

            // To avoid a cluster f**k, namely trying multiple queries to simply get a group member count...
            handler.SendSysMessage(CypherStrings.GroupType, (groupTarget.IsRaidGroup() ? "raid" : "party"), members.Count);
            // ... we simply move the group type and member count print after retrieving the slots and simply output it's size.

            // While rather dirty codestyle-wise, it saves space (if only a little). For each member, we look several informations up.
            foreach (var slot in members)
            {
                // Check for given flag and assign it to that iterator
                string flags = "";
                if (slot.flags.HasAnyFlag(GroupMemberFlags.Assistant))
                {
                    flags = "Assistant";
                }

                if (slot.flags.HasAnyFlag(GroupMemberFlags.MainTank))
                {
                    if (!string.IsNullOrEmpty(flags))
                    {
                        flags += ", ";
                    }
                    flags += "MainTank";
                }

                if (slot.flags.HasAnyFlag(GroupMemberFlags.MainAssist))
                {
                    if (!string.IsNullOrEmpty(flags))
                    {
                        flags += ", ";
                    }
                    flags += "MainAssist";
                }

                if (string.IsNullOrEmpty(flags))
                {
                    flags = "None";
                }

                // Check if iterator is online. If is...
                Player p      = Global.ObjAccessor.FindPlayer(slot.guid);
                string phases = "";
                if (p && p.IsInWorld)
                {
                    // ... than, it prints information like "is online", where he is, etc...
                    onlineState = "online";
                    phases      = PhasingHandler.FormatPhases(p.GetPhaseShift());

                    AreaTableRecord area = CliDB.AreaTableStorage.LookupByKey(p.GetAreaId());
                    if (area != null)
                    {
                        AreaTableRecord zone = CliDB.AreaTableStorage.LookupByKey(area.ParentAreaID);
                        if (zone != null)
                        {
                            zoneName = zone.AreaName[handler.GetSessionDbcLocale()];
                        }
                    }
                }
                else
                {
                    // ... else, everything is set to offline or neutral values.
                    zoneName    = "<ERROR>";
                    onlineState = "Offline";
                }

                // Now we can print those informations for every single member of each group!
                handler.SendSysMessage(CypherStrings.GroupPlayerNameGuid, slot.name, onlineState,
                                       zoneName, phases, slot.guid.ToString(), flags, LFGQueue.GetRolesString(slot.roles));
            }

            // And finish after every iterator is done.
            return(true);
        }
Ejemplo n.º 34
0
        public async Task <SQLResult> Create(LedgerEntry pModel)
        {
            SQLResult result = new SQLResult();

            _Context.Database.BeginTransaction();
            try
            {
                string csql = @" EXEC spmLedgerInsert
                    @pi_LedgerCode
                    , @pi_Ledger
                    , @pi_LedgerGroupFlag
                    , @pi_LedgerGroupId
                    , @pi_MainLedgerGroupId
                    , @pi_LedgerTypeId
                    , @pi_ControlAccountId
                    , @pi_NoJVPosting
                    , @pi_AutomaticPostingId
                    , @pi_mCurrencyId
                    , @pi_LevelNo
                    , @pi_EffectiveFrom
                    , @pi_EffectiveTo
                    , @pi_AnalysisCodeApplicableFlag
                    , @pi_CostCenterApplication
                    , @pi_VersionNo
                    , @pi_Active
                    , @pi_mMyParentId
                    , @pi_UserId
                    , @pi_HostName
                    , @pi_IPAddress
                    , @pi_DeviceType
                    , @pi_MACAddress";
                List <SqlParameter> sqlparam = new List <SqlParameter>()
                {
                    new SqlParameter("@pi_LedgerCode", pModel.LedgerCode),
                    new SqlParameter("@pi_Ledger", pModel.Ledger),
                    new SqlParameter("@pi_LedgerGroupFlag", pModel.LedgerGroupFlag),
                    new SqlParameter("@pi_LedgerGroupId", pModel.LedgerGroupId),
                    new SqlParameter("@pi_MainLedgerGroupId", pModel.MainLedgerGroupId),
                    new SqlParameter("@pi_LedgerTypeId", pModel.LedgerTypeId),
                    new SqlParameter("@pi_ControlAccountId", pModel.ControlAccountId),
                    new SqlParameter("@pi_NoJVPosting", pModel.NoJVPosting),
                    new SqlParameter("@pi_AutomaticPostingId", pModel.AutomaticPostingId),
                    new SqlParameter("@pi_mCurrencyId", pModel.CurrencyId),
                    new SqlParameter("@pi_LevelNo", pModel.LevelNo),
                    new SqlParameter("@pi_EffectiveFrom", pModel.EffectiveFrom),
                    new SqlParameter("@pi_EffectiveTo", pModel.EffectiveTo),
                    new SqlParameter("@pi_AnalysisCodeApplicableFlag", pModel.AnalysisCodeApplicableFlag),
                    new SqlParameter("@pi_CostCenterApplication", pModel.CostCenterApplication),
                    new SqlParameter("@pi_Active", pModel.Active),
                    new SqlParameter("@pi_UserId", pModel.AuditColumns.UserId),
                    new SqlParameter("@pi_HostName", pModel.AuditColumns.HostName),
                    new SqlParameter("@pi_IPAddress", pModel.AuditColumns.IPAddress),
                    new SqlParameter("@pi_DeviceType", pModel.AuditColumns.DeviceType),
                    new SqlParameter("@pi_MACAddress", pModel.AuditColumns.MACAddress),
                };
                result = await _Context.DBResult.FromSql(csql, sqlparam.ToArray()).SingleOrDefaultAsync();

                if (result.ErrorNo != 0)
                {
                    _Context.Database.RollbackTransaction();
                }
                else
                {
                    _Context.Database.CommitTransaction();
                }
            }
            catch (Exception ex)
            {
                _Context.Database.RollbackTransaction();
                result.ErrorNo         = 9999999999;
                result.ErrorMessage    = ex.Message.ToString();
                result.SQLErrorNumber  = ex.HResult;
                result.SQLErrorMessage = ex.Source.ToString();
            }
            return(result);
        }
Ejemplo n.º 35
0
        /// <summary>
        /// Executing a SQL query against current DB
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public SQLResult Execute(SQLRequest request)
        {
            //save executing query into history
            if (request.SaveToHistory)
            {
                _sqlCommandServices.SaveCommand(request);
            }

            //Prepare the result object based on basic information from request
            var result = new SQLResult
            {
                ConnectionString = _connection.ConnectionString,
                Query            = request.Query,
                ReadOnly         = request.ReadOnly,
                HtmlEncode       = request.HtmlEncode
            };
            var returnData = new List <DataResult>();
            var startTime  = DateTime.Now.Ticks;

            IDbTransaction transaction    = null;
            bool           openConnection = false;

            try
            {
                //open connection if needed
                if (_connection.State != ConnectionState.Open)
                {
                    _connection.Open();
                    openConnection = true;
                }
                IDbCommand command = _connection.CreateCommand();
                command.CommandText = request.Query;
                command.CommandType = CommandType.Text;
                //if executing in read only, we put all SQL statement into a DB transaction
                //then roll back after then
                if (request.ReadOnly)
                {
                    transaction         = _connection.BeginTransaction();
                    command.Transaction = transaction;
                }
                //Excuting and parse result
                IDataReader reader = command.ExecuteReader();
                if (reader != null)
                {
                    do
                    {
                        DataResult dataResult = getResult(reader);
                        if (dataResult != null)
                        {
                            returnData.Add(dataResult);
                        }
                    } while (reader.NextResult());
                    result.RecordsAffected = reader.RecordsAffected;
                }
            }
            catch (Exception ex)
            {
                result.Error = ex;
            }
            finally
            {
                //Roll back transaction if needed
                if (transaction != null)
                {
                    try
                    {
                        transaction.Rollback();
                    }
                    catch { }
                }
                //Close connection if it was opened by us
                if (openConnection)
                {
                    try
                    {
                        _connection.Close();
                    }
                    catch { }
                }
            }
            //Other properties for resutl object
            result.Tables = GetTableNames();
            long endTime = DateTime.Now.Ticks;

            result.ReturnData  = returnData;
            result.ProcessTime = (long)new TimeSpan(endTime - startTime).TotalMilliseconds;

            var defaultHistoryLength = _settingServices.GetSetting <int>(SettingNames.DefaultHistoryLength);
            var defaultHistoryStart  = _settingServices.GetSetting <int>(SettingNames.DefaultHistoryStart);

            result.Histories = _sqlCommandServices.GetHistories(defaultHistoryStart, defaultHistoryLength);
            return(result);
        }