Next() приватный Метод

private Next ( ) : string
Результат string
Пример #1
1
        protected FuncDrawOperation(Player player, Command cmd)
            : base(player)
        {
            string strFunc = cmd.Next();
            if (string.IsNullOrWhiteSpace(strFunc))
            {
                player.Message("&WEmpty function expression");
                return;
            }
            if (strFunc.Length < 3)
            {
                player.Message("&WExpression is too short (should be like z=f(x,y))");
                return;
            }

            strFunc = strFunc.ToLower();

            _vaxis = GetAxis(SimpleParser.PreparseAssignment(ref strFunc));

            _expression = SimpleParser.Parse(strFunc, GetVarArray(_vaxis));

            Player.Message("Expression parsed as "+_expression.Print());
            string scalingStr=cmd.Next();
            _scaler = new Scaler(scalingStr);
        }
Пример #2
1
        void DoZone( Player player, Command cmd ) {
            if( !player.Can( Permissions.SetSpawn ) ) {
                world.NoAccessMessage( player );
                return;
            }

            string name = cmd.Next();
            if( name == null ) {
                player.Message( "No zone name specified. See " + Color.Help + "/help zone" );
                return;
            }
            if( !Player.IsValidName( name ) ) {
                player.Message( "\"" + name + "\" is not a valid zone name" );
                return;
            }
            Zone zone = new Zone();
            zone.name = name;

            string property = cmd.Next();
            if( property == null ) {
                player.Message( "No zone rank/whitelist/blacklist specified. See " + Color.Help + "/help zone" );
                return;
            }
            PlayerClass minRank = world.classes.ParseClass( property );
            
            if( minRank != null ) {
                zone.buildRank = minRank.rank;
                player.tag = zone;
                player.marksExpected = 2;
                player.marks.Clear();
                player.markCount = 0;
                player.selectionCallback = MakeZone;
            }
        }
Пример #3
1
 static void TrollHandler(Player player, Command cmd)
 {
     string Name = cmd.Next();
     if (Name == null)
     {
         player.Message("Player not found. Please specify valid name.");
         return;
     }
     if (!Player.IsValidName(Name))
         return;
     Player target = Server.FindPlayerOrPrintMatches(player, Name, true, true);
     if (target == null)
         return;
     string options = cmd.Next();
     if (options == null)
     {
         CdTroll.PrintUsage(player);
         return;
     }
     string Message = cmd.NextAll();
     if (Message.Length < 1 && options.ToLower() != "leave")
     {
         player.Message("&WError: Please enter a message for {0}.", target.ClassyName);
         return;
     }
     switch (options.ToLower())
     {
         case "pm":
             if (player.Can(Permission.UseColorCodes) && Message.Contains("%"))
             {
                 Message = Color.ReplacePercentCodes(Message);
             }
             Server.Players.Message("&Pfrom {0}: {1}",
                 target.Name, Message);
             break;
         case "ac":
             Chat.SendAdmin(target, Message);
             break;
         case "st":
         case "staff":
             Chat.SendStaff(target, Message);
             break;
         case "i":
         case "impersonate":
         case "msg":
         case "message":
         case "m":
             Server.Message("{0}&S&F: {1}",
                               target.ClassyName, Message);
             break;
         case "leave":
         case "disconnect":
         case "gtfo":
             Server.Players.Message("&SPlayer {0}&S left the server.",
                 target.ClassyName);
             break;
         default: player.Message("Invalid option. Please choose st, ac, pm, message or leave");
             break;
     }
 }
Пример #4
1
        static void PayHandler(Player player, Command cmd)
        {
            string targetName = cmd.Next();
            string money = cmd.Next();
            int amount;

            if (money == null)
            {
                player.Message("&ePlease select the amount of bits you wish to send.");
                return;
            }

            Player target = Server.FindPlayerOrPrintMatches(player, targetName, false, true);
            if (target == null)
            {
                player.Message("&ePlease select a player to pay bits towards.");
                return;
            }

            if (!int.TryParse(money, out amount))
            {
                player.Message("&ePlease select from a whole number.");
                return;
            }

            PayHandler(player, new Command("/economy pay " + target + " " + money));
        }
        public static void SetParametrization(Player p, Command cmd)
        {
            string strFunc = cmd.Next();
            if (string.IsNullOrWhiteSpace(strFunc))
            {
                p.Message("Error: empty parametrization expression");
                return;
            }
            if (strFunc.Length < 3)
            {
                p.Message("Error: expression is too short (should be like x=f(t,u,v))");
                return;
            }

            strFunc = strFunc.ToLower();

            try
            {
                string coordVar = SimpleParser.PreparseAssignment(ref strFunc);
                CheckCoordVar(coordVar);

                Expression expression = SimpleParser.Parse(strFunc, new string[] { "t", "u", "v" });

                p.Message("Expression parsed as " + coordVar + "=" + expression.Print());

                GetPlayerParametrizationCoordsStorage(p)[VarNameToIdx(coordVar[0])] = expression;
            }
            catch (Exception e)
            {
                p.Message("Error: "+e.Message);
            }
        }
Пример #6
1
 internal static void CModeWater(Player player, Command cmd)
 {
     if (!player.Can(Permissions.ControlPhysics))
     {
         player.NoAccessMessage(Permissions.ControlPhysics);
         return;
     }
     string blockpar = cmd.Next();
     string wmt = "";
     int BlockAddr = -1;
     try { BlockAddr = Convert.ToInt32(blockpar); }
     catch
     {
         player.Message("Incorrect parameter!"); return;
     }
     if (BlockAddr < 3 && BlockAddr >= 0)
     {
         player.world.map.modeWater = BlockAddr;
         switch (BlockAddr)
         {
             case 0: wmt = "'none'"; break;
             case 1: wmt = "'infinite'"; break;
             case 2: wmt = "'finite'"; break;
         }
         player.Message("Water mode set to " + wmt + ".");
     }
 }
Пример #7
0
        void Compass( Player player, Command cmd ) {
            int offset = (int)(player.pos.r / 255f * 64f) + 32;
            string name = cmd.Next();

            if( name != null ) {
                Player target = world.FindPlayer( name );
                if( target != null ) {
                    player.Message( "Coordinates of player \"" + target.name + "\":" );
                    offset = (int)(target.pos.r / 255f * 64f) + 32;
                } else {
                    world.NoPlayerMessage( player, name );
                    return;
                }
            }

            player.Message( Color.Silver, String.Format( "({0},{1},{2}) - {3}[{4}{5}{6}{3}{7}]",
                            player.pos.x / 32,
                            player.pos.y / 32,
                            player.pos.h / 32,
                            Color.White,
                            compass.Substring( offset - 12, 11 ),
                            Color.Red,
                            compass.Substring( offset - 1, 3 ),
                            compass.Substring( offset + 2, 11 ) ) );
        }
Пример #8
0
        internal static void DumpStats( Player player, Command cmd ) {
            string fileName = cmd.Next();
            if( fileName == null ) {
                cdDumpStats.PrintUsage( player );
                return;
            }

            if( !Paths.Contains( Paths.WorkingPath, fileName ) ) {
                player.UnsafePathMessage();
                return;
            }

            if( Paths.IsProtectedFileName( Path.GetFileName( fileName ) ) ) {
                player.Message( "You may not use this file." );
                return;
            }

            if( Path.HasExtension( fileName ) &&
                !Path.GetExtension( fileName ).Equals( ".txt", StringComparison.OrdinalIgnoreCase ) ) {
                player.Message( "Stats filename must end with .txt" );
                return;
            }

            if( File.Exists( fileName ) && !cmd.IsConfirmed ) {
                player.AskForConfirmation( cmd, "File \"{0}\" already exists. Overwrite?", Path.GetFileName( fileName ) );
                return;
            }

            if( !Paths.TestFile( "dumpstats file", fileName, false, true, false ) ) {
                player.Message( "Cannot create specified file. See log for details." );
                return;
            }

            PlayerInfo[] infos;
            using( FileStream fs = File.Create( fileName ) ) {
                using( StreamWriter writer = new StreamWriter( fs ) ) {
                    infos = PlayerDB.GetPlayerListCopy();
                    if( infos.Length == 0 ) {
                        writer.WriteLine( "{0} (0 players)", "(TOTAL)" );
                        writer.WriteLine();
                    } else {
                        DumpPlayerGroupStats( writer, infos, "(TOTAL)" );
                    }

                    foreach( Rank rank in RankManager.Ranks ) {
                        infos = PlayerDB.GetPlayerListCopy( rank );
                        if( infos.Length == 0 ) {
                            writer.WriteLine( "{0} (0 players)", rank.Name );
                            writer.WriteLine();
                        } else {
                            DumpPlayerGroupStats( writer, infos, rank.Name );
                        }
                    }
                }
            }

            player.Message( "Stats saved to \"{0}\"", Path.GetFileName( fileName ) );
        }
Пример #9
0
        public InequalityDrawOperation( Player player, Command cmd )
            : base(player)
        {
            string strFunc = cmd.Next();
            if ( string.IsNullOrWhiteSpace( strFunc ) )
                throw new ArgumentException( "empty inequality expression" );
            if ( strFunc.Length < 3 )
                throw new ArgumentException( "expression is too short (should be like f(x,y,z)>g(x,y,z))" );

            strFunc = strFunc.ToLower();

            _expression = SimpleParser.Parse( strFunc, new string[] { "x", "y", "z" } );
            if ( !_expression.IsInEquality() )
                throw new ArgumentException( "the expression given is not an inequality (should be like f(x,y,z)>g(x,y,z))" );

            player.Message( "Expression parsed as " + _expression.Print() );
            string scalingStr = cmd.Next();
            _scaler = new Scaler( scalingStr );
        }
Пример #10
0
        public EqualityDrawOperation( Player player, Command cmd )
            : base(player)
        {
            string strFunc = cmd.Next();
            if ( string.IsNullOrWhiteSpace( strFunc ) ) {
                player.Message( "empty equality expression" );
                return;
            }
            if ( strFunc.Length < 3 ) {
                player.Message( "expression is too short (should be like f(x,y,z)=g(x,y,z))" );
                return;
            }

            strFunc = strFunc.ToLower();

            _expression = SimpleParser.ParseAsEquality( strFunc, new string[] { "x", "y", "z" } );

            player.Message( "Expression parsed as " + _expression.Print() );
            string scalingStr = cmd.Next();
            _scaler = new Scaler( scalingStr );
        }
Пример #11
0
        void Draw( Player player, Command command, DrawMode mode ) {
            if( !player.Can( Permissions.Draw ) ) {
                world.NoAccessMessage( player );
                return;
            }
            if( player.drawingInProgress ) {
                player.Message( "Another draw command is already in progress. Please wait." );
                return;
            }
            string blockName = command.Next();
            Block block;
            if( blockName == null || blockName == "" ) {
                if( mode == DrawMode.Cuboid ) {
                    player.Message( "Usage: " + Color.Help + "/cuboid blockName" + Color.Sys + " or " + Color.Help + "/cub blockName" );
                } else {
                    player.Message( "Usage: " + Color.Help + "/ellipsoid blockName" + Color.Sys + " or " + Color.Help + "/ell blockName" );
                }
                return;
            }
            try {
                block = Map.GetBlockByName( blockName );
            } catch( Exception ) {
                player.Message( "Unknown block name: " + blockName );
                return;
            }
            player.tag = block;

            Permissions permission = Permissions.Build;
            switch( block ) {
                case Block.Admincrete: permission = Permissions.PlaceAdmincrete; break;
                case Block.Air: permission = Permissions.Delete; break;
                case Block.Water:
                case Block.StillWater: permission = Permissions.PlaceWater; break;
                case Block.Lava:
                case Block.StillLava: permission = Permissions.PlaceLava; break;
            }
            if( !player.Can( permission ) ) {
                player.Message( "You are not allowed to draw with this block." );
                return;
            }

            player.marksExpected = 2;
            player.markCount = 0;
            player.marks.Clear();
            player.Message( mode.ToString() + ": Place a block or type /mark to use your location." );

            if( mode == DrawMode.Cuboid ) {
                player.selectionCallback = DrawCuboid;
            } else {
                player.selectionCallback = DrawEllipsoid;
            }
        }
Пример #12
0
        internal static void WorldInfo( Player player, Command cmd ) {
            string worldName = cmd.Next();
            if( worldName == null ) {
                if( player.World == null ) {
                    player.Message( "Please specify a world name when calling /winfo form console." );
                    return;
                } else {
                    worldName = player.World.Name;
                }
            }

            World world = WorldManager.FindWorldOrPrintMatches( player, worldName );
            if( world == null ) return;

            player.Message( "World {0}&S has {1} player(s) on.",
                            world.GetClassyName(),
                            world.CountVisiblePlayers(player) );

            Map map = world.Map;

            // If map is not currently loaded, grab its header from disk
            if( map == null ) {
                try {
                    map = MapUtility.LoadHeader( Path.Combine( Paths.MapPath, world.GetMapName() ) );
                } catch( Exception ex ) {
                    player.Message( "Map information could not be loaded: {0}: {1}",
                                    ex.GetType().Name, ex.Message );
                }
            }

            if( map != null ) {
                player.Message( "Map dimensions are {0} x {1} x {2}",
                                map.WidthX, map.WidthY, map.Height );
            }

            // Print access/build limits
            world.AccessSecurity.PrintDescription( player, world, "world", "accessed" );
            world.BuildSecurity.PrintDescription( player, world, "world", "modified" );

            // Print lock/unlock information
            if( world.IsLocked ) {
                player.Message( "{0}&S was locked {1} ago by {2}",
                                world.GetClassyName(),
                                DateTime.UtcNow.Subtract( world.LockedDate ).ToMiniString(),
                                world.LockedBy );
            } else if( world.UnlockedBy != null ) {
                player.Message( "{0}&S was unlocked {1} ago by {2}",
                                world.GetClassyName(),
                                DateTime.UtcNow.Subtract( world.UnlockedDate ).ToMiniString(),
                                world.UnlockedBy );
            }
        }
Пример #13
0
 public static void ProcessCommand( Player p, Command cmd )
 {
     string command = cmd.Next();
     if ( String.IsNullOrWhiteSpace( command ) ) {
         p.Message( "&WLife command is missing or empty" );
         return;
     }
     LifeCommand c;
     if ( !Commands.TryGetValue( command.ToLower(), out c ) ) {
         p.Message( "&WUnknown life command " + command + ". &hType '/life help' for the list of commands." );
         return;
     }
     c.F( p, cmd );
 }
Пример #14
0
 internal static void ItemEntAdd(Player player, Command cmd)
 {
     string blockpar = cmd.Next();
     ItemEntType IPar1 = ItemEntType.Null;
     //byte IPar2 = 255;
     try { IPar1 = (ItemEntType)Convert.ToInt32(blockpar); }
     catch
     {
         try { IPar1 = Map.GetItemEntityByName(blockpar); }
         catch { player.Message("Incorrect parameter 1!"); return; }
     }
     blockpar = cmd.Next();
     string[] tmpsa = new string[16];
     int i = 0;
     while (blockpar != "" && blockpar != null)
     {
         tmpsa[i] = blockpar;
         i++;
         blockpar = cmd.Next();
     }
     player.ientpl = i;
     player.ientp = tmpsa;
     if (player.ientmode == BlockPlacementMode.ItemEnt)
     {
         player.ientmode = BlockPlacementMode.Normal;
         player.Message("ItemEntity mode: OFF");
     }
     else if (player.Can(Permissions.PlaceItemEnt))
     {
         player.ientmode = BlockPlacementMode.ItemEnt;
         player.Message("ItemEntity mode: ON. Your next blocks will be ItemEntities.");
         player.ienttype = IPar1;
         /*
         if (IPar2 >= 0 && IPar2 <= 49)
         {
             player.isIentBTDef = true;
             player.ientbt = IPar2;
         }
         */
     }
     else
     {
         player.NoAccessMessage(Permissions.PlaceItemEnt);
     }
 }
Пример #15
0
 internal static void Bring( Player player, Command cmd )
 {
     if( player.Can( Permissions.Bring ) ) {
         string name = cmd.Next();
         Player target = player.world.FindPlayer( name );
         if( target != null ) {
             Position pos = player.pos;
             pos.x += 1;
             pos.y += 1;
             pos.h += 1;
             target.Send( PacketWriter.MakeTeleport( 255, pos ) );
         } else {
             player.NoPlayerMessage( name );
         }
     } else {
         player.NoAccessMessage( Permissions.Bring );
     }
 }
Пример #16
0
 static void BanHandler( Player player, Command cmd ) {
     string targetName = cmd.Next();
     if( targetName == null ) {
         CdBan.PrintUsage( player );
         return;
     }
     PlayerInfo target = PlayerDB.FindPlayerInfoOrPrintMatches( player, targetName );
     if( target == null ) return;
     string reason = cmd.NextAll();
     try {
         Player targetPlayer = target.PlayerObject;
         target.Ban( player, reason, true, true );
         WarnIfOtherPlayersOnIP( player, target, targetPlayer );
     } catch( PlayerOpException ex ) {
         player.Message( ex.MessageColored );
         if( ex.ErrorCode == PlayerOpExceptionCode.ReasonRequired ) {
             FreezeIfAllowed( player, target );
         }
     }
 }
Пример #17
0
        public ManifoldDrawOperation(Player p, Command cmd)
            : base(p)
        {
            _expressions = PrepareParametrizedManifold.GetPlayerParametrizationCoordsStorage(p);
            if (null == _expressions[0])
                throw new InvalidExpressionException("x is undefined");
            if (null == _expressions[1])
                throw new InvalidExpressionException("y is undefined");
            if (null == _expressions[2])
                throw new InvalidExpressionException("z is undefined");

            _paramIterations = PrepareParametrizedManifold.GetPlayerParametrizationParamsStorage(p);
            if (null==_paramIterations[0] && null==_paramIterations[1] && null==_paramIterations[2])
                throw new InvalidExpressionException("all parametrization variables are undefined");

            if (GetNumOfSteps(0) * GetNumOfSteps(1) * GetNumOfSteps(2) > MaxIterationSteps)
                throw new InvalidExpressionException("too many iteration steps (over " + MaxIterationSteps + ")");

            _scaler=new Scaler(cmd.Next());

            p.Message("Going to draw the following parametrization:\nx=" + _expressions[0].Print()+
                "\ny=" + _expressions[1].Print() + "\nz=" + _expressions[2].Print());
        }
Пример #18
0
 void Nick( Player player, Command cmd ) {
     if( !player.Can( Permissions.ChangeName ) ) {
         world.NoAccessMessage( player );
         return;
     }
     string name = cmd.Next();
     if( name == null ) {
         if( player.nick != player.name ) {
             world.SendToAll( Color.Sys + player.nick + " is now known as " + player.name, player );
             player.Message( "You are now known as " + name + ". Use " + Color.Help + "/nick" + Color.Sys + " again to reset." );
             player.nick = player.name;
             world.UpdatePlayer( player );
         } else {
             player.Message( "You do not have an alias set." );
         }
     } else if( Player.IsValidName( name ) ) {
         world.SendToAll( Color.Sys + player.nick + " is now known as " + name, player );
         player.Message( "You are now known as " + name + ". Use " + Color.Help + "/nick" + Color.Sys + " again to reset." );
         player.nick = name;
         world.UpdatePlayer( player );
     } else {
         player.Message( "Invalid player name." );
     }
 }
        static void SetInfoHandler( Player player, Command cmd )
        {
            string targetName = cmd.Next();
            string propertyName = cmd.Next();
            string valName = cmd.NextAll();

            if( targetName == null || propertyName == null ) {
                CdSetInfo.PrintUsage( player );
                return;
            }

            PlayerInfo info = PlayerDB.FindPlayerInfoOrPrintMatches( player, targetName );
            if( info == null ) return;

            switch( propertyName.ToLower() ) {
                case "timeskicked":
                    int oldTimesKicked = info.TimesKicked;
                    if( ValidateInt( valName, 0, 9999 ) ) {
                        info.TimesKicked = Int32.Parse( valName );
                        player.Message( "SetInfo: TimesKicked for {0}&S changed from {1} to {2}",
                                        info.ClassyName,
                                        oldTimesKicked,
                                        info.TimesKicked );
                    } else {
                        player.Message( "SetInfo: TimesKicked value acceptible (Acceptible value range: 0-9999)" );
                    }
                    return;

                case "previousrank":
                    Rank newPreviousRank;
                    if( valName.Length > 0 ) {
                        newPreviousRank = RankManager.FindRank( valName );
                        if( newPreviousRank == null ) {
                            player.MessageNoRank( valName );
                            return;
                        }
                    } else {
                        newPreviousRank = null;
                    }

                    Rank oldPreviousRank = info.PreviousRank;

                    if( newPreviousRank == oldPreviousRank ) {
                        if( newPreviousRank == null ) {
                            player.Message( "SetInfo: PreviousRank for {0}&S is not set.",
                                            info.ClassyName );
                        } else {
                            player.Message( "SetInfo: PreviousRank for {0}&S is already set to {1}",
                                            info.ClassyName,
                                            newPreviousRank.ClassyName );
                        }
                        return;
                    }

                    if( oldPreviousRank == null ) {
                        player.Message( "SetInfo: PreviousRank for {0}&S set to {1}&",
                                        info.ClassyName,
                                        newPreviousRank.ClassyName );
                    } else if( newPreviousRank == null ) {
                        player.Message( "SetInfo: PreviousRank for {0}&S was reset (was {1}&S)",
                                        info.ClassyName,
                                        oldPreviousRank.ClassyName );
                    } else {
                        player.Message( "SetInfo: PreviousRank for {0}&S changed from {1}&S to {2}",
                                        info.ClassyName,
                                        oldPreviousRank.ClassyName,
                                        newPreviousRank.ClassyName );
                    }
                    return;

                case "totaltime":
                    TimeSpan newTotalTime;
                    TimeSpan oldTotalTime = info.TotalTime;
                    if( valName.TryParseMiniTimespan( out newTotalTime ) ) {
                        info.TotalTime = newTotalTime;
                        player.Message( "SetInfo: TotalTime for {0}&S changed from {1} ({2}) to {3} ({4})",
                                        info.ClassyName,
                                        oldTotalTime.ToMiniString(),
                                        oldTotalTime.ToCompactString(),
                                        info.TotalTime.ToMiniString(),
                                        info.TotalTime.ToCompactString() );
                    } else {
                        player.Message( "SetInfo: Could not parse value given for TotalTime." );
                    }
                    return;

                case "rankchangetype":
                    RankChangeType oldType = info.RankChangeType;
                    try {
                        info.RankChangeType = (RankChangeType)Enum.Parse( typeof( RankChangeType ), valName, true );
                    } catch( ArgumentException ) {
                        player.Message( "SetInfo: Could not parse RankChangeType. Allowed values: {0}",
                                        String.Join( ", ", Enum.GetNames( typeof( RankChangeType ) ) ) );
                        return;
                    }
                    player.Message( "SetInfo: RankChangeType for {0}&S changed from {1} to {2}",
                                    info.ClassyName,
                                    oldType,
                                    info.RankChangeType );
                    return;

                case "banreason":
                    if( valName.Length == 0 ) valName = null;
                    if( SetPlayerInfoField( player, "BanReason", info, info.BanReason, valName ) ) {
                        info.BanReason = valName;
                    }
                    return;

                case "unbanreason":
                    if( valName.Length == 0 ) valName = null;
                    if( SetPlayerInfoField( player, "UnbanReason", info, info.UnbanReason, valName ) ) {
                        info.UnbanReason = valName;
                    }
                    return;

                case "rankreason":
                    if( valName.Length == 0 ) valName = null;
                    if( SetPlayerInfoField( player, "RankReason", info, info.RankChangeReason, valName ) ) {
                        info.RankChangeReason = valName;
                    }
                    return;

                case "kickreason":
                    if( valName.Length == 0 ) valName = null;
                    if( SetPlayerInfoField( player, "KickReason", info, info.LastKickReason, valName ) ) {
                        info.LastKickReason = valName;
                    }
                    return;

                case "displayedname":
                    string oldDisplayedName = info.DisplayedName;
                    if( player.Can( Permission.UseColorCodes ) ) {
                        valName = Color.ReplacePercentCodes( valName );
                    }
                    if( valName.Length == 0 ) valName = null;
                    if( valName == info.DisplayedName ) {
                        if( valName == null ) {
                            player.Message( "SetInfo: DisplayedName for {0} is not set.",
                                            info.Name );
                        } else {
                            player.Message( "SetInfo: DisplayedName for {0} is already set to \"{1}&S\"",
                                            info.Name,
                                            valName );
                        }
                        return;
                    }
                    info.DisplayedName = valName;

                    if( oldDisplayedName == null ) {
                        player.Message( "SetInfo: DisplayedName for {0} set to \"{1}&S\"",
                                        info.Name,
                                        valName );
                    } else if( valName == null ) {
                        player.Message( "SetInfo: DisplayedName for {0} was reset (was \"{1}&S\")",
                                        info.Name,
                                        oldDisplayedName );
                    } else {
                        player.Message( "SetInfo: DisplayedName for {0} changed from \"{1}&S\" to \"{2}&S\"",
                                        info.Name,
                                        oldDisplayedName,
                                        valName );
                    }
                    return;

                default:
                    player.Message( "Only the following properties are editable: " +
                                    "TimesKicked, PreviousRank, TotalTime, RankChangeType, " +
                                    "BanReason, UnbanReason, RankReason, KickReason, DisplayedName" );
                    return;
            }
        }
        static void AutoRankAllHandler( Player player, Command cmd )
        {
            string rankName = cmd.Next();
            Rank rank = null;
            if( rankName != null ) {
                rank = RankManager.FindRank( rankName );
                if( rank == null ) {
                    player.MessageNoRank( rankName );
                    return;
                }
            }

            PlayerInfo[] list;
            if( rank == null ) {
                list = PlayerDB.PlayerInfoList;
            } else {
                list = PlayerDB.PlayerInfoList.Where( p => p.Rank == rank ).ToArray();
            }
            DoAutoRankAll( player, list, false, "~AutoRankAll" );
        }
Пример #21
0
        internal static void RulesHandler( Player player, Command cmd ) {
            string sectionName = cmd.Next();

            // if no section name is given
            if( sectionName == null ) {
                FileInfo ruleFile = new FileInfo( Paths.RulesFileName );

                if( ruleFile.Exists ) {
                    PrintRuleFile( player, ruleFile );
                } else {
                    player.Message( DefaultRules );
                }

                // print a list of available sections
                string[] sections = GetRuleSectionList();
                if( sections != null ) {
                    player.Message( "Rule sections: {0}. Type &H/Rules SectionName&S to read.", sections.JoinToString() );
                }
                return;
            }

            // if a section name is given, but no section files exist
            if( !Directory.Exists( Paths.RulesPath ) ) {
                player.Message( "There are no rule sections defined." );
                return;
            }

            string ruleFileName = null;
            string[] sectionFiles = Directory.GetFiles( Paths.RulesPath,
                                                        "*.txt",
                                                        SearchOption.TopDirectoryOnly );

            for( int i = 0; i < sectionFiles.Length; i++ ) {
                string sectionFullName = Path.GetFileNameWithoutExtension( sectionFiles[i] );
                if( sectionFullName == null ) continue;
                if( sectionFullName.StartsWith( sectionName, StringComparison.OrdinalIgnoreCase ) ) {
                    if( sectionFullName.Equals( sectionName, StringComparison.OrdinalIgnoreCase ) ) {
                        // if there is an exact match, break out of the loop early
                        ruleFileName = sectionFiles[i];
                        break;

                    } else if( ruleFileName == null ) {
                        // if there is a partial match, keep going to check for multiple matches
                        ruleFileName = sectionFiles[i];

                    } else {
                        var matches = sectionFiles.Select( f => Path.GetFileNameWithoutExtension( f ) )
                                                  .Where( sn => sn != null && sn.StartsWith( sectionName, StringComparison.OrdinalIgnoreCase ) );
                        // if there are multiple matches, print a list
                        player.Message( "Multiple rule sections matched \"{0}\": {1}",
                                        sectionName, matches.JoinToString() );
                        return;
                    }
                }
            }

            if( ruleFileName != null ) {
                string sectionFullName = Path.GetFileNameWithoutExtension( ruleFileName );
                // ReSharper disable AssignNullToNotNullAttribute
                player.Message( "Rule section \"{0}\":", sectionFullName );
                // ReSharper restore AssignNullToNotNullAttribute
                PrintRuleFile( player, new FileInfo( ruleFileName ) );

            } else {
                var sectionList = GetRuleSectionList();
                if( sectionList == null ) {
                    player.Message( "There are no rule sections defined." );
                } else {
                    player.Message( "No rule section defined for \"{0}\". Available sections: {1}",
                                    sectionName, sectionList.JoinToString() );
                }
            }
        }
Пример #22
0
        internal static void PlayersHandler( Player player, Command cmd ) {
            string param = cmd.Next();
            Player[] players;
            string worldName = null;
            string qualifier;
            int offset = 0;

            if( param == null || Int32.TryParse( param, out offset ) ) {
                // No world name given; Start with a list of all players.
                players = Server.Players;
                qualifier = "online";
                if( cmd.HasNext ) {
                    CdPlayers.PrintUsage( player );
                    return;
                }

            } else {
                // Try to find the world
                World world = WorldManager.FindWorldOrPrintMatches( player, param );
                if( world == null ) return;

                worldName = param;
                // If found, grab its player list
                players = world.Players;
                qualifier = String.Format( "in world {0}&S", world.ClassyName );

                if( cmd.HasNext && !cmd.NextInt( out offset ) ) {
                    CdPlayers.PrintUsage( player );
                    return;
                }
            }

            if( players.Length > 0 ) {
                // Filter out hidden players, and sort
                Player[] visiblePlayers = players.Where( player.CanSee )
                                                 .OrderBy( p => p, PlayerListSorter.Instance )
                                                 .ToArray();


                if( visiblePlayers.Length == 0 ) {
                    player.Message( "There are no players {0}", qualifier );

                } else if( visiblePlayers.Length <= PlayersPerPage || player.IsSuper ) {
                    player.MessagePrefixed( "&S  ", "&SThere are {0} players {1}: {2}",
                                            visiblePlayers.Length, qualifier, visiblePlayers.JoinToClassyString() );

                } else {
                    if( offset >= visiblePlayers.Length ) {
                        offset = Math.Max( 0, visiblePlayers.Length - PlayersPerPage );
                    }
                    Player[] playersPart = visiblePlayers.Skip( offset ).Take( PlayersPerPage ).ToArray();
                    player.MessagePrefixed( "&S   ", "&SPlayers {0}: {1}",
                                            qualifier, playersPart.JoinToClassyString() );

                    if( offset + playersPart.Length < visiblePlayers.Length ) {
                        player.Message( "Showing {0}-{1} (out of {2}). Next: &H/Players {3}{1}",
                                        offset + 1, offset + playersPart.Length,
                                        visiblePlayers.Length,
                                        (worldName == null ? "" : worldName + " ") );
                    } else {
                        player.Message( "Showing players {0}-{1} (out of {2}).",
                                        offset + 1, offset + playersPart.Length,
                                        visiblePlayers.Length );
                    }
                }
            } else {
                player.Message( "There are no players {0}", qualifier );
            }
        }
        static void ImportRanks( Player player, Command cmd )
        {
            string serverName = cmd.Next();
            string fileName = cmd.Next();
            string rankName = cmd.Next();
            bool silent = (cmd.Next() != null);

            // Make sure all parameters are specified
            if( serverName == null || fileName == null || rankName == null ) {
                CdImport.PrintUsage( player );
                return;
            }

            // Check if file exists
            if( !File.Exists( fileName ) ) {
                player.Message( "File not found: {0}", fileName );
                return;
            }

            Rank targetRank = RankManager.FindRank( rankName );
            if( targetRank == null ) {
                player.MessageNoRank( rankName );
                return;
            }

            string[] names;

            switch( serverName.ToLower() ) {
                case "mcsharp":
                case "mczall":
                case "mclawl":
                    try {
                        names = File.ReadAllLines( fileName );
                    } catch( Exception ex ) {
                        Logger.Log( LogType.Error,
                                    "Could not open \"{0}\" to import ranks: {1}",
                                    fileName, ex );
                        return;
                    }
                    break;
                default:
                    player.Message( "fCraft does not support importing from {0}", serverName );
                    return;
            }

            if( !cmd.IsConfirmed ) {
                player.Confirm( cmd, "You are about to import {0} player ranks.", names.Length );
                return;
            }

            string reason = "(Import from " + serverName + ")";
            foreach( string name in names ) {
                PlayerInfo info = PlayerDB.FindPlayerInfoExact( name ) ??
                                  PlayerDB.AddFakeEntry( name, RankChangeType.Promoted );
                try {
                    info.ChangeRank( player, targetRank, reason, !silent, true, false );
                } catch( PlayerOpException ex ) {
                    player.Message( ex.MessageColored );
                }
            }

            PlayerDB.Save();
        }
        static void ReloadHandler( Player player, Command cmd )
        {
            string whatToReload = cmd.Next();
            if( whatToReload == null ) {
                CdReload.PrintUsage( player );
                return;
            }

            whatToReload = whatToReload.ToLower();

            using( LogRecorder rec = new LogRecorder() ) {
                bool success;

                switch( whatToReload ) {
                    case "config":
                        success = Config.Load( true, true );
                        break;

                    case "autorank":
                        success = AutoRankManager.Init();
                        break;

                    case "salt":
                        Heartbeat.Salt = Server.GetRandomString( 32 );
                        player.Message( "&WNote: Until server synchronizes with Minecraft.net, " +
                                        "connecting players may have trouble verifying names." );
                        success = true;
                        break;

                    default:
                        CdReload.PrintUsage( player );
                        return;
                }

                if( rec.HasMessages ) {
                    foreach( string msg in rec.MessageList ) {
                        player.Message( msg );
                    }
                }

                if( success ) {
                    player.Message( "Reload: reloaded {0}.", whatToReload );
                } else {
                    player.Message( "&WReload: Error(s) occured while reloading {0}.", whatToReload );
                }
            }
        }
Пример #25
0
        private static void ZoneAddHandler(Player player, Command cmd)
        {
            World playerWorld = player.World;

            if (playerWorld == null)
            {
                PlayerOpException.ThrowNoWorld(player);
            }

            string givenZoneName = cmd.Next();

            if (givenZoneName == null)
            {
                CdZoneAdd.PrintUsage(player);
                return;
            }

            if (!player.Info.Rank.AllowSecurityCircumvention)
            {
                SecurityCheckResult buildCheck = playerWorld.BuildSecurity.CheckDetailed(player.Info);
                switch (buildCheck)
                {
                case SecurityCheckResult.BlackListed:
                    player.Message("Cannot add zones to world {0}&S: You are barred from building here.",
                                   playerWorld.ClassyName);
                    return;

                case SecurityCheckResult.RankTooLow:
                    player.Message("Cannot add zones to world {0}&S: You are not allowed to build here.",
                                   playerWorld.ClassyName);
                    return;
                    //case SecurityCheckResult.RankTooHigh:
                }
            }

            Zone           newZone        = new Zone();
            ZoneCollection zoneCollection = player.WorldMap.Zones;

            if (givenZoneName.StartsWith("+"))
            {
                // personal zone (/ZAdd +Name)
                givenZoneName = givenZoneName.Substring(1);

                // Find the target player
                PlayerInfo info = PlayerDB.FindPlayerInfoOrPrintMatches(player, givenZoneName);
                if (info == null)
                {
                    return;
                }

                // Make sure that the name is not taken already.
                // If a zone named after the player already exists, try adding a number after the name (e.g. "Notch2")
                newZone.Name = info.Name;
                for (int i = 2; zoneCollection.Contains(newZone.Name); i++)
                {
                    newZone.Name = givenZoneName + i;
                }

                newZone.Controller.MinRank = info.Rank.NextRankUp ?? info.Rank;
                newZone.Controller.Include(info);
                player.Message("Zone: Creating a {0}+&S zone for player {1}&S.",
                               newZone.Controller.MinRank.ClassyName, info.ClassyName);
            }
            else
            {
                // Adding an ordinary, rank-restricted zone.
                if (!World.IsValidName(givenZoneName))
                {
                    player.Message("\"{0}\" is not a valid zone name", givenZoneName);
                    return;
                }

                if (zoneCollection.Contains(givenZoneName))
                {
                    player.Message("A zone with this name already exists. Use &H/ZEdit&S to edit.");
                    return;
                }

                newZone.Name = givenZoneName;

                string rankName = cmd.Next();
                if (rankName == null)
                {
                    player.Message("No rank was specified. See &H/Help zone");
                    return;
                }
                Rank minRank = RankManager.FindRank(rankName);

                if (minRank != null)
                {
                    string name;
                    while ((name = cmd.Next()) != null)
                    {
                        if (name.Length == 0)
                        {
                            continue;
                        }

                        if (name.ToLower().StartsWith("msg="))
                        {
                            newZone.Message = name.Substring(4) + " " + (cmd.NextAll() ?? "");
                            player.Message("Zone: Custom denied messaged changed to '" + newZone.Message + "'");
                            break;
                        }

                        PlayerInfo info = PlayerDB.FindPlayerInfoOrPrintMatches(player, name.Substring(1));
                        if (info == null)
                        {
                            return;
                        }

                        if (name.StartsWith("+"))
                        {
                            newZone.Controller.Include(info);
                        }
                        else if (name.StartsWith("-"))
                        {
                            newZone.Controller.Exclude(info);
                        }
                    }

                    newZone.Controller.MinRank = minRank;
                }
                else
                {
                    player.MessageNoRank(rankName);
                    return;
                }
            }
            player.Message("Zone " + newZone.ClassyName + "&S: Place a block or type &H/Mark&S to use your location.");
            player.SelectionStart(2, ZoneAddCallback, newZone, CdZoneAdd.Permissions);
        }
        static void ImportBans( Player player, Command cmd )
        {
            string serverName = cmd.Next();
            string file = cmd.Next();

            // Make sure all parameters are specified
            if( serverName == null || file == null ) {
                CdImport.PrintUsage( player );
                return;
            }

            // Check if file exists
            if( !File.Exists( file ) ) {
                player.Message( "File not found: {0}", file );
                return;
            }

            string[] names;

            switch( serverName.ToLower() ) {
                case "mcsharp":
                case "mczall":
                case "mclawl":
                    try {
                        names = File.ReadAllLines( file );
                    } catch( Exception ex ) {
                        Logger.Log( LogType.Error,
                                    "Could not open \"{0}\" to import bans: {1}",
                                    file, ex );
                        return;
                    }
                    break;
                default:
                    player.Message( "fCraft does not support importing from {0}", serverName );
                    return;
            }

            if( !cmd.IsConfirmed ) {
                player.Confirm( cmd, "You are about to import {0} bans.", names.Length );
                return;
            }

            string reason = "(import from " + serverName + ")";
            foreach( string name in names ) {
                if( Player.IsValidName( name ) ) {
                    PlayerInfo info = PlayerDB.FindPlayerInfoExact( name ) ??
                                      PlayerDB.AddFakeEntry( name, RankChangeType.Default );
                    info.Ban( player, reason, true, true );

                } else {
                    IPAddress ip;
                    if( Server.IsIP( name ) && IPAddress.TryParse( name, out ip ) ) {
                        ip.BanIP( player, reason, true, true );
                    } else {
                        player.Message( "Could not parse \"{0}\" as either name or IP. Skipping.", name );
                    }
                }
            }

            PlayerDB.Save();
            IPBanList.Save();
        }
Пример #27
0
        private static void ZoneRenameHandler(Player player, Command cmd)
        {
            World playerWorld = player.World;

            if (playerWorld == null)
            {
                PlayerOpException.ThrowNoWorld(player);
            }

            // make sure that both parameters are given
            string oldName = cmd.Next();
            string newName = cmd.Next();

            if (oldName == null || newName == null)
            {
                CdZoneRename.PrintUsage(player);
                return;
            }

            // make sure that the new name is valid
            if (!World.IsValidName(newName))
            {
                player.Message("\"{0}\" is not a valid zone name", newName);
                return;
            }

            // find the old zone
            var  zones   = player.WorldMap.Zones;
            Zone oldZone = zones.Find(oldName);

            if (oldZone == null)
            {
                player.MessageNoZone(oldName);
                return;
            }

            // Check if a zone with "newName" name already exists
            Zone newZone = zones.FindExact(newName);

            if (newZone != null && newZone != oldZone)
            {
                player.Message("A zone with the name \"{0}\" already exists.", newName);
                return;
            }

            // check if any change is needed
            string fullOldName = oldZone.Name;

            if (fullOldName == newName)
            {
                player.Message("The zone is already named \"{0}\"", fullOldName);
                return;
            }

            // actually rename the zone
            zones.Rename(oldZone, newName);

            // announce the rename
            playerWorld.Players.Message("&SZone \"{0}\" was renamed to \"{1}&S\" by {2}",
                                        fullOldName, oldZone.ClassyName, player.ClassyName);
            Logger.Log(LogType.UserActivity,
                       "Player {0} renamed zone \"{1}\" to \"{2}\" on world {3}",
                       player.Name, fullOldName, newName, playerWorld.Name);
        }
Пример #28
0
        private static void ZoneInfoHandler(Player player, Command cmd)
        {
            string zoneName = cmd.Next();

            if (zoneName == null)
            {
                player.Message("No zone name specified. See &H/Help ZInfo");
                return;
            }

            Zone zone = player.WorldMap.Zones.Find(zoneName);

            if (zone == null)
            {
                player.MessageNoZone(zoneName);
                return;
            }

            player.Message("About zone \"{0}\": size {1} x {2} x {3}, contains {4} blocks, editable by {5}+.",
                           zone.Name,
                           zone.Bounds.Width, zone.Bounds.Length, zone.Bounds.Height,
                           zone.Bounds.Volume,
                           zone.Controller.MinRank.ClassyName);

            player.Message("  Zone center is at ({0},{1},{2}).",
                           (zone.Bounds.XMin + zone.Bounds.XMax) / 2,
                           (zone.Bounds.YMin + zone.Bounds.YMax) / 2,
                           (zone.Bounds.ZMin + zone.Bounds.ZMax) / 2);

            if (zone.CreatedBy != null)
            {
                player.Message("  Zone created by {0}&S on {1:MMM d} at {1:h:mm} ({2} ago).",
                               zone.CreatedByClassy,
                               zone.CreatedDate,
                               DateTime.UtcNow.Subtract(zone.CreatedDate).ToMiniString());
            }

            if (zone.EditedBy != null)
            {
                player.Message("  Zone last edited by {0}&S on {1:MMM d} at {1:h:mm} ({2}d {3}h ago).",
                               zone.EditedByClassy,
                               zone.EditedDate,
                               DateTime.UtcNow.Subtract(zone.EditedDate).Days,
                               DateTime.UtcNow.Subtract(zone.EditedDate).Hours);
            }

            PlayerExceptions zoneExceptions = zone.ExceptionList;

            if (zoneExceptions.Included.Length > 0)
            {
                player.Message("  Zone whitelist includes: {0}",
                               zoneExceptions.Included.JoinToClassyString());
            }

            if (zoneExceptions.Excluded.Length > 0)
            {
                player.Message("  Zone blacklist excludes: {0}",
                               zoneExceptions.Excluded.JoinToClassyString());
            }

            if (null != zone.Message)
            {
                player.Message("  Zone has custom deny build message: " + zone.Message);
            }
            else
            {
                player.Message("  Zone has no custom deny build message");
            }
        }
Пример #29
0
        static void TimerHandler(Player player, Command cmd)
        {
            string param = cmd.Next();

            // List timers
            if (param == null)
            {
                ChatTimer[] list = ChatTimer.TimerList.OrderBy(timer => timer.TimeLeft).ToArray();
                if (list.Length == 0)
                {
                    player.Message("No timers running.");
                }
                else
                {
                    player.Message("There are {0} timers running:", list.Length);
                    foreach (ChatTimer timer in list)
                    {
                        player.Message("  #{0} \"{1}&S\" (started by {2}, {3} left)",
                                       timer.Id, timer.Message, timer.StartedBy, timer.TimeLeft.ToMiniString());
                    }
                }
                return;
            }

            // Abort a timer
            if (param.Equals("abort", StringComparison.OrdinalIgnoreCase))
            {
                int timerId;
                if (cmd.NextInt(out timerId))
                {
                    ChatTimer timer = ChatTimer.FindTimerById(timerId);
                    if (timer == null || !timer.IsRunning)
                    {
                        player.Message("Given timer (#{0}) does not exist.", timerId);
                    }
                    else
                    {
                        timer.Stop();
                        string abortMsg = String.Format("&Y(Timer) {0}&Y aborted a timer with {1} left: {2}",
                                                        player.ClassyName, timer.TimeLeft.ToMiniString(), timer.Message);
                        Chat.SendSay(player, abortMsg);
                    }
                }
                else
                {
                    CdTimer.PrintUsage(player);
                }
                return;
            }

            // Start a timer
            if (player.Info.IsMuted)
            {
                player.MessageMuted();
                return;
            }
            if (player.DetectChatSpam())
            {
                return;
            }
            TimeSpan duration;

            if (!param.TryParseMiniTimespan(out duration))
            {
                CdTimer.PrintUsage(player);
                return;
            }
            if (duration > DateTimeUtil.MaxTimeSpan)
            {
                player.MessageMaxTimeSpan();
                return;
            }
            if (duration < ChatTimer.MinDuration)
            {
                player.Message("Timer: Must be at least 1 second.");
                return;
            }

            string sayMessage;
            string message = cmd.NextAll();

            if (String.IsNullOrEmpty(message))
            {
                sayMessage = String.Format("&Y(Timer) {0}&Y started a {1} timer",
                                           player.ClassyName,
                                           duration.ToMiniString());
            }
            else
            {
                sayMessage = String.Format("&Y(Timer) {0}&Y started a {1} timer: {2}",
                                           player.ClassyName,
                                           duration.ToMiniString(),
                                           message);
            }
            Chat.SendSay(player, sayMessage);
            ChatTimer.Start(duration, message, player.Name);
        }
Пример #30
0
        public static void VoteParams(Player player, Command cmd)
        {
            string option = cmd.Next();

            if (option == null)
            {
                player.Message("Invalid param"); return;
            }
            switch (option)
            {
            default:
                if (VoteIsOn)
                {
                    if (VoteKickReason == null)
                    {
                        player.Message("Last Question: {0}&C asked: {1}", VoteStarter, Question);
                        player.Message(Usage);
                        return;
                    }
                    else
                    {
                        player.Message("Last VoteKick: &CA VoteKick has started for {0}&C, reason: {1}", TargetName, VoteKickReason);
                    }
                    player.Message(Usage);
                    return;
                }
                else
                {
                    player.Message(option);
                }
                break;

            case "abort":
            case "stop":
                if (!VoteIsOn)
                {
                    player.Message("No vote is currently running");
                    return;
                }

                if (!player.Can(Permission.MakeVotes))
                {
                    player.Message("You do not have Permission to abort votes");
                    return;
                }
                VoteIsOn = false;
                foreach (Player V in Voted)
                {
                    if (V.Info.HasVoted)
                    {
                        V.Info.HasVoted = false;
                    }
                    V.Message("Your vote was cancelled");
                }
                Voted.Clear();
                TargetName = null;
                Server.Players.Message("{0} &Saborted the vote.", player.ClassyName);
                break;

            case "yes":
                if (!VoteIsOn)
                {
                    player.Message("No vote is currently running");
                    return;
                }

                if (player.Info.HasVoted)
                {
                    player.Message("&CYou have already voted");
                    return;
                }
                Voted.Add(player);
                VotedYes++;
                player.Info.HasVoted = true;
                player.Message("&8You have voted for 'Yes'");
                break;

            case "kick":
                string toKick = cmd.Next();
                string Reason = cmd.NextAll();
                VoteKickReason = Reason;
                if (toKick == null)
                {
                    player.Message("Target cannot be empty. " + Usage);
                    return;
                }

                Player target = Server.FindPlayerOrPrintMatches(player, toKick, false, true);

                if (target == null)
                {
                    // FIX: Target is null when no such player is online, this caused crashes
                    return;
                }

                if (!Player.IsValidName(target.Name))
                {
                    return;
                }

                if (!player.Can(Permission.MakeVoteKicks))
                {
                    player.Message("You do not have permissions to start a VoteKick");
                    return;
                }

                if (VoteIsOn)
                {
                    player.Message("A vote has already started. Each vote lasts 1 minute.");
                    return;
                }

                if (VoteKickReason.Length < 3)
                {
                    player.Message("Invalid reason");
                    return;
                }

                if (target == player)
                {
                    player.Message("You cannot VoteKick yourself, lol");
                    return;
                }

                VoteThread = new Thread(new ThreadStart(delegate
                {
                    TargetName = target.Name;
                    if (!Player.IsValidName(TargetName))
                    {
                        player.Message("Invalid name");
                        return;
                    }
                    NewVote();
                    VoteStarter = player.ClassyName;
                    Server.Players.Message("{0}&S started a VoteKick for player: {1}", player.ClassyName, target.ClassyName);
                    Server.Players.Message("&WReason: {0}", VoteKickReason);
                    Server.Players.Message("&9Vote now! &S/Vote &AYes &Sor /Vote &CNo");
                    VoteIsOn = true;
                    Logger.Log(LogType.SystemActivity, "{0} started a votekick on player {1} reason: {2}", player.Name, target.Name, VoteKickReason);
                    Thread.Sleep(60000);
                    VoteKickCheck();
                })); VoteThread.Start();
                break;

            case "no":
                if (!VoteIsOn)
                {
                    player.Message("No vote is currently running");
                    return;
                }
                if (player.Info.HasVoted)
                {
                    player.Message("&CYou have already voted");
                    return;
                }
                VotedNo++;
                Voted.Add(player);
                player.Info.HasVoted = true;
                player.Message("&8You have voted for 'No'");
                break;

            case "ask":
                string AskQuestion = cmd.NextAll();
                Question = AskQuestion;
                if (!player.Can(Permission.MakeVotes))
                {
                    player.Message("You do not have permissions to ask a question");
                    return;
                }
                if (VoteIsOn)
                {
                    player.Message("A vote has already started. Each vote lasts 1 minute.");
                    return;
                }
                if (Question.Length < 5)
                {
                    player.Message("Invalid question");
                    return;
                }

                VoteThread = new Thread(new ThreadStart(delegate
                {
                    NewVote();
                    VoteStarter = player.ClassyName;
                    Server.Players.Message("{0}&S Asked: {1}", player.ClassyName, Question);
                    Server.Players.Message("&9Vote now! &S/Vote &AYes &Sor /Vote &CNo");
                    VoteIsOn = true;
                    Thread.Sleep(60000);
                    VoteCheck();
                })); VoteThread.Start();
                break;
            }
        }
Пример #31
0
        internal static void RealmAccess(Player player, Command cmd, string worldName, string name)
        {
            // Print information about the current realm
            if (worldName == null)
            {
                if (player.World == null)
                {
                    player.Message("Error.");
                }
                else
                {
                    player.Message(player.World.AccessSecurity.GetDescription(player.World, "realm", "accessed"));
                }
                return;
            }

            // Find a realm by name
            World realm = WorldManager.FindWorldOrPrintMatches(player, worldName);

            if (realm == null)
            {
                return;
            }


            if (name == null)
            {
                player.Message(realm.AccessSecurity.GetDescription(realm, "realm", "accessed"));
                return;
            }
            if (realm == WorldManager.MainWorld)
            {
                player.Message("The main realm cannot have access restrictions.");
                return;
            }

            bool changesWereMade = false;

            do
            {
                if (name.Length < 2)
                {
                    continue;
                }
                // Whitelisting individuals
                if (name.StartsWith("+"))
                {
                    PlayerInfo info;
                    if (!PlayerDB.FindPlayerInfo(name.Substring(1), out info))
                    {
                        player.Message("More than one player found matching \"{0}\"", name.Substring(1));
                        continue;
                    }
                    else if (info == null)
                    {
                        player.MessageNoPlayer(name.Substring(1));
                        continue;
                    }

                    // prevent players from whitelisting themselves to bypass protection


                    if (realm.AccessSecurity.CheckDetailed(info) == SecurityCheckResult.Allowed)
                    {
                        player.Message("{0}&S is already allowed to access {1}&S (by rank)",
                                       info.ClassyName, realm.ClassyName);
                        continue;
                    }

                    Player target = info.PlayerObject;
                    if (target == player)
                    {
                        target = null;                   // to avoid duplicate messages
                    }
                    switch (realm.AccessSecurity.Include(info))
                    {
                    case PermissionOverride.Deny:
                        if (realm.AccessSecurity.Check(info))
                        {
                            player.Message("{0}&S is unbanned from Realm {1}",
                                           info.ClassyName, realm.ClassyName);
                            if (target != null)
                            {
                                target.Message(
                                    "You are now unbanned from Realm {0}&S (removed from blacklist by {1}&S).",
                                    realm.ClassyName, player.ClassyName);
                            }
                        }
                        else
                        {
                            player.Message("{0}&S was unbanned from Realm {1}&S. " +
                                           "Player is still NOT allowed to join (by rank).",
                                           info.ClassyName, realm.ClassyName);
                            if (target != null)
                            {
                                target.Message("You were Unbanned from Realm {0}&S by {1}&S. " +
                                               "You are still NOT allowed to join (by rank).",
                                               player.ClassyName, realm.ClassyName);
                            }
                        }
                        Logger.Log(LogType.UserActivity, "{0} removed {1} from the access blacklist of {2}",
                                   player.Name, info.Name, realm.Name);
                        changesWereMade = true;
                        break;

                    case PermissionOverride.None:
                        player.Message("{0}&S is now allowed to access {1}",
                                       info.ClassyName, realm.ClassyName);
                        if (target != null)
                        {
                            target.Message("You can now access realm {0}&S (whitelisted by {1}&S).",
                                           realm.ClassyName, player.ClassyName);
                        }
                        Logger.Log(LogType.UserActivity, "{0} added {1} to the access whitelist on realm {2}",
                                   player.Name, info.Name, realm.Name);
                        changesWereMade = true;
                        break;

                    case PermissionOverride.Allow:
                        player.Message("{0}&S is already on the access whitelist of {1}",
                                       info.ClassyName, realm.ClassyName);
                        break;
                    }

                    // Blacklisting individuals
                }
                else if (name.StartsWith("-"))
                {
                    PlayerInfo info;
                    if (!PlayerDB.FindPlayerInfo(name.Substring(1), out info))
                    {
                        player.Message("More than one player found matching \"{0}\"", name.Substring(1));
                        continue;
                    }
                    else if (info == null)
                    {
                        player.MessageNoPlayer(name.Substring(1));
                        continue;
                    }

                    if (realm.AccessSecurity.CheckDetailed(info) == SecurityCheckResult.RankTooHigh ||
                        realm.AccessSecurity.CheckDetailed(info) == SecurityCheckResult.RankTooLow)
                    {
                        player.Message("{0}&S is already barred from accessing {1}&S (by rank)",
                                       info.ClassyName, realm.ClassyName);
                        continue;
                    }

                    Player target = info.PlayerObject;
                    if (target == player)
                    {
                        target = null;                   // to avoid duplicate messages
                    }
                    switch (realm.AccessSecurity.Exclude(info))
                    {
                    case PermissionOverride.Deny:
                        player.Message("{0}&S is already banned from Realm {1}",
                                       info.ClassyName, realm.ClassyName);
                        break;

                    case PermissionOverride.None:
                        player.Message("{0}&S is now banned from accessing {1}",
                                       info.ClassyName, realm.ClassyName);
                        if (target != null)
                        {
                            target.Message("&WYou were banned by {0}&W from accessing realm {1}",
                                           player.ClassyName, realm.ClassyName);
                        }
                        Logger.Log(LogType.UserActivity, "{0} added {1} to the access blacklist on realm {2}",
                                   player.Name, info.Name, realm.Name);
                        changesWereMade = true;
                        break;

                    case PermissionOverride.Allow:
                        if (realm.AccessSecurity.Check(info))
                        {
                            player.Message("{0}&S is no longer on the access whitelist of {1}&S. " +
                                           "Player is still allowed to join (by rank).",
                                           info.ClassyName, realm.ClassyName);
                            if (target != null)
                            {
                                target.Message("You were banned from Realm {0}&S by {1}&S. " +
                                               "You are still allowed to join (by rank).",
                                               player.ClassyName, realm.ClassyName);
                            }
                        }
                        else
                        {
                            player.Message("{0}&S is no longer allowed to access {1}",
                                           info.ClassyName, realm.ClassyName);
                            if (target != null)
                            {
                                target.Message("&WYou were banned from Realm {0}&W (Banned by {1}&W).",
                                               realm.ClassyName, player.ClassyName);
                            }
                        }
                        Logger.Log(LogType.UserActivity, "{0} removed {1} from the access whitelist on realm {2}",
                                   player.Name, info.Name, realm.Name);
                        changesWereMade = true;
                        break;
                    }

                    // Setting minimum rank
                }
                else
                {
                    Rank rank = RankManager.FindRank(name);
                    if (rank == null)
                    {
                        player.MessageNoRank(name);
                    }

                    else
                    {
                        // list players who are redundantly blacklisted
                        var          exceptionList    = realm.AccessSecurity.ExceptionList;
                        PlayerInfo[] noLongerExcluded =
                            exceptionList.Excluded.Where(excludedPlayer => excludedPlayer.Rank < rank).ToArray();
                        if (noLongerExcluded.Length > 0)
                        {
                            player.Message(
                                "Following players no longer need to be blacklisted to be barred from {0}&S: {1}",
                                realm.ClassyName,
                                noLongerExcluded.JoinToClassyString());
                        }

                        // list players who are redundantly whitelisted
                        PlayerInfo[] noLongerIncluded =
                            exceptionList.Included.Where(includedPlayer => includedPlayer.Rank >= rank).ToArray();
                        if (noLongerIncluded.Length > 0)
                        {
                            player.Message("Following players no longer need to be whitelisted to access {0}&S: {1}",
                                           realm.ClassyName,
                                           noLongerIncluded.JoinToClassyString());
                        }

                        // apply changes
                        realm.AccessSecurity.MinRank = rank;
                        changesWereMade = true;
                        if (realm.AccessSecurity.MinRank == RankManager.LowestRank)
                        {
                            Server.Message("{0}&S made the realm {1}&S accessible to everyone.",
                                           player.ClassyName, realm.ClassyName);
                        }
                        else
                        {
                            Server.Message("{0}&S made the realm {1}&S accessible only by {2}+",
                                           player.ClassyName, realm.ClassyName,
                                           realm.AccessSecurity.MinRank.ClassyName);
                        }
                        Logger.Log(LogType.UserActivity, "{0} set access rank for realm {1} to {2}+",
                                   player.Name, realm.Name, realm.AccessSecurity.MinRank.Name);
                    }
                }
            } while ((name = cmd.Next()) != null);

            if (changesWereMade)
            {
                var playersWhoCantStay = realm.Players.Where(p => !p.CanJoin(realm));
                foreach (Player p in playersWhoCantStay)
                {
                    p.Message("&WYou are no longer allowed to join realm {0}", realm.ClassyName);
                    p.JoinWorld(WorldManager.MainWorld, WorldChangeReason.PermissionChanged);
                }

                WorldManager.SaveWorldList();
            }
        }
        static void DoPlayerDB( Player player, Command cmd )
        {
            string p1Name = cmd.Next();
            string p2Name = cmd.Next();
            if( p1Name == null || p2Name == null ) {
                CdInfoSwap.PrintUsage( player );
                return;
            }

            PlayerInfo p1 = PlayerDB.FindPlayerInfoOrPrintMatches( player, p1Name );
            if( p1 == null ) return;
            PlayerInfo p2 = PlayerDB.FindPlayerInfoOrPrintMatches( player, p2Name );
            if( p2 == null ) return;

            if( p1 == p2 ) {
                player.Message( "InfoSwap: Please specify 2 different players." );
                return;
            }

            if( p1.IsOnline || p2.IsOnline ) {
                player.Message( "InfoSwap: Both players must be offline to swap info." );
                return;
            }

            if( !cmd.IsConfirmed ) {
                player.Confirm( cmd, "InfoSwap: Swap stats of players {0}&S and {1}&S?", p1.ClassyName, p2.ClassyName );
                return;
            } else {
                PlayerDB.SwapPlayerInfo( p1, p2 );
                player.Message( "InfoSwap: Stats of {0}&S and {1}&S have been swapped.",
                                p1.ClassyName, p2.ClassyName );
            }
        }
Пример #33
0
        private static void ZoneEditHandler(Player player, Command cmd)
        {
            bool   changesWereMade = false;
            string zoneName        = cmd.Next();

            if (zoneName == null)
            {
                player.Message("No zone name specified. See &H/Help ZEdit");
                return;
            }

            Zone zone = player.WorldMap.Zones.Find(zoneName);

            if (zone == null)
            {
                player.MessageNoZone(zoneName);
                return;
            }

            string name;

            while ((name = cmd.Next()) != null)
            {
                if (name.StartsWith("+"))
                {
                    if (name.Length == 1)
                    {
                        CdZoneEdit.PrintUsage(player);
                        break;
                    }
                    PlayerInfo info = PlayerDB.FindPlayerInfoOrPrintMatches(player, name.Substring(1));
                    if (info == null)
                    {
                        return;
                    }

                    // prevent players from whitelisting themselves to bypass protection
                    if (!player.Info.Rank.AllowSecurityCircumvention && player.Info == info)
                    {
                        if (!zone.Controller.Check(info))
                        {
                            player.Message("You must be {0}+&S to add yourself to this zone's whitelist.",
                                           zone.Controller.MinRank.ClassyName);
                            continue;
                        }
                    }

                    switch (zone.Controller.Include(info))
                    {
                    case PermissionOverride.Deny:
                        player.Message("{0}&S is no longer excluded from zone {1}",
                                       info.ClassyName, zone.ClassyName);
                        changesWereMade = true;
                        break;

                    case PermissionOverride.None:
                        player.Message("{0}&S is now included in zone {1}",
                                       info.ClassyName, zone.ClassyName);
                        changesWereMade = true;
                        break;

                    case PermissionOverride.Allow:
                        player.Message("{0}&S is already included in zone {1}",
                                       info.ClassyName, zone.ClassyName);
                        break;
                    }
                }
                else if (name.StartsWith("-"))
                {
                    if (name.Length == 1)
                    {
                        CdZoneEdit.PrintUsage(player);
                        break;
                    }
                    PlayerInfo info = PlayerDB.FindPlayerInfoOrPrintMatches(player, name.Substring(1));
                    if (info == null)
                    {
                        return;
                    }

                    switch (zone.Controller.Exclude(info))
                    {
                    case PermissionOverride.Deny:
                        player.Message("{0}&S is already excluded from zone {1}",
                                       info.ClassyName, zone.ClassyName);
                        break;

                    case PermissionOverride.None:
                        player.Message("{0}&S is now excluded from zone {1}",
                                       info.ClassyName, zone.ClassyName);
                        changesWereMade = true;
                        break;

                    case PermissionOverride.Allow:
                        player.Message("{0}&S is no longer included in zone {1}",
                                       info.ClassyName, zone.ClassyName);
                        changesWereMade = true;
                        break;
                    }
                }
                else if (name.ToLower().StartsWith("msg="))
                {
                    zone.Message    = name.Substring(4) + " " + (cmd.NextAll() ?? "");
                    changesWereMade = true;
                    player.Message("Zedit: Custom denied messaged changed to '" + zone.Message + "'");
                    break;
                }
                else
                {
                    Rank minRank = RankManager.FindRank(name);

                    if (minRank != null)
                    {
                        // prevent players from lowering rank so bypass protection
                        if (!player.Info.Rank.AllowSecurityCircumvention &&
                            zone.Controller.MinRank > player.Info.Rank && minRank <= player.Info.Rank)
                        {
                            player.Message("You are not allowed to lower the zone's rank.");
                            continue;
                        }

                        if (zone.Controller.MinRank != minRank)
                        {
                            zone.Controller.MinRank = minRank;
                            player.Message("Permission for zone \"{0}\" changed to {1}+",
                                           zone.Name,
                                           minRank.ClassyName);
                            changesWereMade = true;
                        }
                    }
                    else
                    {
                        player.MessageNoRank(name);
                    }
                }
            }
            if (changesWereMade)
            {
                zone.Edit(player.Info);
            }
            else
            {
                player.Message("No changes were made to the zone.");
            }
        }
        static void DumpStatsHandler( Player player, Command cmd )
        {
            string fileName = cmd.Next();
            if( fileName == null ) {
                CdDumpStats.PrintUsage( player );
                return;
            }

            if( !Paths.Contains( Paths.WorkingPath, fileName ) ) {
                player.MessageUnsafePath();
                return;
            }

            // ReSharper disable AssignNullToNotNullAttribute
            if( Paths.IsProtectedFileName( Path.GetFileName( fileName ) ) ) {
                // ReSharper restore AssignNullToNotNullAttribute
                player.Message( "You may not use this file." );
                return;
            }

            string extension = Path.GetExtension( fileName );
            if( extension == null || !extension.Equals( ".txt", StringComparison.OrdinalIgnoreCase ) ) {
                player.Message( "Stats filename must end with .txt" );
                return;
            }

            if( File.Exists( fileName ) && !cmd.IsConfirmed ) {
                player.Confirm( cmd, "File \"{0}\" already exists. Overwrite?", Path.GetFileName( fileName ) );
                return;
            }

            if( !Paths.TestFile( "DumpStats file", fileName, false, FileAccess.Write ) ) {
                player.Message( "Cannot create specified file. See log for details." );
                return;
            }

            PlayerInfo[] infos;
            using( FileStream fs = File.Create( fileName ) ) {
                using( StreamWriter writer = new StreamWriter( fs ) ) {
                    infos = PlayerDB.PlayerInfoList;
                    if( infos.Length == 0 ) {
                        writer.WriteLine( "(TOTAL) (0 players)" );
                        writer.WriteLine();
                    } else {
                        DumpPlayerGroupStats( writer, infos, "(TOTAL)" );
                    }

                    List<PlayerInfo> rankPlayers = new List<PlayerInfo>();
                    foreach( Rank rank in RankManager.Ranks ) {
                        // ReSharper disable LoopCanBeConvertedToQuery
                        for( int i = 0; i < infos.Length; i++ ) {
                            // ReSharper restore LoopCanBeConvertedToQuery
                            if( infos[i].Rank == rank ) rankPlayers.Add( infos[i] );
                        }
                        if( rankPlayers.Count == 0 ) {
                            writer.WriteLine( "{0}: 0 players, 0 banned, 0 inactive", rank.Name );
                            writer.WriteLine();
                        } else {
                            DumpPlayerGroupStats( writer, rankPlayers, rank.Name );
                        }
                        rankPlayers.Clear();
                    }
                }
            }

            player.Message( "Stats saved to \"{0}\"", fileName );
        }
Пример #35
0
        private static void PolarRoseHandler(Player player, Command cmd)
        {
            //prepping variables, converting them to ints to enter into the equations
            string petals = cmd.Next();
            int    pet;
            bool   parsedPet = Int32.TryParse(petals, out pet);
            int    petTest   = (pet / 2);

            string length = cmd.Next();
            int    len;
            bool   parsedLen = Int32.TryParse(length, out len);

            string revolutions = cmd.Next();
            int    rev;
            bool   parsedRev = Int32.TryParse(revolutions, out rev);
            double numRev    = (6.28 * rev);

            string Height = cmd.Next();
            int    height;
            bool   parsedHeight = Int32.TryParse(Height, out height);

            double NumHeight = (height * 0.01);             //This makes the Height more managable for the user
            double RevIter   = (0.01 + (rev * 0.005));      //Iteration needs to be adjusted based on how many revolutions are made.
            double RevIter6  = (rev * 0.015);               //Seperate RevIter for when 6 petals (required because of method used for 6 petals)

            if (player.Can(Permission.DrawAdvanced) && pet > 2 && len > 0 && len < 5 && rev > 0 && rev < 5)
            {
                if (!parsedPet || !parsedLen || !parsedRev)                //if the player enters in invalid values for length or number of petals
                {
                    player.Message("Please enter whole number values for each of the variables. (Height is optional) Type /help pr for the ranges.");
                    return;
                }

                if (petals == null || length == null || revolutions == null)
                {
                    player.Message("Please enter values for number of petals, length of petals and number of revolutions.");
                }

                if (pet == 4 || pet == 8 || pet == 10 || pet == 12 || pet == 14 || pet == 16)   //When the number of petals is even, the  number entered has to be halved to get the
                {                                                                               //right number of petals. I figured numbers over 16, the user wouldn't even notice.
                    PrepareSpring.SetParametrization(player, new Command("/scp x=" + len + "*sin(" + petTest + "*u)*cos(u)"));
                    PrepareSpring.SetParametrization(player, new Command("/scp y=" + len + "*sin(" + petTest + "*u)*sin(u)"));
                }

                else if (pet == 6)  //The math behind this is complicated, but getting 6 petals with this method is impossible. I am using a different method
                {                   //for when the user asks for 6 petals. They will be slightly overlapping, unlike the others.
                    PrepareSpring.SetParametrization(player, new Command("/scp x=" + len + "*sin(1.5*u)*cos(u)"));
                    PrepareSpring.SetParametrization(player, new Command("/scp y=" + len + "*sin(1.5*u)*sin(u)"));
                }

                else
                {
                    PrepareSpring.SetParametrization(player, new Command("/scp x=" + len + "*sin(" + pet + "*u)*cos(u)"));
                    PrepareSpring.SetParametrization(player, new Command("/scp y=" + len + "*sin(" + pet + "*u)*sin(u)"));
                }

                if (Height == null || Height.Length == 0) //If no height is specified, the rose will be flat.
                {
                    PrepareSpring.SetParametrization(player, new Command("/scp z=0"));
                }

                else if (Height.Length >= 1 && parsedHeight)
                {
                    PrepareSpring.SetParametrization(player, new Command("/scp z=" + NumHeight + "*u"));
                }

                else
                {
                    player.Message("Please enter whole integer values for each of the variables. (Height is optional) Type /help pr for the ranges.");
                    return;
                }

                if (pet == 6)
                {
                    PrepareSpring.SetParamIteration(player, new Command("/spi u 0 12.56 " + RevIter6));
                    PrepareSpring.SetParamIteration(player, new Command("/spi v 0 12.56 " + RevIter6));
                }

                else
                {
                    PrepareSpring.SetParamIteration(player, new Command("/spi u 0 " + numRev + " " + RevIter));
                    PrepareSpring.SetParamIteration(player, new Command("/spi v 0 " + numRev + " " + RevIter));
                }

                StartCmdDraw(player, new Command("/spd uu"));           //uses custom handler as to not display messages to user
            }

            else if (pet < 3 || len < 1 || len > 4 || rev < 0 || height < 1 || rev > 4)
            {
                player.Message("&cRanges: &hPetals[3,infinity), Length[1,4], Revolutions[1,4), Height[1,infinity).");
                return;
            }

            else
            {
                CdPolarRose.PrintUsage(player);
            }
        }
        static void ImportHandler( Player player, Command cmd )
        {
            string action = cmd.Next();
            if( action == null ) {
                CdImport.PrintUsage( player );
                return;
            }

            switch( action.ToLower() ) {
                case "bans":
                    if( !player.Can( Permission.Ban ) ) {
                        player.MessageNoAccess( Permission.Ban );
                        return;
                    }
                    ImportBans( player, cmd );
                    break;

                case "ranks":
                    if( !player.Can( Permission.Promote ) ) {
                        player.MessageNoAccess( Permission.Promote );
                        return;
                    }
                    ImportRanks( player, cmd );
                    break;

                default:
                    CdImport.PrintUsage( player );
                    break;
            }
        }
Пример #37
0
        internal static void RealmBuild(Player player, Command cmd, string worldName, string name,
                                        string NameIfRankIsName)
        {
            // Print information about the current realm
            if (worldName == null)
            {
                if (player.World == null)
                {
                    player.Message("When calling /wbuild from console, you must specify a realm name.");
                }
                else
                {
                    player.Message(player.World.BuildSecurity.GetDescription(player.World, "realm", "modified"));
                }
                return;
            }

            // Find a realm by name
            World realm = WorldManager.FindWorldOrPrintMatches(player, worldName);

            if (realm == null)
            {
                return;
            }


            if (name == null)
            {
                player.Message(realm.BuildSecurity.GetDescription(realm, "realm", "modified"));
                return;
            }

            bool changesWereMade = false;

            do
            {
                if (name.Length < 2)
                {
                    continue;
                }
                // Whitelisting individuals
                if (name.StartsWith("+"))
                {
                    PlayerInfo info;
                    if (!PlayerDB.FindPlayerInfo(name.Substring(1), out info))
                    {
                        player.Message("More than one player found matching \"{0}\"", name.Substring(1));
                        continue;
                    }
                    else if (info == null)
                    {
                        player.MessageNoPlayer(name.Substring(1));
                        continue;
                    }


                    if (realm.BuildSecurity.CheckDetailed(info) == SecurityCheckResult.Allowed)
                    {
                        player.Message("{0}&S is already allowed to build in {1}&S (by rank)",
                                       info.ClassyName, realm.ClassyName);
                        continue;
                    }

                    Player target = info.PlayerObject;
                    if (target == player)
                    {
                        target = null;                   // to avoid duplicate messages
                    }
                    switch (realm.BuildSecurity.Include(info))
                    {
                    case PermissionOverride.Deny:
                        if (realm.BuildSecurity.Check(info))
                        {
                            player.Message("{0}&S is no longer barred from building in {1}",
                                           info.ClassyName, realm.ClassyName);
                            if (target != null)
                            {
                                target.Message(
                                    "You can now build in realm {0}&S (removed from blacklist by {1}&S).",
                                    realm.ClassyName, player.ClassyName);
                            }
                        }
                        else
                        {
                            player.Message("{0}&S was removed from the build blacklist of {1}&S. " +
                                           "Player is still NOT allowed to build (by rank).",
                                           info.ClassyName, realm.ClassyName);
                            if (target != null)
                            {
                                target.Message(
                                    "You were removed from the build blacklist of realm {0}&S by {1}&S. " +
                                    "You are still NOT allowed to build (by rank).",
                                    player.ClassyName, realm.ClassyName);
                            }
                        }
                        Logger.Log(LogType.UserActivity, "{0} removed {1} from the build blacklist of {2}",
                                   player.Name, info.Name, realm.Name);
                        changesWereMade = true;
                        break;

                    case PermissionOverride.None:
                        player.Message("{0}&S is now allowed to build in {1}",
                                       info.ClassyName, realm.ClassyName);
                        if (target != null)
                        {
                            target.Message("You can now build in realm {0}&S (whitelisted by {1}&S).",
                                           realm.ClassyName, player.ClassyName);
                        }
                        Logger.Log(LogType.UserActivity, "{0} added {1} to the build whitelist on realm {2}",
                                   player.Name, info.Name, realm.Name);
                        break;

                    case PermissionOverride.Allow:
                        player.Message("{0}&S is already on the build whitelist of {1}",
                                       info.ClassyName, realm.ClassyName);
                        break;
                    }

                    // Blacklisting individuals
                }
                else if (name.StartsWith("-"))
                {
                    PlayerInfo info;
                    if (!PlayerDB.FindPlayerInfo(name.Substring(1), out info))
                    {
                        player.Message("More than one player found matching \"{0}\"", name.Substring(1));
                        continue;
                    }
                    else if (info == null)
                    {
                        player.MessageNoPlayer(name.Substring(1));
                        continue;
                    }

                    if (realm.BuildSecurity.CheckDetailed(info) == SecurityCheckResult.RankTooHigh ||
                        realm.BuildSecurity.CheckDetailed(info) == SecurityCheckResult.RankTooLow)
                    {
                        player.Message("{0}&S is already barred from building in {1}&S (by rank)",
                                       info.ClassyName, realm.ClassyName);
                        continue;
                    }

                    Player target = info.PlayerObject;
                    if (target == player)
                    {
                        target = null;                   // to avoid duplicate messages
                    }
                    switch (realm.BuildSecurity.Exclude(info))
                    {
                    case PermissionOverride.Deny:
                        player.Message("{0}&S is already on build blacklist of {1}",
                                       info.ClassyName, realm.ClassyName);
                        break;

                    case PermissionOverride.None:
                        player.Message("{0}&S is now barred from building in {1}",
                                       info.ClassyName, realm.ClassyName);
                        if (target != null)
                        {
                            target.Message("&WYou were barred by {0}&W from building in realm {1}",
                                           player.ClassyName, realm.ClassyName);
                        }
                        Logger.Log(LogType.UserActivity, "{0} added {1} to the build blacklist on realm {2}",
                                   player.Name, info.Name, realm.Name);
                        changesWereMade = true;
                        break;

                    case PermissionOverride.Allow:
                        if (realm.BuildSecurity.Check(info))
                        {
                            player.Message("{0}&S is no longer on the build whitelist of {1}&S. " +
                                           "Player is still allowed to build (by rank).",
                                           info.ClassyName, realm.ClassyName);
                            if (target != null)
                            {
                                target.Message(
                                    "You were removed from the build whitelist of realm {0}&S by {1}&S. " +
                                    "You are still allowed to build (by rank).",
                                    player.ClassyName, realm.ClassyName);
                            }
                        }
                        else
                        {
                            player.Message("{0}&S is no longer allowed to build in {1}",
                                           info.ClassyName, realm.ClassyName);
                            if (target != null)
                            {
                                target.Message(
                                    "&WYou can no longer build in realm {0}&W (removed from whitelist by {1}&W).",
                                    realm.ClassyName, player.ClassyName);
                            }
                        }
                        Logger.Log(LogType.UserActivity, "{0} removed {1} from the build whitelist on realm {2}",
                                   player.Name, info.Name, realm.Name);
                        changesWereMade = true;
                        break;
                    }

                    // Setting minimum rank
                }
                else
                {
                    Rank rank = RankManager.FindRank(name);
                    if (rank == null)
                    {
                        player.MessageNoRank(name);
                    }
                    else if (!player.Info.Rank.AllowSecurityCircumvention &&
                             realm.BuildSecurity.MinRank > rank &&
                             realm.BuildSecurity.MinRank > player.Info.Rank)
                    {
                        player.Message("&WYou must be ranked {0}&W+ to lower build restrictions for realm {1}",
                                       realm.BuildSecurity.MinRank.ClassyName, realm.ClassyName);
                    }
                    else
                    {
                        // list players who are redundantly blacklisted
                        var          exceptionList    = realm.BuildSecurity.ExceptionList;
                        PlayerInfo[] noLongerExcluded =
                            exceptionList.Excluded.Where(excludedPlayer => excludedPlayer.Rank < rank).ToArray();
                        if (noLongerExcluded.Length > 0)
                        {
                            player.Message("Following players no longer need to be blacklisted on realm {0}&S: {1}",
                                           realm.ClassyName,
                                           noLongerExcluded.JoinToClassyString());
                        }

                        // list players who are redundantly whitelisted
                        PlayerInfo[] noLongerIncluded =
                            exceptionList.Included.Where(includedPlayer => includedPlayer.Rank >= rank).ToArray();
                        if (noLongerIncluded.Length > 0)
                        {
                            player.Message("Following players no longer need to be whitelisted on realm {0}&S: {1}",
                                           realm.ClassyName,
                                           noLongerIncluded.JoinToClassyString());
                        }

                        // apply changes
                        realm.BuildSecurity.MinRank = rank;
                        changesWereMade             = true;
                        if (realm.BuildSecurity.MinRank == RankManager.LowestRank)
                        {
                            Server.Message("{0}&S allowed anyone to build on realm {1}",
                                           player.ClassyName, realm.ClassyName);
                        }
                        else
                        {
                            Server.Message("{0}&S allowed only {1}+&S to build in realm {2}",
                                           player.ClassyName, realm.BuildSecurity.MinRank.ClassyName, realm.ClassyName);
                        }
                        Logger.Log(LogType.UserActivity, "{0} set build rank for realm {1} to {2}+",
                                   player.Name, realm.Name, realm.BuildSecurity.MinRank.Name);
                    }
                }
            } while ((name = cmd.Next()) != null);

            if (changesWereMade)
            {
                WorldManager.SaveWorldList();
            }
        }
        static void MassRankHandler( Player player, Command cmd )
        {
            string fromRankName = cmd.Next();
            string toRankName = cmd.Next();
            string reason = cmd.NextAll();
            if( fromRankName == null || toRankName == null ) {
                CdMassRank.PrintUsage( player );
                return;
            }

            Rank fromRank = RankManager.FindRank( fromRankName );
            if( fromRank == null ) {
                player.MessageNoRank( fromRankName );
                return;
            }

            Rank toRank = RankManager.FindRank( toRankName );
            if( toRank == null ) {
                player.MessageNoRank( toRankName );
                return;
            }

            if( fromRank == toRank ) {
                player.Message( "Ranks must be different" );
                return;
            }

            int playerCount = fromRank.PlayerCount;
            string verb = (fromRank > toRank ? "demot" : "promot");

            if( !cmd.IsConfirmed ) {
                player.Confirm( cmd, "About to {0}e {1} players.", verb, playerCount );
                return;
            }

            player.Message( "MassRank: {0}ing {1} players...",
                            verb, playerCount );

            int affected = PlayerDB.MassRankChange( player, fromRank, toRank, reason );
            player.Message( "MassRank: done, {0} records affected.", affected );
        }
Пример #39
0
        void Load(Player player, Command cmd)
        {
            lock ( loadLock ) {
                if (world.loadInProgress || world.loadSendingInProgress)
                {
                    player.Message("Loading already in progress, please wait.");
                    return;
                }
                world.loadInProgress = true;
            }

            if (!player.Can(Permissions.SaveAndLoad))
            {
                world.NoAccessMessage(player);
                world.loadInProgress = false;
                return;
            }

            string mapName = cmd.Next();

            if (mapName == null)
            {
                player.Message("Syntax: " + Color.Help + "/load mapName");
                world.loadInProgress = false;
                return;
            }

            string mapFileName = mapName + ".fcm";

            if (!File.Exists(mapFileName))
            {
                player.Message("No backup file \"" + mapName + "\" found.");
                world.loadInProgress = false;
                return;
            }

            Map newMap = Map.Load(world, mapFileName);

            if (newMap == null)
            {
                player.Message("Could not load \"" + mapFileName + "\". Check logfile for details.");
                world.loadInProgress = false;
                return;
            }

            if (newMap.widthX != world.map.widthX ||
                newMap.widthY != world.map.widthY ||
                newMap.height != world.map.height)
            {
                player.Message("Map sizes of \"" + mapName + "\" and the current map do not match.");
                world.loadInProgress = false;
                return;
            }

            world.log.Log("{0} is loading the map \"{1}\".", LogType.UserActivity, player.name, mapName);
            player.Message("Loading map \"" + mapName + "\"...");
            world.BeginLockDown();
            MapSenderParams param = new MapSenderParams()
            {
                map    = newMap,
                player = player,
                world  = world
            };

            world.tasks.Add(MapSender.StreamLoad, param, true);
        }
        static void RestartHandler( Player player, Command cmd )
        {
            string delayString = cmd.Next();
            TimeSpan delayTime = DefaultShutdownTime;
            string reason = "";

            if( delayString != null ) {
                if( delayString.Equals( "abort", StringComparison.OrdinalIgnoreCase ) ) {
                    if( Server.CancelShutdown() ) {
                        Logger.Log( LogType.UserActivity,
                                    "Restart aborted by {0}.", player.Name );
                        Server.Message( "&WRestart aborted by {0}", player.ClassyName );
                    } else {
                        player.MessageNow( "Cannot abort restart - too late." );
                    }
                    return;
                } else if( !delayString.TryParseMiniTimespan( out delayTime ) ) {
                    CdShutdown.PrintUsage( player );
                    return;
                }
                reason = cmd.NextAll();
            }

            if( delayTime.TotalMilliseconds > Int32.MaxValue - 1 ) {
                player.Message( "Restart: Delay is too long, maximum is {0}",
                                TimeSpan.FromMilliseconds( Int32.MaxValue - 1 ).ToMiniString() );
                return;
            }

            Server.Message( "&WServer restarting in {0}", delayTime.ToMiniString() );

            if( String.IsNullOrEmpty( reason ) ) {
                Logger.Log( LogType.UserActivity,
                            "{0} scheduled a restart ({1} delay).",
                            player.Name, delayTime.ToCompactString() );
                ShutdownParams sp = new ShutdownParams( ShutdownReason.Restarting, delayTime, true, true );
                Server.Shutdown( sp, false );
            } else {
                Server.Message( "&WRestart reason: {0}", reason );
                Logger.Log( LogType.UserActivity,
                            "{0} scheduled a restart ({1} delay). Reason: {2}",
                            player.Name, delayTime.ToCompactString(), reason );
                ShutdownParams sp = new ShutdownParams( ShutdownReason.Restarting, delayTime, true, true, reason, player );
                Server.Shutdown( sp, false );
            }
        }
Пример #41
0
        public static void RealmCreate(Player player, Command cmd, string themeName, string templateName)
        {
            MapGenTemplate template;
            MapGenTheme    theme;

            int wx, wy, height = 128;

            if (!(cmd.NextInt(out wx) && cmd.NextInt(out wy) && cmd.NextInt(out height)))
            {
                if (player.World != null)
                {
                    wx     = 128;
                    wy     = 128;
                    height = 128;
                }
                else
                {
                    player.Message("When used from console, /gen requires map dimensions.");

                    return;
                }
                cmd.Rewind();
                cmd.Next();
                cmd.Next();
            }

            if (!Map.IsValidDimension(wx))
            {
                player.Message("Cannot make map with width {0}: dimensions must be multiples of 16.", wx);
                return;
            }
            else if (!Map.IsValidDimension(wy))
            {
                player.Message("Cannot make map with length {0}: dimensions must be multiples of 16.", wy);
                return;
            }
            else if (!Map.IsValidDimension(height))
            {
                player.Message("Cannot make map with height {0}: dimensions must be multiples of 16.", height);
                return;
            }

            string fileName     = player.Name;
            string fullFileName = null;

            if (fileName == null)
            {
                if (player.World == null)
                {
                    player.Message("When used from console, /gen requires FileName.");

                    return;
                }
                if (!cmd.IsConfirmed)
                {
                    player.Confirm(cmd, "Replace this realm's map with a generated one?");
                    return;
                }
            }
            else
            {
                fileName = fileName.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar);
                if (!fileName.EndsWith(".fcm", StringComparison.OrdinalIgnoreCase))
                {
                    fileName += ".fcm";
                }
                fullFileName = Path.Combine(Paths.MapPath, fileName);
                if (!Paths.IsValidPath(fullFileName))
                {
                    player.Message("Invalid filename.");
                    return;
                }
                if (!Paths.Contains(Paths.MapPath, fullFileName))
                {
                    player.MessageUnsafePath();
                    return;
                }
                string dirName = fullFileName.Substring(0, fullFileName.LastIndexOf(Path.DirectorySeparatorChar));
                if (!Directory.Exists(dirName))
                {
                    Directory.CreateDirectory(dirName);
                }
                if (!cmd.IsConfirmed && File.Exists(fullFileName))
                {
                    player.Confirm(cmd, "The mapfile \"{0}\" already exists. Overwrite?", fileName);
                    return;
                }
            }

            bool noTrees;

            if (themeName.Equals("grass", StringComparison.OrdinalIgnoreCase))
            {
                theme   = MapGenTheme.Forest;
                noTrees = true;
            }
            else
            {
                try
                {
                    theme   = (MapGenTheme)Enum.Parse(typeof(MapGenTheme), themeName, true);
                    noTrees = (theme != MapGenTheme.Forest);
                }
                catch (Exception)
                {
                    player.MessageNow("Unrecognized theme \"{0}\". Available themes are: Grass, {1}",
                                      themeName,
                                      String.Join(", ", Enum.GetNames(typeof(MapGenTheme))));
                    return;
                }
            }

            try
            {
                template = (MapGenTemplate)Enum.Parse(typeof(MapGenTemplate), templateName, true);
            }
            catch (Exception)
            {
                player.Message("Unrecognized template \"{0}\". Available templates are: {1}",
                               templateName,
                               String.Join(", ", Enum.GetNames(typeof(MapGenTemplate))));
                return;
            }

            if (!Enum.IsDefined(typeof(MapGenTheme), theme) || !Enum.IsDefined(typeof(MapGenTemplate), template))
            {
                return;
            }

            MapGeneratorArgs args = MapGenerator.MakeTemplate(template);

            args.MapWidth  = wx;
            args.MapLength = wy;
            args.MapHeight = height;
            args.MaxHeight = (int)(args.MaxHeight / 80d * height);
            args.MaxDepth  = (int)(args.MaxDepth / 80d * height);
            args.Theme     = theme;
            args.AddTrees  = !noTrees;

            Map map;

            try
            {
                if (theme == MapGenTheme.Forest && noTrees)
                {
                    player.MessageNow("Generating Grass {0}...", template);
                }
                else
                {
                    player.MessageNow("Generating {0} {1}...", theme, template);
                }
                if (theme == MapGenTheme.Forest && noTrees && template == MapGenTemplate.Flat)
                {
                    map = MapGenerator.GenerateFlatgrass(args.MapWidth, args.MapLength, args.MapHeight);
                }
                else
                {
                    MapGenerator generator = new MapGenerator(args);
                    map = generator.Generate();
                }
            }
            catch (Exception ex)
            {
                Logger.Log(LogType.Error, "MapGenerator: Generation failed: {0}",
                           ex);
                player.MessageNow("&WAn error occured while generating the map.");
                return;
            }

            if (fileName != null)
            {
                if (map.Save(fullFileName))
                {
                    player.MessageNow("Generation done. Saved to {0}", fileName);
                }
                else
                {
                    player.Message("&WAn error occured while saving generated map to {0}", fileName);
                }
            }
            else
            {
                player.MessageNow("Generation done. Changing map...");
                player.World.ChangeMap(map);
            }
        }