private void FetchRoles() { this.DebugWrite("fetchRoles starting!", 6); //Make sure database connection active if (this.HandlePossibleDisconnect()) { return; } try { //Lock all command dictionaries for this operation lock (this._RoleKeyDictionary) { lock (this._RoleIDDictionary) { lock (this._RoleNameDictionary) { //Create the connection using (MySqlConnection connection = this.GetDatabaseConnection()) { //Create the command Dictionary<long, AdKatsRole> roleList = new Dictionary<long, AdKatsRole>(); using (MySqlCommand sqlcommand = connection.CreateCommand()) { //Query to fetch all roles const string sql = @" SELECT `role_id`, `role_key`, `role_name` FROM `adkats_roles`"; sqlcommand.CommandText = sql; using (MySqlDataReader reader = sqlcommand.ExecuteReader()) { //Grab the commands while (reader.Read()) { //Create as new AdKats_Command AdKatsRole role = new AdKatsRole { role_id = reader.GetInt64("role_id"), role_key = reader.GetString("role_key"), role_name = reader.GetString("role_name") }; //Add the command to temp list roleList.Add(role.role_id, role); } } } using (MySqlCommand sqlcommand = connection.CreateCommand()) { //Query to fetch all command assignments const string sql = @" SELECT `role_id`, `command_id` FROM `adkats_rolecommands` ORDER BY `role_id` ASC"; sqlcommand.CommandText = sql; using (MySqlDataReader reader = sqlcommand.ExecuteReader()) { //Grab the command assignments AdKatsRole currentRole = null; while (reader.Read()) { Int32 roleID = reader.GetInt32("role_id"); Int32 commandID = reader.GetInt32("command_id"); //Is the fetched role different than the current operating role? if (currentRole == null || roleID != currentRole.role_id) { //Yes it's different, grab it if (roleList.TryGetValue(roleID, out currentRole)) { currentRole.allowedCommands.Clear(); } else { //Failed to grab the role this.ConsoleError("Failed to grab current role for " + roleID + " when fetching command assignments."); return; } } AdKatsCommand currentCommand = null; if (this._CommandIDDictionary.TryGetValue(commandID, out currentCommand)) { currentRole.allowedCommands.Add(currentCommand.command_key, currentCommand); } else { this.ConsoleError("Could not assign command " + commandID + " to role " + roleID + " when fetching command assignments."); //return false; } } } } if (roleList.Count > 0) { //Empty all the role dictionaries this._RoleKeyDictionary.Clear(); this._RoleNameDictionary.Clear(); this._RoleIDDictionary.Clear(); //Loop over each role found and add them into the dictionaries foreach (AdKatsRole role in roleList.Values) { this._RoleKeyDictionary.Add(role.role_key, role); this._RoleNameDictionary.Add(role.role_name, role); this._RoleIDDictionary.Add(role.role_id, role); } //Successful return; } this.ConsoleError("Roles could not be fetched."); return; } } } } } catch (Exception e) { this.HandleException(new AdKatsException("Error while fetching roles from database.", e)); } this.DebugWrite("fetchRoles finished!", 6); }
public Boolean RoleIsInteractionAble(AdKatsRole aRole) { lock (aRole) { lock (aRole.allowedCommands) { if (aRole.allowedCommands.Values.Any(command => command.command_playerInteraction)) { return true; } } } return false; }
public void SetPluginVariable(String strVariable, String strValue) { if (strValue == null) { return; } try { //this.ConsoleWrite("'" + strVariable + "' -> '" + strValue + "'"); if (strVariable == "UpdateSettings") { //Do nothing. Settings page will be updated after return. } else if (Regex.Match(strVariable, @"Auto-Enable/Keep-Alive").Success) { Boolean autoEnable = Boolean.Parse(strValue); if (autoEnable != this._UseKeepAlive) { if(autoEnable) this.Enable(); this._UseKeepAlive = autoEnable; //Once setting has been changed, upload the change to database this.QueueSettingForUpload(new CPluginVariable(@"Auto-Enable/Keep-Alive", typeof (Boolean), this._UseKeepAlive)); } } else if (Regex.Match(strVariable, @"Send Query").Success) { this.SendQuery(strValue, true); } else if (Regex.Match(strVariable, @"Send Non-Query").Success) { this.SendNonQuery("Experimental Query", strValue, true); } else if (Regex.Match(strVariable, @"Hacker-Check Player").Success) { if (String.IsNullOrEmpty(strValue) || !this._ThreadsReady) { return; } this.ConsoleWarn("Preparing to hacker check " + strValue); if (String.IsNullOrEmpty(strValue) || strValue.Length < 3) { this.ConsoleError("Player name must be at least 3 characters long."); return; } if (!this.SoldierNameValid(strValue)) { this.ConsoleError("Player name contained invalid characters."); return; } AdKatsPlayer aPlayer = new AdKatsPlayer() { player_name = strValue }; this.FetchPlayerStats(aPlayer); if (aPlayer.stats != null) { this.RunStatSiteHackCheck(aPlayer, true); } else { this.ConsoleError("Stats not found for " + strValue); } } else if (Regex.Match(strVariable, @"Setting Import").Success) { Int32 tmp = -1; if (int.TryParse(strValue, out tmp)) { if (tmp != -1) this.QueueSettingImport(tmp); } else { this.ConsoleError("Invalid Input for Setting Import"); } } else if (Regex.Match(strVariable, @"Using AdKats WebAdmin").Success) { Boolean tmp = false; if (Boolean.TryParse(strValue, out tmp)) { this._UsingAwa = tmp; //Update necessary settings for AWA use if (this._UsingAwa) { this._UseBanEnforcer = true; this._FetchActionsFromDb = true; this._DbCommunicationWaitHandle.Set(); } } else { this.ConsoleError("Invalid Input for Using AdKats WebAdmin"); } } #region debugging else if (Regex.Match(strVariable, @"Command Entry").Success) { if (String.IsNullOrEmpty(strValue)) { return; } //Check if the message is a command if (strValue.StartsWith("@") || strValue.StartsWith("!")) { strValue = strValue.Substring(1); } else if (strValue.StartsWith("/@") || strValue.StartsWith("/!")) { strValue = strValue.Substring(2); } else if (strValue.StartsWith("/")) { strValue = strValue.Substring(1); } else { this.ConsoleError("Invalid command format."); return; } AdKatsRecord record = new AdKatsRecord { record_source = AdKatsRecord.Sources.Settings, source_name = "SettingsAdmin" }; this.CompleteRecordInformation(record, strValue); } else if (Regex.Match(strVariable, @"Debug level").Success) { Int32 tmp = 2; if (int.TryParse(strValue, out tmp)) { if (tmp != this._DebugLevel) { this._DebugLevel = tmp; //Once setting has been changed, upload the change to database this.QueueSettingForUpload(new CPluginVariable(@"Debug level", typeof (int), this._DebugLevel)); } } } else if (Regex.Match(strVariable, @"Debug Soldier Name").Success) { if (this.SoldierNameValid(strValue)) { if (strValue != this._DebugSoldierName) { this._DebugSoldierName = strValue; //Once setting has been changed, upload the change to database this.QueueSettingForUpload(new CPluginVariable(@"Debug Soldier Name", typeof (String), this._DebugSoldierName)); } } } else if (Regex.Match(strVariable, @"Server VOIP Address").Success) { if (strValue != this._ServerVoipAddress) { this._ServerVoipAddress = strValue; //Once setting has been changed, upload the change to database this.QueueSettingForUpload(new CPluginVariable(@"Server VOIP Address", typeof (String), this._ServerVoipAddress)); } } else if (Regex.Match(strVariable, @"Rule Print Delay").Success) { Double delay = Double.Parse(strValue); if (this._ServerRulesDelay != delay) { if (delay <= 0) { this.ConsoleError("Delay cannot be negative."); delay = 1.0; } this._ServerRulesDelay = delay; //Once setting has been changed, upload the change to database this.QueueSettingForUpload(new CPluginVariable(@"Rule Print Delay", typeof (Double), this._ServerRulesDelay)); } } else if (Regex.Match(strVariable, @"Rule Print Interval").Success) { Double interval = Double.Parse(strValue); if (this._ServerRulesInterval != interval) { if (interval <= 0) { this.ConsoleError("Interval cannot be negative."); interval = 5.0; } this._ServerRulesInterval = interval; //Once setting has been changed, upload the change to database this.QueueSettingForUpload(new CPluginVariable(@"Rule Print Interval", typeof (Double), this._ServerRulesInterval)); } } else if (Regex.Match(strVariable, @"Server Rule List").Success) { this._ServerRulesList = CPluginVariable.DecodeStringArray(strValue); //Once setting has been changed, upload the change to database this.QueueSettingForUpload(new CPluginVariable(@"Server Rule List", typeof (String), CPluginVariable.EncodeStringArray(this._ServerRulesList))); } else if (Regex.Match(strVariable, @"Feed MULTIBalancer Whitelist").Success) { Boolean feedMTB = Boolean.Parse(strValue); if (feedMTB != this._FeedMultiBalancerWhitelist) { this._FeedMultiBalancerWhitelist = feedMTB; this.FetchUserList(); //Once setting has been changed, upload the change to database this.QueueSettingForUpload(new CPluginVariable(@"Feed MULTIBalancer Whitelist", typeof (Boolean), this._FeedMultiBalancerWhitelist)); } } else if (Regex.Match(strVariable, @"Feed Server Reserved Slots").Success) { Boolean feedSRS = Boolean.Parse(strValue); if (feedSRS != this._FeedServerReservedSlots) { this._FeedServerReservedSlots = feedSRS; this.FetchUserList(); //Once setting has been changed, upload the change to database this.QueueSettingForUpload(new CPluginVariable(@"Feed Server Reserved Slots", typeof(Boolean), this._FeedServerReservedSlots)); } } else if (Regex.Match(strVariable, @"Feed Server Spectator List").Success) { Boolean feedSSL = Boolean.Parse(strValue); if (feedSSL != this._FeedServerSpectatorList) { if (this._GameVersion != GameVersion.BF4) { this.ConsoleError("This feature can only be enabled on BF4 servers."); return; } this._FeedServerSpectatorList = feedSSL; this.FetchUserList(); //Once setting has been changed, upload the change to database this.QueueSettingForUpload(new CPluginVariable(@"Feed Server Spectator List", typeof(Boolean), this._FeedServerSpectatorList)); } } else if (Regex.Match(strVariable, @"Feed Stat Logger Settings").Success) { Boolean feedSLS = Boolean.Parse(strValue); if (feedSLS != this._FeedStatLoggerSettings) { this._FeedStatLoggerSettings = feedSLS; //Once setting has been changed, upload the change to database this.QueueSettingForUpload(new CPluginVariable(@"Feed Stat Logger Settings", typeof (Boolean), this._FeedStatLoggerSettings)); } } else if (Regex.Match(strVariable, @"Use Experimental Tools").Success) { Boolean useEXP = Boolean.Parse(strValue); if (useEXP != this._UseExperimentalTools) { this._UseExperimentalTools = useEXP; if (this._UseExperimentalTools) { if (this._ThreadsReady) { this.ConsoleWarn("Using experimental tools. Take caution."); } } else { this.ConsoleWarn("Experimental tools disabled."); this._UseWeaponLimiter = false; this._UseGrenadeCookCatcher = false; this._UseHackerChecker = false; this._UseDpsChecker = false; this._UseHskChecker = false; } //Once setting has been changed, upload the change to database this.QueueSettingForUpload(new CPluginVariable(@"Use Experimental Tools", typeof (Boolean), this._UseExperimentalTools)); this.QueueSettingForUpload(new CPluginVariable(@"Use NO EXPLOSIVES Limiter", typeof (Boolean), this._UseWeaponLimiter)); } } else if (Regex.Match(strVariable, @"Round Timer: Enable").Success) { Boolean useTimer = Boolean.Parse(strValue); if (useTimer != this._UseRoundTimer) { this._UseRoundTimer = useTimer; if (this._UseRoundTimer) { if (this._ThreadsReady) { this.ConsoleWarn("Internal Round Timer activated, will enable on next round."); } } else { this.ConsoleWarn("Internal Round Timer disabled."); } //Once setting has been changed, upload the change to database this.QueueSettingForUpload(new CPluginVariable(@"Round Timer: Enable", typeof (Boolean), this._UseRoundTimer)); } } else if (Regex.Match(strVariable, @"Round Timer: Round Duration Minutes").Success) { Double duration = Double.Parse(strValue); if (this._RoundTimeMinutes != duration) { if (duration <= 0) { duration = 30.0; } this._RoundTimeMinutes = duration; //Once setting has been changed, upload the change to database this.QueueSettingForUpload(new CPluginVariable(@"Round Timer: Round Duration Minutes", typeof (Double), this._RoundTimeMinutes)); } } else if (Regex.Match(strVariable, @"Use NO EXPLOSIVES Limiter").Success) { Boolean useLimiter = Boolean.Parse(strValue); if (useLimiter != this._UseWeaponLimiter) { this._UseWeaponLimiter = useLimiter; if (this._UseWeaponLimiter) { if (this._ThreadsReady) { this.ConsoleWarn("Internal NO EXPLOSIVES punish limit activated."); } } else { this.ConsoleWarn("Internal NO EXPLOSIVES punish limit disabled."); } //Once setting has been changed, upload the change to database this.QueueSettingForUpload(new CPluginVariable(@"Use NO EXPLOSIVES Limiter", typeof (Boolean), this._UseWeaponLimiter)); } } else if (Regex.Match(strVariable, @"NO EXPLOSIVES Weapon String").Success) { if (this._WeaponLimiterString != strValue) { if (!String.IsNullOrEmpty(strValue)) { this._WeaponLimiterString = strValue; //Once setting has been changed, upload the change to database this.QueueSettingForUpload(new CPluginVariable(@"NO EXPLOSIVES Weapon String", typeof (String), this._WeaponLimiterString)); } else { this.ConsoleError("Weapon String cannot be empty."); } } } else if (Regex.Match(strVariable, @"NO EXPLOSIVES Exception String").Success) { if (this._WeaponLimiterExceptionString != strValue) { if (!String.IsNullOrEmpty(strValue)) { this._WeaponLimiterExceptionString = strValue; //Once setting has been changed, upload the change to database this.QueueSettingForUpload(new CPluginVariable(@"NO EXPLOSIVES Exception String", typeof (String), this._WeaponLimiterExceptionString)); } else { this.ConsoleError("Weapon exception String cannot be empty."); } } } else if (Regex.Match(strVariable, @"Use Grenade Cook Catcher").Success) { Boolean useCookCatcher = Boolean.Parse(strValue); if (useCookCatcher != this._UseGrenadeCookCatcher) { this._UseGrenadeCookCatcher = useCookCatcher; if (this._UseGrenadeCookCatcher) { if (this._ThreadsReady) { this.ConsoleWarn("Internal Grenade Cook Catcher activated."); } } else { this.ConsoleWarn("Internal Grenade Cook Catcher disabled."); } //Once setting has been changed, upload the change to database this.QueueSettingForUpload(new CPluginVariable(@"Use Grenade Cook Catcher", typeof (Boolean), this._UseGrenadeCookCatcher)); } } else if (Regex.Match(strVariable, @"HackerChecker: Enable").Success) { Boolean useHackChecker = Boolean.Parse(strValue); if (useHackChecker != this._UseHackerChecker) { this._UseHackerChecker = useHackChecker; if (this._UseHackerChecker) { if (this._ThreadsReady) { this.ConsoleWarn("Internal Hacker Checker activated."); } } else { this.ConsoleWarn("Internal Hacker Checker disabled."); } //Once setting has been changed, upload the change to database this.QueueSettingForUpload(new CPluginVariable(@"HackerChecker: Enable", typeof (Boolean), this._UseHackerChecker)); } } else if (Regex.Match(strVariable, @"HackerChecker: Whitelist").Success) { this._HackerCheckerWhitelist = CPluginVariable.DecodeStringArray(strValue); //Once setting has been changed, upload the change to database this.QueueSettingForUpload(new CPluginVariable(@"HackerChecker: Whitelist", typeof (String), CPluginVariable.EncodeStringArray(this._HackerCheckerWhitelist))); } else if (Regex.Match(strVariable, @"HackerChecker: DPS Checker: Enable").Success) { Boolean useDamageChecker = Boolean.Parse(strValue); if (useDamageChecker != this._UseDpsChecker) { this._UseDpsChecker = useDamageChecker; if (this._UseDpsChecker) { if (this._ThreadsReady) { this.ConsoleWarn("Internal Damage Mod Checker activated."); } } else { this.ConsoleWarn("Internal Damage Mod Checker disabled."); } //Once setting has been changed, upload the change to database this.QueueSettingForUpload(new CPluginVariable(@"HackerChecker: DPS Checker: Enable", typeof (Boolean), this._UseDpsChecker)); } } else if (Regex.Match(strVariable, @"HackerChecker: DPS Checker: Trigger Level").Success) { Double triggerLevel = Double.Parse(strValue); if (this._DpsTriggerLevel != triggerLevel) { if (triggerLevel <= 0) { triggerLevel = 100.0; } this._DpsTriggerLevel = triggerLevel; //Once setting has been changed, upload the change to database this.QueueSettingForUpload(new CPluginVariable(@"HackerChecker: DPS Checker: Trigger Level", typeof (Double), this._DpsTriggerLevel)); } } else if (Regex.Match(strVariable, @"HackerChecker: DPS Checker: Ban Message").Success) { if (this._HackerCheckerDPSBanMessage != strValue) { this._HackerCheckerDPSBanMessage = strValue; //Once setting has been changed, upload the change to database this.QueueSettingForUpload(new CPluginVariable(@"HackerChecker: DPS Checker: Ban Message", typeof(String), this._HackerCheckerDPSBanMessage)); } } else if (Regex.Match(strVariable, @"HackerChecker: HSK Checker: Enable").Success) { Boolean useAimbotChecker = Boolean.Parse(strValue); if (useAimbotChecker != this._UseHskChecker) { this._UseHskChecker = useAimbotChecker; if (this._UseHskChecker) { if (this._ThreadsReady) { this.ConsoleWarn("Internal Aimbot Checker activated."); } } else { this.ConsoleWarn("Internal Aimbot Checker disabled."); } //Once setting has been changed, upload the change to database this.QueueSettingForUpload(new CPluginVariable(@"HackerChecker: HSK Checker: Enable", typeof (Boolean), this._UseHskChecker)); } } else if (Regex.Match(strVariable, @"HackerChecker: HSK Checker: Trigger Level").Success) { Double triggerLevel = Double.Parse(strValue); if (this._HskTriggerLevel != triggerLevel) { if (triggerLevel <= 0) { triggerLevel = 100.0; } this._HskTriggerLevel = triggerLevel; //Once setting has been changed, upload the change to database this.QueueSettingForUpload(new CPluginVariable(@"HackerChecker: HSK Checker: Trigger Level", typeof (Double), this._HskTriggerLevel)); } } else if (Regex.Match(strVariable, @"HackerChecker: HSK Checker: Ban Message").Success) { if (this._HackerCheckerHSKBanMessage != strValue) { this._HackerCheckerHSKBanMessage = strValue; //Once setting has been changed, upload the change to database this.QueueSettingForUpload(new CPluginVariable(@"HackerChecker: HSK Checker: Ban Message", typeof(String), this._HackerCheckerHSKBanMessage)); } } #endregion #region HTTP settings else if (Regex.Match(strVariable, @"External Access Key").Success) { if (strValue != this._ExternalCommandAccessKey) { this._ExternalCommandAccessKey = strValue; //Once setting has been changed, upload the change to database this.QueueSettingForUpload(new CPluginVariable(@"External Access Key", typeof (String), this._ExternalCommandAccessKey)); } } else if (Regex.Match(strVariable, @"Fetch Actions from Database").Success) { Boolean fetch = Boolean.Parse(strValue); if (fetch != this._FetchActionsFromDb) { this._FetchActionsFromDb = fetch; this._DbCommunicationWaitHandle.Set(); //Once setting has been changed, upload the change to database this.QueueSettingForUpload(new CPluginVariable(@"Fetch Actions from Database", typeof (Boolean), this._FetchActionsFromDb)); } } #endregion #region ban settings else if (Regex.Match(strVariable, @"Use Additional Ban Message").Success) { Boolean use = Boolean.Parse(strValue); if (this._UseBanAppend != use) { this._UseBanAppend = use; //Once setting has been changed, upload the change to database this.QueueSettingForUpload(new CPluginVariable(@"Use Additional Ban Message", typeof (Boolean), this._UseBanAppend)); } } else if (Regex.Match(strVariable, @"Additional Ban Message").Success) { if (strValue.Length > 30) { strValue = strValue.Substring(0, 30); this.ConsoleError("Ban append cannot be more than 30 characters."); } if (this._BanAppend != strValue) { this._BanAppend = strValue; //Once setting has been changed, upload the change to database this.QueueSettingForUpload(new CPluginVariable(@"Additional Ban Message", typeof (String), this._BanAppend)); } } else if (Regex.Match(strVariable, @"Procon Ban Admin Name").Success) { if (strValue.Length > 16) { strValue = strValue.Substring(0, 16); this.ConsoleError("Procon ban admin id cannot be more than 16 characters."); } if (this._CBanAdminName != strValue) { this._CBanAdminName = strValue; //Once setting has been changed, upload the change to database this.QueueSettingForUpload(new CPluginVariable(@"Procon Ban Admin Name", typeof (String), this._CBanAdminName)); } } else if (Regex.Match(strVariable, @"Use Ban Enforcer").Success) { Boolean use = Boolean.Parse(strValue); if (this._UseBanEnforcer != use) { this._UseBanEnforcer = use; //Once setting has been changed, upload the change to database this.QueueSettingForUpload(new CPluginVariable(@"Use Ban Enforcer", typeof (Boolean), this._UseBanEnforcer)); if (this._UseBanEnforcer) { this._FetchActionsFromDb = true; this._DbCommunicationWaitHandle.Set(); } } } else if (Regex.Match(strVariable, @"Enforce New Bans by NAME").Success) { Boolean enforceName = Boolean.Parse(strValue); if (this._DefaultEnforceName != enforceName) { this._DefaultEnforceName = enforceName; //Once setting has been changed, upload the change to database this.QueueSettingForUpload(new CPluginVariable(@"Enforce New Bans by NAME", typeof (Boolean), this._DefaultEnforceName)); } } else if (Regex.Match(strVariable, @"Enforce New Bans by GUID").Success) { Boolean enforceGUID = Boolean.Parse(strValue); if (this._DefaultEnforceGUID != enforceGUID) { this._DefaultEnforceGUID = enforceGUID; //Once setting has been changed, upload the change to database this.QueueSettingForUpload(new CPluginVariable(@"Enforce New Bans by GUID", typeof (Boolean), this._DefaultEnforceGUID)); } } else if (Regex.Match(strVariable, @"Enforce New Bans by IP").Success) { Boolean enforceIP = Boolean.Parse(strValue); if (this._DefaultEnforceIP != enforceIP) { this._DefaultEnforceIP = enforceIP; //Once setting has been changed, upload the change to database this.QueueSettingForUpload(new CPluginVariable(@"Enforce New Bans by IP", typeof(Boolean), this._DefaultEnforceIP)); } } else if (Regex.Match(strVariable, @"Ban Search").Success) { if (String.IsNullOrEmpty(strValue) || strValue.Length < 3) { this.ConsoleError("Search query must be 3 or more characters."); return; } lock (this._BanEnforcerSearchResults) { this._BanEnforcerSearchResults = new List<AdKatsBan>(); List<AdKatsPlayer> matchingPlayers; if (this.FetchMatchingPlayers(strValue, out matchingPlayers, false)) { foreach (AdKatsPlayer aPlayer in matchingPlayers) { AdKatsBan aBan = this.FetchPlayerBan(aPlayer); if (aBan != null) { this._BanEnforcerSearchResults.Add(aBan); } } } if (this._BanEnforcerSearchResults.Count == 0) { this.ConsoleError("No players matching '" + strValue + "' have active bans."); } } } #endregion #region In-Game Command Settings else if (Regex.Match(strVariable, @"Minimum Required Reason Length").Success) { Int32 required = Int32.Parse(strValue); if (this._RequiredReasonLength != required) { this._RequiredReasonLength = required; if (this._RequiredReasonLength < 1) { this._RequiredReasonLength = 1; } //Once setting has been changed, upload the change to database this.QueueSettingForUpload(new CPluginVariable(@"Minimum Required Reason Length", typeof (Int32), this._RequiredReasonLength)); } } else if (Regex.Match(strVariable, @"Allow Commands from Admin Say").Success) { Boolean allowSayCommands = Boolean.Parse(strValue); if (this._AllowAdminSayCommands != allowSayCommands) { this._AllowAdminSayCommands = allowSayCommands; //Once setting has been changed, upload the change to database this.QueueSettingForUpload(new CPluginVariable(@"Allow Commands from Admin Say", typeof(Boolean), this._AllowAdminSayCommands)); } } else if (strVariable.StartsWith("USR")) { //USR1 | ColColonCleaner | User Email //USR1 | ColColonCleaner | User Phone //USR1 | ColColonCleaner | User Role //USR1 | ColColonCleaner | Delete User? //USR1 | ColColonCleaner | Add Soldier? //USR1 | ColColonCleaner | Soldiers | 293492 | ColColonCleaner | Delete Soldier? String[] commandSplit = CPluginVariable.DecodeStringArray(strVariable); String user_id_str = commandSplit[0].TrimStart("USR".ToCharArray()).Trim(); Int32 user_id = Int32.Parse(user_id_str); String section = commandSplit[2].Trim(); AdKatsUser aUser = null; if (this._UserCache.TryGetValue(user_id, out aUser)) { switch (section) { case "User Email": if (String.IsNullOrEmpty(strValue) || Regex.IsMatch(strValue, @"^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$")) { aUser.user_email = strValue; } else { this.ConsoleError(strValue + " is an invalid email address."); return; } //Reupload the user this.QueueUserForUpload(aUser); break; case "User Phone": aUser.user_phone = strValue; //Reupload the user this.QueueUserForUpload(aUser); break; case "User Role": AdKatsRole aRole = null; if (this._RoleNameDictionary.TryGetValue(strValue, out aRole)) { aUser.user_role = aRole; } else { this.ConsoleError("Role " + strValue + " not found."); return; } //Reupload the user this.QueueUserForUpload(aUser); break; case "Delete User?": if (strValue.ToLower() == "delete") { this.QueueUserForRemoval(aUser); } break; case "Add Soldier?": this.TryAddUserSoldier(aUser, strValue); //Reupload the user this.QueueUserForUpload(aUser); break; case "Soldiers": if (strVariable.Contains("Delete Soldier?") && strValue.ToLower() == "delete") { String player_id_str = commandSplit[3].Trim(); Int64 player_id = Int64.Parse(player_id_str); aUser.soldierDictionary.Remove(player_id); //Reupload the user this.QueueUserForUpload(aUser); } break; default: this.ConsoleError("Section " + section + " not found."); break; } } } else if (strVariable.StartsWith("CDE")) { //Trim off all but the command ID and section //5. Command List|CDE1 | Kill Player | Active //5. Command List|CDE1 | Kill Player | Logging //5. Command List|CDE1 | Kill Player | Text String[] commandSplit = CPluginVariable.DecodeStringArray(strVariable); String command_id_str = commandSplit[0].TrimStart("CDE".ToCharArray()).Trim(); Int32 command_id = Int32.Parse(command_id_str); String section = commandSplit[2].Trim(); AdKatsCommand command = null; if (this._CommandIDDictionary.TryGetValue(command_id, out command)) { if (section == "Active") { //Check for valid value if (strValue == "Active") { command.command_active = AdKatsCommand.CommandActive.Active; } else if (strValue == "Disabled") { command.command_active = AdKatsCommand.CommandActive.Disabled; } else if (strValue == "Invisible") { command.command_active = AdKatsCommand.CommandActive.Invisible; } else { this.ConsoleError("Activity setting " + strValue + " was invalid."); return; } } else if (section == "Logging") { //Check for valid value switch (strValue) { case "Log": command.command_logging = AdKatsCommand.CommandLogging.Log; break; case "Mandatory": command.command_logging = AdKatsCommand.CommandLogging.Mandatory; break; case "Ignore": command.command_logging = AdKatsCommand.CommandLogging.Ignore; break; case "Unable": command.command_logging = AdKatsCommand.CommandLogging.Unable; break; default: this.ConsoleError("Logging setting " + strValue + " was invalid."); return; } } else if (section == "Text") { if (String.IsNullOrEmpty(strValue)) { this.ConsoleError("Command text cannot be blank."); return; } //Make sure command text only contains alphanumeric chars, underscores, and dashes Regex rgx = new Regex("[^a-zA-Z0-9_-]"); strValue = rgx.Replace(strValue, ""); //Check to make sure text is not a duplicate foreach (AdKatsCommand testCommand in this._CommandNameDictionary.Values) { if (testCommand.command_text == strValue) { this.ConsoleError("Command text cannot be the same as another command."); return; } } //Assign the command text command.command_text = strValue; } else { this.ConsoleError("Section " + section + " not understood."); return; } //Upload the command changes this.QueueCommandForUpload(command); } else { this.ConsoleError("Command " + command_id + " not found in command dictionary."); } } else if (strVariable.StartsWith("RLE")) { //Trim off all but the command ID and section //RLE1 | Default Guest | CDE3 | Kill Player String[] commandSplit = CPluginVariable.DecodeStringArray(strVariable); String roleIDStr = commandSplit[0].TrimStart("RLE".ToCharArray()).Trim(); Int32 roleID = Int32.Parse(roleIDStr); //If second section is a command prefix, this is the allow/deny clause if (commandSplit[2].Trim().StartsWith("CDE")) { String commandIDStr = commandSplit[2].Trim().TrimStart("CDE".ToCharArray()); Int32 commandID = Int32.Parse(commandIDStr); //Fetch needed role AdKatsRole aRole = null; if (this._RoleIDDictionary.TryGetValue(roleID, out aRole)) { //Fetch needed command AdKatsCommand aCommand = null; if (this._CommandIDDictionary.TryGetValue(commandID, out aCommand)) { switch (strValue.ToLower()) { case "allow": lock (aRole.allowedCommands) { if (!aRole.allowedCommands.ContainsKey(aCommand.command_key)) { aRole.allowedCommands.Add(aCommand.command_key, aCommand); } } this.QueueRoleForUpload(aRole); break; case "deny": lock (aRole.allowedCommands) { aRole.allowedCommands.Remove(aCommand.command_key); } this.QueueRoleForUpload(aRole); break; default: this.ConsoleError("Unknown setting when assigning command allowance."); return; } } else { this.ConsoleError("Command " + commandID + " not found in command dictionary."); } } else { this.ConsoleError("Role " + roleID + " not found in role dictionary."); } } else if (commandSplit[2].Contains("Delete Role?") && strValue.ToLower() == "delete") { //Fetch needed role AdKatsRole aRole = null; if (this._RoleIDDictionary.TryGetValue(roleID, out aRole)) { this.QueueRoleForRemoval(aRole); } else { this.ConsoleError("Unable to fetch role for deletion."); } } } else if (strVariable.StartsWith("BAN")) { //Trim off all but the command ID and section //BAN1 | ColColonCleaner | Some Reason String[] commandSplit = CPluginVariable.DecodeStringArray(strVariable); String banIDStr = commandSplit[0].TrimStart("BAN".ToCharArray()).Trim(); Int32 banID = Int32.Parse(banIDStr); AdKatsBan aBan = null; foreach (AdKatsBan innerBan in this._BanEnforcerSearchResults) { if (innerBan.ban_id == banID) { aBan = innerBan; break; } } if (aBan != null) { switch (strValue) { case "Active": aBan.ban_status = strValue; break; case "Disabled": aBan.ban_status = strValue; break; default: this.ConsoleError("Unknown setting when assigning ban status."); return; } this.UpdateBanStatus(aBan); this.ConsoleSuccess("Ban " + aBan.ban_id + " is now " + strValue); } else { this.ConsoleError("Unable to update ban. This should not happen."); } } #endregion #region punishment settings else if (Regex.Match(strVariable, @"Punishment Hierarchy").Success) { this._PunishmentHierarchy = CPluginVariable.DecodeStringArray(strValue); //Once setting has been changed, upload the change to database this.QueueSettingForUpload(new CPluginVariable(@"Punishment Hierarchy", typeof (String), CPluginVariable.EncodeStringArray(this._PunishmentHierarchy))); } else if (Regex.Match(strVariable, @"Combine Server Punishments").Success) { Boolean combine = Boolean.Parse(strValue); if (this._CombineServerPunishments != combine) { this._CombineServerPunishments = combine; //Once setting has been changed, upload the change to database this.QueueSettingForUpload(new CPluginVariable(@"Combine Server Punishments", typeof (Boolean), this._CombineServerPunishments)); } } else if (Regex.Match(strVariable, @"Only Kill Players when Server in low population").Success) { Boolean onlyKill = Boolean.Parse(strValue); if (onlyKill != this._OnlyKillOnLowPop) { this._OnlyKillOnLowPop = onlyKill; //Once setting has been changed, upload the change to database this.QueueSettingForUpload(new CPluginVariable(@"Only Kill Players when Server in low population", typeof (Boolean), this._OnlyKillOnLowPop)); } } else if (Regex.Match(strVariable, @"Low Population Value").Success) { Int32 lowPop = Int32.Parse(strValue); if (lowPop != this._LowPopPlayerCount) { this._LowPopPlayerCount = lowPop; //Once setting has been changed, upload the change to database this.QueueSettingForUpload(new CPluginVariable(@"Low Population Value", typeof (Int32), this._LowPopPlayerCount)); } } else if (Regex.Match(strVariable, @"Use IRO Punishment").Success) { Boolean iro = Boolean.Parse(strValue); if (iro != this._IROActive) { this._IROActive = iro; //Once setting has been changed, upload the change to database this.QueueSettingForUpload(new CPluginVariable(@"Use IRO Punishment", typeof (Boolean), this._IROActive)); } } else if (Regex.Match(strVariable, @"IRO Punishment Overrides Low Pop").Success) { Boolean overrideIRO = Boolean.Parse(strValue); if (overrideIRO != this._IROOverridesLowPop) { this._IROOverridesLowPop = overrideIRO; //Once setting has been changed, upload the change to database this.QueueSettingForUpload(new CPluginVariable(@"IRO Punishment Overrides Low Pop", typeof (Boolean), this._IROOverridesLowPop)); } } else if (Regex.Match(strVariable, @"IRO Timeout Minutes").Success) { Int32 timeout = Int32.Parse(strValue); if (timeout != this._IROTimeout) { this._IROTimeout = timeout; //Once setting has been changed, upload the change to database this.QueueSettingForUpload(new CPluginVariable(@"IRO Timeout (Minutes)", typeof (Int32), this._IROTimeout)); } } #endregion #region sql settings else if (Regex.Match(strVariable, @"MySQL Hostname").Success) { _MySqlHostname = strValue; this._DbSettingsChanged = true; this._DbCommunicationWaitHandle.Set(); } else if (Regex.Match(strVariable, @"MySQL Port").Success) { Int32 tmp = 3306; int.TryParse(strValue, out tmp); if (tmp > 0 && tmp < 65536) { _MySqlPort = strValue; this._DbSettingsChanged = true; this._DbCommunicationWaitHandle.Set(); } else { this.ConsoleError("Invalid value for MySQL Port: '" + strValue + "'. Must be number between 1 and 65535!"); } } else if (Regex.Match(strVariable, @"MySQL Database").Success) { this._MySqlDatabaseName = strValue; this._DbSettingsChanged = true; this._DbCommunicationWaitHandle.Set(); } else if (Regex.Match(strVariable, @"MySQL Username").Success) { _MySqlUsername = strValue; this._DbSettingsChanged = true; this._DbCommunicationWaitHandle.Set(); } else if (Regex.Match(strVariable, @"MySQL Password").Success) { _MySqlPassword = strValue; this._DbSettingsChanged = true; this._DbCommunicationWaitHandle.Set(); } #endregion #region email settings else if (Regex.Match(strVariable, @"Send Emails").Success) { //Disabled this._UseEmail = Boolean.Parse(strValue); //Once setting has been changed, upload the change to database this.QueueSettingForUpload(new CPluginVariable("Send Emails", typeof (Boolean), this._UseEmail)); } else if (Regex.Match(strVariable, @"Use SSL?").Success) { this._EmailHandler.UseSSL = Boolean.Parse(strValue); //Once setting has been changed, upload the change to database this.QueueSettingForUpload(new CPluginVariable("Use SSL?", typeof(Boolean), this._EmailHandler.UseSSL)); } else if (Regex.Match(strVariable, @"SMTP-Server address").Success) { if (!String.IsNullOrEmpty(strValue)) { this._EmailHandler.SMTPServer = strValue; //Once setting has been changed, upload the change to database this.QueueSettingForUpload(new CPluginVariable("SMTP-Server address", typeof (String), this._EmailHandler.SMTPServer)); } } else if (Regex.Match(strVariable, @"SMTP-Server port").Success) { Int32 iPort = Int32.Parse(strValue); if (iPort > 0) { this._EmailHandler.SMTPPort = iPort; //Once setting has been changed, upload the change to database this.QueueSettingForUpload(new CPluginVariable("SMTP-Server port", typeof(Int32), this._EmailHandler.SMTPPort)); } } else if (Regex.Match(strVariable, @"Sender address").Success) { if (string.IsNullOrEmpty(strValue)) { this._EmailHandler.SenderEmail = "SENDER_CANNOT_BE_EMPTY"; this.ConsoleError("No sender for email was given! Canceling Operation."); } else { this._EmailHandler.SenderEmail = strValue; //Once setting has been changed, upload the change to database this.QueueSettingForUpload(new CPluginVariable("Sender address", typeof(String), this._EmailHandler.SenderEmail)); } } else if (Regex.Match(strVariable, @"SMTP-Server username").Success) { if (string.IsNullOrEmpty(strValue)) { this._EmailHandler.SMTPUser = "******"; this.ConsoleError("No username for SMTP was given! Canceling Operation."); } else { this._EmailHandler.SMTPUser = strValue; //Once setting has been changed, upload the change to database this.QueueSettingForUpload(new CPluginVariable("SMTP-Server username", typeof(String), this._EmailHandler.SMTPUser)); } } else if (Regex.Match(strVariable, @"SMTP-Server password").Success) { if (string.IsNullOrEmpty(strValue)) { this._EmailHandler.SMTPPassword = "******"; this.ConsoleError("No password for SMTP was given! Canceling Operation."); } else { this._EmailHandler.SMTPPassword = strValue; //Once setting has been changed, upload the change to database this.QueueSettingForUpload(new CPluginVariable("SMTP-Server password", typeof(String), this._EmailHandler.SMTPPassword)); } } else if (Regex.Match(strVariable, @"Custom HTML Addition").Success) { this._EmailHandler.CustomHTMLAddition = strValue; //Once setting has been changed, upload the change to database this.QueueSettingForUpload(new CPluginVariable("Custom HTML Addition", typeof(String), this._EmailHandler.CustomHTMLAddition)); } else if (Regex.Match(strVariable, @"Extra Recipient Email Addresses").Success) { this._EmailHandler.RecipientEmails = CPluginVariable.DecodeStringArray(strValue).ToList(); //Once setting has been changed, upload the change to database this.QueueSettingForUpload(new CPluginVariable(@"Extra Recipient Email Addresses", typeof (String), strValue)); } #endregion #region mute settings else if (Regex.Match(strVariable, @"On-Player-Muted Message").Success) { if (this._MutedPlayerMuteMessage != strValue) { this._MutedPlayerMuteMessage = strValue; //Once setting has been changed, upload the change to database this.QueueSettingForUpload(new CPluginVariable(@"On-Player-Muted Message", typeof (String), this._MutedPlayerMuteMessage)); } } else if (Regex.Match(strVariable, @"On-Player-Killed Message").Success) { if (this._MutedPlayerKillMessage != strValue) { this._MutedPlayerKillMessage = strValue; //Once setting has been changed, upload the change to database this.QueueSettingForUpload(new CPluginVariable(@"On-Player-Killed Message", typeof (String), this._MutedPlayerKillMessage)); } } else if (Regex.Match(strVariable, @"On-Player-Kicked Message").Success) { if (this._MutedPlayerKickMessage != strValue) { this._MutedPlayerKickMessage = strValue; //Once setting has been changed, upload the change to database this.QueueSettingForUpload(new CPluginVariable(@"On-Player-Kicked Message", typeof (String), this._MutedPlayerKickMessage)); } } if (Regex.Match(strVariable, @"# Chances to give player before kicking").Success) { Int32 tmp = 5; int.TryParse(strValue, out tmp); if (this._MutedPlayerChances != tmp) { this._MutedPlayerChances = tmp; //Once setting has been changed, upload the change to database this.QueueSettingForUpload(new CPluginVariable(@"# Chances to give player before kicking", typeof (Int32), this._MutedPlayerChances)); } } #endregion #region TeamSwap settings else if (Regex.Match(strVariable, @"Auto-Whitelist Count").Success) { Int32 tmp = 1; int.TryParse(strValue, out tmp); if (tmp != this._PlayersToAutoWhitelist) { if (tmp < 0) tmp = 0; this._PlayersToAutoWhitelist = tmp; //Once setting has been changed, upload the change to database this.QueueSettingForUpload(new CPluginVariable(@"Auto-Whitelist Count", typeof (Int32), this._PlayersToAutoWhitelist)); } } else if (Regex.Match(strVariable, @"Ticket Window High").Success) { Int32 tmp = 2; int.TryParse(strValue, out tmp); if (tmp != this._TeamSwapTicketWindowHigh) { this._TeamSwapTicketWindowHigh = tmp; //Once setting has been changed, upload the change to database this.QueueSettingForUpload(new CPluginVariable(@"Ticket Window High", typeof (Int32), this._TeamSwapTicketWindowHigh)); } } else if (Regex.Match(strVariable, @"Ticket Window Low").Success) { Int32 tmp = 2; int.TryParse(strValue, out tmp); if (tmp != this._TeamSwapTicketWindowLow) { this._TeamSwapTicketWindowLow = tmp; //Once setting has been changed, upload the change to database this.QueueSettingForUpload(new CPluginVariable(@"Ticket Window Low", typeof (Int32), this._TeamSwapTicketWindowLow)); } } #endregion #region Admin Assistants else if (Regex.Match(strVariable, @"Enable Admin Assistant Perk").Success) { Boolean enableAA = Boolean.Parse(strValue); if (this._EnableAdminAssistantPerk != enableAA) { this._EnableAdminAssistantPerk = enableAA; //Once setting has been changed, upload the change to database this.QueueSettingForUpload(new CPluginVariable(@"Enable Admin Assistant Perk", typeof (Boolean), this._EnableAdminAssistantPerk)); } } else if (Regex.Match(strVariable, @"Minimum Confirmed Reports Per Month").Success) { Int32 monthlyReports = Int32.Parse(strValue); if (this._MinimumRequiredMonthlyReports != monthlyReports) { this._MinimumRequiredMonthlyReports = monthlyReports; //Once setting has been changed, upload the change to database this.QueueSettingForUpload(new CPluginVariable(@"Minimum Confirmed Reports Per Month", typeof (Int32), this._MinimumRequiredMonthlyReports)); } } #endregion #region Messaging Settings else if (Regex.Match(strVariable, @"Yell display time seconds").Success) { Int32 yellTime = Int32.Parse(strValue); if (this._YellDuration != yellTime) { this._YellDuration = yellTime; //Once setting has been changed, upload the change to database this.QueueSettingForUpload(new CPluginVariable(@"Yell display time seconds", typeof (Int32), this._YellDuration)); } } else if (Regex.Match(strVariable, @"Pre-Message List").Success) { this._PreMessageList = new List<String>(CPluginVariable.DecodeStringArray(strValue)); //Once setting has been changed, upload the change to database this.QueueSettingForUpload(new CPluginVariable(@"Pre-Message List", typeof (String), CPluginVariable.EncodeStringArray(this._PreMessageList.ToArray()))); } else if (Regex.Match(strVariable, @"Require Use of Pre-Messages").Success) { Boolean require = Boolean.Parse(strValue); if (require != this._RequirePreMessageUse) { this._RequirePreMessageUse = require; //Once setting has been changed, upload the change to database this.QueueSettingForUpload(new CPluginVariable(@"Require Use of Pre-Messages", typeof (Boolean), this._RequirePreMessageUse)); } } else if (Regex.Match(strVariable, @"Display Admin Name in Kick and Ban Announcement").Success) { Boolean display = Boolean.Parse(strValue); if (display != this._ShowAdminNameInSay) { this._ShowAdminNameInSay = display; //Once setting has been changed, upload the change to database this.QueueSettingForUpload(new CPluginVariable(@"Display Admin Name in Kick and Ban Announcement", typeof (Boolean), this._ShowAdminNameInSay)); } } #endregion #region access settings else if (Regex.Match(strVariable, @"Add User").Success) { if (this.SoldierNameValid(strValue)) { //Create the access objectdd AdKatsUser user = new AdKatsUser { user_name = strValue }; Boolean valid = true; lock (this._UserCache) { foreach (AdKatsUser aUser in this._UserCache.Values) { if (user.user_name == aUser.user_name) { valid = false; } } } if (!valid) { this.ConsoleError("Unable to add " + user.user_name + ", a user with that user id already exists."); return; } //Queue it for processing this.QueueUserForUpload(user); } else { this.ConsoleError("User id had invalid formatting, please try again."); } } else if (Regex.Match(strVariable, @"Add Role").Success) { if (!String.IsNullOrEmpty(strValue)) { String roleName = new Regex("[^a-zA-Z0-9 _-]").Replace(strValue, ""); String roleKey = roleName.Replace(' ', '_'); if (!String.IsNullOrEmpty(roleName) && !String.IsNullOrEmpty(roleKey)) { AdKatsRole aRole = new AdKatsRole { role_key = roleKey, role_name = roleName }; //By default we should include all commands as allowed lock (this._CommandNameDictionary) { foreach (AdKatsCommand aCommand in this._CommandNameDictionary.Values) { aRole.allowedCommands.Add(aCommand.command_key, aCommand); } } //Queue it for upload this.QueueRoleForUpload(aRole); } else { this.ConsoleError("Role id had invalid characters, please try again."); } } } #endregion } catch (Exception e) { this.HandleException(new AdKatsException("Error occured while updating AdKats settings.", e)); } }
//DONE private void RemoveRole(AdKatsRole aRole) { DebugWrite("removeRole starting!", 6); //Make sure database connection active if (this.HandlePossibleDisconnect()) { return; } try { //Assign "Default Guest" to all users currently on this role AdKatsRole guestRole = null; if (this._RoleKeyDictionary.TryGetValue("guest_default", out guestRole)) { foreach (AdKatsUser aUser in this._UserCache.Values) { if (aUser.user_role.role_key == aRole.role_key) { aUser.user_role = guestRole; } this.UploadUser(aUser); } } else { this.ConsoleError("Could not fetch default guest user role. Unsafe to remove requested user role."); return; } using (MySqlConnection connection = this.GetDatabaseConnection()) { //Delete all role commands for this role using (MySqlCommand command = connection.CreateCommand()) { //Set the insert command structure command.CommandText = "DELETE FROM `" + this._MySqlDatabaseName + "`.`adkats_rolecommands` WHERE `role_id` = @role_id"; //Set values command.Parameters.AddWithValue("@role_id", aRole.role_id); //Attempt to execute the query Int32 rowsAffected = command.ExecuteNonQuery(); } //Finally delete the role using (MySqlCommand command = connection.CreateCommand()) { //Set the insert command structure command.CommandText = "DELETE FROM `" + this._MySqlDatabaseName + "`.`adkats_roles` WHERE `role_id` = @role_id"; //Set values command.Parameters.AddWithValue("@role_id", aRole.role_id); //Attempt to execute the query Int32 rowsAffected = command.ExecuteNonQuery(); } } } catch (Exception e) { this.HandleException(new AdKatsException("Error while removing user.", e)); } DebugWrite("removeRole finished!", 6); }
//DONE private void UploadRole(AdKatsRole aRole) { DebugWrite("uploadRole starting!", 6); //Make sure database connection active if (this.HandlePossibleDisconnect()) { return; } try { lock (aRole) { lock (aRole.allowedCommands) { this.DebugWrite("Uploading role: " + aRole.role_name, 5); //Open db connection using (MySqlConnection connection = this.GetDatabaseConnection()) { //Upload/Update the main role object using (MySqlCommand command = connection.CreateCommand()) { //Set the insert command structure command.CommandText = @" INSERT INTO `adkats_roles` ( `role_key`, `role_name` ) VALUES ( @role_key, @role_name ) ON DUPLICATE KEY UPDATE `role_key` = @role_key, `role_name` = @role_name"; //Set values command.Parameters.AddWithValue("@role_key", aRole.role_key); command.Parameters.AddWithValue("@role_name", aRole.role_name); //Attempt to execute the query Int32 rowsAffected = command.ExecuteNonQuery(); if (rowsAffected > 0) { //Set the user's new ID if new if (aRole.role_id < 0) { aRole.role_id = command.LastInsertedId; } this.DebugWrite("Role uploaded to database SUCCESSFULY.", 5); } else { this.ConsoleError("Unable to upload role " + aRole.role_name + " to database."); return; } } //Delete all current allowed commands using (MySqlCommand command = connection.CreateCommand()) { command.CommandText = @"DELETE FROM `adkats_rolecommands` where `role_id` = " + aRole.role_id; //Attempt to execute the query Int32 rowsAffected = command.ExecuteNonQuery(); } foreach (AdKatsCommand aCommand in aRole.allowedCommands.Values) { //Upload the role's allowed commands using (MySqlCommand command = connection.CreateCommand()) { //Set the insert command structure command.CommandText = @" INSERT INTO `adkats_rolecommands` ( `role_id`, `command_id` ) VALUES ( @role_id, @command_id ) ON DUPLICATE KEY UPDATE `role_id` = @role_id, `command_id` = @command_id"; //Set values command.Parameters.AddWithValue("@role_id", aRole.role_id); command.Parameters.AddWithValue("@command_id", aCommand.command_id); //Attempt to execute the query Int32 rowsAffected = command.ExecuteNonQuery(); if (rowsAffected > 0) { //Set the user's new ID if new if (aRole.role_id < 0) { aRole.role_id = command.LastInsertedId; } this.DebugWrite("Role-command uploaded to database SUCCESSFULY.", 5); } else { this.ConsoleError("Unable to upload role-command for " + aRole.role_name + "."); return; } } } } } } } catch (Exception e) { this.HandleException(new AdKatsException("Error while uploading role.", e)); } DebugWrite("uploadRole finished!", 6); }
public void SetPluginVariable(String strVariable, String strValue) { if (strValue == null) { return; } try { if (strVariable == "UpdateSettings") { //Do nothing. Settings page will be updated after return. } else if (Regex.Match(strVariable, @"Auto-Enable/Keep-Alive").Success) { Boolean autoEnable = Boolean.Parse(strValue); if (autoEnable != _useKeepAlive) { if (autoEnable) Enable(); _useKeepAlive = autoEnable; //Once setting has been changed, upload the change to database QueueSettingForUpload(new CPluginVariable(@"Auto-Enable/Keep-Alive", typeof (Boolean), _useKeepAlive)); } } else if (Regex.Match(strVariable, @"Unlock Settings").Success) { if (String.IsNullOrEmpty(strValue) || strValue.Length < 5) { return; } if (strValue != _settingsPassword) { ConsoleError("Password incorrect."); return; } _settingsLocked = false; ConsoleSuccess("Settings unlocked."); QueueSettingForUpload(new CPluginVariable(@"Settings Locked", typeof (Boolean), _settingsLocked)); } else if (Regex.Match(strVariable, @"Lock Settings - Create Password").Success) { if (String.IsNullOrEmpty(strValue) || strValue.Length < 5) { ConsoleError("Password had invalid format/length, unable to submit."); return; } _settingsPassword = strValue; _settingsLocked = true; ConsoleSuccess("Password created. Settings Locked."); QueueSettingForUpload(new CPluginVariable(@"Settings Password", typeof (String), _settingsPassword)); QueueSettingForUpload(new CPluginVariable(@"Settings Locked", typeof (Boolean), _settingsLocked)); } else if (Regex.Match(strVariable, @"Lock Settings").Success) { if (String.IsNullOrEmpty(strValue) || strValue.Length < 5) { return; } if (strValue != _settingsPassword) { ConsoleError("Password incorrect."); return; } _settingsLocked = true; ConsoleSuccess("Settings locked."); QueueSettingForUpload(new CPluginVariable(@"Settings Locked", typeof (Boolean), _settingsLocked)); } else if (Regex.Match(strVariable, @"Settings Password").Success) { if (String.IsNullOrEmpty(strValue) || strValue.Length < 5) { return; } _settingsPassword = strValue; } else if (Regex.Match(strVariable, @"Settings Locked").Success) { _settingsLocked = Boolean.Parse(strValue); } else if (Regex.Match(strVariable, @"Send Query").Success) { SendQuery(strValue, true); } else if (Regex.Match(strVariable, @"Send Non-Query").Success) { SendNonQuery("Experimental Query", strValue, true); } else if (Regex.Match(strVariable, @"Hacker-Check Player").Success) { //Create new thread to run hack check var statCheckingThread = new Thread(new ThreadStart(delegate { try { Thread.CurrentThread.Name = "SpecialHackerCheck"; if (String.IsNullOrEmpty(strValue) || !_threadsReady) { return; } ConsoleWarn("Preparing to hacker check " + strValue); if (String.IsNullOrEmpty(strValue) || strValue.Length < 3) { ConsoleError("Player name must be at least 3 characters long."); return; } if (!SoldierNameValid(strValue)) { ConsoleError("Player name contained invalid characters."); return; } var aPlayer = new AdKatsPlayer { player_name = strValue }; FetchPlayerStats(aPlayer); if (aPlayer.stats != null) { RunStatSiteHackCheck(aPlayer, true); } else { ConsoleError("Stats not found for " + strValue); } } catch (Exception e) { HandleException(new AdKatsException("Error while manual stat checking player.", e)); } LogThreadExit(); })); //Start the thread StartAndLogThread(statCheckingThread); } else if (Regex.Match(strVariable, @"Setting Import").Success) { Int32 tmp = -1; if (int.TryParse(strValue, out tmp)) { if (tmp != -1) QueueSettingImport(tmp); } else { ConsoleError("Invalid Input for Setting Import"); } } else if (Regex.Match(strVariable, @"Using AdKats WebAdmin").Success) { Boolean tmp = false; if (Boolean.TryParse(strValue, out tmp)) { _UsingAwa = tmp; //Update necessary settings for AWA use if (_UsingAwa) { _UseBanEnforcer = true; _fetchActionsFromDb = true; _DbCommunicationWaitHandle.Set(); } } else { ConsoleError("Invalid Input for Using AdKats WebAdmin"); } } else if (Regex.Match(strVariable, @"Command Entry").Success) { if (String.IsNullOrEmpty(strValue)) { return; } //Check if the message is a command if (strValue.StartsWith("@") || strValue.StartsWith("!") || strValue.StartsWith(".")) { strValue = strValue.Substring(1); } else if (strValue.StartsWith("/@") || strValue.StartsWith("/!") || strValue.StartsWith("/.")) { strValue = strValue.Substring(2); } else if (strValue.StartsWith("/")) { strValue = strValue.Substring(1); } else { ConsoleError("Invalid command format."); return; } var record = new AdKatsRecord { record_source = AdKatsRecord.Sources.Settings, source_name = "SettingsAdmin" }; CompleteRecordInformation(record, strValue); } else if (Regex.Match(strVariable, @"Debug level").Success) { Int32 tmp; if (int.TryParse(strValue, out tmp)) { if (tmp == 23548) { Boolean wasAuth = _isTestingAuthorized; _isTestingAuthorized = true; if (!wasAuth) { ConsoleWrite("Server is priviledged for testing during this instance."); } } else if (tmp != _debugLevel) { _debugLevel = tmp; //Once setting has been changed, upload the change to database QueueSettingForUpload(new CPluginVariable(@"Debug level", typeof (int), _debugLevel)); } } } else if (Regex.Match(strVariable, @"Debug Soldier Name").Success) { if (SoldierNameValid(strValue)) { if (strValue != _debugSoldierName) { _debugSoldierName = strValue; //Once setting has been changed, upload the change to database QueueSettingForUpload(new CPluginVariable(@"Debug Soldier Name", typeof (String), _debugSoldierName)); } } } else if (Regex.Match(strVariable, @"Maximum Temp-Ban Duration Minutes").Success) { Double maxDuration = Double.Parse(strValue); if (maxDuration <= 0) { ConsoleError("Max duration cannot be negative."); return; } TimeSpan tempMaxDur = TimeSpan.FromMinutes(maxDuration); if (tempMaxDur.TotalDays > 3650) { ConsoleError("Max duration cannot be longer than 10 years."); return; } _MaxTempBanDuration = tempMaxDur; //Once setting has been changed, upload the change to database QueueSettingForUpload(new CPluginVariable(@"Maximum Temp-Ban Duration Minutes", typeof(Double), _MaxTempBanDuration.TotalMinutes)); } else if (Regex.Match(strVariable, @"Server VOIP Address").Success) { if (strValue != _ServerVoipAddress) { _ServerVoipAddress = strValue; //Once setting has been changed, upload the change to database QueueSettingForUpload(new CPluginVariable(@"Server VOIP Address", typeof (String), _ServerVoipAddress)); } } else if (Regex.Match(strVariable, @"Rule Print Delay").Success) { Double delay = Double.Parse(strValue); if (_ServerRulesDelay != delay) { if (delay <= 0) { ConsoleError("Delay cannot be negative."); delay = 1.0; } _ServerRulesDelay = delay; //Once setting has been changed, upload the change to database QueueSettingForUpload(new CPluginVariable(@"Rule Print Delay", typeof(Double), _ServerRulesDelay)); } } else if (Regex.Match(strVariable, @"Rule Print Interval").Success) { Double interval = Double.Parse(strValue); if (_ServerRulesInterval != interval) { if (interval <= 0) { ConsoleError("Interval cannot be negative."); interval = 5.0; } _ServerRulesInterval = interval; //Once setting has been changed, upload the change to database QueueSettingForUpload(new CPluginVariable(@"Rule Print Interval", typeof(Double), _ServerRulesInterval)); } } else if (Regex.Match(strVariable, @"Server Rule List").Success) { _ServerRulesList = CPluginVariable.DecodeStringArray(strValue); //Once setting has been changed, upload the change to database QueueSettingForUpload(new CPluginVariable(@"Server Rule List", typeof(String), CPluginVariable.EncodeStringArray(_ServerRulesList))); } else if (Regex.Match(strVariable, @"Server Rule Numbers").Success) { Boolean ruleNumbers = Boolean.Parse(strValue); if (ruleNumbers != _ServerRulesNumbers) { _ServerRulesNumbers = ruleNumbers; //Once setting has been changed, upload the change to database QueueSettingForUpload(new CPluginVariable(@"Server Rule Numbers", typeof(Boolean), _ServerRulesNumbers)); } } else if (Regex.Match(strVariable, @"AFK System Enable").Success) { Boolean afkSystemEnable = Boolean.Parse(strValue); if (afkSystemEnable != _AFKSystemEnable) { _AFKSystemEnable = afkSystemEnable; //Once setting has been changed, upload the change to database QueueSettingForUpload(new CPluginVariable(@"AFK System Enable", typeof(Boolean), _AFKSystemEnable)); } } else if (Regex.Match(strVariable, @"AFK Ignore Chat").Success) { Boolean afkIgnoreChat = Boolean.Parse(strValue); if (afkIgnoreChat != _AFKIgnoreChat) { _AFKIgnoreChat = afkIgnoreChat; //Once setting has been changed, upload the change to database QueueSettingForUpload(new CPluginVariable(@"AFK Ignore Chat", typeof(Boolean), _AFKIgnoreChat)); } } else if (Regex.Match(strVariable, @"AFK Auto-Kick Enable").Success) { Boolean afkAutoKickEnable = Boolean.Parse(strValue); if (afkAutoKickEnable != _AFKAutoKickEnable) { _AFKAutoKickEnable = afkAutoKickEnable; //Once setting has been changed, upload the change to database QueueSettingForUpload(new CPluginVariable(@"AFK Auto-Kick Enable", typeof(Boolean), _AFKAutoKickEnable)); } } else if (Regex.Match(strVariable, @"AFK Trigger Minutes").Success) { Double afkAutoKickDurationMinutes = Double.Parse(strValue); if (_AFKTriggerDurationMinutes != afkAutoKickDurationMinutes) { if (afkAutoKickDurationMinutes < 0) { ConsoleError("Duration cannot be negative."); return; } _AFKTriggerDurationMinutes = afkAutoKickDurationMinutes; //Once setting has been changed, upload the change to database QueueSettingForUpload(new CPluginVariable(@"AFK Trigger Minutes", typeof(Double), _AFKTriggerDurationMinutes)); } } else if (Regex.Match(strVariable, @"AFK Minimum Players").Success) { Int32 afkAutoKickMinimumPlayers = Int32.Parse(strValue); if (_AFKTriggerMinimumPlayers != afkAutoKickMinimumPlayers) { if (afkAutoKickMinimumPlayers < 0) { ConsoleError("Minimum players cannot be negative."); return; } _AFKTriggerMinimumPlayers = afkAutoKickMinimumPlayers; //Once setting has been changed, upload the change to database QueueSettingForUpload(new CPluginVariable(@"AFK Minimum Players", typeof(Int32), _AFKTriggerMinimumPlayers)); } } else if (Regex.Match(strVariable, @"AFK Ignore User List").Success) { Boolean afkIgnoreUserList = Boolean.Parse(strValue); if (afkIgnoreUserList != _AFKIgnoreUserList) { _AFKIgnoreUserList = afkIgnoreUserList; //Once setting has been changed, upload the change to database QueueSettingForUpload(new CPluginVariable(@"AFK Ignore User List", typeof(Boolean), _AFKIgnoreUserList)); } } else if (Regex.Match(strVariable, @"AFK Ignore Roles").Success) { _AFKIgnoreRoles = CPluginVariable.DecodeStringArray(strValue); //Once setting has been changed, upload the change to database QueueSettingForUpload(new CPluginVariable(@"AFK Ignore Roles", typeof(String), CPluginVariable.EncodeStringArray(_AFKIgnoreRoles))); } else if (Regex.Match(strVariable, @"Feed MULTIBalancer Whitelist").Success) { Boolean feedMTBWhite = Boolean.Parse(strValue); if (feedMTBWhite != _FeedMultiBalancerWhitelist) { _FeedMultiBalancerWhitelist = feedMTBWhite; FetchAllAccess(true); //Once setting has been changed, upload the change to database QueueSettingForUpload(new CPluginVariable(@"Feed MULTIBalancer Whitelist", typeof (Boolean), _FeedMultiBalancerWhitelist)); } } else if (Regex.Match(strVariable, @"Automatic MULTIBalancer Whitelist for Admins").Success) { Boolean feedMTBWhiteUser = Boolean.Parse(strValue); if (feedMTBWhiteUser != _FeedMultiBalancerWhitelist_UserCache) { _FeedMultiBalancerWhitelist_UserCache = feedMTBWhiteUser; FetchAllAccess(true); //Once setting has been changed, upload the change to database QueueSettingForUpload(new CPluginVariable(@"Automatic MULTIBalancer Whitelist for Admins", typeof (Boolean), _FeedMultiBalancerWhitelist_UserCache)); } } else if (Regex.Match(strVariable, @"Feed MULTIBalancer Even Dispersion List").Success) { Boolean feedMTBBlack = Boolean.Parse(strValue); if (feedMTBBlack != _FeedMultiBalancerDisperseList) { _FeedMultiBalancerDisperseList = feedMTBBlack; FetchAllAccess(true); //Once setting has been changed, upload the change to database QueueSettingForUpload(new CPluginVariable(@"Feed MULTIBalancer Even Dispersion List", typeof (Boolean), _FeedMultiBalancerDisperseList)); } } else if (Regex.Match(strVariable, @"Feed Server Reserved Slots").Success) { Boolean feedSRS = Boolean.Parse(strValue); if (feedSRS != _FeedServerReservedSlots) { _FeedServerReservedSlots = feedSRS; FetchAllAccess(true); //Once setting has been changed, upload the change to database QueueSettingForUpload(new CPluginVariable(@"Feed Server Reserved Slots", typeof (Boolean), _FeedServerReservedSlots)); } } else if (Regex.Match(strVariable, @"Automatic Reserved Slot for User Cache").Success) { Boolean feedSRSUser = Boolean.Parse(strValue); if (feedSRSUser != _FeedServerReservedSlots_UserCache) { _FeedServerReservedSlots_UserCache = feedSRSUser; FetchAllAccess(true); //Once setting has been changed, upload the change to database QueueSettingForUpload(new CPluginVariable(@"Automatic Reserved Slot for User Cache", typeof (Boolean), _FeedServerReservedSlots_UserCache)); } } else if (Regex.Match(strVariable, @"Feed Server Spectator List").Success) { Boolean feedSSL = Boolean.Parse(strValue); if (feedSSL != _FeedServerSpectatorList) { if (_gameVersion != GameVersion.BF4) { ConsoleError("This feature can only be enabled on BF4 servers."); return; } _FeedServerSpectatorList = feedSSL; FetchAllAccess(true); //Once setting has been changed, upload the change to database QueueSettingForUpload(new CPluginVariable(@"Feed Server Spectator List", typeof (Boolean), _FeedServerSpectatorList)); } } else if (Regex.Match(strVariable, @"Automatic Spectator Slot for User Cache").Success) { Boolean feedSSLUser = Boolean.Parse(strValue); if (feedSSLUser != _FeedServerSpectatorList_UserCache) { _FeedServerSpectatorList_UserCache = feedSSLUser; FetchAllAccess(true); //Once setting has been changed, upload the change to database QueueSettingForUpload(new CPluginVariable(@"Automatic Spectator Slot for User Cache", typeof (Boolean), _FeedServerSpectatorList_UserCache)); } } else if (Regex.Match(strVariable, @"Feed Stat Logger Settings").Success) { Boolean feedSLS = Boolean.Parse(strValue); if (feedSLS != _FeedStatLoggerSettings) { _FeedStatLoggerSettings = feedSLS; //Once setting has been changed, upload the change to database QueueSettingForUpload(new CPluginVariable(@"Feed Stat Logger Settings", typeof (Boolean), _FeedStatLoggerSettings)); } } else if (Regex.Match(strVariable, @"Use Experimental Tools").Success) { Boolean useEXP = Boolean.Parse(strValue); if (useEXP != _useExperimentalTools) { _useExperimentalTools = useEXP; if (_useExperimentalTools) { if (_threadsReady) { ConsoleWarn("Using experimental tools. Take caution."); } } else { ConsoleWarn("Experimental tools disabled."); _UseWeaponLimiter = false; _UseGrenadeCookCatcher = false; _UseHackerChecker = false; _UseDpsChecker = false; _UseHskChecker = false; } //Once setting has been changed, upload the change to database QueueSettingForUpload(new CPluginVariable(@"Use Experimental Tools", typeof (Boolean), _useExperimentalTools)); QueueSettingForUpload(new CPluginVariable(@"Use NO EXPLOSIVES Limiter", typeof (Boolean), _UseWeaponLimiter)); } } else if (Regex.Match(strVariable, @"Round Timer: Enable").Success) { Boolean useTimer = Boolean.Parse(strValue); if (useTimer != _useRoundTimer) { _useRoundTimer = useTimer; if (_useRoundTimer) { if (_threadsReady) { ConsoleWarn("Internal Round Timer activated, will enable on next round."); } } else { ConsoleWarn("Internal Round Timer disabled."); } //Once setting has been changed, upload the change to database QueueSettingForUpload(new CPluginVariable(@"Round Timer: Enable", typeof (Boolean), _useRoundTimer)); } } else if (Regex.Match(strVariable, @"Round Timer: Round Duration Minutes").Success) { Double duration = Double.Parse(strValue); if (_maxRoundTimeMinutes != duration) { if (duration <= 0) { duration = 30.0; } _maxRoundTimeMinutes = duration; //Once setting has been changed, upload the change to database QueueSettingForUpload(new CPluginVariable(@"Round Timer: Round Duration Minutes", typeof (Double), _maxRoundTimeMinutes)); } } else if (Regex.Match(strVariable, @"Use NO EXPLOSIVES Limiter").Success) { Boolean useLimiter = Boolean.Parse(strValue); if (useLimiter != _UseWeaponLimiter) { _UseWeaponLimiter = useLimiter; if (_UseWeaponLimiter) { if (_threadsReady) { ConsoleWarn("Internal NO EXPLOSIVES punish limit activated."); } } else { ConsoleWarn("Internal NO EXPLOSIVES punish limit disabled."); } //Once setting has been changed, upload the change to database QueueSettingForUpload(new CPluginVariable(@"Use NO EXPLOSIVES Limiter", typeof (Boolean), _UseWeaponLimiter)); } } else if (Regex.Match(strVariable, @"NO EXPLOSIVES Weapon String").Success) { if (_WeaponLimiterString != strValue) { if (!String.IsNullOrEmpty(strValue)) { _WeaponLimiterString = strValue; } else { ConsoleError("Weapon String cannot be empty."); } //Once setting has been changed, upload the change to database QueueSettingForUpload(new CPluginVariable(@"NO EXPLOSIVES Weapon String", typeof (String), _WeaponLimiterString)); } } else if (Regex.Match(strVariable, @"NO EXPLOSIVES Exception String").Success) { if (_WeaponLimiterExceptionString != strValue) { if (!String.IsNullOrEmpty(strValue)) { _WeaponLimiterExceptionString = strValue; } else { ConsoleError("Weapon exception String cannot be empty."); } //Once setting has been changed, upload the change to database QueueSettingForUpload(new CPluginVariable(@"NO EXPLOSIVES Exception String", typeof (String), _WeaponLimiterExceptionString)); } } else if (Regex.Match(strVariable, @"Use Grenade Cook Catcher").Success) { Boolean useCookCatcher = Boolean.Parse(strValue); if (useCookCatcher != _UseGrenadeCookCatcher) { _UseGrenadeCookCatcher = useCookCatcher; if (_UseGrenadeCookCatcher) { if (_threadsReady) { ConsoleWarn("Internal Grenade Cook Catcher activated."); } } else { ConsoleWarn("Internal Grenade Cook Catcher disabled."); } //Once setting has been changed, upload the change to database QueueSettingForUpload(new CPluginVariable(@"Use Grenade Cook Catcher", typeof (Boolean), _UseGrenadeCookCatcher)); } } else if (Regex.Match(strVariable, @"HackerChecker: Enable").Success) { Boolean useHackChecker = Boolean.Parse(strValue); if (useHackChecker != _UseHackerChecker) { _UseHackerChecker = useHackChecker; if (_UseHackerChecker) { if (_threadsReady) { ConsoleWarn("Internal Hacker Checker activated."); } } else { ConsoleWarn("Internal Hacker Checker disabled."); _UseDpsChecker = false; QueueSettingForUpload(new CPluginVariable(@"HackerChecker: DPS Checker: Enable", typeof (Boolean), _UseDpsChecker)); _UseHskChecker = false; QueueSettingForUpload(new CPluginVariable(@"HackerChecker: HSK Checker: Enable", typeof (Boolean), _UseHskChecker)); _UseKpmChecker = false; QueueSettingForUpload(new CPluginVariable(@"HackerChecker: KPM Checker: Enable", typeof (Boolean), _UseKpmChecker)); } //Once setting has been changed, upload the change to database QueueSettingForUpload(new CPluginVariable(@"HackerChecker: Enable", typeof (Boolean), _UseHackerChecker)); } } else if (Regex.Match(strVariable, @"HackerChecker: Whitelist").Success) { //_HackerCheckerWhitelist = CPluginVariable.DecodeStringArray(strValue); //Once setting has been changed, upload the change to database //QueueSettingForUpload(new CPluginVariable(@"HackerChecker: Whitelist", typeof (String), CPluginVariable.EncodeStringArray(_HackerCheckerWhitelist))); } else if (Regex.Match(strVariable, @"HackerChecker: DPS Checker: Enable").Success) { Boolean useDamageChecker = Boolean.Parse(strValue); if (useDamageChecker != _UseDpsChecker) { _UseDpsChecker = useDamageChecker; if (_UseDpsChecker) { if (_threadsReady) { ConsoleWarn("Internal Damage Mod Checker activated."); } } else { ConsoleWarn("Internal Damage Mod Checker disabled."); } //Once setting has been changed, upload the change to database QueueSettingForUpload(new CPluginVariable(@"HackerChecker: DPS Checker: Enable", typeof (Boolean), _UseDpsChecker)); } } else if (Regex.Match(strVariable, @"HackerChecker: DPS Checker: Trigger Level").Success) { Double triggerLevel = Double.Parse(strValue); if (_DpsTriggerLevel != triggerLevel) { if (triggerLevel <= 0) { triggerLevel = 100.0; } _DpsTriggerLevel = triggerLevel; //Once setting has been changed, upload the change to database QueueSettingForUpload(new CPluginVariable(@"HackerChecker: DPS Checker: Trigger Level", typeof (Double), _DpsTriggerLevel)); } } else if (Regex.Match(strVariable, @"HackerChecker: DPS Checker: Ban Message").Success) { if (_HackerCheckerDPSBanMessage != strValue) { _HackerCheckerDPSBanMessage = strValue; //Once setting has been changed, upload the change to database QueueSettingForUpload(new CPluginVariable(@"HackerChecker: DPS Checker: Ban Message", typeof (String), _HackerCheckerDPSBanMessage)); } } else if (Regex.Match(strVariable, @"HackerChecker: HSK Checker: Enable").Success) { Boolean useAimbotChecker = Boolean.Parse(strValue); if (useAimbotChecker != _UseHskChecker) { _UseHskChecker = useAimbotChecker; if (_UseHskChecker) { if (_threadsReady) { ConsoleWarn("Internal Aimbot Checker activated."); } } else { ConsoleWarn("Internal Aimbot Checker disabled."); } //Once setting has been changed, upload the change to database QueueSettingForUpload(new CPluginVariable(@"HackerChecker: HSK Checker: Enable", typeof (Boolean), _UseHskChecker)); } } else if (Regex.Match(strVariable, @"HackerChecker: HSK Checker: Trigger Level").Success) { Double triggerLevel = Double.Parse(strValue); if (_HskTriggerLevel != triggerLevel) { if (triggerLevel <= 0) { triggerLevel = 100.0; } _HskTriggerLevel = triggerLevel; //Once setting has been changed, upload the change to database QueueSettingForUpload(new CPluginVariable(@"HackerChecker: HSK Checker: Trigger Level", typeof (Double), _HskTriggerLevel)); } } else if (Regex.Match(strVariable, @"HackerChecker: HSK Checker: Ban Message").Success) { if (_HackerCheckerHSKBanMessage != strValue) { _HackerCheckerHSKBanMessage = strValue; //Once setting has been changed, upload the change to database QueueSettingForUpload(new CPluginVariable(@"HackerChecker: HSK Checker: Ban Message", typeof (String), _HackerCheckerHSKBanMessage)); } } else if (Regex.Match(strVariable, @"HackerChecker: KPM Checker: Enable").Success) { Boolean useKPMChecker = Boolean.Parse(strValue); if (useKPMChecker != _UseKpmChecker) { _UseKpmChecker = useKPMChecker; if (_UseKpmChecker) { if (_threadsReady) { ConsoleWarn("Internal KPM Checker activated."); } } else { ConsoleWarn("Internal KPM Checker disabled."); } //Once setting has been changed, upload the change to database QueueSettingForUpload(new CPluginVariable(@"HackerChecker: KPM Checker: Enable", typeof (Boolean), _UseKpmChecker)); } } else if (Regex.Match(strVariable, @"HackerChecker: KPM Checker: Trigger Level").Success) { Double triggerLevel = Double.Parse(strValue); if (_KpmTriggerLevel != triggerLevel) { if (triggerLevel <= 0) { triggerLevel = 100.0; } _KpmTriggerLevel = triggerLevel; //Once setting has been changed, upload the change to database QueueSettingForUpload(new CPluginVariable(@"HackerChecker: KPM Checker: Trigger Level", typeof (Double), _KpmTriggerLevel)); } } else if (Regex.Match(strVariable, @"HackerChecker: KPM Checker: Ban Message").Success) { if (_HackerCheckerKPMBanMessage != strValue) { _HackerCheckerKPMBanMessage = strValue; //Once setting has been changed, upload the change to database QueueSettingForUpload(new CPluginVariable(@"HackerChecker: KPM Checker: Ban Message", typeof (String), _HackerCheckerKPMBanMessage)); } } else if (Regex.Match(strVariable, @"External Access Key").Success) { if (strValue != _ExternalCommandAccessKey) { _ExternalCommandAccessKey = strValue; //Once setting has been changed, upload the change to database QueueSettingForUpload(new CPluginVariable(@"External Access Key", typeof (String), _ExternalCommandAccessKey)); } } else if (Regex.Match(strVariable, @"Fetch Actions from Database").Success) { Boolean fetch = Boolean.Parse(strValue); if (fetch != _fetchActionsFromDb) { _fetchActionsFromDb = fetch; _DbCommunicationWaitHandle.Set(); //Once setting has been changed, upload the change to database QueueSettingForUpload(new CPluginVariable(@"Fetch Actions from Database", typeof (Boolean), _fetchActionsFromDb)); } } else if (Regex.Match(strVariable, @"Use Additional Ban Message").Success) { Boolean use = Boolean.Parse(strValue); if (_UseBanAppend != use) { _UseBanAppend = use; //Once setting has been changed, upload the change to database QueueSettingForUpload(new CPluginVariable(@"Use Additional Ban Message", typeof (Boolean), _UseBanAppend)); } } else if (Regex.Match(strVariable, @"Additional Ban Message").Success) { if (strValue.Length > 30) { strValue = strValue.Substring(0, 30); ConsoleError("Ban append cannot be more than 30 characters."); } if (_BanAppend != strValue) { _BanAppend = strValue; //Once setting has been changed, upload the change to database QueueSettingForUpload(new CPluginVariable(@"Additional Ban Message", typeof (String), _BanAppend)); } } else if (Regex.Match(strVariable, @"Procon Ban Admin Name").Success) { if (strValue.Length > 16) { strValue = strValue.Substring(0, 16); ConsoleError("Procon ban admin id cannot be more than 16 characters."); } if (_CBanAdminName != strValue) { _CBanAdminName = strValue; //Once setting has been changed, upload the change to database QueueSettingForUpload(new CPluginVariable(@"Procon Ban Admin Name", typeof (String), _CBanAdminName)); } } else if (Regex.Match(strVariable, @"Use Ban Enforcer").Success) { Boolean use = Boolean.Parse(strValue); if (_UseBanEnforcer != use) { _UseBanEnforcer = use; //Once setting has been changed, upload the change to database QueueSettingForUpload(new CPluginVariable(@"Use Ban Enforcer", typeof (Boolean), _UseBanEnforcer)); if (_UseBanEnforcer) { _fetchActionsFromDb = true; _DbCommunicationWaitHandle.Set(); } } } else if (Regex.Match(strVariable, @"Enforce New Bans by NAME").Success) { Boolean enforceName = Boolean.Parse(strValue); if (_DefaultEnforceName != enforceName) { _DefaultEnforceName = enforceName; //Once setting has been changed, upload the change to database QueueSettingForUpload(new CPluginVariable(@"Enforce New Bans by NAME", typeof (Boolean), _DefaultEnforceName)); } } else if (Regex.Match(strVariable, @"Enforce New Bans by GUID").Success) { Boolean enforceGUID = Boolean.Parse(strValue); if (_DefaultEnforceGUID != enforceGUID) { _DefaultEnforceGUID = enforceGUID; //Once setting has been changed, upload the change to database QueueSettingForUpload(new CPluginVariable(@"Enforce New Bans by GUID", typeof (Boolean), _DefaultEnforceGUID)); } } else if (Regex.Match(strVariable, @"Enforce New Bans by IP").Success) { Boolean enforceIP = Boolean.Parse(strValue); if (_DefaultEnforceIP != enforceIP) { _DefaultEnforceIP = enforceIP; //Once setting has been changed, upload the change to database QueueSettingForUpload(new CPluginVariable(@"Enforce New Bans by IP", typeof (Boolean), _DefaultEnforceIP)); } } else if (Regex.Match(strVariable, @"Ban Search").Success) { if (_isTestingAuthorized) PushThreadDebug(DateTime.Now.Ticks, (String.IsNullOrEmpty(Thread.CurrentThread.Name) ? ("mainthread") : (Thread.CurrentThread.Name)), Thread.CurrentThread.ManagedThreadId, new System.Diagnostics.StackTrace(true).GetFrame(0).GetFileLineNumber(), ""); if (String.IsNullOrEmpty(strValue) || strValue.Length < 3) { ConsoleError("Search query must be 3 or more characters."); return; } lock (_BanEnforcerSearchResults) { _BanEnforcerSearchResults = FetchMatchingBans(strValue, 5); if (_BanEnforcerSearchResults.Count == 0) { ConsoleError("No players matching '" + strValue + "' have active bans."); } } } else if (Regex.Match(strVariable, @"Minimum Required Reason Length").Success) { Int32 required = Int32.Parse(strValue); if (_RequiredReasonLength != required) { _RequiredReasonLength = required; if (_RequiredReasonLength < 1) { _RequiredReasonLength = 1; } //Once setting has been changed, upload the change to database QueueSettingForUpload(new CPluginVariable(@"Minimum Required Reason Length", typeof (Int32), _RequiredReasonLength)); } } else if (Regex.Match(strVariable, @"Minimum Report Handle Seconds").Success) { Int32 minimumReportHandleSeconds = Int32.Parse(strValue); if (_MinimumReportHandleSeconds != minimumReportHandleSeconds) { _MinimumReportHandleSeconds = minimumReportHandleSeconds; if (_MinimumReportHandleSeconds < 0) { _MinimumReportHandleSeconds = 0; } //Once setting has been changed, upload the change to database QueueSettingForUpload(new CPluginVariable(@"Minimum Report Handle Seconds", typeof (Int32), _MinimumReportHandleSeconds)); } } else if (Regex.Match(strVariable, @"Allow Commands from Admin Say").Success) { Boolean allowSayCommands = Boolean.Parse(strValue); if (_AllowAdminSayCommands != allowSayCommands) { _AllowAdminSayCommands = allowSayCommands; //Once setting has been changed, upload the change to database QueueSettingForUpload(new CPluginVariable(@"Allow Commands from Admin Say", typeof (Boolean), _AllowAdminSayCommands)); } } else if (Regex.Match(strVariable, @"External plugin player commands").Success) { _ExternalPlayerCommands = new List<String>(CPluginVariable.DecodeStringArray(strValue)); //Once setting has been changed, upload the change to database QueueSettingForUpload(new CPluginVariable(@"External plugin player commands", typeof(String), CPluginVariable.EncodeStringArray(_ExternalPlayerCommands.ToArray()))); } else if (Regex.Match(strVariable, @"External plugin admin commands").Success) { _ExternalAdminCommands = new List<String>(CPluginVariable.DecodeStringArray(strValue)); //Once setting has been changed, upload the change to database QueueSettingForUpload(new CPluginVariable(@"External plugin admin commands", typeof(String), CPluginVariable.EncodeStringArray(_ExternalAdminCommands.ToArray()))); } else if (strVariable.StartsWith("USR")) { //USR1 | ColColonCleaner | User Email //USR1 | ColColonCleaner | User Phone //USR1 | ColColonCleaner | User Role //USR1 | ColColonCleaner | Delete User? //USR1 | ColColonCleaner | Add Soldier? //USR1 | ColColonCleaner | Soldiers | 293492 | ColColonCleaner | Delete Soldier? String[] commandSplit = CPluginVariable.DecodeStringArray(strVariable); String user_id_str = commandSplit[0].TrimStart("USR".ToCharArray()).Trim(); Int32 user_id = Int32.Parse(user_id_str); String section = commandSplit[2].Trim(); AdKatsUser aUser = null; if (_userCache.TryGetValue(user_id, out aUser)) { switch (section) { case "User Email": if (String.IsNullOrEmpty(strValue) || Regex.IsMatch(strValue, @"^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$")) { aUser.user_email = strValue; //Reupload the user QueueUserForUpload(aUser); } else { ConsoleError(strValue + " is an invalid email address."); return; } break; case "User Expiration": DateTime newExpiration; if (DateTime.TryParse(strValue, out newExpiration)) { aUser.user_expiration = newExpiration; //Reupload the user QueueUserForUpload(aUser); } else { ConsoleError(strValue + " is an invalid date."); } break; case "User Notes": if (String.IsNullOrEmpty(strValue)) { ConsoleError("User notes cannot be blank."); return; } aUser.user_notes = strValue; //Reupload the user QueueUserForUpload(aUser); break; case "User Phone": aUser.user_phone = strValue; //Reupload the user QueueUserForUpload(aUser); break; case "User Role": AdKatsRole aRole = null; if (_RoleNameDictionary.TryGetValue(strValue, out aRole)) { aUser.user_role = aRole; } else { ConsoleError("Role " + strValue + " not found."); return; } //Reupload the user QueueUserForUpload(aUser); break; case "Delete User?": if (strValue.ToLower() == "delete") { QueueUserForRemoval(aUser); } break; case "Add Soldier?": var addSoldierThread = new Thread(new ThreadStart(delegate { Thread.CurrentThread.Name = "addsoldier"; DebugWrite("Starting a user change thread.", 2); TryAddUserSoldier(aUser, strValue); QueueUserForUpload(aUser); DebugWrite("Exiting a user change thread.", 2); LogThreadExit(); })); StartAndLogThread(addSoldierThread); break; case "Soldiers": if (strVariable.Contains("Delete Soldier?") && strValue.ToLower() == "delete") { String player_id_str = commandSplit[3].Trim(); Int64 player_id = Int64.Parse(player_id_str); aUser.soldierDictionary.Remove(player_id); //Reupload the user QueueUserForUpload(aUser); } break; default: ConsoleError("Section " + section + " not found."); break; } } } else if (strVariable.StartsWith("CDE")) { //Trim off all but the command ID and section //5. Command List|CDE1 | Kill Player | Active //5. Command List|CDE1 | Kill Player | Logging //5. Command List|CDE1 | Kill Player | Text String[] commandSplit = CPluginVariable.DecodeStringArray(strVariable); String command_id_str = commandSplit[0].TrimStart("CDE".ToCharArray()).Trim(); Int32 command_id = Int32.Parse(command_id_str); String section = commandSplit[2].Trim(); AdKatsCommand command = null; if (_CommandIDDictionary.TryGetValue(command_id, out command)) { if (section == "Active") { //Check for valid value if (strValue == "Active") { command.command_active = AdKatsCommand.CommandActive.Active; } else if (strValue == "Disabled") { command.command_active = AdKatsCommand.CommandActive.Disabled; } else if (strValue == "Invisible") { command.command_active = AdKatsCommand.CommandActive.Invisible; } else { ConsoleError("Activity setting " + strValue + " was invalid."); return; } } else if (section == "Logging") { //Check for valid value switch (strValue) { case "Log": command.command_logging = AdKatsCommand.CommandLogging.Log; break; case "Mandatory": command.command_logging = AdKatsCommand.CommandLogging.Mandatory; break; case "Ignore": command.command_logging = AdKatsCommand.CommandLogging.Ignore; break; case "Unable": command.command_logging = AdKatsCommand.CommandLogging.Unable; break; default: ConsoleError("Logging setting " + strValue + " was invalid."); return; } } else if (section == "Text") { if (String.IsNullOrEmpty(strValue)) { ConsoleError("Command text cannot be blank."); return; } //Make sure command text only contains alphanumeric chars, underscores, and dashes var rgx = new Regex("[^a-zA-Z0-9_-]"); strValue = rgx.Replace(strValue, "").ToLower(); //Check to make sure text is not a duplicate foreach (AdKatsCommand testCommand in _CommandNameDictionary.Values) { if (testCommand.command_text == strValue) { ConsoleError("Command text cannot be the same as another command."); return; } } //Assign the command text if (_isTestingAuthorized) PushThreadDebug(DateTime.Now.Ticks, (String.IsNullOrEmpty(Thread.CurrentThread.Name) ? ("mainthread") : (Thread.CurrentThread.Name)), Thread.CurrentThread.ManagedThreadId, new System.Diagnostics.StackTrace(true).GetFrame(0).GetFileLineNumber(), ""); lock (_CommandTextDictionary) { _CommandTextDictionary.Remove(command.command_text); command.command_text = strValue; _CommandTextDictionary.Add(command.command_text, command); } } else { ConsoleError("Section " + section + " not understood."); return; } //Upload the command changes QueueCommandForUpload(command); } else { ConsoleError("Command " + command_id + " not found in command dictionary."); } } else if (strVariable.StartsWith("RLE")) { //Trim off all but the role ID and section //RLE1 | Default Guest | CDE3 | Kill Player String[] commandSplit = CPluginVariable.DecodeStringArray(strVariable); String roleIDStr = commandSplit[0].TrimStart("RLE".ToCharArray()).Trim(); Int32 roleID = Int32.Parse(roleIDStr); //If second section is a command prefix, this is the allow/deny clause if (commandSplit[2].Trim().StartsWith("CDE")) { String commandIDStr = commandSplit[2].Trim().TrimStart("CDE".ToCharArray()); Int32 commandID = Int32.Parse(commandIDStr); //Fetch needed role AdKatsRole aRole = null; if (_RoleIDDictionary.TryGetValue(roleID, out aRole)) { //Fetch needed command AdKatsCommand aCommand = null; if (_CommandIDDictionary.TryGetValue(commandID, out aCommand)) { switch (strValue.ToLower()) { case "allow": if (_isTestingAuthorized) PushThreadDebug(DateTime.Now.Ticks, (String.IsNullOrEmpty(Thread.CurrentThread.Name) ? ("mainthread") : (Thread.CurrentThread.Name)), Thread.CurrentThread.ManagedThreadId, new System.Diagnostics.StackTrace(true).GetFrame(0).GetFileLineNumber(), ""); lock (aRole.RoleAllowedCommands) { if (!aRole.RoleAllowedCommands.ContainsKey(aCommand.command_key)) { aRole.RoleAllowedCommands.Add(aCommand.command_key, aCommand); } } QueueRoleForUpload(aRole); break; case "deny": if (_isTestingAuthorized) PushThreadDebug(DateTime.Now.Ticks, (String.IsNullOrEmpty(Thread.CurrentThread.Name) ? ("mainthread") : (Thread.CurrentThread.Name)), Thread.CurrentThread.ManagedThreadId, new System.Diagnostics.StackTrace(true).GetFrame(0).GetFileLineNumber(), ""); lock (aRole.RoleAllowedCommands) { aRole.RoleAllowedCommands.Remove(aCommand.command_key); } QueueRoleForUpload(aRole); break; default: ConsoleError("Unknown setting when assigning command allowance."); return; } } else { ConsoleError("Command " + commandID + " not found in command dictionary."); } } else { ConsoleError("Role " + roleID + " not found in role dictionary."); } } else if (commandSplit[2].Contains("Delete Role?") && strValue.ToLower() == "delete") { //Fetch needed role AdKatsRole aRole = null; if (_RoleIDDictionary.TryGetValue(roleID, out aRole)) { QueueRoleForRemoval(aRole); } else { ConsoleError("Unable to fetch role for deletion."); } } } else if (strVariable.StartsWith("BAN")) { //Trim off all but the command ID and section //BAN1 | ColColonCleaner | Some Reason String[] commandSplit = CPluginVariable.DecodeStringArray(strVariable); String banIDStr = commandSplit[0].TrimStart("BAN".ToCharArray()).Trim(); Int32 banID = Int32.Parse(banIDStr); AdKatsBan aBan = null; foreach (AdKatsBan innerBan in _BanEnforcerSearchResults) { if (innerBan.ban_id == banID) { aBan = innerBan; break; } } if (aBan != null) { switch (strValue) { case "Active": aBan.ban_status = strValue; break; case "Disabled": aBan.ban_status = strValue; break; default: ConsoleError("Unknown setting when assigning ban status."); return; } UpdateBanStatus(aBan); ConsoleSuccess("Ban " + aBan.ban_id + " is now " + strValue); } else { ConsoleError("Unable to update ban. This should not happen."); } } else if (Regex.Match(strVariable, @"Punishment Hierarchy").Success) { _PunishmentHierarchy = CPluginVariable.DecodeStringArray(strValue); //Once setting has been changed, upload the change to database QueueSettingForUpload(new CPluginVariable(@"Punishment Hierarchy", typeof (String), CPluginVariable.EncodeStringArray(_PunishmentHierarchy))); } else if (Regex.Match(strVariable, @"Combine Server Punishments").Success) { Boolean combine = Boolean.Parse(strValue); if (_CombineServerPunishments != combine) { _CombineServerPunishments = combine; //Once setting has been changed, upload the change to database QueueSettingForUpload(new CPluginVariable(@"Combine Server Punishments", typeof (Boolean), _CombineServerPunishments)); } } else if (Regex.Match(strVariable, @"Only Kill Players when Server in low population").Success) { Boolean onlyKill = Boolean.Parse(strValue); if (onlyKill != _OnlyKillOnLowPop) { _OnlyKillOnLowPop = onlyKill; //Once setting has been changed, upload the change to database QueueSettingForUpload(new CPluginVariable(@"Only Kill Players when Server in low population", typeof (Boolean), _OnlyKillOnLowPop)); } } else if (Regex.Match(strVariable, @"Low Population Value").Success) { Int32 lowPop = Int32.Parse(strValue); if (lowPop != _lowPopulationPlayerCount) { _lowPopulationPlayerCount = lowPop; //Once setting has been changed, upload the change to database QueueSettingForUpload(new CPluginVariable(@"Low Population Value", typeof (Int32), _lowPopulationPlayerCount)); } } else if (Regex.Match(strVariable, @"Use IRO Punishment").Success) { Boolean iro = Boolean.Parse(strValue); if (iro != _IROActive) { _IROActive = iro; //Once setting has been changed, upload the change to database QueueSettingForUpload(new CPluginVariable(@"Use IRO Punishment", typeof (Boolean), _IROActive)); } } else if (Regex.Match(strVariable, @"IRO Punishment Overrides Low Pop").Success) { Boolean overrideIRO = Boolean.Parse(strValue); if (overrideIRO != _IROOverridesLowPop) { _IROOverridesLowPop = overrideIRO; //Once setting has been changed, upload the change to database QueueSettingForUpload(new CPluginVariable(@"IRO Punishment Overrides Low Pop", typeof (Boolean), _IROOverridesLowPop)); } } else if (Regex.Match(strVariable, @"IRO Timeout Minutes").Success) { Int32 timeout = Int32.Parse(strValue); if (timeout != _IROTimeout) { _IROTimeout = timeout; //Once setting has been changed, upload the change to database QueueSettingForUpload(new CPluginVariable(@"IRO Timeout Minutes", typeof(Int32), _IROTimeout)); } } else if (Regex.Match(strVariable, @"MySQL Hostname").Success) { _mySqlHostname = strValue; _dbSettingsChanged = true; _DbCommunicationWaitHandle.Set(); } else if (Regex.Match(strVariable, @"MySQL Port").Success) { Int32 tmp = 3306; int.TryParse(strValue, out tmp); if (tmp > 0 && tmp < 65536) { _mySqlPort = strValue; _dbSettingsChanged = true; _DbCommunicationWaitHandle.Set(); } else { ConsoleError("Invalid value for MySQL Port: '" + strValue + "'. Must be number between 1 and 65535!"); } } else if (Regex.Match(strVariable, @"MySQL Database").Success) { _mySqlDatabaseName = strValue; _dbSettingsChanged = true; _DbCommunicationWaitHandle.Set(); } else if (Regex.Match(strVariable, @"MySQL Username").Success) { _mySqlUsername = strValue; _dbSettingsChanged = true; _DbCommunicationWaitHandle.Set(); } else if (Regex.Match(strVariable, @"MySQL Password").Success) { _mySqlPassword = strValue; _dbSettingsChanged = true; _DbCommunicationWaitHandle.Set(); } else if (Regex.Match(strVariable, @"Send Emails").Success) { //Disabled _UseEmail = Boolean.Parse(strValue); //Once setting has been changed, upload the change to database QueueSettingForUpload(new CPluginVariable("Send Emails", typeof (Boolean), _UseEmail)); } else if (Regex.Match(strVariable, @"Use SSL?").Success) { _EmailHandler.UseSSL = Boolean.Parse(strValue); //Once setting has been changed, upload the change to database QueueSettingForUpload(new CPluginVariable("Use SSL?", typeof (Boolean), _EmailHandler.UseSSL)); } else if (Regex.Match(strVariable, @"SMTP-Server address").Success) { if (!String.IsNullOrEmpty(strValue)) { _EmailHandler.SMTPServer = strValue; //Once setting has been changed, upload the change to database QueueSettingForUpload(new CPluginVariable("SMTP-Server address", typeof (String), _EmailHandler.SMTPServer)); } } else if (Regex.Match(strVariable, @"SMTP-Server port").Success) { Int32 iPort = Int32.Parse(strValue); if (iPort > 0) { _EmailHandler.SMTPPort = iPort; //Once setting has been changed, upload the change to database QueueSettingForUpload(new CPluginVariable("SMTP-Server port", typeof (Int32), _EmailHandler.SMTPPort)); } } else if (Regex.Match(strVariable, @"Sender address").Success) { if (string.IsNullOrEmpty(strValue)) { _EmailHandler.SenderEmail = "SENDER_CANNOT_BE_EMPTY"; ConsoleError("No sender for email was given! Canceling Operation."); } else { _EmailHandler.SenderEmail = strValue; //Once setting has been changed, upload the change to database QueueSettingForUpload(new CPluginVariable("Sender address", typeof (String), _EmailHandler.SenderEmail)); } } else if (Regex.Match(strVariable, @"SMTP-Server username").Success) { if (string.IsNullOrEmpty(strValue)) { _EmailHandler.SMTPUser = "******"; ConsoleError("No username for SMTP was given! Canceling Operation."); } else { _EmailHandler.SMTPUser = strValue; //Once setting has been changed, upload the change to database QueueSettingForUpload(new CPluginVariable("SMTP-Server username", typeof (String), _EmailHandler.SMTPUser)); } } else if (Regex.Match(strVariable, @"SMTP-Server password").Success) { if (string.IsNullOrEmpty(strValue)) { _EmailHandler.SMTPPassword = "******"; ConsoleError("No password for SMTP was given! Canceling Operation."); } else { _EmailHandler.SMTPPassword = strValue; //Once setting has been changed, upload the change to database QueueSettingForUpload(new CPluginVariable("SMTP-Server password", typeof (String), _EmailHandler.SMTPPassword)); } } else if (Regex.Match(strVariable, @"Custom HTML Addition").Success) { _EmailHandler.CustomHTMLAddition = strValue; //Once setting has been changed, upload the change to database QueueSettingForUpload(new CPluginVariable("Custom HTML Addition", typeof (String), _EmailHandler.CustomHTMLAddition)); } else if (Regex.Match(strVariable, @"Extra Recipient Email Addresses").Success) { _EmailHandler.RecipientEmails = CPluginVariable.DecodeStringArray(strValue).ToList(); //Once setting has been changed, upload the change to database QueueSettingForUpload(new CPluginVariable(@"Extra Recipient Email Addresses", typeof (String), strValue)); } else if (Regex.Match(strVariable, @"Use Metabans?").Success) { _useMetabans = Boolean.Parse(strValue); //Once setting has been changed, upload the change to database QueueSettingForUpload(new CPluginVariable("Use Metabans?", typeof (Boolean), _useMetabans)); } else if (Regex.Match(strVariable, @"Metabans API Key").Success) { if (string.IsNullOrEmpty(strValue)) { _metabansAPIKey = ""; ConsoleError("No API key for Metabans was given! Canceling Operation."); } else { _metabansAPIKey = strValue; //Once setting has been changed, upload the change to database QueueSettingForUpload(new CPluginVariable(@"Metabans API Key", typeof (String), _metabansAPIKey)); } } else if (Regex.Match(strVariable, @"Metabans Username").Success) { if (string.IsNullOrEmpty(strValue)) { _metabansUsername = ""; ConsoleError("No username for Metabans was given! Canceling Operation."); } else { _metabansUsername = strValue; //Once setting has been changed, upload the change to database QueueSettingForUpload(new CPluginVariable(@"Metabans Username", typeof (String), _metabansUsername)); } } else if (Regex.Match(strVariable, @"On-Player-Muted Message").Success) { if (_MutedPlayerMuteMessage != strValue) { _MutedPlayerMuteMessage = strValue; //Once setting has been changed, upload the change to database QueueSettingForUpload(new CPluginVariable(@"On-Player-Muted Message", typeof (String), _MutedPlayerMuteMessage)); } } else if (Regex.Match(strVariable, @"On-Player-Killed Message").Success) { if (_MutedPlayerKillMessage != strValue) { _MutedPlayerKillMessage = strValue; //Once setting has been changed, upload the change to database QueueSettingForUpload(new CPluginVariable(@"On-Player-Killed Message", typeof (String), _MutedPlayerKillMessage)); } } else if (Regex.Match(strVariable, @"On-Player-Kicked Message").Success) { if (_MutedPlayerKickMessage != strValue) { _MutedPlayerKickMessage = strValue; //Once setting has been changed, upload the change to database QueueSettingForUpload(new CPluginVariable(@"On-Player-Kicked Message", typeof (String), _MutedPlayerKickMessage)); } } if (Regex.Match(strVariable, @"# Chances to give player before kicking").Success) { Int32 tmp = 5; int.TryParse(strValue, out tmp); if (_MutedPlayerChances != tmp) { _MutedPlayerChances = tmp; //Once setting has been changed, upload the change to database QueueSettingForUpload(new CPluginVariable(@"# Chances to give player before kicking", typeof (Int32), _MutedPlayerChances)); } } else if (Regex.Match(strVariable, @"Ignore commands for mute enforcement").Success) { Boolean ignoreCommands = Boolean.Parse(strValue); if (_MutedPlayerIgnoreCommands != ignoreCommands) { _MutedPlayerIgnoreCommands = ignoreCommands; //Once setting has been changed, upload the change to database QueueSettingForUpload(new CPluginVariable(@"Ignore commands for mute enforcement", typeof(Boolean), _MutedPlayerIgnoreCommands)); } } else if (Regex.Match(strVariable, @"Ticket Window High").Success) { Int32 tmp = 2; int.TryParse(strValue, out tmp); if (tmp != _TeamSwapTicketWindowHigh) { _TeamSwapTicketWindowHigh = tmp; //Once setting has been changed, upload the change to database QueueSettingForUpload(new CPluginVariable(@"Ticket Window High", typeof (Int32), _TeamSwapTicketWindowHigh)); } } else if (Regex.Match(strVariable, @"Ticket Window Low").Success) { Int32 tmp = 2; int.TryParse(strValue, out tmp); if (tmp != _TeamSwapTicketWindowLow) { _TeamSwapTicketWindowLow = tmp; //Once setting has been changed, upload the change to database QueueSettingForUpload(new CPluginVariable(@"Ticket Window Low", typeof (Int32), _TeamSwapTicketWindowLow)); } } else if (Regex.Match(strVariable, @"Enable Admin Assistants").Success) { Boolean enableAA = Boolean.Parse(strValue); if (_EnableAdminAssistants != enableAA) { _EnableAdminAssistants = enableAA; //Once setting has been changed, upload the change to database QueueSettingForUpload(new CPluginVariable(@"Enable Admin Assistants", typeof (Boolean), _EnableAdminAssistants)); } } else if (Regex.Match(strVariable, @"Enable Admin Assistant Perk").Success) { Boolean enableAA = Boolean.Parse(strValue); if (_EnableAdminAssistantPerk != enableAA) { _EnableAdminAssistantPerk = enableAA; //Once setting has been changed, upload the change to database QueueSettingForUpload(new CPluginVariable(@"Enable Admin Assistant Perk", typeof (Boolean), _EnableAdminAssistantPerk)); } } else if (Regex.Match(strVariable, @"Use AA Report Auto Handler").Success) { Boolean useAAHandler = Boolean.Parse(strValue); if (useAAHandler != _UseAAReportAutoHandler) { _UseAAReportAutoHandler = useAAHandler; if (_UseAAReportAutoHandler) { if (_threadsReady) { ConsoleWarn("Internal Automatic Report Handler activated."); } } else { ConsoleWarn("Internal Automatic Report Handler disabled."); } //Once setting has been changed, upload the change to database QueueSettingForUpload(new CPluginVariable(@"Use AA Report Auto Handler", typeof (Boolean), _UseAAReportAutoHandler)); } } else if (Regex.Match(strVariable, @"Auto-Report-Handler Strings").Success) { _AutoReportHandleStrings = CPluginVariable.DecodeStringArray(strValue); //Once setting has been changed, upload the change to database QueueSettingForUpload(new CPluginVariable(@"Auto-Report-Handler Strings", typeof (String), CPluginVariable.EncodeStringArray(_AutoReportHandleStrings))); } else if (Regex.Match(strVariable, @"Minimum Confirmed Reports Per Month").Success) { Int32 monthlyReports = Int32.Parse(strValue); if (_MinimumRequiredMonthlyReports != monthlyReports) { _MinimumRequiredMonthlyReports = monthlyReports; //Once setting has been changed, upload the change to database QueueSettingForUpload(new CPluginVariable(@"Minimum Confirmed Reports Per Month", typeof (Int32), _MinimumRequiredMonthlyReports)); } } else if (Regex.Match(strVariable, @"Yell display time seconds").Success) { Int32 yellTime = Int32.Parse(strValue); if (_YellDuration != yellTime) { _YellDuration = yellTime; //Once setting has been changed, upload the change to database QueueSettingForUpload(new CPluginVariable(@"Yell display time seconds", typeof (Int32), _YellDuration)); } } else if (Regex.Match(strVariable, @"Pre-Message List").Success) { _PreMessageList = new List<String>(CPluginVariable.DecodeStringArray(strValue)); //Once setting has been changed, upload the change to database QueueSettingForUpload(new CPluginVariable(@"Pre-Message List", typeof (String), CPluginVariable.EncodeStringArray(_PreMessageList.ToArray()))); } else if (Regex.Match(strVariable, @"Require Use of Pre-Messages").Success) { Boolean require = Boolean.Parse(strValue); if (require != _RequirePreMessageUse) { _RequirePreMessageUse = require; //Once setting has been changed, upload the change to database QueueSettingForUpload(new CPluginVariable(@"Require Use of Pre-Messages", typeof (Boolean), _RequirePreMessageUse)); } } else if (Regex.Match(strVariable, @"Use first spawn message").Success) { Boolean useFirstSpawnMessage = Boolean.Parse(strValue); if (useFirstSpawnMessage != _UseFirstSpawnMessage) { _UseFirstSpawnMessage = useFirstSpawnMessage; //Once setting has been changed, upload the change to database QueueSettingForUpload(new CPluginVariable(@"Use first spawn message", typeof(Boolean), _UseFirstSpawnMessage)); } } else if (Regex.Match(strVariable, @"First spawn message text").Success) { if (_FirstSpawnMessage != strValue) { _FirstSpawnMessage = strValue; //Once setting has been changed, upload the change to database QueueSettingForUpload(new CPluginVariable(@"First spawn message text", typeof(String), _FirstSpawnMessage)); } } else if (Regex.Match(strVariable, @"Display Admin Name in Kick and Ban Announcement").Success) { Boolean display = Boolean.Parse(strValue); if (display != _ShowAdminNameInSay) { _ShowAdminNameInSay = display; //Once setting has been changed, upload the change to database QueueSettingForUpload(new CPluginVariable(@"Display Admin Name in Kick and Ban Announcement", typeof (Boolean), _ShowAdminNameInSay)); } } else if (Regex.Match(strVariable, @"Inform players of reports against them").Success) { Boolean inform = Boolean.Parse(strValue); if (inform != _InformReportedPlayers) { _InformReportedPlayers = inform; //Once setting has been changed, upload the change to database QueueSettingForUpload(new CPluginVariable(@"Inform players of reports against them", typeof (Boolean), _InformReportedPlayers)); } } else if (Regex.Match(strVariable, @"Player Inform Exclusion Strings").Success) { _PlayerInformExclusionStrings = CPluginVariable.DecodeStringArray(strValue); //Once setting has been changed, upload the change to database QueueSettingForUpload(new CPluginVariable(@"Player Inform Exclusion Strings", typeof (String), CPluginVariable.EncodeStringArray(_PlayerInformExclusionStrings))); } else if (Regex.Match(strVariable, @"Add User").Success) { if (SoldierNameValid(strValue)) { var aUser = new AdKatsUser { user_name = strValue, user_expiration = DateTime.UtcNow.AddYears(20), user_notes = "No Notes" }; Boolean valid = true; if (_isTestingAuthorized) PushThreadDebug(DateTime.Now.Ticks, (String.IsNullOrEmpty(Thread.CurrentThread.Name) ? ("mainthread") : (Thread.CurrentThread.Name)), Thread.CurrentThread.ManagedThreadId, new System.Diagnostics.StackTrace(true).GetFrame(0).GetFileLineNumber(), ""); lock (_userCache) { valid = _userCache.Values.All(iUser => aUser.user_name != iUser.user_name); } if (!valid) { ConsoleError("Unable to add " + aUser.user_name + ", a user with that name already exists."); return; } var addUserThread = new Thread(new ThreadStart(delegate { Thread.CurrentThread.Name = "userchange"; DebugWrite("Starting a user change thread.", 2); //Attempt to add soldiers matching the user's name TryAddUserSoldier(aUser, aUser.user_name); QueueUserForUpload(aUser); DebugWrite("Exiting a user change thread.", 2); LogThreadExit(); })); StartAndLogThread(addUserThread); } else { ConsoleError("User id had invalid formatting, please try again."); } } else if (Regex.Match(strVariable, @"Add Role").Success) { if (!String.IsNullOrEmpty(strValue)) { String roleName = new Regex("[^a-zA-Z0-9 _-]").Replace(strValue, ""); String roleKey = roleName.Replace(' ', '_'); if (!String.IsNullOrEmpty(roleName) && !String.IsNullOrEmpty(roleKey)) { var aRole = new AdKatsRole { role_key = roleKey, role_name = roleName }; //By default we should include all commands as allowed if (_isTestingAuthorized) PushThreadDebug(DateTime.Now.Ticks, (String.IsNullOrEmpty(Thread.CurrentThread.Name) ? ("mainthread") : (Thread.CurrentThread.Name)), Thread.CurrentThread.ManagedThreadId, new System.Diagnostics.StackTrace(true).GetFrame(0).GetFileLineNumber(), ""); lock (_CommandNameDictionary) { foreach (AdKatsCommand aCommand in _CommandNameDictionary.Values) { aRole.RoleAllowedCommands.Add(aCommand.command_key, aCommand); } } //Queue it for upload QueueRoleForUpload(aRole); } else { ConsoleError("Role had invalid characters, please try again."); } } } if (FullDebug) { ConsoleWrite("updating settings page"); } } catch (Exception e) { HandleException(new AdKatsException("Error occured while updating AdKats settings.", e)); } }
private void QueueRoleForUpload(AdKatsRole aRole) { this.DebugWrite("Entering queueRoleForUpload", 7); try { if (this._IsEnabled) { this.DebugWrite("Preparing to queue role " + aRole.role_key + " for upload", 6); lock (this._RoleUploadQueue) { this._RoleUploadQueue.Enqueue(aRole); this._DbCommunicationWaitHandle.Set(); } } } catch (Exception e) { this.HandleException(new AdKatsException("Error while queueing role for upload.", e)); } this.DebugWrite("Exiting queueRoleForUpload", 7); }
public Boolean RoleIsAdmin(AdKatsRole aRole) { if (aRole == null) { ConsoleError("role null in RoleIsAdmin"); return false; } if (_isTestingAuthorized) PushThreadDebug(DateTime.Now.Ticks, (String.IsNullOrEmpty(Thread.CurrentThread.Name) ? ("mainthread") : (Thread.CurrentThread.Name)), Thread.CurrentThread.ManagedThreadId, new System.Diagnostics.StackTrace(true).GetFrame(0).GetFileLineNumber(), ""); lock (aRole) { if (_isTestingAuthorized) PushThreadDebug(DateTime.Now.Ticks, (String.IsNullOrEmpty(Thread.CurrentThread.Name) ? ("mainthread") : (Thread.CurrentThread.Name)), Thread.CurrentThread.ManagedThreadId, new System.Diagnostics.StackTrace(true).GetFrame(0).GetFileLineNumber(), ""); lock (aRole.RoleAllowedCommands) { if (aRole.RoleAllowedCommands.Values.Any(command => command.command_playerInteraction)) { return true; } } } return false; }
private void QueueRoleForRemoval(AdKatsRole aRole) { DebugWrite("Entering queueRoleForRemoval", 7); try { if (_pluginEnabled) { DebugWrite("Preparing to queue role " + aRole.role_key + " for removal", 6); if (_isTestingAuthorized) PushThreadDebug(DateTime.Now.Ticks, (String.IsNullOrEmpty(Thread.CurrentThread.Name) ? ("mainthread") : (Thread.CurrentThread.Name)), Thread.CurrentThread.ManagedThreadId, new System.Diagnostics.StackTrace(true).GetFrame(0).GetFileLineNumber(), ""); lock (_RoleRemovalQueue) { _RoleRemovalQueue.Enqueue(aRole); _DbCommunicationWaitHandle.Set(); } } } catch (Exception e) { HandleException(new AdKatsException("Error while queueing role for removal.", e)); } DebugWrite("Exiting queueRoleForRemoval", 7); }
private void FillConditionalAllowedCommands(AdKatsRole aRole) { //Teamswap Command AdKatsCommand teamswapCommand; if (_CommandKeyDictionary.TryGetValue("self_teamswap", out teamswapCommand)) { if (!aRole.ConditionalAllowedCommands.ContainsKey(teamswapCommand.command_key)) aRole.ConditionalAllowedCommands.Add(teamswapCommand.command_key, new KeyValuePair<Func<AdKats, AdKatsPlayer, Boolean>, AdKatsCommand>(AAPerkFunc, teamswapCommand)); } else { ConsoleError("Unable to find teamswap command when assigning conditional commands."); } //Admins Command AdKatsCommand adminsCommand; if (_CommandKeyDictionary.TryGetValue("self_admins", out adminsCommand)) { if (!aRole.ConditionalAllowedCommands.ContainsKey(adminsCommand.command_key)) aRole.ConditionalAllowedCommands.Add(adminsCommand.command_key, new KeyValuePair<Func<AdKats, AdKatsPlayer, Boolean>, AdKatsCommand>(AAPerkFunc, adminsCommand)); } else { ConsoleError("Unable to find teamswap command when assigning conditional commands."); } }
private void FetchRoles() { DebugWrite("fetchRoles starting!", 6); if (HandlePossibleDisconnect()) { return; } try { if (_isTestingAuthorized) PushThreadDebug(DateTime.Now.Ticks, (String.IsNullOrEmpty(Thread.CurrentThread.Name) ? ("mainthread") : (Thread.CurrentThread.Name)), Thread.CurrentThread.ManagedThreadId, new System.Diagnostics.StackTrace(true).GetFrame(0).GetFileLineNumber(), ""); lock (_RoleIDDictionary) { using (MySqlConnection connection = GetDatabaseConnection()) { using (MySqlCommand sqlcommand = connection.CreateCommand()) { const string sql = @" SELECT `role_id`, `role_key`, `role_name` FROM `adkats_roles`"; sqlcommand.CommandText = sql; var validIDs = new HashSet<Int64>(); using (MySqlDataReader reader = sqlcommand.ExecuteReader()) { _RoleKeyDictionary.Clear(); _RoleNameDictionary.Clear(); while (reader.Read()) { long roleID = reader.GetInt64("role_id"); string roleKey = reader.GetString("role_key"); string roleName = reader.GetString("role_name"); validIDs.Add(roleID); AdKatsRole currentRole; if (_RoleIDDictionary.TryGetValue(roleID, out currentRole)) { if (currentRole.role_key != roleKey) { ConsoleWarn(currentRole.role_key + " role key being changed from " + currentRole.role_key + " to " + roleKey); currentRole.role_key = roleKey; } if (currentRole.role_name != roleName) { ConsoleWarn(currentRole.role_key + " role name being changed from " + currentRole.role_name + " to " + roleName); currentRole.role_name = roleName; } } else { currentRole = new AdKatsRole { role_id = roleID, role_key = roleKey, role_name = roleName }; _RoleIDDictionary.Add(currentRole.role_id, currentRole); } _RoleKeyDictionary.Add(currentRole.role_key, currentRole); _RoleNameDictionary.Add(currentRole.role_name, currentRole); } foreach (AdKatsRole remRole in _RoleIDDictionary.Values.Where(aRole => !validIDs.Contains(aRole.role_id)).ToList()) { ConsoleWarn("Removing role " + remRole.role_key); _RoleIDDictionary.Remove(remRole.role_id); } } } using (MySqlCommand sqlcommand = connection.CreateCommand()) { const string sql = @" SELECT `role_id`, `command_id` FROM `adkats_rolecommands` ORDER BY `role_id` ASC"; sqlcommand.CommandText = sql; using (MySqlDataReader reader = sqlcommand.ExecuteReader()) { var rIDcIDDictionary = new Dictionary<Int64, HashSet<Int64>>(); while (reader.Read()) { int roleID = reader.GetInt32("role_id"); long commandID = reader.GetInt64("command_id"); HashSet<Int64> allowedCommandIDs; if (!rIDcIDDictionary.TryGetValue(roleID, out allowedCommandIDs)) { allowedCommandIDs = new HashSet<Int64>(); rIDcIDDictionary.Add(roleID, allowedCommandIDs); } allowedCommandIDs.Add(commandID); } foreach (var currentRoleElement in rIDcIDDictionary) { AdKatsRole aRole; Boolean uploadRequired = false; if (!_RoleIDDictionary.TryGetValue(currentRoleElement.Key, out aRole)) { ConsoleWarn("Role for ID " + currentRoleElement.Key + " not found in role dictionary when assigning commands."); continue; } foreach (long curRoleID in currentRoleElement.Value) { AdKatsCommand aCommand; if (!_CommandIDDictionary.TryGetValue(curRoleID, out aCommand)) { ConsoleWarn("Command for ID " + curRoleID + " not found in command dictionary when assigning commands."); uploadRequired = true; continue; } if (!aRole.RoleAllowedCommands.ContainsKey(aCommand.command_key) && aCommand.command_active==AdKatsCommand.CommandActive.Active) { aRole.RoleAllowedCommands.Add(aCommand.command_key, aCommand); } } KeyValuePair<Int64, HashSet<Int64>> element = currentRoleElement; foreach (AdKatsCommand remCommand in aRole.RoleAllowedCommands.Values.ToList().Where(remCommand => !element.Value.Contains(remCommand.command_id))) { ConsoleWarn("Removing command " + remCommand.command_key + " from role " + aRole.role_key); aRole.RoleAllowedCommands.Remove(remCommand.command_key); uploadRequired = true; } FillConditionalAllowedCommands(aRole); if (_CommandIDDictionary.Any() && uploadRequired) { QueueRoleForUpload(aRole); } } } } if (_RoleIDDictionary.Count == 0) { ConsoleError("Roles could not be fetched."); } } } } catch (Exception e) { HandleException(new AdKatsException("Error while fetching roles from database.", e)); } UpdateSettingPage(); DebugWrite("fetchRoles finished!", 6); }
//DONE private void UploadRole(AdKatsRole aRole) { DebugWrite("uploadRole starting!", 6); //Make sure database connection active if (HandlePossibleDisconnect()) { return; } try { if (_isTestingAuthorized) PushThreadDebug(DateTime.Now.Ticks, (String.IsNullOrEmpty(Thread.CurrentThread.Name) ? ("mainthread") : (Thread.CurrentThread.Name)), Thread.CurrentThread.ManagedThreadId, new System.Diagnostics.StackTrace(true).GetFrame(0).GetFileLineNumber(), ""); lock (aRole) { if (_isTestingAuthorized) PushThreadDebug(DateTime.Now.Ticks, (String.IsNullOrEmpty(Thread.CurrentThread.Name) ? ("mainthread") : (Thread.CurrentThread.Name)), Thread.CurrentThread.ManagedThreadId, new System.Diagnostics.StackTrace(true).GetFrame(0).GetFileLineNumber(), ""); lock (aRole.RoleAllowedCommands) { DebugWrite("Uploading role: " + aRole.role_name, 5); //Open db connection using (MySqlConnection connection = GetDatabaseConnection()) { //Upload/Update the main role object using (MySqlCommand command = connection.CreateCommand()) { //Set the insert command structure command.CommandText = @" INSERT INTO `adkats_roles` ( `role_key`, `role_name` ) VALUES ( @role_key, @role_name ) ON DUPLICATE KEY UPDATE `role_key` = @role_key, `role_name` = @role_name"; //Set values command.Parameters.AddWithValue("@role_key", aRole.role_key); command.Parameters.AddWithValue("@role_name", aRole.role_name); //Attempt to execute the query Int32 rowsAffected = command.ExecuteNonQuery(); if (rowsAffected > 0) { //Set the user's new ID if new if (aRole.role_id < 0) { aRole.role_id = command.LastInsertedId; } DebugWrite("Role uploaded to database SUCCESSFULY.", 5); } else { ConsoleError("Unable to upload role " + aRole.role_name + " to database."); return; } } //Delete all current allowed commands using (MySqlCommand command = connection.CreateCommand()) { command.CommandText = @"DELETE FROM `adkats_rolecommands` where `role_id` = " + aRole.role_id; //Attempt to execute the query Int32 rowsAffected = command.ExecuteNonQuery(); } foreach (AdKatsCommand aCommand in aRole.RoleAllowedCommands.Values) { //Upload the role's allowed commands using (MySqlCommand command = connection.CreateCommand()) { //Set the insert command structure command.CommandText = @" INSERT INTO `adkats_rolecommands` ( `role_id`, `command_id` ) VALUES ( @role_id, @command_id ) ON DUPLICATE KEY UPDATE `role_id` = @role_id, `command_id` = @command_id"; //Set values command.Parameters.AddWithValue("@role_id", aRole.role_id); command.Parameters.AddWithValue("@command_id", aCommand.command_id); //Attempt to execute the query Int32 rowsAffected = command.ExecuteNonQuery(); if (rowsAffected > 0) { //Set the user's new ID if new if (aRole.role_id < 0) { aRole.role_id = command.LastInsertedId; } DebugWrite("Role-command uploaded to database SUCCESSFULY.", 5); } else { ConsoleError("Unable to upload role-command for " + aRole.role_name + "."); return; } } } } } } } catch (Exception e) { HandleException(new AdKatsException("Error while uploading role.", e)); } DebugWrite("uploadRole finished!", 6); }
private void RemoveRole(AdKatsRole aRole) { DebugWrite("removeRole starting!", 6); if (HandlePossibleDisconnect()) { return; } try { //Assign "Default Guest" to all users currently on this role AdKatsRole guestRole = null; if (_RoleKeyDictionary.TryGetValue("guest_default", out guestRole)) { foreach (AdKatsUser aUser in _userCache.Values) { if (aUser.user_role.role_key == aRole.role_key) { aUser.user_role = guestRole; } UploadUser(aUser); } } else { ConsoleError("Could not fetch default guest user role. Unsafe to remove requested user role."); return; } using (MySqlConnection connection = GetDatabaseConnection()) { using (MySqlCommand command = connection.CreateCommand()) { command.CommandText = "DELETE FROM `" + _mySqlDatabaseName + "`.`adkats_rolecommands` WHERE `role_id` = @role_id"; command.Parameters.AddWithValue("@role_id", aRole.role_id); Int32 rowsAffected = command.ExecuteNonQuery(); } using (MySqlCommand command = connection.CreateCommand()) { command.CommandText = "DELETE FROM `" + _mySqlDatabaseName + "`.`adkats_roles` WHERE `role_id` = @role_id"; command.Parameters.AddWithValue("@role_id", aRole.role_id); Int32 rowsAffected = command.ExecuteNonQuery(); } } } catch (Exception e) { HandleException(new AdKatsException("Error while removing user.", e)); } DebugWrite("removeRole finished!", 6); }
private List<AdKatsPlayer> FetchSoldiersOfRole(AdKatsRole aRole) { var roleSoldiers = new List<AdKatsPlayer>(); //Loop over the user list if (_isTestingAuthorized) PushThreadDebug(DateTime.Now.Ticks, (String.IsNullOrEmpty(Thread.CurrentThread.Name) ? ("mainthread") : (Thread.CurrentThread.Name)), Thread.CurrentThread.ManagedThreadId, new System.Diagnostics.StackTrace(true).GetFrame(0).GetFileLineNumber(), ""); lock (_userCache) { foreach (AdKatsUser user in _userCache.Values.Where(user => user.user_role.role_key == aRole.role_key)) { roleSoldiers.AddRange(user.soldierDictionary.Values); } } return roleSoldiers; }