public UserBattleStatus(string name, User lobbyUser, string password= null)
		{
		    Name = name;
		    if (password != null) ScriptPassword = password;
		    else ScriptPassword = name;
			LobbyUser = lobbyUser;
		}
 private bool GetBattleAndFounder(out Battle battle, out User founder)
 {
     founder = null;
     if (Program.TasClient.ExistingBattles.TryGetValue(battleID, out battle)) {
         founder = battle.Founder;
         return true;
     }
     return false;
 }
        private void Setup_MyInfo()
        {
            string myName = Program.Conf.LobbyPlayerName == null ? "unnamed" : Program.Conf.LobbyPlayerName;
            User myUser = new User { Name = myName };
            myUser.Country = "Unknown";
            UserBattleStatus myBattleStatus = new UserBattleStatus(myName, myUser) { AllyNumber = 0, SyncStatus = SyncStatuses.Unknown, IsSpectator = spectateCheckBox.Checked };
            myItem = new PlayerListItem
            {
                UserName = myBattleStatus.Name,
                AllyTeam = myBattleStatus.AllyNumber,
                isOfflineMode = true,
                isZK = false,
            };
            myItem.offlineUserInfo = myUser;
            myItem.offlineUserBattleStatus = myBattleStatus;

            botsMissionSlot = new List<MissionSlot>();
        }
        public static ContextMenu GetPlayerContextMenu(User user, bool isBattle)
        {
            var contextMenu = new ContextMenu();
            try
            {
                var headerItem = new System.Windows.Forms.MenuItem("Player - " + user.Name) { Enabled = false, DefaultItem = true };
                // default is to make it appear bold
                contextMenu.MenuItems.Add(headerItem);

                if (user.Name != Program.TasClient.UserName)
                {
                    contextMenu.MenuItems.Add("-");

                    var details = new MenuItem("Details");
                    details.Click += (s, e) => Program.MainWindow.navigationControl.Path = string.Format("{1}/Users/LobbyDetail/{0}", user.AccountID, GlobalConst.BaseSiteUrl);
                    contextMenu.MenuItems.Add(details);

                    var pmItem = new MenuItem("Send Message");
                    pmItem.Click += (s, e) => Program.MainWindow.navigationControl.Path = "chat/user/" + user.Name;
                    contextMenu.MenuItems.Add(pmItem);

                    if (Program.FriendManager.Friends.Contains(user.Name))
                    {
                        var pinItem = new MenuItem("Unfriend");
                        pinItem.Click += (s, e) => Program.FriendManager.RemoveFriend(user.Name);
                        contextMenu.MenuItems.Add(pinItem);
                    }
                    else
                    {
                        var pinItem = new MenuItem("Friend");
                        pinItem.Click += (s, e) => Program.FriendManager.AddFriend(user.Name);
                        contextMenu.MenuItems.Add(pinItem);
                    }

                    var joinItem = new MenuItem("Join Same Battle") { Enabled = Program.TasClient.ExistingUsers[user.Name].IsInBattleRoom };
                    joinItem.Click += (s, e) => ActionHandler.JoinPlayer(user.Name);
                    contextMenu.MenuItems.Add(joinItem);

                    var ignoreUser = new MenuItem("Ignore User") { Checked = Program.Conf.IgnoredUsers.Contains(user.Name) };
                    ignoreUser.Click += (s, e) =>
                        {
                            ignoreUser.Checked = !ignoreUser.Checked;
                            if (ignoreUser.Checked) Program.Conf.IgnoredUsers.Add(user.Name);
                            else Program.Conf.IgnoredUsers.Remove(user.Name);
                        };
                    contextMenu.MenuItems.Add(ignoreUser);

                    var reportUser = new MenuItem("Report User");
                    reportUser.Click += (s, e) => Program.MainWindow.navigationControl.Path = string.Format("{1}/Users/ReportToAdminFromLobby/{0}", user.Name, GlobalConst.BaseSiteUrl);
                    contextMenu.MenuItems.Add(reportUser);
                }

                if (Program.TasClient.MyBattle != null)
                {
                    var battleStatus = Program.TasClient.MyBattle.Users[user.Name];
                    var myStatus = Program.TasClient.MyBattleStatus;

                    if (isBattle)
                    {
                        contextMenu.MenuItems.Add("-");

                        if (!Program.TasClient.MyBattle.IsQueue)
                        {
                            if (user.Name != Program.TasClient.UserName)
                            {
                                var allyWith = new MenuItem("Ally")
                                               {
                                                   Enabled =
                                                       !battleStatus.IsSpectator &&
                                                       (battleStatus.AllyNumber != myStatus.AllyNumber || myStatus.IsSpectator)
                                               };
                                allyWith.Click += (s, e) => ActionHandler.JoinAllyTeam(battleStatus.AllyNumber);
                                contextMenu.MenuItems.Add(allyWith);
                            }
                            contextMenu.MenuItems.Add(GetSetAllyTeam(user));

                            contextMenu.MenuItems.Add("-");
                            contextMenu.MenuItems.Add(GetShowGameOptionsItem());
                            contextMenu.MenuItems.Add(GetAddBot());
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Trace.WriteLine("Error generating player context menu: " + e);
            }
            return contextMenu;
        }
 public PlayerEntry(User user, List<MatchMakerSetup.Queue> queueTypes)
 {
     QueueTypes = queueTypes;
     LobbyUser = user;
 }
 public void UpdateWith(User u)
 {
     AccountID = u.AccountID;
     SpringieLevel = u.SpringieLevel;
     SteamID = u.SteamID;
     AwaySince = u.AwaySince;
     Clan = u.Clan;
     Avatar = u.Avatar;
     Country = u.Country;
     EffectiveElo = u.EffectiveElo;
     Effective1v1Elo = u.Effective1v1Elo;
     Faction = u.Faction;
     InGameSince = u.InGameSince;
     IsAdmin = u.IsAdmin;
     IsBot = u.IsBot;
     // todo hacky fix IsInBattleRoom = u.IsInBattleRoom;
     BanMute = u.BanMute;
     BanSpecChat = u.BanSpecChat;
     Level = u.Level;
     ClientType = u.ClientType;
     LobbyVersion = u.LobbyVersion;
     DisplayName = u.DisplayName;
     Name = u.Name;
 }
        public static void UpdateUserFromAccount(User user, Account acc)
        {
            user.Name = acc.Name;
            user.DisplayName = acc.SteamName;
            user.Avatar = acc.Avatar;
            user.Level = acc.Level;
            user.EffectiveMmElo = (int)acc.EffectiveMmElo;
            user.RawMmElo = (int)acc.EloMm;
            user.CompetitiveRank = acc.CompetitiveRank;
            user.SteamID = (ulong?)acc.SteamID;
            user.IsAdmin = acc.IsZeroKAdmin;
            user.IsBot = acc.IsBot;
            user.Country = acc.Country;
            user.Faction = acc.Faction != null ? acc.Faction.Shortcut : null;
            user.Clan = acc.Clan != null ? acc.Clan.Shortcut : null;
            user.AccountID = acc.AccountID;
            Interlocked.Increment(ref user.SyncVersion);

            user.BanMute = Punishment.GetActivePunishment(acc.AccountID, user.IpAddress, 0, x => x.BanMute) != null;
            user.BanSpecChat = Punishment.GetActivePunishment(acc.AccountID, user.IpAddress, 0, x => x.BanSpecChat) != null;
        }
 public static Tuple<Image, string> GetClanOrFactionImage(User user) {
     Image ret = null;
     string rets = null;
     if (!String.IsNullOrEmpty(user.Clan)) {
         Image clanImg = Program.ServerImages.GetImage(String.Format("Clans/{0}.png", user.Clan));
         ret = clanImg;
         rets = user.Clan + " " + user.Faction;
     }
     else if (!String.IsNullOrEmpty(user.Faction)) {
         Image facImg = Program.ServerImages.GetImage(String.Format("Factions/{0}.png", user.Faction));
         ret = facImg;
         rets = user.Faction;
     }
     return Tuple.Create(ret, rets);
 }
 public Image GetAvatarImage(User user) {
     if (!string.IsNullOrEmpty(user.Avatar)) return GetImage(String.Format("Avatars/{0}.png", user.Avatar));
     else return null;
 }
        public static void GeneratePlayerSection(List<UserBattleStatus> playersExport,
            List<UserBattleStatus> users,
            StringBuilder script,
            List<BotBattleStatus> bots,
            IDictionary<int, BattleRect> _rectangles,
            Dictionary<string, string> _modOptions,
            User localUser = null,
            SpringBattleStartSetup startSetup = null
           )
        {
            // ordinary battle stuff

            var userNum = 0;
            var teamNum = 0;
            var aiNum = 0;

            //players is excluding self (so "springie doesn't appear as spec ingame") & excluding bots (bots is added later for each owner)
            var non_botUsers = users.Where(u => !bots.Any(b => b.Name == u.Name)); //.OrderBy(x => x.TeamNumber);
            if (localUser != null) //I am a server
                non_botUsers = non_botUsers.Where(x => x.Name != localUser.Name);

            foreach (var u in non_botUsers.OrderBy(x => x.TeamNumber))
            {
                ScriptAddUser(script, userNum, playersExport, startSetup, teamNum, u);

                if (!u.IsSpectator)
                {
                    ScriptAddTeam(script, teamNum, userNum, u);
                    teamNum++;
                }

                foreach (var b in bots.Where(x => x.owner == u.Name))
                {
                    ScriptAddBot(script, aiNum, teamNum, userNum, b);
                    aiNum++;
                    ScriptAddTeam(script, teamNum, userNum, b);
                    teamNum++;
                }
                userNum++;
            }

            // ALLIANCES
            script.AppendLine();
            foreach (var allyNumber in
                users.Where(x => !x.IsSpectator).Select(x => x.AllyNumber).Union(bots.Select(x => x.AllyNumber)).Union(_rectangles.Keys).Distinct())
            {
                // get allies from each player, bot and rectangles (for koth)
                script.AppendFormat("[ALLYTEAM{0}]\n", allyNumber);
                script.AppendLine("{");
                script.AppendFormat("     NumAllies={0};\n", 0);
                double left = 0, top = 0, right = 1, bottom = 1;
                BattleRect rect;
                if (_rectangles.TryGetValue(allyNumber, out rect)) rect.ToFractions(out left, out top, out right, out bottom);
                script.AppendFormat(CultureInfo.InvariantCulture, "     StartRectLeft={0};\n", left);
                script.AppendFormat(CultureInfo.InvariantCulture, "     StartRectTop={0};\n", top);
                script.AppendFormat(CultureInfo.InvariantCulture, "     StartRectRight={0};\n", right);
                script.AppendFormat(CultureInfo.InvariantCulture, "     StartRectBottom={0};\n", bottom);
                script.AppendLine("}");
            }

            script.AppendLine();

                script.AppendLine("  [MODOPTIONS]");
                script.AppendLine("  {");

                var options = new Dictionary<string, string>(_modOptions);

                // replace/add custom modoptions from startsetup (if they exist)
                if (startSetup != null && startSetup.ModOptions != null) foreach (var entry in startSetup.ModOptions) options[entry.Key] = entry.Value;

                // write final options to script
                foreach (var kvp in options) script.AppendFormat("    {0}={1};\n", kvp.Key, kvp.Value);

                script.AppendLine("  }");


            script.AppendLine("}");
        }
 private static Image GetUserImageRaw(User user) {
     if (user != null)
     {
         if (user.IsBot) return ZklResources.robot;
         if (Program.FriendManager.Friends.Contains(user.Name)) return ZklResources.friend;
         if (user.IsAdmin) return ZklResources.police;
         if (user.EffectiveElo >= 1800) return ZklResources.napoleon;
         if (user.EffectiveElo >= 1600) return ZklResources.soldier;
         if (user.EffectiveElo < 1400) return ZklResources.smurf;
     }
     return ZklResources.user;
 }
 void ShowPlayerContextMenu(User user, Control control, Point location) {
     var contextMenu = ContextMenus.GetPlayerContextMenu(user, this is BattleChatControl);
     
     contextMenu = LineDehighlighter(contextMenu, user.Name);
     
     try {
         Program.ToolTip.Visible = false;
         contextMenu.Show(control, location);
     } catch (Exception ex) {
         Trace.TraceError("Error displaying tooltip:{0}", ex);
     } finally {
         Program.ToolTip.Visible = true;
     }
 }
 void TasClient_UserAdded(object sender, User user)
 {
   var userName = user.Name;
   if (userName != UserName) return;
   AddLine(new JoinLine(userName));
 }
        private ContextMenu Get_PlayerContextMenu(User user) //from ContextMenu.cs
        {
            var contextMenu = new ContextMenu();
            try
            {
                var headerItem = new MenuItem("Player - " + user.Name) { Enabled = false, DefaultItem = true };
                // default is to make it appear bold
                contextMenu.MenuItems.Add(headerItem);

                var battleStatus = allUser.SingleOrDefault(u => u.Name == user.Name);

                contextMenu.MenuItems.Add("-");

                if (user.Name != myItem.UserName)
                {
                    var allyWith = new MenuItem("Ally")
                    {
                        Enabled =
                            !battleStatus.IsSpectator &&
                            (battleStatus.AllyNumber != myItem.AllyTeam || myItem.offlineUserBattleStatus.IsSpectator)
                    };
                    allyWith.Click += (s, e) =>
                        {
                            myItem.AllyTeam = battleStatus.AllyNumber;
                            myItem.offlineUserBattleStatus.AllyNumber = battleStatus.AllyNumber;
                            spectateCheckBox.Checked = false;
                            myItem.offlineUserBattleStatus.TeamNumber = Get_FreeTeamID(myItem.UserName);
                            Refresh_PlayerBox();

                        };

                    contextMenu.MenuItems.Add(allyWith);
                }

                contextMenu.MenuItems.Add(Get_SetAllyTeamItem(user));

                contextMenu.MenuItems.Add("-");
                contextMenu.MenuItems.Add(Get_ShowOptions());
                contextMenu.MenuItems.Add(Get_ModBotItem());
                contextMenu.MenuItems.Add(Get_SpringBotItem());
            }
            catch (Exception e)
            {
                Trace.WriteLine("Error generating player context menu: " + e);
            }
            return contextMenu;
        }
 public void UpdateWith(User u)
 {
     AccountID = u.AccountID;
     SteamID = u.SteamID;
     AwaySince = u.AwaySince;
     Clan = u.Clan;
     Avatar = u.Avatar;
     Country = u.Country;
     EffectiveMmElo = u.EffectiveMmElo;
     Faction = u.Faction;
     InGameSince = u.InGameSince;
     IsAdmin = u.IsAdmin;
     IsBot = u.IsBot;
     BanMute = u.BanMute;
     BanSpecChat = u.BanSpecChat;
     Level = u.Level;
     ClientType = u.ClientType;
     LobbyVersion = u.LobbyVersion;
     DisplayName = u.DisplayName;
     CompetitiveRank = u.CompetitiveRank;
 }
		void client_UserAdded(object sender, User user)
		{
			Task.Factory.StartNew(() =>
				{
					try
					{
						List<LobbyMessage> messages;
						using (var db = new ZkDataContext())
						
						{
							messages = db.LobbyMessages.Where(x => (x.TargetLobbyID == user.AccountID || x.TargetName == user.Name) && x.Channel == null).OrderBy(x => x.Created).ToList();
							db.LobbyMessages.DeleteAllOnSubmit(messages);
							db.SubmitChanges();
						}
						foreach (var m in messages)
						{
							var text = string.Format("!pm|{0}|{1}|{2}|{3}", m.Channel, m.SourceName, m.Created.ToString(CultureInfo.InvariantCulture), m.Message);
							client.Say(SayPlace.User, user.Name, text, false);
							Thread.Sleep(MessageDelay);
						}
					}

					catch (Exception ex)
					{
						Trace.TraceError("Error sending PM:{0}", ex);
					}
				});
		}
 public PlayerEntry(User user, List<MatchMakerSetup.Queue> queueTypes, PartyManager.Party party)
 {
     Party = party;
     QueueTypes = queueTypes;
     LobbyUser = user;
 }
        public LoginResponse Login(User user, Login login, Client client)
        {
            string ip = client.RemoteEndpointIP;
            long userID = login.UserID;
            string lobbyVersion = login.LobbyVersion;

            using (var db = new ZkDataContext()) {
                Account acc = db.Accounts.Include(x => x.Clan).Include(x => x.Faction).FirstOrDefault(x => x.Name == login.Name);
                if (acc == null) return new LoginResponse { ResultCode = LoginResponse.Code.InvalidName };
                if (!acc.VerifyPassword(login.PasswordHash)) return new LoginResponse { ResultCode = LoginResponse.Code.InvalidPassword };
                if (state.Clients.ContainsKey(login.Name)) return new LoginResponse { ResultCode = LoginResponse.Code.AlreadyConnected };
                
                acc.Country = ResolveCountry(ip);
                if (acc.Country == null || String.IsNullOrEmpty(acc.Country)) acc.Country = "unknown";
                acc.LobbyVersion = lobbyVersion;
                acc.LastLogin = DateTime.UtcNow;

                user.ClientType = login.ClientType;
                user.LobbyVersion = login.LobbyVersion;
                UpdateUserFromAccount(user, acc);

                LogIP(db, acc, ip);

                LogUserID(db, acc, userID);

                db.SaveChanges();


                var banMute = Punishment.GetActivePunishment(acc.AccountID, ip, userID, x => x.BanMute, db);
                if (banMute != null) user.BanMute = true;
                

                Punishment banPenalty = Punishment.GetActivePunishment(acc.AccountID, ip, userID, x => x.BanLobby, db);

                if (banPenalty != null) {
                    return
                        BlockLogin(
                            string.Format("Banned until {0} (match to {1}), reason: {2}", banPenalty.BanExpires, banPenalty.AccountByAccountID.Name,
                                banPenalty.Reason), acc, ip, userID);
                }

                Account accAnteep = db.Accounts.FirstOrDefault(x => x.AccountID == 4490);
                if (accAnteep != null) {
                    if (accAnteep.AccountUserIDs.Any(y => y.UserID == userID)) {
                        Talk(String.Format("Suspected Anteep smurf: {0} (ID match {1}) {2}", acc.Name, userID,
                            string.Format("{1}/Users/Detail/{0}", acc.AccountID, GlobalConst.BaseSiteUrl)));
                    }

                    if (userID > 0 && userID < 1000) {
                        Talk(String.Format("Suspected Anteep smurf: {0} (too short userID {1}) {2}", acc.Name, userID,
                            string.Format("{1}/Users/Detail/{0}", acc.AccountID, GlobalConst.BaseSiteUrl)));
                    }

                    if (accAnteep.AccountIPs.Any(y => y.IP == ip)) {
                        Talk(String.Format("Suspected Anteep smurf: {0} (IP match {1}) {2}", acc.Name, ip,
                            string.Format("{1}/Users/Detail/{0}", acc.AccountID, GlobalConst.BaseSiteUrl)));
                    }
                }

                if (!acc.HasVpnException && GlobalConst.VpnCheckEnabled) {
                    // check user IP against http://dnsbl.tornevall.org
                    // does not catch all smurfs
                    // mostly false positives, do not use
                    string reversedIP = string.Join(".", ip.Split('.').Reverse().ToArray());
                    try {
                        IPAddress[] resolved = Dns.GetHostEntry(string.Format("{0}.dnsbl.tornevall.org", reversedIP)).AddressList;
                        if (resolved.Length > 0) {
                            Talk(String.Format("User {0} {3} has IP {1} on dnsbl.tornevall.org ({2} result/s)", acc.Name, ip, resolved.Length,
                                string.Format("{1}/Users/Detail/{0}", acc.AccountID, GlobalConst.BaseSiteUrl)));
                        }
                    } catch (SocketException sockEx) {
                        // not in database, do nothing
                    }
                }

                try {
                    if (!acc.HasVpnException) {
                        for (int i = 0; i <= 1; i++) {
                            var whois = new Whois();
                            Dictionary<string, string> data = whois.QueryByIp(ip, i == 1);

                            if (!data.ContainsKey("netname")) data["netname"] = "UNKNOWN NETNAME";
                            if (!data.ContainsKey("org-name")) data["org-name"] = "UNKNOWN ORG";
                            if (!data.ContainsKey("abuse-mailbox")) data["abuse-mailbox"] = "no mailbox";
                            if (!data.ContainsKey("notify")) data["notify"] = "no notify address";
                            if (!data.ContainsKey("role")) data["role"] = "UNKNOWN ROLE";
                            if (!data.ContainsKey("descr")) data["descr"] = "no description";
                            if (!data.ContainsKey("remarks")) data["remarks"] = "no remarks";

                            List<string> blockedCompanies = db.BlockedCompanies.Select(x => x.CompanyName.ToLower()).ToList();
                            List<string> blockedHosts = db.BlockedHosts.Select(x => x.HostName).ToList();
                            /*if (acc.Country == "MY")
                        {
                            client.Say(SayPlace.User, "KingRaptor", String.Format("USER {0}\nnetname: {1}\norgname: {2}\ndescr: {3}\nabuse-mailbox: {4}",
                                acc.Name, data["netname"], data["org-name"], data["descr"], data["abuse-mailbox"]), false);
                        }*/

                            bool blockedHost = blockedHosts.Any(x => data["abuse-mailbox"].Contains(x)) ||
                                               (blockedHosts.Any(x => data["notify"].Contains(x)));

                            foreach (string company in blockedCompanies) {
                                if (data["netname"].ToLower().Contains(company) || data["org-name"].ToLower().Contains(company) ||
                                    data["descr"].ToLower().Contains(company) || data["role"].ToLower().Contains(company) ||
                                    data["remarks"].ToLower().Contains(company)) {
                                    blockedHost = true;
                                    break;
                                }
                            }

                            string hostname = Dns.GetHostEntry(ip).HostName;
                            if (blockedHosts.Any(hostname.Contains)) blockedHost = true;

                            if (blockedHost) return BlockLogin("Connection using proxy or VPN is not allowed! (You can ask for exception)", acc, ip, userID);
                        }
                    }
                } catch (SocketException sockEx) {} catch (Exception ex) {
                    Trace.TraceError("VPN check error: {0}", ex);
                }

                if (state.Clients.TryAdd(login.Name, client)) return new LoginResponse { ResultCode = LoginResponse.Code.Ok };
                else return new LoginResponse() {ResultCode = LoginResponse.Code.AlreadyConnected};
            }
        }
 static void UpdateUserFromAccount(User user, Account acc)
 {
     user.Name = acc.Name;
     user.DisplayName = acc.SteamName;
     user.Avatar = acc.Avatar;
     user.SpringieLevel = acc.SpringieLevel;
     user.Level = acc.Level;
     user.EffectiveElo = (int)acc.EffectiveElo;
     user.Effective1v1Elo = (int)acc.Effective1v1Elo;
     user.SteamID = (ulong?)acc.SteamID;
     user.IsAdmin = acc.IsZeroKAdmin;
     user.IsBot = acc.IsBot;
     user.Country = acc.Country;
     user.Faction = acc.Faction != null ? acc.Faction.Shortcut : null;
     user.Clan = acc.Clan != null ? acc.Clan.Shortcut : null;
     user.AccountID = acc.AccountID;
 }
        private MenuItem Get_SetAllyTeamItem(User user)
        {
            var setAllyTeamItem = new System.Windows.Forms.MenuItem("Select Team");

            if (user.Name != myItem.UserName) setAllyTeamItem.Enabled = false;
            else
            {
                int freeAllyTeam;

                foreach (var allyTeam in Get_ExistingTeams(out freeAllyTeam).Distinct())
                {
                    var at = allyTeam; //to maintain reference to this object
                    if (allyTeam != myItem.offlineUserBattleStatus.AllyNumber)
                    {
                        var item = new MenuItem("Join Team " + (allyTeam + 1));
                        item.Click += (s, e) =>
                            {
                                Set_MyBattleStatus(at, Get_FreeTeamID(user.Name), false);
                            };
                        setAllyTeamItem.MenuItems.Add(item);
                    }
                }

                setAllyTeamItem.MenuItems.Add("-");

                var newTeamItem = new System.Windows.Forms.MenuItem("Start New Team");
                newTeamItem.Click += (s, e) =>
                    {
                        Set_MyBattleStatus(freeAllyTeam, Get_FreeTeamID(myItem.UserName), false);
                    };
                setAllyTeamItem.MenuItems.Add(newTeamItem);

                if (!myItem.offlineUserBattleStatus.IsSpectator)
                {
                    var specItem = new System.Windows.Forms.MenuItem("Spectate");
                    specItem.Click += (s, e) =>
                        {
                            Set_MyBattleStatus(null,null,true);
                        };
                    setAllyTeamItem.MenuItems.Add(specItem);
                }
            }

            return setAllyTeamItem;
        }
        static MenuItem GetSetAllyTeam(User user)
        {
            var setAllyTeamItem = new MenuItem("Select Team");

            if (Program.TasClient.MyBattle == null || user.Name != Program.TasClient.UserName) setAllyTeamItem.Enabled = false;
            else if (Program.TasClient.MyBattle != null)
            {
                setAllyTeamItem.MenuItems.AddRange(GetSetAllyItems());
            }

            return setAllyTeamItem;
        }
        static bool FilterSpecialWordCheck(User user, string word, out bool isMatch) {
            switch (word) {
                case "BOT":
                    isMatch = user.IsBot;
                    return true;
                case "AFK":
                    isMatch = user.IsAway;
                    return true;
                case "ADMIN":
                    isMatch = user.IsAdmin;
                    return true;
                case "INGAME":
                    isMatch = user.IsInGame;
                    return true;
                case "INBATTLE":
                    isMatch = user.IsInBattleRoom;
                    return true;
                case "FRIEND":
                    isMatch = Program.FriendManager.Friends.Any(x => x == user.Name);
                    return true;
            }

            isMatch = false;
            return false;
        }
        /// <summary>
        /// Generates script
        /// </summary>
        /// <param name="playersExport">list of players</param>
        /// <param name="localUser">myself</param>
        /// <param name="loopbackListenPort">listen port for autohost interface</param>
        /// <param name="zkSearchTag">hackish search tag</param>
        /// <param name="startSetup">structure with custom extra data</param>
        /// <returns></returns>
        public string GenerateScript(out List<UserBattleStatus> playersExport,
                                     User localUser,
                                     int loopbackListenPort,
                                     string zkSearchTag,
                                     SpringBattleStartSetup startSetup)
        {
            var previousCulture = Thread.CurrentThread.CurrentCulture;
            try
            {
                Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;

                playersExport = new List<UserBattleStatus>();
                var isHost = localUser.Name == Founder.Name;

                var myUbs = Users[localUser.Name];
                if (!isHost)
                {
                    var sb = new StringBuilder();
                    sb.AppendLine("[GAME]");
                    sb.AppendLine("{");
                    sb.AppendFormat("HostIP={0};\n", Ip);
                    sb.AppendFormat("HostPort={0};\n", HostPort);
                    sb.AppendLine("IsHost=0;");
                    sb.AppendFormat("MyPlayerName={0};\n", localUser.Name);
                    if (myUbs != null)
                    {
                        if (myUbs.ScriptPassword != null) sb.AppendFormat("MyPasswd={0};\n", myUbs.ScriptPassword);
                    }
                    else
                    {
                        sb.AppendFormat("MyPasswd={0};\n", localUser.Name); // used for mid-game join .. if no userbattlestatus, use own name
                    }
                    sb.AppendLine("}");
                    return sb.ToString();
                }
                else
                {

                    var script = new StringBuilder();

                    script.AppendLine("[GAME]");
                    script.AppendLine("{");

                    script.AppendFormat("   ZkSearchTag={0};\n", zkSearchTag);
                    script.AppendFormat("  Mapname={0};\n", MapName);

                    script.AppendFormat("  StartPosType=2;\n");

                    script.AppendFormat("  GameType={0};\n", ModName);
                    script.AppendFormat("  ModHash=1;\n");
                    script.AppendFormat("  MapHash=1;\n");

                    script.AppendFormat("  AutohostPort={0};\n", loopbackListenPort);
                    script.AppendLine();
                    script.AppendFormat("  HostIP={0};\n", Ip);
                    script.AppendFormat("  HostPort={0};\n", HostPort);
                    script.AppendFormat("  SourcePort={0};\n", 8300);
                    script.AppendFormat("  IsHost=1;\n");
                    script.AppendLine();

                    //script.AppendFormat("  MyPlayerName={0};\n", localUser.Name);

                    List<UserBattleStatus> users;
                    List<BotBattleStatus> bots;

                    if (startSetup != null && startSetup.BalanceTeamsResult != null && startSetup.BalanceTeamsResult.Players != null)
                    {
                        // if there is a balance results as a part of start setup, use values from this (override lobby state)
                        users = Users.Values.ToList();
                        bots = new List<BotBattleStatus>(this.Bots.Values.Select(x => (BotBattleStatus)x.Clone()));
                        foreach (var p in startSetup.BalanceTeamsResult.Players)
                        {
                            var us = users.FirstOrDefault(x => x.Name == p.Name);
                            if (us == null)
                            {
                                us = new UserBattleStatus(p.Name, new User() { AccountID = p.LobbyID }, Password); // TODO this "password" use does not look right
                                users.Add(us);
                            }
                            us.TeamNumber = p.TeamID;
                            us.IsSpectator = p.IsSpectator;
                            us.AllyNumber = p.AllyID;

                        }
                        foreach (var p in startSetup.BalanceTeamsResult.Bots)
                        {
                            var bot = bots.FirstOrDefault(x => x.Name == p.BotName);
                            if (bot == null)
                            {
                                bot = new BotBattleStatus(p.BotName, p.Owner, p.BotAI);
                                bots.Add(bot);
                            }
                            bot.AllyNumber = bot.AllyNumber;
                            bot.TeamNumber = bot.TeamNumber;
                        }

                        foreach (var u in users.Where(x => !startSetup.BalanceTeamsResult.Players.Any(y => y.Name == x.Name)))
                        {
                            u.IsSpectator = true;
                        } // spec those not known at the time of balance
                    }
                    else
                    {
                        users = this.Users.Values.ToList();
                        bots = this.Bots.Values.ToList();
                    }


                    GeneratePlayerSection(playersExport, users, script, bots, Rectangles, ModOptions, localUser, startSetup);

                    return script.ToString();
                }
            }
            finally
            {
                Thread.CurrentThread.CurrentCulture = previousCulture;
            }
        }
 void TasClient_UserAdded(object sender, User user)
 {
     var userName = user.Name;
     var pmControl = GetPrivateMessageControl(userName);
     if (pmControl != null)
         toolTabs.SetIcon(userName, Program.FriendManager.Friends.Contains(userName) ? ZklResources.friend : TextImage.GetUserImage(userName),
             true);
 }
        public static void UpdateUserFromAccount(User user, Account acc)
        {
            user.Name = acc.Name;
            user.DisplayName = acc.SteamName;
            user.Avatar = acc.Avatar;
            user.Level = acc.Level;
            user.EffectiveMmElo = (int)acc.EffectiveMmElo;
            user.CompetitiveRank = acc.CompetitiveRank;
            user.SteamID = (ulong?)acc.SteamID;
            user.IsAdmin = acc.IsZeroKAdmin;
            user.IsBot = acc.IsBot;
            user.Country = acc.Country;
            user.Faction = acc.Faction != null ? acc.Faction.Shortcut : null;
            user.Clan = acc.Clan != null ? acc.Clan.Shortcut : null;
            user.AccountID = acc.AccountID;


            var banMute = Punishment.GetActivePunishment(acc.AccountID, "", 0, x => x.BanMute, null);
            if (banMute != null) user.BanMute = true;
            // note: we do not do "else = false" because this just checks accountID (there can still be active bans per IP or userID)

            var banSpecChat = Punishment.GetActivePunishment(acc.AccountID, "", 0, x => x.BanSpecChat, null);
            if (banSpecChat != null) user.BanSpecChat = true;
        }