Ejemplo n.º 1
0
        public bool CheckPermissions(TSPlayer player)
        {
            if (player == null) return false;

              var sPly = SignCommands.ScPlayers[player.Index];
              if (sPly == null) {
            TShock.Log.ConsoleError("An error occured while executing a sign command."
                         + "TSPlayer {0} at index {1} does not exist as an ScPlayer",
            player.Name, player.Index);
            player.SendErrorMessage("An error occured. Please try again");
            return false;
              }

              if (freeAccess) return true;

              if (!string.IsNullOrEmpty(requiredPermission))
            if (player.Group.HasPermission(requiredPermission))
              return true;
            else {
              if (sPly.AlertPermissionCooldown == 0) {
            player.SendErrorMessage("You do not have the required permission to use this sign.");
            sPly.AlertPermissionCooldown = 3;
              }
              return false;
            }

              if (commands.Values.All(command => command.CanRun(player)))
            return true;

              if (sPly.AlertPermissionCooldown == 0) {
            player.SendErrorMessage("You do not have access to the commands on this sign.");
            sPly.AlertPermissionCooldown = 3;
              }
              return false;
        }
Ejemplo n.º 2
0
 public static void InvalidNewBountyUsage(TSPlayer player)
 {
     player.SendErrorMessage("Invalid usage! Proper usages:");
     player.SendErrorMessage("/nbty <bounty name> <target>");
     player.SendErrorMessage("/nbty <-setrewards> [SEconomy currency amount]");
     player.SendErrorMessage("/nbty <-confirm/-cancel>");
 }
Ejemplo n.º 3
0
        /// <summary>
        /// This is a copy of TShocks handlecommand method, sans the permission checks
        /// </summary>
        public static bool PermissionlessInvoke(this TShockAPI.TSPlayer player, string text, bool silent = false)
        {
            IEnumerable <TShockAPI.Command> cmds;
            List <string> args;
            string        cmdName;
            string        cmdText;

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

            cmdText = text.Remove(0, 1);
            args    = typeof(TShockAPI.Commands).CallPrivateMethod <List <string> >(true, "ParseParameters", cmdText);

            if (args.Count < 1)
            {
                return(false);
            }

            cmdName = args[0].ToLower();
            args.RemoveAt(0);
            cmds = TShockAPI.Commands.ChatCommands.Where(c => c.HasAlias(cmdName));

            if (Enumerable.Count(cmds) == 0)
            {
                if (player.AwaitingResponse.ContainsKey(cmdName))
                {
                    Action <TShockAPI.CommandArgs> call = player.AwaitingResponse[cmdName];
                    player.AwaitingResponse.Remove(cmdName);
                    call(new TShockAPI.CommandArgs(cmdText, player, args));
                    return(true);
                }
                player.SendErrorMessage("Invalid command entered. Type /help for a list of valid commands.");
                return(true);
            }

            foreach (TShockAPI.Command cmd in cmds)
            {
                if (!cmd.AllowServer && !player.RealPlayer)
                {
                    player.SendErrorMessage("You must use this command in-game.");
                }
                else
                {
                    if (cmd.DoLog && silent == false)
                    {
                        TShockAPI.TShock.Utils.SendLogs(string.Format("{0} executed: /{1}.", player.Name, cmdText), Color.Red);
                    }
                    cmd.RunWithoutPermissions(cmdText, player, args);
                }
            }

            return(true);
        }
Ejemplo n.º 4
0
        public void ReloadConfig(bool console = false, TSPlayer receiver = null)
        {
            var configPath = Path.Combine(TShock.SavePath, "BossConfig.json");
            (AutoBoss.config = Config.Read(configPath)).Write(configPath);

            var invalidRegions = new List<string>();

            foreach (var arena in AutoBoss.config.BossArenas.Where(a => a.Value))
            {
                var region = TShock.Regions.GetRegionByName(arena.Key);
                if (region == null)
                {
                    invalidRegions.Add(arena.Key);
                    continue;
                }
                if (!AutoBoss.ActiveArenas.Contains(region)) AutoBoss.ActiveArenas.Add(region);
            }

            arenaCount = AutoBoss.ActiveArenas.Count;

            if (invalidRegions.Count == 0)
            {
                AutoBoss.Timers = new BossTimer();
                return;
            }
            TShock.Log.ConsoleError("Invalid regions encountered: " + string.Join(", ", invalidRegions));

            if (!console && receiver != null)
                receiver.SendErrorMessage("Invalid regions encountered: " + string.Join(", ", invalidRegions));
        }
Ejemplo n.º 5
0
 public static void Error(TSPlayer to, string message)
 {
     if (to is TSServerPlayer)
     {
         to.SendErrorMessage(message);
         return;
     }
     to.SendMessage(message, Color.OrangeRed);
 }
        /// <summary>
        /// Invokes a command ignoring permissions
        /// </summary>
        public static bool RunWithoutPermissions(this TShockAPI.Command cmd, string msg, TShockAPI.TSPlayer ply, List <string> parms)
        {
            try {
                TShockAPI.CommandDelegate cmdDelegateRef = cmd.CommandDelegate;

                cmdDelegateRef(new TShockAPI.CommandArgs(msg, ply, parms));
            } catch (Exception e) {
                ply.SendErrorMessage("Command failed, check logs for more details.");
                TShock.Log.Error(e.ToString());
            }

            return(true);
        }
Ejemplo n.º 7
0
        public static bool MatchPlayerByName(
            string name, out TSPlayer matchedPlayer, TSPlayer messagesReceiver = null
            )
        {
            matchedPlayer = null;
              List<TSPlayer> matchedPlayers = TShock.Utils.FindPlayer(name);
              if (matchedPlayers.Count == 0) {
            if (messagesReceiver != null)
              messagesReceiver.SendErrorMessage(string.Format("Could not match any players for \"{0}\".", name));

            return false;
              } if (matchedPlayers.Count > 1) {
            if (messagesReceiver != null) {
              messagesReceiver.SendErrorMessage(
            "More than one player matched! Matches: " + string.Join(", ", matchedPlayers.Select(p => p.Name))
              );
            }
            return false;
              }

              matchedPlayer = matchedPlayers[0];
              return true;
        }
Ejemplo n.º 8
0
        public void EndTrivia(TSPlayer ts)
        {
            Reset();
            TSPlayer.All.SendInfoMessage(string.Format("{0} answered the trivia correctly! the answer{1} {2}", ts.Name, CurrentQandA.Answers.Count > 1 ? "s were" : " was", string.Join(", ", CurrentQandA.Answers)));
            if (Config.DisplayWrongAnswers && WrongAnswers.Count > 0)
                TSPlayer.All.SendErrorMessage(string.Format("Wrong answers were: {0}", string.Join(", ", WrongAnswers)));
            WrongAnswers.Clear();

            if (SEconomyPlugin.Instance != null)
            {
                IBankAccount Server = SEconomyPlugin.Instance.GetBankAccount(TSServerPlayer.Server.UserID);
                IBankAccount Player = SEconomyPlugin.Instance.GetBankAccount(ts.Index);
                Server.TransferToAsync(Player, Config.CurrencyAmount, BankAccountTransferOptions.AnnounceToReceiver, "answering the trivia question correctly", "Answered trivia question");
            }
            else
                ts.SendErrorMessage("[Trivia] Transaction failed because SEconomy is disabled!");
        }
Ejemplo n.º 9
0
        public Config Read(string path, TSPlayer ts = null)
        {
            if (!File.Exists(path))
            {
                Write(path);
            }

            try
            {
                Config res = JsonConvert.DeserializeObject<Config>(File.ReadAllText(path));
                return res;
            }
            catch (System.Exception e)
            {
                if (ts != null)
                {
                    ts.SendErrorMessage("[ChatChannels] Config reading failed. See logs for more details.");
                }
                TShock.Log.ConsoleError($"[ChatChannels] Config reading failed: {e}");
                return null;
            }
        }
Ejemplo n.º 10
0
        public Config Read(TSPlayer ts = null)
        {
            if (!File.Exists(ConfigPath))
                write();

            try
            {
                Config res = JsonConvert.DeserializeObject<Config>(File.ReadAllText(ConfigPath));
                return res;
            }
            catch (Exception ex)
            {
                if (ts == null)
                {
                    Console.WriteLine("[Clans] an error has occurred while reading the config file! See below for more info:");
                    Console.WriteLine(ex.ToString());
                }
                else
                    ts.SendErrorMessage("[Clans] There was an error reloading the config file, check the console for more info!");
                return this;
            }
        }
Ejemplo n.º 11
0
        public static bool TryParsePageNumber(List <string> commandParameters, int expectedParameterIndex, TSPlayer errorMessageReceiver, out int pageNumber)
        {
            pageNumber = 1;
            if (commandParameters.Count <= expectedParameterIndex)
            {
                return(true);
            }

            string pageNumberRaw = commandParameters[expectedParameterIndex];

            if (!int.TryParse(pageNumberRaw, out pageNumber) || pageNumber < 1)
            {
                if (errorMessageReceiver != null)
                {
                    errorMessageReceiver.SendErrorMessage("\"{0}\" is not a valid page number.", pageNumberRaw);
                }

                pageNumber = 1;
                return(false);
            }

            return(true);
        }
        public virtual bool HandlePlayerSpawn(TSPlayer player, DPoint spawnTileLocation)
        {
            if (this.IsDisposed)
            return false;

              bool isBedSpawn = (spawnTileLocation.X != -1 || spawnTileLocation.Y != -1);
              RemoteClient client = Netplay.Clients[player.Index];
              if (!isBedSpawn || client.State <= 3)
            return false;

              DPoint bedTileLocation = new DPoint(spawnTileLocation.X, spawnTileLocation.Y - 1);
              Tile spawnTile = TerrariaUtils.Tiles[bedTileLocation];
              bool isInvalidBedSpawn = (!spawnTile.active() || spawnTile.type != TileID.Beds);

              bool allowNewSpawnSet = true;
              if (isInvalidBedSpawn) {
            player.Teleport(Main.spawnTileX * TerrariaUtils.TileSize, (Main.spawnTileY - 3) * TerrariaUtils.TileSize);
            this.PluginTrace.WriteLineWarning($"Player \"{player.Name}\" tried to spawn on an invalid location.");

            allowNewSpawnSet = false;
              } else if (this.Config.EnableBedSpawnProtection) {
            if (this.CheckProtected(player, bedTileLocation, false)) {
              player.SendErrorMessage("The bed you have set spawn at is protected, you can not spawn there.");
              player.SendErrorMessage("You were transported to your last valid spawn location instead.");

              if (player.TPlayer.SpawnX == -1 && player.TPlayer.SpawnY == -1)
            player.Teleport(Main.spawnTileX * TerrariaUtils.TileSize, (Main.spawnTileY - 3) * TerrariaUtils.TileSize);
              else
            player.Teleport(player.TPlayer.SpawnX * TerrariaUtils.TileSize, (player.TPlayer.SpawnY - 3) * TerrariaUtils.TileSize);

              allowNewSpawnSet = false;
            }
              }

              if (allowNewSpawnSet) {
            player.TPlayer.SpawnX = spawnTileLocation.X;
            player.TPlayer.SpawnY = spawnTileLocation.Y;
            player.sX = spawnTileLocation.X;
            player.sY = spawnTileLocation.X;
              }

              player.TPlayer.Spawn();
              NetMessage.SendData(12, -1, player.Index, string.Empty, player.Index);
              player.Dead = false;

              return true;
        }
Ejemplo n.º 13
0
        public static bool TryParsePageNumber(
            List<string> commandParameters, int expectedParamterIndex, TSPlayer errorMessageReceiver, out int pageNumber
            )
        {
            pageNumber = 1;
              if (commandParameters.Count <= expectedParamterIndex)
            return true;

              string pageNumberRaw = commandParameters[expectedParamterIndex];
              if (!int.TryParse(pageNumberRaw, out pageNumber) || pageNumber < 1) {
            if (errorMessageReceiver != null)
              errorMessageReceiver.SendErrorMessage(string.Format("\"{0}\" is not a valid page number.", pageNumberRaw));

            pageNumber = 1;
            return false;
              }

              return true;
        }
Ejemplo n.º 14
0
 internal void processAccept(TSPlayer player, OfferObj obj)
 {
     //deactivate offer in db
     main.Database.Query("UPDATE storeoffer SET Active = @0 WHERE ID = @1", 0, obj.ID);
     //remove trade and create offer inplace of trade
     if (obj.Type != -1)
     {
         TradeObj obj2 = TradeObjByID(obj.Type);
         if (obj2 == null)
         {
             player.SendErrorMessage("Error: Major Database Desync has occured - Transaction ID: {0} does not exist!", obj.Type);
             return;
         }
         main.Database.Query("UPDATE storetrade SET TradeID = @0 WHERE ID = @1 AND Active = @2",0 ,obj2.ID, 1);
         main.Database.Query("INSERT INTO storeoffer(ID, User, ItemID, Stack, TradeID, Active) VALUES(@0,@1,@2,@3,@4,@5)", offerID, obj.User, obj2.ItemID, obj2.Stack, -1, 1);
         offerObj.Add(new OfferObj(offerID, obj.User, obj2.ItemID, obj2.Stack, -1, 1));
         offerID += 1;
         obj2.Active = 0;
     }
     obj.Active = 0;
 }
Ejemplo n.º 15
0
Archivo: Shop.cs Proyecto: Tygra/Shop
 private Item getItem(TSPlayer player, string itemNameOrId, int stack)
 {
     Item item = new Item();
     List<Item> matchedItems = TShock.Utils.GetItemByIdOrName(itemNameOrId);
     if (matchedItems == null || matchedItems.Count == 0)
     {
         player.SendErrorMessage("Error: Incorrect item name or ID, please use quotes if the item has a space in it!");
         player.SendErrorMessage("Error: You have entered: {0}", itemNameOrId);
         return null;
     }
     else if (matchedItems.Count > 1)
     {
         TShock.Utils.SendMultipleMatchError(player, matchedItems.Select(i => i.name));
         return null;
     }
     else
     {
         item = matchedItems[0];
     }
     if (stack > item.maxStack)
     {
         player.SendErrorMessage("Error: Stacks entered is greater then maximum stack size");
         return null;
     }
     //all checks passed return true;
     return item;
 }
Ejemplo n.º 16
0
Archivo: Shop.cs Proyecto: Tygra/Shop
 private Boolean freeSlots(TSPlayer player, Item item, int itemAmount)
 {
     if (player.InventorySlotAvailable || (item.name.Contains("Coin") && item.type != 905) || item.type == 58 || item.type == 184)
     {
         if (player.GiveItemCheck(item.type, item.name, item.width, item.height, itemAmount))
         {
             return true;
         }
         player.SendErrorMessage("Error: An unknown error has occured - this code should not be reachable!");
         return false;
     }
     else
     {
         player.SendErrorMessage("Error: Your inventory seems to be full!");
         return false;
     }
 }
Ejemplo n.º 17
0
Archivo: Shop.cs Proyecto: Tygra/Shop
        void BuyItem(TSPlayer player, string itemNameOrId, int stack = 1)
        {
            //Check if you can purchase that many stacks of that item in the first place...
            Item item = getItem(player, itemNameOrId, stack);
            //if null then exit
            if (item == null)
            {
                return;
            }
            //find item value
            ShopObj obj = ShopList.FindShopObjbyItemName(item.name);
            if (obj == null)
            {
                player.SendErrorMessage("Error: This item cannot be Purchased! - {0}", item.name);
                return;
            }

            //Check if in stock
            if (obj.Stock == 0)
            {
                player.SendErrorMessage("Error: No current stock for {0}", item.name);
                return;
            }

            //Check if there is enough stock
            if (obj.Stock <= stack)
            {
                player.SendErrorMessage("Error: Not enough stock left for {0} to purchase {1}", item.name, stack);
                return;
            }

            //Check if has locked down group permissions
            if (!groupAllowed(player, obj.Group))
            {
                player.SendErrorMessage("Error: You do not have permissions to purchase {0}", item.name);
                return;
            }

            //Check if within region
            if (!inRegion(player, obj.Region))
            {
                player.SendErrorMessage("Error: You are currently not in range of the shop");
                return;
            }

            int cost = obj.Price * stack;

            //check if onsale if yes lower cost amount
            if (obj.Onsale.Count != 0)
            {
                foreach (string str in obj.Onsale)
                {
                    switch (str.ToLower())
                    {
                        case "bloodmoon":
                            if (Main.bloodMoon)
                                cost = (int)(cost * ((100 - configObj.bloodmoon)/100));
                            break;
                        case "eclipse":
                            if (Main.eclipse)
                                cost = (int)(cost * ((100 - configObj.eclipse) / 100));
                            break;
                        case "night":
                            if (!Main.dayTime)
                                cost = (int)(cost * ((100 - configObj.night)/100));
                            break;
                        case "day":
                            if (Main.dayTime)
                                cost = (int)(cost * ((100 - configObj.day)/100));
                            break;
                    }
                }
            }

            //Check if player has enough money to purchase the item
            var account = Wolfje.Plugins.SEconomy.SEconomyPlugin.Instance.GetBankAccount(player.Index);
            //Make sure balance of user is greater then group cost
            if (account.Balance < cost)
            {
                player.SendErrorMessage("Error: You do not have enough to Purchase this item!");
                player.SendErrorMessage("Required: {0}!", ((Money)cost).ToLongString());
                return;
            }

            //Check if player has free inventory
            if (freeSlots(player, item, stack))
            {
                //All checks completed
                //Remove money and place in worldaccount
                account.TransferToAsync(SEconomyPlugin.Instance.WorldAccount, cost, Wolfje.Plugins.SEconomy.Journal.BankAccountTransferOptions.IsPayment, obj.Item, string.Format("Shop: {0} purhcase {1} stack of {2}", player.Name, stack, item.name));
            }
            else
            {
                return;
            }
            ShopList.lowerStock(obj, stack);
        }
Ejemplo n.º 18
0
        public static void ShowFile(TSCommand command, string chat, TSPlayer player)
        {
            try
            {
                String filetoshow = Path.Combine(SavePath, command.file);
                foreach (var group in command.groups)
                {
                    if (group.Key == player.Group.Name)
                    {
                        filetoshow = Path.Combine(SavePath, group.Value);
                    }
                }

                Dictionary<string, Color> displayLines = new Dictionary<string, Color>();

                TSUtils.CheckFile(filetoshow);

                var file = File.ReadAllLines(filetoshow);

                var messages = TSUtils.ReplaceVariables(file, player);

                int page = 0;
                if (chat.Contains(" "))
                {
                    var data = chat.Split(' ');
                    if (int.TryParse(data[1], out page))
                        page--;
                    else
                        player.SendErrorMessage(string.Format("Invalid page number ({0})", data[1]), Color.Red);
                }

                TSUtils.Paginate(TSUtils.GetPaginationHeader(command.name, command.command, page + 1, (messages.Count / 6) + 1),
                                 messages, page, player);
            }
            catch (Exception ex)
            {
                TShock.Log.ConsoleError("Something when wrong when showing {0} \"{1}\". Check the Logs.".SFormat(player.Name, command.command));
                TShock.Log.Error(ex.ToString());
            }
        }
        private bool TryRemoveProtection(TSPlayer player, DPoint tileLocation, bool sendFailureMessages = true)
        {
            if (!player.IsLoggedIn) {
            if (sendFailureMessages)
              player.SendErrorMessage("You have to be logged in to alter protections.");

            return false;
              }

              try {
            this.ProtectionManager.RemoveProtection(player, tileLocation);

            BlockType blockType = (BlockType)TerrariaUtils.Tiles[tileLocation].type;
            player.SendSuccessMessage(
              string.Format("This {0} is not protected anymore.", TerrariaUtils.Tiles.GetBlockTypeName(blockType))
            );

            return true;
              } catch (InvalidBlockTypeException ex) {
            if (sendFailureMessages) {
              string messageFormat;
              if (TerrariaUtils.Tiles.IsSolidBlockType(ex.BlockType, true))
            messageFormat = "Deprotecting {0} blocks is not allowed.";
              else
            messageFormat = "Deprotecting {0} objects is not allowed.";

              player.SendErrorMessage(string.Format(messageFormat, TerrariaUtils.Tiles.GetBlockTypeName(ex.BlockType)));
            }

            return false;
              } catch (NoProtectionException) {
            BlockType blockType = (BlockType)TerrariaUtils.Tiles[tileLocation].type;
            if (sendFailureMessages) {
              player.SendErrorMessage(string.Format(
            "This {0} is not protected by Protector at all.", TerrariaUtils.Tiles.GetBlockTypeName(blockType)
              ));
            }

            return false;
              } catch (TileProtectedException) {
            BlockType blockType = (BlockType)TerrariaUtils.Tiles[tileLocation].type;
            player.SendErrorMessage(string.Format(
              "This {0} is owned by someone else, you can't deprotect it.", TerrariaUtils.Tiles.GetBlockTypeName(blockType)
            ));

            return false;
              }
        }
        public virtual bool HandleChestModifySlot(TSPlayer player, int chestIndex, int slotIndex, ItemData newItem)
        {
            if (this.IsDisposed)
            return false;

              // Get the chest location of the chest the player has last opened.
              IChest chest = this.LastOpenedChest(player);
              if (chest == null)
            return true;

              ProtectionEntry protection = null;
              // Only need the first enumerated entry as we don't need the protections of adjacent blocks.
              foreach (ProtectionEntry enumProtection in this.ProtectionManager.EnumerateProtectionEntries(chest.Location)) {
            protection = enumProtection;
            break;
              }

              bool playerHasAccess = true;
              if (protection != null)
            playerHasAccess = this.ProtectionManager.CheckProtectionAccess(protection, player, false);

              if (!playerHasAccess)
            return true;

              if (protection != null && protection.RefillChestData != null) {
            RefillChestMetadata refillChest = protection.RefillChestData;
            // The player who set up the refill chest or masters shall modify its contents.
            if (
              this.Config.AllowRefillChestContentChanges &&
              (refillChest.Owner == player.User.ID || player.Group.HasPermission(ProtectorPlugin.ProtectionMaster_Permission))
            ) {
              refillChest.RefillItems[slotIndex] = newItem;

              this.ChestManager.TryRefillChest(chest, refillChest);

              if (refillChest.RefillTime == TimeSpan.Zero) {
            player.SendSuccessMessage("The content of this refill chest was updated.");
              } else {
            lock (this.ChestManager.RefillTimers) {
              if (this.ChestManager.RefillTimers.IsTimerRunning(refillChest.RefillTimer))
                this.ChestManager.RefillTimers.RemoveTimer(refillChest.RefillTimer);
            }

            player.SendSuccessMessage("The content of this refill chest was updated and the timer was reset.");
              }

              return false;
            }

            if (refillChest.OneLootPerPlayer || refillChest.RemainingLoots > 0) {
              Contract.Assert(refillChest.Looters != null);
              if (!refillChest.Looters.Contains(player.User.ID)) {
            refillChest.Looters.Add(player.User.ID);

            if (refillChest.RemainingLoots > 0)
              refillChest.RemainingLoots--;
              }
            }

            // As the first item is taken out, we start the refill timer.
            ItemData oldItem = chest.Items[slotIndex];
            if (newItem.Type == ItemType.None || (newItem.Type == oldItem.Type && newItem.StackSize <= oldItem.StackSize)) {
              // TODO: Bad code, refill timers shouldn't be public at all.
              lock (this.ChestManager.RefillTimers)
            this.ChestManager.RefillTimers.StartTimer(refillChest.RefillTimer);
            } else {
              player.SendErrorMessage("You can not put items into this chest.");
              return true;
            }
              } else if (protection != null && protection.BankChestKey != BankChestDataKey.Invalid) {
            BankChestDataKey bankChestKey = protection.BankChestKey;
            this.ServerMetadataHandler.EnqueueUpdateBankChestItem(bankChestKey, slotIndex, newItem);
              }

              chest.Items[slotIndex] = newItem;
              return true;
        }
Ejemplo n.º 21
0
        private void RegisterCommands(string text, TSPlayer ply)
        {
            var cmdList = ParseCommands(text);

            foreach (var cmdArgs in cmdList)
            {
                var args = new List<string>(cmdArgs);
                if (args.Count < 1)
                    continue;

                var cmdName = args[0];

                switch (cmdName)
                {
                    case "no-perm":
                        if (!ply.Group.HasPermission("essentials.signs.negateperms"))
                        {
                            ply.SendErrorMessage("You do not have permission to create that sign command.");
                            continue;
                        }
                        freeAccess = true;
                        continue;
                    case "confirm":
                        _confirm = true;
                        continue;
                    case "no-read":
                        noRead = true;
                        continue;
                    case "no-edit":
                        noEdit = true;
                        continue;
                    case "require-perm":
                    case "rperm":
                        requiredPermission = args[1];
                        continue;
                    case "cd":
                    case "cooldown":
                        ParseSignCd(args);
                        continue;
                    case "allowg":
                        if (!ply.Group.HasPermission("essentials.signs.allowgroups"))
                        {
                            ply.SendErrorMessage("You do not have permission to create that sign command.");
                            continue;
                        }
                        ParseGroups(args);
                        continue;
                    case "allowu":
                        if (!ply.Group.HasPermission("essentials.signs.allowusers"))
                        {
                            ply.SendErrorMessage("You do not have permission to create that sign command.");
                            continue;
                        }
                        ParseUsers(args);
                        continue;
                    case "spawnmob":
                    case "sm":
                        if (!ply.Group.HasPermission(Permissions.spawnmob))
                        {
                            ply.SendErrorMessage("You do not have permission to create that sign command.");
                            continue;
                        }
                        ParseSpawnMob(args, ply);
                        continue;
                    case "spawnboss":
                    case "sb":
                        if (!ply.Group.HasPermission(Permissions.spawnboss))
                        {
                            ply.SendErrorMessage("You do not have permission to create that sign command.");
                            continue;
                        }
                        ParseSpawnBoss(args, ply);
                        continue;
                }

                IEnumerable<Command> cmds = Commands.ChatCommands.Where(c => c.HasAlias(cmdName)).ToList();

                foreach (var cmd in cmds)
                {
                    if (!CheckPermissions(ply))
                        return;

                    var sCmd = new SignCommand(cooldown, cmd.Permissions, cmd.CommandDelegate, cmdName);
                    commands.Add(args, sCmd);
                }
            }
        }
Ejemplo n.º 22
0
        private void ParseSpawnBoss(IEnumerable<string> args, TSPlayer player)
        {
            var list = new List<string>(args);
            list.RemoveAt(0);
            foreach (var obj in list)
            {
                try
                {
                    var boss = obj.Split(':')[0];
                    var num = obj.Split(':')[1];

                    int spawnCount;
                    if (!int.TryParse(num, out spawnCount))
                        continue;

                    _bosses.Add(boss, spawnCount);
                }
                catch
                {
                    player.SendErrorMessage("Invalid naming format. Format: \"bossname:spawncount\"");
                }
            }
        }
Ejemplo n.º 23
0
        public bool Run(string msg, bool silent, TSPlayer ply, List<string> parms)
        {
            if (!CanRun(ply))
                return false;

            try
            {
                CommandDelegate(new CommandArgs(msg, silent, ply, parms));
            }
            catch (Exception e)
            {
                ply.SendErrorMessage("Command failed, check logs for more details.");
                TShock.Log.Error(e.ToString());
            }

            return true;
        }
        public virtual bool HandleChestUnlock(TSPlayer player, DPoint chestLocation)
        {
            if (this.IsDisposed)
            return false;

              ProtectionEntry protection = null;
              // Only need the first enumerated entry as we don't need the protections of adjacent blocks.
              foreach (ProtectionEntry enumProtection in this.ProtectionManager.EnumerateProtectionEntries(chestLocation)) {
            protection = enumProtection;
            break;
              }
              if (protection == null)
            return false;

              bool undoUnlock = false;
              if (!this.ProtectionManager.CheckProtectionAccess(protection, player, false)) {
            player.SendErrorMessage("This chest is protected, you can't unlock it.");
            undoUnlock = true;
              }
              if (protection.RefillChestData != null && !this.CheckRefillChestLootability(protection.RefillChestData, player))
            undoUnlock = true;

              if (undoUnlock) {
            bool dummy;
            if (TerrariaUtils.Tiles.GetChestStyle(TerrariaUtils.Tiles[chestLocation], out dummy) == ChestStyle.GoldChest) {
              int itemIndex = Item.NewItem(
            chestLocation.X * TerrariaUtils.TileSize, chestLocation.Y * TerrariaUtils.TileSize, 0, 0, (int)ItemType.GoldenKey
              );
              player.SendData(PacketTypes.ItemDrop, string.Empty, itemIndex);
            }

            player.SendTileSquare(chestLocation, 3);
            return true;
              }

              return false;
        }
        public virtual bool HandleChestRename(TSPlayer player, int chestIndex, string newName)
        {
            if (this.IsDisposed)
            return false;

              IChest chest = this.LastOpenedChest(player);
              if (chest == null)
            return true;

              bool isAllowed = true;
              if (this.CheckProtected(player, chest.Location, true)) {
            player.SendErrorMessage("You have to be the owner of the chest in order to rename it.");
            isAllowed = false;
              }

              if (this.Config.LoginRequiredForChestUsage && !player.IsLoggedIn) {
            player.SendErrorMessage("You have to be logged in in order to rename chests.");
            isAllowed = false;
              }

              if (!isAllowed) {
            string originalName = string.Empty;
            if (chest.IsWorldChest)
              originalName = chest.Name;

            // The name change will already have happened locally for the player, so gotta send the original name back to them.
            player.SendData(PacketTypes.ChestName, originalName, chest.Index, chest.Location.X, chest.Location.Y);
            return true;
              } else {
            // Only world chests can have names, so attempt to convert it into one.
            if (!chest.IsWorldChest && !this.TrySwapChestData(null, chest.Location, out chest)) {
              player.SendErrorMessage("The maximum amount of named chests for this world has been reached.");
              return true;
            }

            chest.Name = newName;
            player.SendData(PacketTypes.ChestName, chest.Name, chest.Index, chest.Location.X, chest.Location.Y);

            return true;
              }
        }
        public virtual bool HandleChestPlace(TSPlayer player, DPoint location, int storageType, int storageStyle)
        {
            if (this.IsDisposed)
            return false;

              ushort tileToPlace = TileID.Containers;
              bool isDresser = (storageType == 2);
              if (isDresser)
            tileToPlace = TileID.Dressers;

              try {
            this.ChestManager.PlaceChest(tileToPlace, storageStyle, location);
              } catch (LimitEnforcementException ex) {
            player.SendTileSquare(location.X, location.Y, 2);
            player.SendErrorMessage("The limit of maximum possible chests has been reached. Please report this to a server administrator.");
            this.PluginTrace.WriteLineWarning($"Chest limit of {Main.chest.Length + this.Config.MaxProtectorChests - 1} has been reached!");
              }

              if (this.Config.AutoProtectedTiles[tileToPlace])
            this.TryCreateAutoProtection(player, location);

              return true;
        }
Ejemplo n.º 27
0
        public static bool HandleCommand(TSPlayer player, string text)
        {
            string cmdText = text.Remove(0, 1);
            string cmdPrefix = text[0].ToString();
            bool silent = false;

            if (cmdPrefix == SilentSpecifier)
                silent = true;

            var args = ParseParameters(cmdText);
            if (args.Count < 1)
                return false;

            string cmdName = args[0].ToLower();
            args.RemoveAt(0);

            IEnumerable<Command> cmds = ChatCommands.FindAll(c => c.HasAlias(cmdName));

            if (Hooks.PlayerHooks.OnPlayerCommand(player, cmdName, cmdText, args, ref cmds, cmdPrefix))
                return true;

            if (cmds.Count() == 0)
            {
                if (player.AwaitingResponse.ContainsKey(cmdName))
                {
                    Action<CommandArgs> call = player.AwaitingResponse[cmdName];
                    player.AwaitingResponse.Remove(cmdName);
                    call(new CommandArgs(cmdText, player, args));
                    return true;
                }
                player.SendErrorMessage("Invalid command entered. Type {0}help for a list of valid commands.", Specifier);
                return true;
            }
            foreach (Command cmd in cmds)
            {
                if (!cmd.CanRun(player))
                {
                    TShock.Utils.SendLogs(string.Format("{0} tried to execute {1}{2}.", player.Name, Specifier, cmdText), Color.PaleVioletRed, player);
                    player.SendErrorMessage("You do not have access to this command.");
                }
                else if (!cmd.AllowServer && !player.RealPlayer)
                {
                    player.SendErrorMessage("You must use this command in-game.");
                }
                else
                {
                    if (cmd.DoLog)
                        TShock.Utils.SendLogs(string.Format("{0} executed: {1}{2}.", player.Name, silent ? SilentSpecifier : Specifier, cmdText), Color.PaleVioletRed, player);
                    cmd.Run(cmdText, silent, player, args);
                }
            }
            return true;
        }
        public override bool HandleTileEdit(
            TSPlayer player, TileEditType editType, BlockType blockType, DPoint location, int objectStyle
            )
        {
            if (this.IsDisposed)
            return false;
              if (base.HandleTileEdit(player, editType, blockType, location, objectStyle))
            return true;

              switch (editType) {
            case TileEditType.PlaceTile: {
              Tile tile = TerrariaUtils.Tiles[location];
              if (tile == null)
            Main.tile[location.X, location.Y] = tile = new Tile();

              WorldGen.PlaceTile(location.X, location.Y, (int)blockType, false, true, -1, objectStyle);
              NetMessage.SendData((int)PacketTypes.Tile, -1, player.Index, string.Empty, 1, location.X, location.Y, (int)blockType, objectStyle);

              if (this.Config.AutoProtectedTiles[(int)blockType])
            this.TryCreateAutoProtection(player, location);

              return true;
            }
            case TileEditType.TileKill:
            case TileEditType.TileKillNoItem: {
              // Is the tile really going to be destroyed or just being hit?
              //if (blockType != 0)
              //  break;

              Tile tile = TerrariaUtils.Tiles[location];
              bool isChest = (tile.type == TileID.Containers || tile.type == TileID.Dressers);
              foreach (ProtectionEntry protection in this.ProtectionManager.EnumerateProtectionEntries(location)) {
            // If the protection is invalid, just remove it.
            if (!TerrariaUtils.Tiles.IsValidCoord(protection.TileLocation)) {
              this.ProtectionManager.RemoveProtection(TSPlayer.Server, protection.TileLocation, false);
              continue;
            }

            Tile protectedTile = TerrariaUtils.Tiles[protection.TileLocation];
            // If the protection is invalid, just remove it.
            if (!protectedTile.active() || protectedTile.type != (int)protection.BlockType) {
              this.ProtectionManager.RemoveProtection(TSPlayer.Server, protection.TileLocation, false);
              continue;
            }

            string tileName = TerrariaUtils.Tiles.GetBlockTypeName((BlockType)protectedTile.type);
            if (
              protection.Owner == player.User.ID || (
                this.Config.AutoDeprotectEverythingOnDestruction &&
                player.Group.HasPermission(ProtectorPlugin.ProtectionMaster_Permission)
              )
            ) {
              if (isChest) {
                bool isBankChest = (protection.BankChestKey != BankChestDataKey.Invalid);
                ObjectMeasureData measureData = TerrariaUtils.Tiles.MeasureObject(protection.TileLocation);
                DPoint chestLocation = measureData.OriginTileLocation;
                IChest chest = this.ChestManager.ChestFromLocation(chestLocation);

                if (chest == null)
                  return true;

                if (isBankChest) {
                  this.DestroyBlockOrObject(chestLocation);
                } else {
                  for (int i = 0; i < Chest.maxItems; i++) {
                    if (chest.Items[i].StackSize > 0)
                      return true;
                  }
                }
              }
              this.ProtectionManager.RemoveProtection(player, protection.TileLocation, false);

              if (this.Config.NotifyAutoDeprotections)
                player.SendWarningMessage($"The {tileName} is not protected anymore.");
            } else {
              player.SendErrorMessage($"The {tileName} is protected.");

              if (protection.TradeChestData != null)
                player.SendWarningMessage("If you want to trade with this chest, right click it first.");

              player.SendTileSquare(location);
              return true;
            }
              }

              if (isChest) {
            ObjectMeasureData measureData = TerrariaUtils.Tiles.MeasureObject(location);
            DPoint chestLocation = measureData.OriginTileLocation;
            IChest chest = this.ChestManager.ChestFromLocation(chestLocation);
            if (chest != null) {
              // Don't allow removing of non empty chests.
              for (int i = 0; i < Chest.maxItems; i++) {
                if (chest.Items[i].StackSize > 0)
                  return true;
              }

              this.DestroyBlockOrObject(chestLocation);
              return true;
            }
              }

              break;
            }
            case TileEditType.PlaceWire:
            case TileEditType.PlaceWireBlue:
            case TileEditType.PlaceWireGreen:
            case TileEditType.PlaceWireYellow:
            case TileEditType.PlaceActuator:
            case TileEditType.DestroyWire:
            case TileEditType.DestroyWireBlue:
            case TileEditType.DestroyWireGreen:
            case TileEditType.DestroyWireYellow:
            case TileEditType.DestroyActuator:
              if (this.Config.AllowWiringProtectedBlocks)
            break;

              if (this.CheckProtected(player, location, false)) {
            player.SendTileSquare(location);
            return true;
              }

              break;
            case TileEditType.PokeLogicGate:
            case TileEditType.Actuate:
              if (this.CheckProtected(player, location, false)) {
            player.SendTileSquare(location);
            return true;
              }

              break;
              }

              return false;
        }
Ejemplo n.º 29
0
        private void ParseSpawnMob(IEnumerable<string> args, TSPlayer player)
        {
            //>sm "blue slime":10 zombie:100
            var list = new List<string>(args);
            list.RemoveAt(0);
            foreach (var obj in list)
            {
                try
                {
                    var mob = obj.Split(':')[0];
                    var num = obj.Split(':')[1];

                    int spawnCount;
                    if (!int.TryParse(num, out spawnCount))
                        continue;

                    _mobs.Add(mob, spawnCount);
                }
                catch
                {
                    player.SendErrorMessage("Invalid naming format. Format: \"mobname:spawncount\"");
                }
            }
        }
 public bool TryLockChest(TSPlayer player, DPoint anyChestTileLocation, bool sendMessages = true)
 {
     try {
     TerrariaUtils.Tiles.LockChest(anyChestTileLocation);
     return true;
       } catch (ArgumentException) {
     player.SendErrorMessage("There is no chest here.");
     return false;
       } catch (InvalidChestStyleException) {
     player.SendErrorMessage("The chest must be an unlocked lockable chest.");
     return false;
       }
 }
Ejemplo n.º 31
0
 /// <summary>
 /// Sends the player an error message stating that more than one match was found
 /// appending a csv list of the matches.
 /// </summary>
 /// <param name="ply">Player to send the message to</param>
 /// <param name="matches">An enumerable list with the matches</param>
 public void SendMultipleMatchError(TSPlayer ply, IEnumerable <object> matches)
 {
     ply.SendErrorMessage("More than one match found: {0}", string.Join(",", matches));
     ply.SendErrorMessage("Use \"my query\" for items with spaces");
 }
        public bool TrySetUpBankChest(TSPlayer player, DPoint tileLocation, int bankChestIndex, bool sendMessages = true)
        {
            if (!player.IsLoggedIn) {
            if (sendMessages)
              player.SendErrorMessage("You have to be logged in in order to set up bank chests.");

            return false;
              }

              if (!this.ProtectionManager.CheckBlockAccess(player, tileLocation, true) && !player.Group.HasPermission(ProtectorPlugin.ProtectionMaster_Permission)) {
            player.SendErrorMessage("You don't own the protection of this chest.");
            return false;
              }

              try {
            this.ChestManager.SetUpBankChest(player, tileLocation, bankChestIndex, true);

            player.SendSuccessMessage(string.Format(
              $"This chest is now an instance of your bank chest with the number {TShock.Utils.ColorTag(bankChestIndex.ToString(), Color.Red)}."
            ));

            return true;
              } catch (ArgumentException ex) {
            if (ex.ParamName == "tileLocation") {
              if (sendMessages)
            player.SendErrorMessage("There is no chest here.");

              return false;
            } else if (ex.ParamName == "bankChestIndex") {
              ArgumentOutOfRangeException actualEx = (ArgumentOutOfRangeException)ex;
              if (sendMessages) {
            string messageFormat;
            if (!player.Group.HasPermission(ProtectorPlugin.NoBankChestLimits_Permision))
              messageFormat = "The bank chest number must be between 1 and {0}.";
            else
              messageFormat = "The bank chest number must be greater than 1.";

            player.SendErrorMessage(string.Format(messageFormat, actualEx.ActualValue));
              }

              return false;
            }

            throw;
              } catch (MissingPermissionException) {
            if (sendMessages)
              player.SendErrorMessage("You are not allowed to define bank chests.");

            return false;
              } catch (InvalidBlockTypeException) {
            if (sendMessages)
              player.SendErrorMessage("Only chests can be converted to bank chests.");

            return false;
              } catch (NoProtectionException) {
            if (sendMessages)
              player.SendErrorMessage("The chest needs to be protected to be converted to a bank chest.");

            return false;
              } catch (ChestNotEmptyException) {
            if (sendMessages)
              player.SendErrorMessage("The chest has to be empty in order to restore a bank chest here.");

            return false;
              } catch (ChestTypeAlreadyDefinedException) {
            if (sendMessages)
              player.SendErrorMessage("The chest is already a bank chest.");

            return false;
              } catch (ChestIncompatibilityException) {
            if (sendMessages)
              player.SendErrorMessage("A bank chest can not be a refill- or trade chest at the same time.");

            return false;
              } catch (NoChestDataException) {
            if (sendMessages) {
              player.SendErrorMessage("Error: There are no chest data for this chest available. This world's data might be");
              player.SendErrorMessage("corrupted.");
            }

            return false;
              } catch (BankChestAlreadyInstancedException) {
            if (sendMessages) {
              player.SendErrorMessage(string.Format("There is already an instance of your bank chest with the index {0} in", bankChestIndex));
              player.SendErrorMessage("this world.");
            }

            return false;
              }
        }
Ejemplo n.º 33
0
 private void SendCorrectiveMessage(TSPlayer player, string itemName)
 {
     player.SendErrorMessage("{0} is banned! Remove it!", itemName);
 }
Ejemplo n.º 34
0
        public bool Run(string msg, TSPlayer ply, List<string> parms)
        {
            if (!ply.Group.HasPermission(Permission))
                return false;

            try
            {
                command(new CommandArgs(msg, ply, parms));
            }
            catch (Exception e)
            {
                ply.SendErrorMessage("Command failed, check logs for more details.");
                Log.Error(e.ToString());
            }

            return true;
        }
Ejemplo n.º 35
0
        public static bool HandleCommand(TSPlayer player, string text)
        {
            string cmdText = text.Remove(0, 1);

            var args = ParseParameters(cmdText);
            if (args.Count < 1)
                return false;

            string cmdName = args[0].ToLower();
            args.RemoveAt(0);

            IEnumerable<Command> cmds = ChatCommands.Where(c => c.HasAlias(cmdName));

            if (cmds.Count() == 0)
            {
                if (player.AwaitingResponse.ContainsKey(cmdName))
                {
                    Action<CommandArgs> call = player.AwaitingResponse[cmdName];
                    player.AwaitingResponse.Remove(cmdName);
                    call(new CommandArgs(cmdText, player, args));
                    return true;
                }
                player.SendErrorMessage("Invalid command entered. Type /help for a list of valid commands.");
                return true;
            }
            foreach (Command cmd in cmds)
            {
                if (!cmd.CanRun(player))
                {
                    TShock.Utils.SendLogs(string.Format("{0} tried to execute /{1}.", player.Name, cmdText), Color.Red);
                    player.SendErrorMessage("You do not have access to that command.");
                }
                else if (!cmd.AllowServer && !player.RealPlayer)
                {
                    player.SendErrorMessage("You must use this command in-game.");
                }
                else
                {
                    if (cmd.DoLog)
                        TShock.Utils.SendLogs(string.Format("{0} executed: /{1}.", player.Name, cmdText), Color.Red);
                    cmd.Run(cmdText, player, args);
                }
            }
            return true;
        }
Ejemplo n.º 36
0
        /// <summary>
        /// Executes the AliasCommand.  Will either forward the command to the tshock handler or do something else
        /// </summary>
        protected void DoCommands(AliasCommand alias, TShockAPI.TSPlayer player, List <string> parameters)
        {
            //loop through each alias and do the commands.
            foreach (string commandToExecute in alias.CommandsToExecute)
            {
                //todo: parse paramaters and dynamics
                string mangledString = commandToExecute;

                //specifies whether the command to run should be executed as a command, or ignored.
                //useful for functions like $msg that does other shit
                bool executeCommand = true;

                //replace parameter markers with actual parameter values
                ReplaceParameterMarkers(parameters, ref mangledString);

                mangledString = mangledString.Replace("$calleraccount", player.User.Name);
                mangledString = mangledString.Replace("$callername", player.Name);

                //$random(x,y) support.  Returns a random number between x and y
                if (randomRegex.IsMatch(mangledString))
                {
                    foreach (Match match in randomRegex.Matches(mangledString))
                    {
                        int randomFrom = 0;
                        int randomTo   = 0;

                        if (!string.IsNullOrEmpty(match.Groups[2].Value) && int.TryParse(match.Groups[2].Value, out randomTo) &&
                            !string.IsNullOrEmpty(match.Groups[1].Value) && int.TryParse(match.Groups[1].Value, out randomFrom))
                        {
                            // this is a critical section
                            // Random class is seeded from the system clock if you construct one without a seed.
                            // therefore, calls to Next() at exactly the same point in time is likely to produce the same number.
                            lock (__rndLock) {
                                mangledString = mangledString.Replace(match.ToString(), randomGenerator.Next(randomFrom, randomTo).ToString());
                            }
                        }
                        else
                        {
                            TShock.Log.ConsoleError(match.ToString() + " has some stupid shit in it, have a look at your AliasCmd config file.");
                            mangledString = mangledString.Replace(match.ToString(), "");
                        }
                    }
                }

                // $runas(u,cmd) support.  Run command as user
                if (runasFunctionRegex.IsMatch(mangledString))
                {
                    foreach (Match match in runasFunctionRegex.Matches(mangledString))
                    {
                        string   impersonatedName   = match.Groups[2].Value;
                        TSPlayer impersonatedPlayer = TShockAPI.TShock.Players.FirstOrDefault(i => i != null && i.Name == impersonatedName);

                        if (impersonatedPlayer != null)
                        {
                            string commandToRun = match.Groups[3].Value;
                            player = impersonatedPlayer;

                            mangledString = commandToRun.Trim();
                        }
                    }
                }

                // $msg(u,msg) support.  Sends the user a non-chat informational message
                if (msgRegex.IsMatch(mangledString))
                {
                    foreach (Match match in msgRegex.Matches(mangledString))
                    {
                        string   msgTarget         = match.Groups[2].Value.Trim();
                        string   message           = match.Groups[3].Value.Trim();
                        TSPlayer destinationPlayer = TShockAPI.TShock.Players.FirstOrDefault(i => i != null && i.Name == msgTarget);

                        if (destinationPlayer != null)
                        {
                            //custom command, skip forwarding of the command to the tshock executer
                            executeCommand = false;

                            destinationPlayer.SendInfoMessage(message);
                        }
                    }
                }

                //and send the command to tshock to do.
                try {
                    //prevent an infinite loop for a subcommand calling the alias again causing a commandloop
                    string command = mangledString.Split(' ')[0].Substring(1);
                    if (!command.Equals(alias.CommandAlias, StringComparison.CurrentCultureIgnoreCase))
                    {
                        if (executeCommand)
                        {
                            player.PermissionlessInvoke(mangledString);
                        }
                    }
                    else
                    {
                        TShock.Log.ConsoleError(string.Format("cmdalias {0}: calling yourself in an alias will cause an infinite loop. Ignoring.", alias.CommandAlias));
                    }
                } catch {
                    //execute the command disregarding permissions
                    player.SendErrorMessage(alias.UsageHelpText);
                }
            }
        }