Ejemplo n.º 1
0
        public ICharacter WithAdminLevel(AdminLevel level)
        {
            var character = MakeCopy(this);

            character.AdminLevel = level;
            return(character);
        }
Ejemplo n.º 2
0
        public ILoginRequestGrantedData WithAdminLevel(AdminLevel adminLevel)
        {
            var copy = MakeCopy(this);

            copy.AdminLevel = adminLevel;
            return(copy);
        }
 public Administrator(string firstName, string lastName, AdminLevel level, User user, int id = 0)
 {
     FirstName = firstName;
     LastName  = lastName;
     Level     = level;
     User      = user;
     Id        = id;
 }
Ejemplo n.º 4
0
        internal void HandleJoin(PacketEventArgs e)
        {
            Login login = (Login)e.Packet;

            Guid       = login.Guid;
            Encryption = login.Encryption == 250;
            ListenPort = login.ListenPort;
            NodeIp     = login.NodeIp;
            NodePort   = login.NodePort;
            name       = login.Username.FormatUsername();
            if (string.IsNullOrWhiteSpace(name))
            {
                name = ExternalIp.AnonUsername();
            }
            orgname     = name;
            Version     = login.Version;
            LocalIp     = login.LocalIp;
            Browsable   = (login.SupportFlag & 2) == 2;
            Compression = (login.SupportFlag & 4) == 4;
            Age         = login.Age;
            Gender      = login.Gender;
            Country     = login.Country;
            Region      = login.Region;
            Features    = login.Features;

            if ((Features & ClientFeatures.OPUS_VOICE) == ClientFeatures.OPUS_VOICE)
            {
                Features |= ClientFeatures.VOICE;
            }

            if ((Features & ClientFeatures.PRIVATE_OPUS_VOICE) == ClientFeatures.PRIVATE_OPUS_VOICE)
            {
                Features |= ClientFeatures.PRIVATE_VOICE;
            }

            var record    = server.History.Add(this);
            var autologin = server.History.Admin.Passwords.Find((s) => s.ClientId.Equals(record));

            admin = (autologin != null) ? autologin.Level : admin;
            admin = (LocalHost) ? AdminLevel.Host : admin;

            if (admin != AdminLevel.User)
            {
                RaisePropertyChanged("Admin");
            }

            if (!LocalHost)
            {
                DnsHelper.Resolve(record, FinishResolve);
            }
            else if (AllowedJoin(record))
            {
                FinishJoin();
            }
        }
Ejemplo n.º 5
0
        internal static void LoadHelp()
        {
            if (help != null)
            {
                return;
            }
            help = new Dictionary <AdminLevel, List <string> >();

            Stream       stream = null;
            StreamReader reader = null;

            try {
                Regex    regex = new Regex("^\\[(\\w+?)\\]$");
                Assembly asm   = Assembly.GetExecutingAssembly();

                stream = asm.GetManifestResourceStream("Commands.Help.txt");
                reader = new StreamReader(stream);

                AdminLevel level = AdminLevel.User;
                help[level] = new List <string>();

                while (!reader.EndOfStream)
                {
                    string line  = reader.ReadLine();
                    Match  match = regex.Match(line);

                    if (match.Success)
                    {
                        string str = match.Groups[1].Value;

                        if (str != "General")
                        {
                            level       = (AdminLevel)Enum.Parse(typeof(AdminLevel), str);
                            help[level] = new List <string>();
                        }
                    }

                    help[level].Add(line);
                }
            }
            catch { }
            finally {
                if (reader != null)
                {
                    reader.Close();
                    reader.Dispose();
                }

                if (stream != null)
                {
                    stream.Dispose();
                }
            }
        }
Ejemplo n.º 6
0
        internal void HandleJoin(PacketEventArgs e)
        {
            Login login = (Login)e.Packet;

            Guid       = login.Guid;
            ClientId   = new ClientId(Guid, ExternalIp);
            Encryption = login.Encryption == 250;
            ListenPort = login.ListenPort;
            NodeIp     = login.NodeIp;
            NodePort   = login.NodePort;
            name       = login.Username.FormatUsername();
            if (string.IsNullOrWhiteSpace(name))
            {
                name = ExternalIp.AnonUsername();
            }
            OrgName = name;
            Version = login.Version;
            LocalIp = login.LocalIp;
            Age     = login.Age;
            Gender  = login.Gender;
            Country = login.Country;
            Region  = login.Region;

            HandleFeatures(login);

            var record    = server.History.Add(this);
            var autologin = server.History.Admin.Passwords.Find((s) => s.ClientId.Equals(record.ClientId));

            admin = (autologin != null) ? autologin.Level : admin;
            admin = (LocalHost) ? AdminLevel.Host : admin;

            if (AllowedJoin(record))
            {
                if (server.Config.BotProtection)
                {
                    if (!record.Trusted)
                    {
                        IsCaptcha = true;
                        return;
                    }
                }

                FinishJoin();
            }
            else
            {
                server.Stats.Rejected++;
            }
        }
Ejemplo n.º 7
0
 /// <summary>
 /// 创建管理员
 /// </summary>
 /// <param name="userName">用户名</param>
 /// <param name="paw">密码</param>
 /// <param name="realName">真实姓名</param>
 /// <param name="userState">用户状态</param>
 /// <param name="adminLevel">管理员等级</param>
 public CreateUserCommand(
     string userName,
     string paw,
     string realName,
     UserState userState,
     AdminLevel adminLevel)
 {
     Guard.IsNotNullOrEmpty(userName, "userName");
     Guard.IsNotNullOrEmpty(paw, "paw");
     Guard.IsNotNullOrEmpty(realName, "realName");
     UserName  = userName;
     Paw       = paw;
     RealName  = realName;
     UserState = userState;
 }
Ejemplo n.º 8
0
 internal CharacterLoginData(OldPacket pkt)
 {
     name      = pkt.GetBreakString();
     id        = pkt.GetInt();
     level     = pkt.GetChar();
     gender    = pkt.GetChar();
     hairstyle = pkt.GetChar();
     haircolor = pkt.GetChar();
     race      = pkt.GetChar();
     admin     = (AdminLevel)pkt.GetChar();
     boots     = pkt.GetShort();
     armor     = pkt.GetShort();
     hat       = pkt.GetShort();
     shield    = pkt.GetShort();
     weapon    = pkt.GetShort();
 }
Ejemplo n.º 9
0
        public bool EditManager(long groupId, long userId, AdminLevel? role, bool? isContact = null, string contactPosition = null, string contactPhone = null, string contactEmail = null)
        {
            VkErrors.ThrowIfNumberIsNegative(() => groupId);
            VkErrors.ThrowIfNumberIsNegative(() => userId);
            var parameters = new GroupsEditManagerParams
            {
                GroupId = groupId,
                UserId = userId,
                ContactEmail = contactEmail,
                ContactPhone = contactPhone,
                ContactPosition = contactPosition,
                IsContact = isContact,
                Role = role
            };

            return EditManager(parameters);
        }
Ejemplo n.º 10
0
        public override async Task <bool> CanModifyEntityAsync(Article entity, AdminLevel adminLevel)
        {
            switch (adminLevel)
            {
            case AdminLevel.Global:
                return(true);

            case AdminLevel.Restricted:
                var user = await _mediator.Send(new GetAuthenticatedUserQuery());

                bool userModeratingArticleBoard = user.BoardsModerating.Contains(entity.BoardId);
                return(userModeratingArticleBoard);

            case AdminLevel.None:
            default:
                return(false);
            }
        }
Ejemplo n.º 11
0
        public static string ToFriendlyString(AdminLevel al)
        {
            switch (al)
            {
            case AdminLevel.USER:
                return("User");

            case AdminLevel.MODERATOR:
                return("Moderator");

            case AdminLevel.ADMIN:
                return("Administrator");

            case AdminLevel.OWNER:
                return("Owner");
            }
            return("");
        }
Ejemplo n.º 12
0
        public User()
        {
            Articles = new List <Article>();
            Comments = new List <Comment>();

            SavedArticles = new List <UserArticle>();
            SavedComments = new List <UserComment>();

            LikedArticles = new List <UserArticleLikes>();
            LikedComments = new List <UserCommentLikes>();

            DislikedArticles = new List <UserArticleDislikes>();
            DislikedComments = new List <UserCommentDislikes>();

            BoardsModerating = new List <BoardUserModerator>();
            BoardsSubscribed = new List <BoardUserSubscriber>();

            AdminLevel = AdminLevel.Restricted;
        }
Ejemplo n.º 13
0
        private ISpriteSheet CreateAdminGraphic(AdminLevel adminLevel)
        {
            var adminGraphic = _gfxManager.TextureFromResource(GFXTypes.PreLoginUI, 22);

            switch (adminLevel)
            {
            case AdminLevel.Player:
                return(new EmptySpriteSheet());

            case AdminLevel.Guide:
                return(new SpriteSheet(adminGraphic, new Rectangle(252, 39, 17, 17)));

            case AdminLevel.Guardian:
            case AdminLevel.GM:
            case AdminLevel.HGM:
                return(new SpriteSheet(adminGraphic, new Rectangle(233, 39, 17, 17)));

            default:
                throw new ArgumentOutOfRangeException(nameof(adminLevel), adminLevel, null);
            }
        }
Ejemplo n.º 14
0
 public abstract Task <bool> CanDeleteEntityAsync(TEntity entity, AdminLevel adminLevel);
Ejemplo n.º 15
0
 public void SendToAdmin(AdminLevel minlevel, string message)
 {
     SendAnnounce((s) => s.Admin >= minlevel, message);
 }
Ejemplo n.º 16
0
        public Dictionary<string, int> GetParentIds(AdminLevel filterBy, AdminLevelType parentType)
        {
            Dictionary<string, int> parentIds = new Dictionary<string, int>();
            if (filterBy == null && parentType == null)
                return parentIds;

            OleDbConnection connection = new OleDbConnection(DatabaseData.Instance.AccessConnectionString);
            using (connection)
            {
                connection.Open();
                try
                {
                    OleDbCommand command = new OleDbCommand();

                    if (filterBy != null)
                    {
                        command = new OleDbCommand(@"Select AdminLevels.ID, AdminLevels.DisplayName
                            FROM AdminLevels WHERE ParentId=@ParentId AND IsDeleted=0 ", connection);
                        command.Parameters.Add(new OleDbParameter("@ParentId", filterBy.Id));
                    }
                    else if (parentType != null)
                    {
                        command = new OleDbCommand(@"Select AdminLevels.ID, AdminLevels.DisplayName
                            FROM AdminLevels  WHERE AdminLevelTypeId = @AdminLevelTypeId AND IsDeleted=0 ", connection);
                        command.Parameters.Add(new OleDbParameter("@AdminLevelTypeId", parentType.Id));
                    }

                    using (OleDbDataReader reader = command.ExecuteReader())
                    {
                        while (reader.Read())
                        {
                            if (!parentIds.ContainsKey(reader.GetValueOrDefault<string>("DisplayName").ToLower()))
                                parentIds.Add(reader.GetValueOrDefault<string>("DisplayName").ToLower(), reader.GetValueOrDefault<int>("ID"));
                        }
                        reader.Close();
                    }

                    return parentIds;

                }
                catch (Exception)
                {
                    throw;
                }
            }
        }
Ejemplo n.º 17
0
        public void SendAdminMessage(string prefix, string message, Color prefixColour, AdminLevel requiredLevel = AdminLevel.Moderator)
        {
            var session = Sessions;

            foreach (var player in session.PlayerList)
            {
                var adminLevel = player.GetLocalData("User.PermissionLevel", AdminLevel.User);
                if (adminLevel >= requiredLevel)
                {
                    Log.ToClient(prefix, message, prefixColour, player.Source);
                }
            }
        }
Ejemplo n.º 18
0
        public List<AdminLevel> GetAdminLevelTreeForDemography(int level, DateTime startDate, DateTime endDate, ref List<AdminLevel> list)
        {
            OleDbConnection connection = new OleDbConnection(DatabaseData.Instance.AccessConnectionString);
            using (connection)
            {
                connection.Open();
                OleDbCommand command = new OleDbCommand(@"Select AdminLevels.ID, ParentId, AdminLevels.DisplayName, UrbanOrRural, LatWho, LngWho, 
                    AdminLevelTypes.AdminLevel, AdminLevels.SortOrder, AdminLevelTypeId
                    FROM AdminLevels inner join AdminLevelTypes on AdminLevels.AdminLevelTypeId = AdminLevelTypes.ID
                    WHERE AdminLevel <= @AdminLevel AND AdminLevels.IsDeleted = 0 
                    ORDER BY AdminLevelTypes.AdminLevel, AdminLevels.SortOrder, AdminLevels.DisplayName ", connection);
                command.Parameters.Add(new OleDbParameter("@AdminLevel", level));
                using (OleDbDataReader reader = command.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        var al = new AdminLevel
                        {
                            Id = reader.GetValueOrDefault<int>("ID"),
                            ParentId = reader.GetValueOrDefault<Nullable<int>>("ParentId"),
                            Name = reader.GetValueOrDefault<string>("DisplayName"),
                            LevelNumber = reader.GetValueOrDefault<int>("AdminLevel"),
                            UrbanOrRural = reader.GetValueOrDefault<string>("UrbanOrRural"),
                            LatWho = reader.GetValueOrDefault<Nullable<double>>("LatWho"),
                            LngWho = reader.GetValueOrDefault<Nullable<double>>("LngWho"),
                            AdminLevelTypeId = reader.GetValueOrDefault<int>("AdminLevelTypeId"),
                            SortOrder = reader.GetValueOrDefault<int>("SortOrder"),
                        };
                        al.CurrentDemography = GetDemoByAdminLevelIdAndYear(al.Id, startDate, endDate);
                        list.Add(al);

                    }
                    reader.Close();
                }
            }
            return MakeTreeFromFlatList(list, 0);
        }
Ejemplo n.º 19
0
        public void AddChildren(AdminLevel parent, List<AdminLevel> children, AdminLevelType childType, int byUserId)
        {
            bool transWasStarted = false;
            OleDbConnection connection = new OleDbConnection(DatabaseData.Instance.AccessConnectionString);
            using (connection)
            {
                connection.Open();
                try
                {
                    // START TRANS
                    OleDbCommand command = new OleDbCommand("BEGIN TRANSACTION", connection);
                    command.ExecuteNonQuery();
                    transWasStarted = true;

                    foreach (var child in children)
                    {
                        command = new OleDbCommand(@"Insert Into AdminLevels (DisplayName, AdminLevelTypeId, 
                        ParentId, UrbanOrRural, LatWho, LngWho,  UpdatedById, UpdatedAt, CreatedById, CreatedAt) VALUES
                        (@DisplayName, @AdminLevelTypeId, @ParentId, @UrbanOrRural, @LatWho, @LngWho, 
                         @updatedby, @updatedat, @CreatedById, @CreatedAt)", connection);
                        command.Parameters.Add(new OleDbParameter("@DisplayName", child.Name));
                        command.Parameters.Add(new OleDbParameter("@AdminLevelTypeId", childType.Id));
                        command.Parameters.Add(new OleDbParameter("@ParentId", parent.Id));
                        command.Parameters.Add(new OleDbParameter("@UrbanOrRural", child.UrbanOrRural));
                        command.Parameters.Add(new OleDbParameter("@LatWho", child.LatWho));
                        command.Parameters.Add(new OleDbParameter("@LngWho", child.LngWho));
                        command.Parameters.Add(new OleDbParameter("@updatedby", byUserId));
                        command.Parameters.Add(OleDbUtil.CreateDateTimeOleDbParameter("@updatedat", DateTime.Now));
                        command.Parameters.Add(new OleDbParameter("@CreatedById", byUserId));
                        command.Parameters.Add(OleDbUtil.CreateDateTimeOleDbParameter("@CreatedAt", DateTime.Now));
                        command.ExecuteNonQuery();
                    }

                    // COMMIT TRANS
                    command = new OleDbCommand("COMMIT TRANSACTION", connection);
                    command.ExecuteNonQuery();
                    transWasStarted = false;
                }
                catch (Exception)
                {
                    if (transWasStarted)
                    {
                        try
                        {
                            OleDbCommand cmd = new OleDbCommand("ROLLBACK TRANSACTION", connection);
                            cmd.ExecuteNonQuery();
                        }
                        catch { }
                    }
                    throw;
                }
            }
        }
Ejemplo n.º 20
0
 private DiseaseDistroCm SplitDdCm(List<DiseaseDistroCm> toMerge, DiseaseDistroDetails details, AdminLevel dest, double multiplier, int redistrictId, OleDbCommand command, OleDbConnection connection)
 {
     var dd = diseaseRepo.GetDiseaseDistributionCm(details.Id, details.TypeId);
     var newForm = Util.DeepClone(dd);
     if (newForm.AdminLevelId != dest.Id)
     {
         newForm.Id = 0;
         newForm.IsRedistricted = true;
         newForm.AdminLevelId = dest.Id;
     }
     newForm.IndicatorValues = RedistributeIndicators(newForm.IndicatorValues, multiplier);
     if (toMerge == null)
     {
         diseaseRepo.SaveCm(newForm, userId, connection, command);
         demoRepo.InsertRedistrictForm(command, connection, userId, redistrictId, dd.Id, newForm.Id, IndicatorEntityType.DiseaseDistribution);
     }
     else
         toMerge.Add(newForm);
     return newForm;
 }
Ejemplo n.º 21
0
        public void InsertRedistrictUnit(OleDbCommand command, OleDbConnection connection, int userId, AdminLevel unit, int redistrictId,
            RedistrictingRelationship relationship, double percent, bool isDeleted)
        {
            command = new OleDbCommand(@"Insert Into RedistrictUnits (AdminLevelUnitId, RelationshipId, Percentage, RedistrictEventId) VALUES
                        (@AdminLevelUnitId, @RelationshipId, @Percentage, @RedistrictEventId)", connection);
            command.Parameters.Add(new OleDbParameter("@AdminLevelUnitId", unit.Id));
            command.Parameters.Add(new OleDbParameter("@RelationshipId", (int)relationship));
            command.Parameters.Add(new OleDbParameter("@Percentage", percent));
            command.Parameters.Add(new OleDbParameter("@RedistrictEventId", redistrictId));
            command.ExecuteNonQuery();

            if (relationship == RedistrictingRelationship.Mother)
            {
                command = new OleDbCommand(@"Update AdminLevels SET RedistrictIdForMother=@RedistrictIdForMother, IsDeleted=@IsDeleted 
                        where ID = @AdminLevelId", connection);
                command.Parameters.Add(new OleDbParameter("@RedistrictIdForMother", redistrictId));
                command.Parameters.Add(new OleDbParameter("@IsDeleted", isDeleted));
                command.Parameters.Add(new OleDbParameter("@AdminLevelId", unit.Id));
                command.ExecuteNonQuery();

            }
            else // for daughters add the new admin levels
            {
                command = new OleDbCommand(@"Update AdminLevels SET RedistrictIdForDaughter=@RedistrictIdForDaughter
                        where ID = @AdminLevelId", connection);
                command.Parameters.Add(new OleDbParameter("@RedistrictIdForDaughter", redistrictId));
                command.Parameters.Add(new OleDbParameter("@AdminLevelId", unit.Id));
                command.ExecuteNonQuery();
                foreach (var child in unit.Children)
                {
                    command = new OleDbCommand(@"Update AdminLevels SET ParentId=@ParentId where ID = @AdminLevelId", connection);
                    command.Parameters.Add(new OleDbParameter("@ParentId", unit.Id));
                    command.Parameters.Add(new OleDbParameter("@AdminLevelId", child.Id));
                    command.ExecuteNonQuery();
                }
            }

        }
Ejemplo n.º 22
0
 private Dictionary<int, SentinelSite> SplitSentinelSites(AdminLevel source, List<AdminLevelAllocation> dests, OleDbCommand command, OleDbConnection connection)
 {
     Dictionary<int, SentinelSite> newSites = new Dictionary<int, SentinelSite>();
     var sites = surveyRepo.GetSitesForAdminLevel(new List<string> { source.Id.ToString() });
     foreach (var site in sites)
     {
         CloneSite(source, dests, command, connection, newSites, site);
     }
     return newSites;
 }
Ejemplo n.º 23
0
 private void CloneSite(AdminLevel source, List<AdminLevelAllocation> dests, OleDbCommand command, OleDbConnection connection, Dictionary<int, SentinelSite> newSites, SentinelSite site)
 {
     var newSite = Util.DeepClone(site);
     // remove other admin levels
     site.AdminLevels = new List<AdminLevel> { source };
     surveyRepo.Update(site, userId, connection, command);
     // update admin levels to new dests
     newSite.Id = 0;
     newSite.AdminLevels.RemoveAll(a => a.Id == source.Id);
     newSite.AdminLevels.AddRange(dests.Select(a => a.Unit));
     newSites.Add(site.Id, surveyRepo.Insert(newSite, userId, connection, command));
 }
Ejemplo n.º 24
0
        private SurveyBase SplitSurveys(SurveyDetails details, AdminLevel source, List<AdminLevelAllocation> dests, int redistrictId, OleDbCommand command, 
            OleDbConnection connection, Dictionary<int, SentinelSite> newSites)
        {
            var oldSurvey = surveyRepo.GetById(details.Id);

            // make new
            var newForm = Util.DeepClone(oldSurvey);
            // save old with only original unit
            oldSurvey.Notes += string.Format(Translations.RedistrictSurveyNote, string.Join(", ", oldSurvey.AdminLevels.Select(s => s.Name).ToArray()));
            oldSurvey.AdminLevels = new List<AdminLevel> { source };
            surveyRepo.SaveSurveyBase(command, connection, oldSurvey, userId);

            // add new units
            // We used to make sure it didn't exist in the destination yet? dont get it, must be split combine... if (!newForm.AdminLevels.Select(a => a.Id).Contains(dest.Id))
            newForm.Id = 0;
            newForm.IsRedistricted = true;
            newForm.AdminLevels.RemoveAll(a => a.Id == source.Id);
            newForm.AdminLevels.AddRange(dests.Select(a => a.Unit));
            if (oldSurvey.SentinelSiteId.HasValue && oldSurvey.SentinelSiteId > 0)
            {
                if (!newSites.ContainsKey(oldSurvey.SentinelSiteId.Value))
                {  
                    var oldSite = surveyRepo.GetSiteById(oldSurvey.SentinelSiteId.Value);
                    CloneSite(source, dests, command, connection, newSites, oldSite);
                }
                newForm.SentinelSiteId = newSites[oldSurvey.SentinelSiteId.Value].Id;
            }

            surveyRepo.SaveSurveyBase(command, connection, newForm, userId);
            demoRepo.InsertRedistrictForm(command, connection, userId, redistrictId, oldSurvey.Id, newForm.Id, IndicatorEntityType.Survey);
            
            return newForm;
        }
Ejemplo n.º 25
0
        private void SplitSourceToDestination(RedistrictingOptions options, OleDbCommand command, OleDbConnection connection, int redistrictId, AdminLevel dest,
            AdminLevel source, double percent, List<AdminLevelDemography> demosToMerge, List<DiseaseDistroCm> ddCmMerge, List<DiseaseDistroPc> ddPcMerge,
            List<IntvBase> intvMerge, List<ProcessBase> procsMerge)
        {
            double percentMultiplier = (percent / 100);
            // split all demography
            List<DemoDetails> demoDetails = demoRepo.GetAdminLevelDemography(source.Id);
            foreach (var deet in demoDetails)
                SplitDemo(demosToMerge, deet, dest.Id, percentMultiplier, redistrictId, command, connection);
            // split all distros 
            List<DiseaseDistroDetails> dds = diseaseRepo.GetAllForAdminLevel(source.Id);
            foreach (var dd in dds)
                if (dd.DiseaseType == "PC")
                    options.DistrosPc.Add(SplitDdPc(ddPcMerge, dd, dest, percentMultiplier, redistrictId, command, connection));
                else
                    options.DistrosCm.Add(SplitDdCm(ddCmMerge, dd, dest, percentMultiplier, redistrictId, command, connection));
            // split all intvs 
            List<IntvDetails> intvs = intvRepo.GetAllForAdminLevel(source.Id);
            foreach (var intv in intvs)
                options.Intvs.Add(SplitIntv(intvMerge, intv, dest, percentMultiplier, redistrictId, command, connection));
            // split all processes 
            IEnumerable<ProcessDetails> processes = processRepo.GetAllForAdminLevel(source.Id).Where(i => i.TypeId != (int)StaticProcessType.SAEs);
            foreach (var process in processes)
                options.Processes.Add(SplitProcesses(procsMerge, process, dest, percentMultiplier, redistrictId, command, connection));

        }
Ejemplo n.º 26
0
        private void MergeSurveys(RedistrictingOptions opts, List<SurveyBase> toMerge, AdminLevel dest, int redistrictId, OleDbCommand command, OleDbConnection connection)
        {   
            foreach (var oldForm in toMerge)
            {
                SurveyBase newForm = Util.DeepClone(oldForm);
                // remove all but merge sources
                oldForm.AdminLevels.RemoveAll(a => !opts.MergeSources.Select(s => s.Id).Contains(a.Id));
                surveyRepo.SaveSurveyBase(command, connection, oldForm, userId);

                newForm.Id = 0;
                newForm.IsRedistricted = true;
                // remove all the old admin levels
                newForm.AdminLevels.RemoveAll(a => opts.MergeSources.Select(s => s.Id).Contains(a.Id));
                newForm.AdminLevels.Add(dest);
                surveyRepo.SaveSurveyBase(command, connection, newForm, userId);
                opts.Surveys.Add(newForm);
                demoRepo.InsertRedistrictForm(command, connection, userId, redistrictId, oldForm.Id, newForm.Id, IndicatorEntityType.Survey);
            }
        }
Ejemplo n.º 27
0
 internal Password(IClient client, string sha1text)
 {
     this.clientid = client.ClientId;
     this.level    = client.Admin;
     this.sha1text = sha1text;
 }
Ejemplo n.º 28
0
 private IntvBase SplitIntv(List<IntvBase> toMerge, IntvDetails details, AdminLevel dest, double multiplier, int redistrictId, OleDbCommand command, OleDbConnection connection)
 {
     var intv = intvRepo.GetById(details.Id);
     var newForm = Util.DeepClone(intv);
     if (newForm.AdminLevelId != dest.Id)
     {
         newForm.Id = 0;
         newForm.IsRedistricted = true;
         newForm.AdminLevelId = dest.Id;
     }
     newForm.IndicatorValues = RedistributeIndicators(intv.IndicatorValues, multiplier);
     if (toMerge == null)
     {
         intvRepo.SaveIntvBase(command, connection, newForm, userId);
         demoRepo.InsertRedistrictForm(command, connection, userId, redistrictId, intv.Id, newForm.Id, IndicatorEntityType.Intervention);
     }
     else
         toMerge.Add(newForm);
     return newForm;
 }
Ejemplo n.º 29
0
 protected override string GetAdminLevelName(AdminLevel adminLevel, IHaveDynamicIndicatorValues form)
 {
     SurveyBase survey = (SurveyBase)form;
     return string.Join(", ", survey.AdminLevels.Select(a => a.Name).ToArray());
 }
Ejemplo n.º 30
0
 private ProcessBase SplitProcesses(List<ProcessBase> toMerge, ProcessDetails details, AdminLevel dest, double multiplier, int redistrictId, OleDbCommand command, OleDbConnection connection)
 {
     var process = processRepo.GetById(details.Id);
     var newForm = Util.DeepClone(process);
     if (newForm.AdminLevelId != dest.Id)
     {
         newForm.Id = 0;
         newForm.IsRedistricted = true;
         newForm.AdminLevelId = dest.Id;
     }
     newForm.IndicatorValues = RedistributeIndicators(process.IndicatorValues, multiplier);
     if (toMerge == null)
     {
         processRepo.Save(command, connection, newForm, userId);
         demoRepo.InsertRedistrictForm(command, connection, userId, redistrictId, process.Id, newForm.Id, IndicatorEntityType.Process);
     }
     else
         toMerge.Add(newForm);
     return newForm;
 }
Ejemplo n.º 31
0
 public AdminLevel GetAdminLevelById(int id)
 {
     AdminLevel al = new AdminLevel();
     OleDbConnection connection = new OleDbConnection(DatabaseData.Instance.AccessConnectionString);
     using (connection)
     {
         connection.Open();
         OleDbCommand command = new OleDbCommand(@"Select AdminLevels.ID, ParentId, AdminLevels.DisplayName, UrbanOrRural, LatWho, LngWho, AdminLevels.SortOrder,
             AdminLevelTypes.AdminLevel, AdminLevelTypes.DisplayName as LevelName
             FROM AdminLevels inner join AdminLevelTypes on AdminLevels.AdminLevelTypeId = AdminLevelTypes.ID
             WHERE AdminLevels.ID = @id", connection);
         command.Parameters.Add(new OleDbParameter("@id", id));
         using (OleDbDataReader reader = command.ExecuteReader())
         {
             while (reader.Read())
             {
                 al = new AdminLevel
                 {
                     Id = reader.GetValueOrDefault<int>("ID"),
                     ParentId = reader.GetValueOrDefault<Nullable<int>>("ParentId"),
                     Name = reader.GetValueOrDefault<string>("DisplayName"),
                     LevelNumber = reader.GetValueOrDefault<int>("AdminLevel"),
                     LevelName = reader.GetValueOrDefault<string>("LevelName"),
                     UrbanOrRural = reader.GetValueOrDefault<string>("UrbanOrRural"),
                     LatWho = reader.GetValueOrDefault<double>("LatWho"),
                     LngWho = reader.GetValueOrDefault<double>("LngWho"),
                     SortOrder = reader.GetValueOrDefault<int>("SortOrder"),
                 };
             }
             reader.Close();
         }
     }
     return al;
 }
Ejemplo n.º 32
0
 public Password(IClient client, string text)
 {
     this.clientid = new ClientId(client);
     this.level    = client.Admin;
     this.sha1text = CreateSha1Text(text);
 }
Ejemplo n.º 33
0
        public List<AdminLevel> GetAdminUnitsWithParentsAndChildren(int level, DateTime startDate, DateTime endDate)
        {
            List<AdminLevel> list = new List<AdminLevel>();
            OleDbConnection connection = new OleDbConnection(DatabaseData.Instance.AccessConnectionString);
            using (connection)
            {
                connection.Open();
                OleDbCommand command = new OleDbCommand(@"Select AdminLevels.ID, ParentId, AdminLevels.DisplayName, UrbanOrRural, LatWho, LngWho, 
                    AdminLevelTypes.AdminLevel, AdminLevels.SortOrder, AdminLevelTypeId, TaskForceName
                    FROM AdminLevels inner join AdminLevelTypes on AdminLevels.AdminLevelTypeId = AdminLevelTypes.ID
                    WHERE AdminLevels.IsDeleted = 0 
                    ORDER BY AdminLevels.SortOrder, AdminLevels.DisplayName ", connection);
                using (OleDbDataReader reader = command.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        var al = new AdminLevel
                        {
                            Id = reader.GetValueOrDefault<int>("ID"),
                            ParentId = reader.GetValueOrDefault<Nullable<int>>("ParentId"),
                            Name = reader.GetValueOrDefault<string>("DisplayName"),
                            TaskForceName = reader.GetValueOrDefault<string>("TaskForceName"),
                            LevelNumber = reader.GetValueOrDefault<int>("AdminLevel"),
                            UrbanOrRural = reader.GetValueOrDefault<string>("UrbanOrRural"),
                            LatWho = reader.GetValueOrDefault<Nullable<double>>("LatWho"),
                            LngWho = reader.GetValueOrDefault<Nullable<double>>("LngWho"),
                            AdminLevelTypeId = reader.GetValueOrDefault<int>("AdminLevelTypeId"),
                            SortOrder = reader.GetValueOrDefault<int>("SortOrder"),
                        };
                        al.CurrentDemography = GetDemoByAdminLevelIdAndYear(al.Id, startDate, endDate);
                        list.Add(al);

                    }
                    reader.Close();
                }
            }
            // Build tree
            var dic = list.ToDictionary(n => n.Id, n => n);
            var tree = new List<AdminLevel>();
            foreach (var node in list)
            {
                if (node.ParentId.HasValue)
                {
                    AdminLevel parent = dic[node.ParentId.Value];
                    node.Parent = parent;
                    parent.Children.Add(node);
                }
                else
                {
                    tree.Add(node);
                }
            }
            // only return required list and flatten children
            List<AdminLevel> reportingLevels = list.Where(i => i.LevelNumber == level).ToList();
            foreach (var u in reportingLevels)
                u.Children = u.Children.Flatten(c => c.Children).ToList();
            return reportingLevels;
        }
Ejemplo n.º 34
0
 public Password(Record record, AdminLevel level, SecureString pass)
 {
     this.clientid = record.ClientId;
     this.level    = level;
     this.sha1text = CreateSha1Text(pass);
 }
Ejemplo n.º 35
0
        public void BulkImportAdminLevels(DataSet ds, int byUserId)
        {
            bool transWasStarted = false;
            OleDbConnection connection = new OleDbConnection(DatabaseData.Instance.AccessConnectionString);
            using (connection)
            {
                connection.Open();
                try
                {
                    // START TRANS
                    OleDbCommand command = new OleDbCommand("BEGIN TRANSACTION", connection);
                    command.ExecuteNonQuery();
                    transWasStarted = true;

                    command = new OleDbCommand(@"Update AdminLevels set IsDeleted=1, UpdatedById=@UpdatedBy, 
                    UpdatedAt=@UpdatedAt WHERE ID > 1", connection);
                    command.Parameters.Add(new OleDbParameter("@UpdatedBy", byUserId));
                    command.Parameters.Add(OleDbUtil.CreateDateTimeOleDbParameter("@UpdatedAt", DateTime.Now));
                    command.ExecuteNonQuery();


                    Dictionary<string, int> regions = new Dictionary<string, int>();
                    foreach (DataRow row in ds.Tables[0].Rows)
                    {
                        if (!regions.ContainsKey(row["Region"].ToString()))
                        {
                            AdminLevel region = new AdminLevel
                            {
                                LevelNumber = 2,
                                Name = row["Region"].ToString(),
                                ParentId = 1
                            };
                            int id = InsertAdminLevelHelper(command, region, connection, byUserId);
                            regions.Add(row["Region"].ToString(), id);
                        }

                        AdminLevel district = new AdminLevel
                        {
                            LevelNumber = 3,
                            Name = row["District"].ToString(),
                            ParentId = regions[row["Region"].ToString()]
                        };
                        InsertAdminLevelHelper(command, district, connection, byUserId);
                    }

                    // COMMIT TRANS
                    command = new OleDbCommand("COMMIT TRANSACTION", connection);
                    command.ExecuteNonQuery();
                    transWasStarted = false;
                }
                catch (Exception)
                {
                    if (transWasStarted)
                    {
                        try
                        {
                            OleDbCommand cmd = new OleDbCommand("ROLLBACK TRANSACTION", connection);
                            cmd.ExecuteNonQuery();
                        }
                        catch { }
                    }
                    throw;
                }
            }
        }
Ejemplo n.º 36
0
        public bool EditManager(ulong groupId, ulong userId, AdminLevel? role, bool? isContact = null, string contactPosition = null, string contactPhone = null, string contactEmail = null)
        {
            var parameters = new VkParameters
                {
                    {"group_id", groupId},
                    {"user_id", userId},
                    {"role", role},
                    {"is_contact", isContact},
                    {"contact_position", contactPosition},
                    {"contact_phone", contactPhone},
                    {"contact_email", contactEmail}
                };

            return _vk.Call("groups.unbanUser", parameters);
        }
Ejemplo n.º 37
0
        public void UpdateTaskForceData(AdminLevel model, int userid)
        {
            bool transWasStarted = false;
            OleDbConnection connection = new OleDbConnection(DatabaseData.Instance.AccessConnectionString);
            using (connection)
            {
                connection.Open();
                try
                {
                    // START TRANS
                    OleDbCommand command = new OleDbCommand("BEGIN TRANSACTION", connection);
                    command.ExecuteNonQuery();
                    transWasStarted = true;

                    command = new OleDbCommand(@"UPDATE AdminLevels set TaskForceName=@TaskForceName, TaskForceId=@TaskForceId, 
                        UpdatedById=@updatedby, UpdatedAt=@updatedat WHERE ID=@ID", connection);
                    command.Parameters.Add(new OleDbParameter("@TaskForceName", model.TaskForceName));
                    command.Parameters.Add(new OleDbParameter("@TaskForceId", model.TaskForceId));
                    command.Parameters.Add(new OleDbParameter("@updatedby", userid));
                    command.Parameters.Add(OleDbUtil.CreateDateTimeOleDbParameter("@updatedat", DateTime.Now));
                    command.Parameters.Add(new OleDbParameter("@ID", model.Id));
                    command.ExecuteNonQuery();

                    // COMMIT TRANS
                    command = new OleDbCommand("COMMIT TRANSACTION", connection);
                    command.ExecuteNonQuery();
                    transWasStarted = false;
                }
                catch (Exception)
                {
                    if (transWasStarted)
                    {
                        try
                        {
                            OleDbCommand cmd = new OleDbCommand("ROLLBACK TRANSACTION", connection);
                            cmd.ExecuteNonQuery();
                        }
                        catch { }
                    }
                    throw;
                }
            }
        }
Ejemplo n.º 38
0
 public async Task <bool> IsAtLeastAsync(IUser user, AdminLevel level)
 {
     return(await GetAdminLevelAsync(user) >= level);
 }
Ejemplo n.º 39
0
        public bool EditManager(long groupId, long userId, AdminLevel? role, bool? isContact = null, string contactPosition = null, string contactPhone = null, string contactEmail = null)
        {
            VkErrors.ThrowIfNumberIsNegative(() => groupId);
            VkErrors.ThrowIfNumberIsNegative(() => userId);
            var parameters = new VkParameters
                {
                    {"group_id", groupId},
                    {"user_id", userId},
                    {"role", role},
                    {"is_contact", isContact},
                    {"contact_position", contactPosition},
                    {"contact_phone", contactPhone},
                    {"contact_email", contactEmail}
                };

            return _vk.Call("groups.unbanUser", parameters);
        }
 public static void RegisterAdminCommand(string commandName, Action <Command> commandFunc, AdminLevel requiredLevel)
 {
     ACEWrappers.CreateRestrictedCommand(commandName, commandFunc, requiredLevel);
 }
Ejemplo n.º 41
0
 public RequireAdmin(AdminLevel level = AdminLevel.ADMIN)
 {
     _level = level;
 }
Ejemplo n.º 42
0
 public bool EditManager(long groupId, long userId, AdminLevel? role)
 {
     // Проверка на неотрицательные значения в след. методе
     return EditManager(groupId, userId, role, null);
 }
Ejemplo n.º 43
0
 internal CharacterRenderData(Packet pkt)
 {
     name = pkt.GetBreakString();
     id = pkt.GetInt();
     level = pkt.GetChar();
     gender = pkt.GetChar();
     hairstyle = pkt.GetChar();
     haircolor = pkt.GetChar();
     race = pkt.GetChar();
     admin = (AdminLevel)pkt.GetChar();
     boots = pkt.GetShort();
     armor = pkt.GetShort();
     hat = pkt.GetShort();
     shield = pkt.GetShort();
     weapon = pkt.GetShort();
 }
Ejemplo n.º 44
0
 public abstract Task <bool> CanModifyEntityAsync(TEntity entity, AdminLevel adminLevel);
Ejemplo n.º 45
0
        private int InsertAdminLevelHelper(OleDbCommand command, AdminLevel adminLevel, OleDbConnection connection, int userId)
        {
            command = new OleDbCommand(@"Insert Into AdminLevels (DisplayName, AdminLevelTypeId, 
                        ParentId, UpdatedById, UpdatedAt, CreatedById, CreatedAt) VALUES
                        (@DisplayName, @AdminLevelTypeId, @ParentId, @UpdatedBy, @UpdatedAt, @CreatedById, @CreatedAt)", connection);
            command.Parameters.Add(new OleDbParameter("@DisplayName", adminLevel.Name));
            command.Parameters.Add(new OleDbParameter("@AdminLevelTypeId", adminLevel.AdminLevelTypeId));
            command.Parameters.Add(new OleDbParameter("@ParentId", adminLevel.ParentId));
            command.Parameters.Add(new OleDbParameter("@UpdatedBy", userId));
            command.Parameters.Add(OleDbUtil.CreateDateTimeOleDbParameter("@UpdatedAt", DateTime.Now));
            command.Parameters.Add(new OleDbParameter("@CreatedById", userId));
            command.Parameters.Add(OleDbUtil.CreateDateTimeOleDbParameter("@CreatedAt", DateTime.Now));
            command.ExecuteNonQuery();

            command = new OleDbCommand(@"SELECT Max(ID) FROM AdminLevels", connection);
            int id = (int)command.ExecuteScalar();

            if (adminLevel.CurrentDemography != null)
            {
                adminLevel.CurrentDemography.AdminLevelId = id;
                SaveAdminDemography(command, connection, adminLevel.CurrentDemography, userId);
            }
            return id;
        }
Ejemplo n.º 46
0
 public void SendToAdmin(AdminLevel minlevel, IPacket packet)
 {
     SendPacket((s) => s.Admin >= minlevel, packet);
 }
 public ServerCommandAttribute(string commandName, AdminLevel usage)
 {
     Command     = commandName;
     AdminLevel  = usage;
     IsRestriced = true;
 }
Ejemplo n.º 48
0
 public void Delete(AdminLevel unit, int userId)
 {
     OleDbConnection connection = new OleDbConnection(DatabaseData.Instance.AccessConnectionString);
     using (connection)
     {
         connection.Open();
         try
         {
             OleDbCommand command = new OleDbCommand(@"UPDATE AdminLevels SET IsDeleted=@IsDeleted,
                    UpdatedById=@UpdatedById, UpdatedAt=@UpdatedAt WHERE ID=@id", connection);
             command.Parameters.Add(new OleDbParameter("@IsDeleted", true));
             command.Parameters.Add(new OleDbParameter("@UpdatedById", userId));
             command.Parameters.Add(OleDbUtil.CreateDateTimeOleDbParameter("@UpdatedAt", DateTime.Now));
             command.Parameters.Add(new OleDbParameter("@id", unit.Id));
             command.ExecuteNonQuery();
         }
         catch (Exception)
         {
             throw;
         }
     }
 }
Ejemplo n.º 49
0
 public Password(Guid guid, IPAddress ip, string sha1text, AdminLevel level)
 {
     this.clientid = new ClientId(guid, ip);
     this.level    = level;
     this.sha1text = sha1text;
 }
Ejemplo n.º 50
0
        internal static bool HandleCommand(IServer server, IClient client, string text)
        {
            string cmd  = String.Empty;
            string args = String.Empty;

            int sep = text.IndexOf('\x20');

            if (sep == -1)
            {
                cmd = text;
            }
            else
            {
                cmd = text.Substring(0, sep);

                if (text.Length > (sep + 1))
                {
                    args = text.Substring(sep + 1);
                }
            }

            switch (cmd)
            {
            case "id":
                server.SendAnnounce(client, String.Format(Strings.UserId, client.Id));
                break;

            case "vroom":
                ushort vroom = 0;

                if (UInt16.TryParse(args, out vroom))
                {
                    client.Vroom = vroom;
                }

                break;

            case "admins":
            case "listadmins": {
                if (client.Admin > AdminLevel.User)
                {
                    var tmp = server.History.Admin.ToList();
                    tmp.Sort((a, b) => ((int)a.Admin) - ((int)b.Admin));

                    server.SendAnnounce(client, String.Format("-- Admins: {0} --", tmp.Count));

                    foreach (var user in tmp)
                    {
                        server.SendAnnounce(client, String.Format("{0}: {1}", user.Admin, user.Name));
                    }
                }
            }
            break;

            case "topic":
                if (client.Admin > AdminLevel.Moderator)
                {
                    server.Config.Topic = args;
                }

                break;

            case "info":
            case "whois": {
                if (client.Admin > AdminLevel.User)
                {
                    IClient target = ParseUserCommand(server, args, out args);

                    if (target != null)
                    {
                        server.SendAnnounce(client, String.Format("-- Whois: {0} --", target.Name));
                        server.SendAnnounce(client, String.Format("Id: {0}", target.Id));
                        server.SendAnnounce(client, String.Format("Level: {0}", target.Admin));
                        server.SendAnnounce(client, String.Format("Vroom: {0}", target.Vroom));
                        server.SendAnnounce(client, String.Format("Muzzled: {0}", target.Muzzled));
                        server.SendAnnounce(client, String.Format("IsCaptcha: {0}", target.IsCaptcha));
                        server.SendAnnounce(client, String.Format("Address: {0}", target.ExternalIp));
                        server.SendAnnounce(client, String.Format("DnsEntry: {0}", target.DnsEntry != null ? target.DnsEntry.HostName : "error"));
                        server.SendAnnounce(client, String.Format("Client: {0}", target.Version));
                    }
                    else
                    {
                        server.SendAnnounce(client, "-- Userlist Info --");

                        foreach (var user in server.Users)
                        {
                            server.SendAnnounce(client, String.Format("[{0}] - {1}", user.Id, user.Name));
                        }
                    }
                }
            }
            break;

            case "whowas": {
                if (client.Admin > AdminLevel.User)
                {
                    var targets = ParseHistoryCommand(server, args, out args);

                    if (targets.Count > 0)
                    {
                        for (int i = 0; i < targets.Count; i++)
                        {
                            var target = targets[i];

                            server.SendAnnounce(client, String.Format("-- Whowas: {0} --", target.Name));
                            server.SendAnnounce(client, String.Format("Muzzled: {0}", target.Muzzled));
                            server.SendAnnounce(client, String.Format("Trusted: {0}", target.Trusted));
                            server.SendAnnounce(client, String.Format("Address: {0}", target.ClientId.ExternalIp));
                            server.SendAnnounce(client, String.Format("DnsEntry: {0}", string.IsNullOrEmpty(target.DnsName) ? target.DnsName : "error"));
                            server.SendAnnounce(client, String.Format("LastSeen: {0} (Server Time)", target.LastSeen));

                            if (i < (targets.Count - 1))
                            {
                                server.SendAnnounce(" ");
                            }
                        }
                    }
                    else
                    {
                        server.SendAnnounce(client, Strings.HistoryNotFound);
                    }
                }
            }
            break;

            case "muzzle": {
                if (client.Admin > AdminLevel.User)
                {
                    IClient target = ParseUserCommand(server, args, out args);

                    if (target != null && client.Admin > target.Admin)
                    {
                        target.Muzzled = true;
                    }
                }
            }
            break;

            case "unmuzzle": {
                if (client.Admin > AdminLevel.User)
                {
                    IClient target = ParseUserCommand(server, args, out args);

                    if (target != null && client.Admin > target.Admin)
                    {
                        target.Muzzled = false;
                    }
                }
            }
            break;

            case "kill":
            case "kick":
            case "disconnect": {
                if (client.Admin > AdminLevel.User)
                {
                    IClient target = ParseUserCommand(server, args, out args);

                    if (target != null && client.Admin > target.Admin)
                    {
                        server.SendAnnounce(String.Format(Strings.Kicked, target.Name));
                        target.Disconnect();
                    }
                }
            }
            break;

            case "redirect": {
                if (client.Admin > AdminLevel.Moderator)
                {
                    IClient target = ParseUserCommand(server, args, out args);
                    Channel hash   = HashConvert.FromHashlinkString <Channel>(args);

                    if (hash != null)
                    {
                        if (target != null && client.Admin > target.Admin)
                        {
                            server.SendPacket(target, new Redirect(hash, String.Format(Strings.Redirected, hash.Name)));
                        }
                    }
                }
            }
            break;

            case "ban": {
                if (client.Admin > AdminLevel.User)
                {
                    IClient target = ParseUserCommand(server, args, out args);

                    if (target != null && client.Admin > target.Admin)
                    {
                        server.SendAnnounce(String.Format(Strings.Banned, target.Name));
                        target.Ban();
                    }
                }
            }
            break;

            case "listbans": {
                if (client.Admin > AdminLevel.User)
                {
                    string format = "[{0}] - {1}";
                    server.SendAnnounce(client, "-- Banned Users --");

                    for (int i = 0; i < server.History.Bans.Count; i++)
                    {
                        var banned = server.History.Bans[i];
                        var record = server.History.Find((s) => banned.Equals(s));

                        if (record != null)
                        {
                            server.SendAnnounce(client, String.Format(format, i, record.Name));
                        }
                    }
                }
            }
            break;

            case "unban": {
                if (client.Admin > AdminLevel.User)
                {
                    var targets = ParseHistoryCommand(server, args, out args);

                    if (targets.Count > 0)
                    {
                        targets.ForEach((s) => {
                                server.History.Bans.Remove(s.ClientId);
                                server.SendAnnounce(String.Format(Strings.Unbanned, s.Name));
                            });
                    }
                    else
                    {
                        server.SendAnnounce(client, Strings.HistoryNotFound);
                    }
                }
            }
            break;

            case "cbans":
            case "clearbans": {
                if (client.Admin > AdminLevel.Moderator)
                {
                    server.History.Bans.Clear();
                    server.SendAnnounce(String.Format(Strings.BansCleared, client.Name));
                }
            }
            break;

            case "bandns": {
                if (client.Admin > AdminLevel.Moderator)
                {
                    try {
                        Regex reg = new Regex(args, RegexOptions.IgnoreCase);
                        server.History.DnsBans.Add(reg);

                        server.SendAnnounce(String.Format(Strings.DnsBanAdd, reg.ToString()));
                    }
                    catch (ArgumentException ex) {
                        server.SendAnnounce(client, String.Format(Strings.InvalidPattern, ex.Message));
                    }
                }
            }
            break;

            case "listdnsbans": {
                if (client.Admin > AdminLevel.Moderator)
                {
                    string format = "[{0}] - {1}";
                    server.SendAnnounce(client, "-- Banned Dns Names --");

                    for (int i = 0; i < server.History.DnsBans.Count; i++)
                    {
                        var regex = server.History.DnsBans[i];
                        server.SendAnnounce(client, String.Format(format, i, regex.ToString()));
                    }
                }
            }
            break;

            case "unbandns":
                if (client.Admin > AdminLevel.Moderator)
                {
                    int index = 0;

                    if (Int32.TryParse(args, out index))
                    {
                        if (index < 0)
                        {
                            index = 0;
                        }

                        if (index >= server.History.DnsBans.Count)
                        {
                            server.SendAnnounce(client, Strings.InvalidIndex);
                        }
                        else
                        {
                            Regex regex = server.History.DnsBans[index];
                            server.History.DnsBans.RemoveAt(index);

                            server.SendAnnounce(String.Format(Strings.DnsBanRemove, regex.ToString()));
                        }
                    }
                    else
                    {
                        try {
                            Regex regex = new Regex(args);
                            server.History.DnsBans.Remove(regex);

                            server.SendAnnounce(String.Format(Strings.DnsBanRemove, regex.ToString()));
                        }
                        catch (ArgumentException ex) {
                            server.SendAnnounce(client, String.Format(Strings.InvalidPattern, ex.Message));
                        }
                    }
                }
                break;

            case "cdnsbans":
            case "cleardnsbans": {
                if (client.Admin > AdminLevel.Moderator)
                {
                    server.History.DnsBans.Clear();
                    server.SendAnnounce(String.Format(Strings.DnsBansCleared, client.Name));
                }
            }
            break;

            case "banrange":
                if (client.Admin > AdminLevel.Moderator)
                {
                    try {
                        Regex reg = new Regex(args, RegexOptions.IgnoreCase);
                        server.History.RangeBans.Add(reg);

                        server.SendAnnounce(String.Format(Strings.RangeBanAdd, reg.ToString()));
                    }
                    catch (ArgumentException ex) {
                        server.SendAnnounce(String.Format(Strings.InvalidPattern, ex.Message));
                    }
                }
                break;

            case "listrangebans": {
                if (client.Admin > AdminLevel.Moderator)
                {
                    string format = "[{0}] - {1}";
                    server.SendAnnounce(client, "-- Banned IP Addresses --");

                    for (int i = 0; i < server.History.RangeBans.Count; i++)
                    {
                        var regex = server.History.RangeBans[i];
                        server.SendAnnounce(client, String.Format(format, i, regex.ToString()));
                    }
                }
            }
            break;

            case "unbanrange":
                if (client.Admin > AdminLevel.Moderator)
                {
                    int index = 0;

                    if (Int32.TryParse(args, out index))
                    {
                        if (index < 0)
                        {
                            index = 0;
                        }

                        if (index >= server.History.RangeBans.Count)
                        {
                            server.SendAnnounce(client, Strings.InvalidIndex);
                        }
                        else
                        {
                            Regex regex = server.History.RangeBans[index];
                            server.History.RangeBans.RemoveAt(index);

                            server.SendAnnounce(String.Format(Strings.RangeBanRemove, regex.ToString()));
                        }
                    }
                    else
                    {
                        try {
                            Regex regex = new Regex(args);
                            server.History.RangeBans.Remove(regex);

                            server.SendAnnounce(String.Format(Strings.RangeBanRemove, regex.ToString()));
                        }
                        catch (Exception ex) {
                            server.SendAnnounce(client, String.Format(Strings.InvalidPattern, ex.Message));
                        }
                    }
                }
                break;

            case "crangebans":
            case "clearrangebans": {
                if (client.Admin > AdminLevel.Moderator)
                {
                    server.History.RangeBans.Clear();
                    server.SendAnnounce(String.Format(Strings.RangeBansCleared, client.Name));
                }
            }
            break;

            case "grant": {
                if (client.Admin >= AdminLevel.Host)
                {
                    AdminLevel tmp    = 0;
                    IClient    target = ParseUserCommand(server, args, out args);

                    if (target != null && Enum.TryParse <AdminLevel>(args, out tmp))
                    {
                        if (client.LocalHost || client.Admin >= target.Admin)
                        {
                            target.Admin = tmp;
                        }

                        else
                        {
                            target.Admin = (AdminLevel)Math.Min((int)client.Admin, (int)tmp);
                        }

                        var password = server.History.Admin.Passwords.Find((s) => s.ClientId.Equals(target));

                        if (password != null)
                        {
                            password.ClientId.Guid       = target.Guid;
                            password.ClientId.ExternalIp = target.ExternalIp;
                            password.Level = tmp;
                        }
                    }
                }
            }
            break;

            case "captcha": {
                if (client.Admin >= AdminLevel.Host)
                {
                    IClient target = ParseUserCommand(server, args, out args);

                    if (target != null)
                    {
                        target.IsCaptcha = true;
                    }
                }
            }
            break;

            case "skipcaptcha": {
                if (client.Admin >= AdminLevel.Host)
                {
                    IClient target = ParseUserCommand(server, args, out args);

                    if (target != null)
                    {
                        target.IsCaptcha = false;
                    }
                }
            }
            break;

            case "loadplugin":
                if (client.Admin >= AdminLevel.Host)
                {
                    server.PluginHost.LoadPlugin(args);
                }

                break;

            case "killplugin":
                if (client.Admin >= AdminLevel.Host)
                {
                    server.PluginHost.KillPlugin(args);
                }

                break;

            case "listplugins":
                if (client.Admin > AdminLevel.User)
                {
                    server.SendAnnounce("-- Active plugins --");

                    foreach (var plugin in server.PluginHost)
                    {
                        if (plugin.Enabled)
                        {
                            server.SendAnnounce(client, plugin.Name);
                        }
                    }
                }
                break;
            }

            return(true);
        }
Ejemplo n.º 51
0
 /// <summary>
 /// Позволяет назначить/разжаловать руководителя в сообществе или изменить уровень его полномочий.
 /// </summary>
 /// <param name="groupId">Идентификатор сообщества (указывается без знака «минус»)</param>
 /// <param name="userId">Идентификатор пользователя, чьи полномочия в сообществе нужно изменить</param>
 /// <param name="role">Уровень полномочий. Если параметр не задан, с пользователя user_id снимаются полномочия руководителя</param>
 /// <returns>В случае успешного выполнения возвращает true</returns>
 /// <remarks>
 /// Страница документации ВКонтакте <see href="http://vk.com/dev/groups.editManager"/>.
 /// </remarks>
 public bool EditManager(ulong groupId, ulong userId, AdminLevel? role)
 {
     return EditManager(groupId, userId, role, null);
 }
Ejemplo n.º 52
0
 public Password(Guid guid, IPAddress ip, SecureString pass, AdminLevel level)
 {
     this.clientid = new ClientId(guid, ip);
     this.level    = level;
     this.sha1text = CreateSha1Text(pass);
 }
Ejemplo n.º 53
0
            public AccountData(Player player, String ipAddress, String serial, String username, String password)
            {
                AccountId = 0;
                Username  = "";
                Admin     = AdminLevel.None;
                Error     = ErrorType.AccessError;

                try
                {
                    NetRequest request = new NetRequest(NetRequestMode.Magestorm, SubscriptionPage, ipAddress, String.Format("u={0}", username), String.Format("p={0}", password));

                    if (!request.Succeeded)
                    {
                        Error = ErrorType.AccessError;
                        return;
                    }

                    String[] uData = request.Response.Split('|');

                    switch (uData.Length)
                    {
                    case 1:
                    {
                        Error = (ErrorType)Math.Abs(Convert.ToInt32(uData[0]));

                        break;
                    }

                    case 4:
                    {
                        AccountId = Convert.ToUInt16(uData[0]);

                        if (AccountId > 0)
                        {
                            Admin         = (AdminLevel)Convert.ToInt32(uData[1]);
                            Username      = Convert.ToString(uData[2]);
                            MagestormPlus = Convert.ToBoolean(uData[3]);
                            Error         = ErrorType.None;
                        }
                        else
                        {
                            Error = ErrorType.InvalidAccount;
                        }

                        break;
                    }

                    default:
                    {
                        Error = ErrorType.UnknownError;

                        break;
                    }
                    }

                    if (PlayerManager.Players.GetFreePlayerCount() > 100 && (!MagestormPlus && Admin == AdminLevel.None))
                    {
                        Error = ErrorType.ServerFull;
                    }

                    if (Error == ErrorType.None)
                    {
                        Player connectedPlayer = PlayerManager.Players.FindByAccountId(AccountId);

                        if (connectedPlayer != null)
                        {
                            Error = player != connectedPlayer ? ErrorType.LoggedIn : ErrorType.None;

                            if (Error == ErrorType.LoggedIn)
                            {
                                connectedPlayer.DisconnectReason = Resources.Strings_Disconnect.MultipleLogin;
                                connectedPlayer.Disconnect       = true;
                            }
                        }

                        if (serial != "Not_Found" && serial != "VMWare" && serial != "VirtualPC")
                        {
                            connectedPlayer = PlayerManager.Players.FindBySerial(serial);

                            if (connectedPlayer != null)
                            {
                                if (!connectedPlayer.IsAdmin && Admin == AdminLevel.None)
                                {
                                    Error = ErrorType.LoggedIn;
                                }
                            }
                        }

                        if (MySQL.BannedSerials.IsBanned(serial))
                        {
                            Error = ErrorType.BannedComputer;
                        }

                        if (Settings.Default.Locked && Admin == AdminLevel.None)
                        {
                            Error = ErrorType.ServerLocked;
                        }
                    }
                }
                catch (Exception)
                {
                    Error = ErrorType.AccessError;
                }
            }
Ejemplo n.º 54
0
        public void Save(AdminLevel model, int userid)
        {
            bool transWasStarted = false;
            OleDbConnection connection = new OleDbConnection(DatabaseData.Instance.AccessConnectionString);
            using (connection)
            {
                connection.Open();
                try
                {
                    // START TRANS
                    OleDbCommand command = new OleDbCommand("BEGIN TRANSACTION", connection);
                    command.ExecuteNonQuery();
                    transWasStarted = true;

                    if (model.Id > 0)
                    {
                        command = new OleDbCommand(@"UPDATE AdminLevels set DisplayName=@DisplayName, UrbanOrRural=@UrbanOrRural, 
                        LatWho=@LatWho, LngWho=@LngWho, UpdatedById=@updatedby, UpdatedAt=@updatedat WHERE ID=@ID", connection);
                        command.Parameters.Add(new OleDbParameter("@DisplayName", model.Name));
                        command.Parameters.Add(OleDbUtil.CreateNullableParam("@UrbanOrRural", model.UrbanOrRural));
                        command.Parameters.Add(OleDbUtil.CreateNullableParam("@LatWho", model.LatWho));
                        command.Parameters.Add(OleDbUtil.CreateNullableParam("@LngWho", model.LngWho));
                        command.Parameters.Add(new OleDbParameter("@updatedby", userid));
                        command.Parameters.Add(OleDbUtil.CreateDateTimeOleDbParameter("@updatedat", DateTime.Now));
                        command.Parameters.Add(new OleDbParameter("@ID", model.Id));
                        command.ExecuteNonQuery();
                    }
                    else
                    {
                        command = new OleDbCommand(@"Insert Into AdminLevels (DisplayName, AdminLevelTypeId, 
                        ParentId, UrbanOrRural, LatWho, LngWho, UpdatedById, UpdatedAt, CreatedById, CreatedAt) VALUES
                        (@DisplayName, @AdminLevelTypeId, @ParentId, @UrbanOrRural, @LatWho, @LngWho, 
                         @updatedby, @updatedat, @CreatedById, @CreatedAt)", connection);
                        command.Parameters.Add(new OleDbParameter("@DisplayName", model.Name));
                        command.Parameters.Add(new OleDbParameter("@AdminLevelTypeId", model.AdminLevelTypeId));
                        command.Parameters.Add(new OleDbParameter("@ParentId", model.ParentId));
                        command.Parameters.Add(OleDbUtil.CreateNullableParam("@UrbanOrRural", model.UrbanOrRural));
                        command.Parameters.Add(OleDbUtil.CreateNullableParam("@LatWho", model.LatWho));
                        command.Parameters.Add(OleDbUtil.CreateNullableParam("@LngWho", model.LngWho));
                        command.Parameters.Add(new OleDbParameter("@updatedby", userid));
                        command.Parameters.Add(OleDbUtil.CreateDateTimeOleDbParameter("@updatedat", DateTime.Now));
                        command.Parameters.Add(new OleDbParameter("@CreatedById", userid));
                        command.Parameters.Add(OleDbUtil.CreateDateTimeOleDbParameter("@CreatedAt", DateTime.Now));
                        command.ExecuteNonQuery();
                        command = new OleDbCommand(@"SELECT Max(ID) FROM AdminLevels", connection);
                        model.Id = (int)command.ExecuteScalar();
                    }

                    // COMMIT TRANS
                    command = new OleDbCommand("COMMIT TRANSACTION", connection);
                    command.ExecuteNonQuery();
                    transWasStarted = false;
                }
                catch (Exception)
                {
                    if (transWasStarted)
                    {
                        try
                        {
                            OleDbCommand cmd = new OleDbCommand("ROLLBACK TRANSACTION", connection);
                            cmd.ExecuteNonQuery();
                        }
                        catch { }
                    }
                    throw;
                }
            }
        }