From b60f0877e189fdbb039098a39c809125d694d8f4 Mon Sep 17 00:00:00 2001 From: kotyara Date: Tue, 26 Jul 2022 16:06:34 +0500 Subject: [PATCH] support php8019 and some cleanup (by @D-aHTuCT) --- src/API/AchievementAPI.php | 192 +- src/API/BanAPI.php | 287 ++- src/API/BlockAPI.php | 844 ++++--- src/API/ChatAPI.php | 107 +- src/API/ConsoleAPI.php | 482 ++-- src/API/EntityAPI.php | 332 ++- src/API/LevelAPI.php | 336 ++- src/API/PlayerAPI.php | 888 ++++---- src/API/PluginAPI.php | 290 ++- src/API/QueryAPI.php | 32 +- src/API/ServerAPI.php | 366 ++- src/API/TileAPI.php | 91 +- src/API/TimeAPI.php | 129 +- src/BaseEvent.php | 130 +- src/Deprecation.php | 26 +- src/Player.php | 1998 ++++++++--------- src/PocketMinecraftServer.php | 884 ++++---- src/config.php | 29 +- src/constants/BlockIDs.php | 19 - src/constants/EntityIDs.php | 19 - src/constants/GeneralConstants.php | 22 - src/constants/ItemIDs.php | 19 - src/dependencies.php | 67 +- src/entity/Entity.php | 19 - src/event/CancellableEvent.php | 19 - src/event/EventHandler.php | 19 - src/event/PluginEvent.php | 19 - src/functions.php | 149 +- src/installer/Installer.php | 19 - src/inventory/Window.php | 21 +- src/material/Block.php | 19 - src/material/Item.php | 19 - src/material/block/DoorBlock.php | 19 - src/material/block/FallableBlock.php | 19 - src/material/block/FlowableBlock.php | 19 - src/material/block/GenericBlock.php | 19 - src/material/block/LiquidBlock.php | 19 - src/material/block/SolidBlock.php | 19 - src/material/block/StairBlock.php | 19 - src/material/block/TransparentBlock.php | 19 - src/material/block/attachable/Ladder.php | 19 - src/material/block/attachable/SignPost.php | 19 - src/material/block/attachable/Torch.php | 19 - src/material/block/attachable/Trapdoor.php | 19 - src/material/block/attachable/WallSign.php | 19 - src/material/block/liquid/Lava.php | 19 - src/material/block/liquid/StillLava.php | 19 - src/material/block/liquid/StillWater.php | 19 - src/material/block/liquid/Water.php | 19 - src/material/block/misc/Air.php | 19 - src/material/block/misc/Bed.php | 19 - src/material/block/misc/Fire.php | 19 - src/material/block/misc/NetherReactor.php | 19 - src/material/block/misc/TNT.php | 19 - src/material/block/nonfull/Cake.php | 19 - src/material/block/nonfull/Carpet.php | 19 - src/material/block/nonfull/Chest.php | 19 - src/material/block/nonfull/Cobweb.php | 19 - src/material/block/nonfull/Farmland.php | 19 - src/material/block/nonfull/Fence.php | 19 - src/material/block/nonfull/FenceGate.php | 19 - src/material/block/nonfull/GlassPane.php | 19 - src/material/block/nonfull/IronBars.php | 19 - src/material/block/nonfull/IronDoor.php | 19 - src/material/block/nonfull/PoweredRail.php | 19 - src/material/block/nonfull/Rail.php | 19 - src/material/block/nonfull/Slab.php | 19 - src/material/block/nonfull/SnowLayer.php | 19 - src/material/block/nonfull/StoneWall.php | 19 - src/material/block/nonfull/WoodDoor.php | 19 - src/material/block/nonfull/WoodSlab.php | 19 - .../block/nonfull/stairs/BirchWoodStairs.php | 19 - .../block/nonfull/stairs/BrickStairs.php | 19 - .../nonfull/stairs/CobblestoneStairs.php | 19 - .../block/nonfull/stairs/JungleWoodStairs.php | 19 - .../nonfull/stairs/NetherBricksStairs.php | 19 - .../block/nonfull/stairs/QuartzStairs.php | 19 - .../block/nonfull/stairs/SandstoneStairs.php | 19 - .../block/nonfull/stairs/SpruceWoodStairs.php | 19 - .../block/nonfull/stairs/StoneBrickStairs.php | 19 - .../block/nonfull/stairs/WoodStairs.php | 19 - src/material/block/ore/CoalOre.php | 19 - src/material/block/ore/DiamondOre.php | 19 - src/material/block/ore/GlowingRedstoneOre.php | 19 - src/material/block/ore/GoldOre.php | 19 - src/material/block/ore/IronOre.php | 19 - src/material/block/ore/LapisOre.php | 19 - src/material/block/ore/RedstoneOre.php | 19 - src/material/block/plant/Beetroot.php | 19 - src/material/block/plant/BrownMushroom.php | 19 - src/material/block/plant/Cactus.php | 19 - src/material/block/plant/Carrot.php | 19 - src/material/block/plant/CyanFlower.php | 19 - src/material/block/plant/Dandelion.php | 19 - src/material/block/plant/DeadBush.php | 19 - src/material/block/plant/MelonStem.php | 19 - src/material/block/plant/PotatoBlock.php | 19 - src/material/block/plant/PumpkinStem.php | 19 - src/material/block/plant/RedMushroom.php | 19 - src/material/block/plant/Sapling.php | 19 - src/material/block/plant/Sugarcane.php | 19 - src/material/block/plant/TallGrass.php | 19 - src/material/block/plant/Wheat.php | 19 - src/material/block/solid/Bedrock.php | 19 - src/material/block/solid/Bookshelf.php | 19 - src/material/block/solid/Bricks.php | 19 - src/material/block/solid/BurningFurnace.php | 19 - src/material/block/solid/Clay.php | 19 - src/material/block/solid/Coal.php | 19 - src/material/block/solid/Cobblestone.php | 19 - src/material/block/solid/Diamond.php | 19 - src/material/block/solid/Dirt.php | 19 - src/material/block/solid/DoubleSlab.php | 19 - src/material/block/solid/DoubleWoodSlab.php | 19 - src/material/block/solid/Furnace.php | 19 - src/material/block/solid/Glass.php | 19 - src/material/block/solid/GlowingObsidian.php | 19 - src/material/block/solid/Glowstone.php | 19 - src/material/block/solid/Gold.php | 19 - src/material/block/solid/Grass.php | 19 - src/material/block/solid/Gravel.php | 19 - src/material/block/solid/HayBale.php | 19 - src/material/block/solid/Ice.php | 19 - src/material/block/solid/InfoUpdate.php | 19 - src/material/block/solid/InfoUpdate2.php | 19 - src/material/block/solid/InvisibleBedrock.php | 19 - src/material/block/solid/Iron.php | 19 - src/material/block/solid/Lapis.php | 19 - src/material/block/solid/Leaves.php | 19 - src/material/block/solid/LitPumpkin.php | 19 - src/material/block/solid/Melon.php | 19 - src/material/block/solid/MossStone.php | 19 - src/material/block/solid/NetherBrick.php | 19 - src/material/block/solid/Netherrack.php | 19 - src/material/block/solid/Obsidian.php | 19 - src/material/block/solid/Planks.php | 19 - src/material/block/solid/Pumpkin.php | 19 - src/material/block/solid/Quartz.php | 19 - src/material/block/solid/Reserved6.php | 19 - src/material/block/solid/Sand.php | 19 - src/material/block/solid/Sandstone.php | 19 - src/material/block/solid/Snow.php | 19 - src/material/block/solid/SoulSand.php | 19 - src/material/block/solid/Sponge.php | 19 - src/material/block/solid/Stone.php | 19 - src/material/block/solid/StoneBricks.php | 19 - src/material/block/solid/Stonecutter.php | 19 - src/material/block/solid/Wood.php | 19 - src/material/block/solid/Wool.php | 19 - src/material/block/solid/Workbench.php | 19 - src/material/item/armor/ChainBoots.php | 21 +- src/material/item/armor/ChainChestplate.php | 21 +- src/material/item/armor/ChainHelmet.php | 21 +- src/material/item/armor/ChainLeggings.php | 21 +- src/material/item/armor/DiamondBoots.php | 21 +- src/material/item/armor/DiamondChestplate.php | 21 +- src/material/item/armor/DiamondHelmet.php | 21 +- src/material/item/armor/DiamondLeggings.php | 21 +- src/material/item/armor/GoldenBoots.php | 21 +- src/material/item/armor/GoldenChestplate.php | 21 +- src/material/item/armor/GoldenHelmet.php | 21 +- src/material/item/armor/GoldenLeggings.php | 21 +- src/material/item/armor/IronBoots.php | 21 +- src/material/item/armor/IronChestplate.php | 21 +- src/material/item/armor/IronHelmet.php | 21 +- src/material/item/armor/IronLeggings.php | 21 +- src/material/item/armor/LeatherBoots.php | 21 +- src/material/item/armor/LeatherCap.php | 21 +- src/material/item/armor/LeatherPants.php | 21 +- src/material/item/armor/LeatherTunic.php | 21 +- src/material/item/food/Apple.php | 19 - src/material/item/food/BakedPotato.php | 19 - src/material/item/food/Beef.php | 19 - src/material/item/food/Beetroot.php | 19 - src/material/item/food/BeetrootSoup.php | 19 - src/material/item/food/Bread.php | 19 - src/material/item/food/Cake.php | 19 - src/material/item/food/Carrot.php | 19 - src/material/item/food/CookedChicken.php | 19 - src/material/item/food/CookedPorkchop.php | 19 - src/material/item/food/MelonItem.php | 19 - src/material/item/food/MushroomStew.php | 19 - src/material/item/food/Potato.php | 19 - src/material/item/food/PumpkinPie.php | 19 - src/material/item/food/RawChicken.php | 19 - src/material/item/food/RawPorkchop.php | 19 - src/material/item/food/Steak.php | 19 - src/material/item/generic/Arrow.php | 19 - src/material/item/generic/Bed.php | 19 - src/material/item/generic/BeetrootSeeds.php | 19 - src/material/item/generic/Bone.php | 19 - src/material/item/generic/Book.php | 19 - src/material/item/generic/Bowl.php | 19 - src/material/item/generic/Brick.php | 19 - src/material/item/generic/Bucket.php | 19 - src/material/item/generic/CameraItem.php | 19 - src/material/item/generic/Clay.php | 19 - src/material/item/generic/Coal.php | 19 - src/material/item/generic/Diamond.php | 19 - src/material/item/generic/Dye.php | 19 - src/material/item/generic/Egg.php | 19 - src/material/item/generic/Feather.php | 19 - src/material/item/generic/Flint.php | 19 - src/material/item/generic/GlowstoneDust.php | 19 - src/material/item/generic/GoldIngot.php | 19 - src/material/item/generic/Gunpowder.php | 19 - src/material/item/generic/IronDoor.php | 19 - src/material/item/generic/IronIngot.php | 19 - src/material/item/generic/Leather.php | 19 - src/material/item/generic/MelonSeeds.php | 19 - src/material/item/generic/Minecart.php | 19 - src/material/item/generic/NetherBrick.php | 19 - src/material/item/generic/Painting.php | 19 - src/material/item/generic/Paper.php | 19 - src/material/item/generic/PumpkinSeeds.php | 19 - src/material/item/generic/Quartz.php | 19 - src/material/item/generic/Redstone.php | 19 - src/material/item/generic/Saddle.php | 21 +- src/material/item/generic/SignItem.php | 19 - src/material/item/generic/Slimeball.php | 19 - src/material/item/generic/Snowball.php | 19 - src/material/item/generic/SpawnEgg.php | 19 - src/material/item/generic/Stick.php | 19 - src/material/item/generic/Sugar.php | 19 - src/material/item/generic/Sugarcane.php | 19 - src/material/item/generic/Wheat.php | 19 - src/material/item/generic/WheatSeeds.php | 19 - src/material/item/generic/WoodenDoor.php | 19 - src/material/item/tool/Bow.php | 19 - src/material/item/tool/Clock.php | 19 - src/material/item/tool/Compass.php | 19 - src/material/item/tool/DiamondAxe.php | 19 - src/material/item/tool/DiamondHoe.php | 19 - src/material/item/tool/DiamondPickaxe.php | 19 - src/material/item/tool/DiamondShovel.php | 19 - src/material/item/tool/DiamondSword.php | 19 - src/material/item/tool/FlintSteel.php | 19 - src/material/item/tool/GoldenAxe.php | 19 - src/material/item/tool/GoldenHoe.php | 19 - src/material/item/tool/GoldenPickaxe.php | 19 - src/material/item/tool/GoldenShovel.php | 19 - src/material/item/tool/GoldenSword.php | 19 - src/material/item/tool/IronAxe.php | 19 - src/material/item/tool/IronHoe.php | 19 - src/material/item/tool/IronPickaxe.php | 19 - src/material/item/tool/IronShovel.php | 19 - src/material/item/tool/IronSword.php | 19 - src/material/item/tool/Shears.php | 19 - src/material/item/tool/StoneAxe.php | 19 - src/material/item/tool/StoneHoe.php | 19 - src/material/item/tool/StonePickaxe.php | 19 - src/material/item/tool/StoneShovel.php | 19 - src/material/item/tool/StoneSword.php | 19 - src/material/item/tool/WoodenAxe.php | 19 - src/material/item/tool/WoodenHoe.php | 19 - src/material/item/tool/WoodenPickaxe.php | 19 - src/material/item/tool/WoodenShovel.php | 19 - src/material/item/tool/WoodenSword.php | 19 - src/math/Matrix.php | 138 +- src/math/Vector2.php | 69 +- src/math/Vector3.php | 101 +- src/math/VectorMath.php | 20 - src/network/MinecraftInterface.php | 36 +- src/network/Packet.php | 20 +- src/network/RCON.php | 247 +- src/network/UDPSocket.php | 37 +- src/network/protocol/ProtocolInfo.php | 21 - .../protocol/packet/AddEntityPacket.php | 19 - .../protocol/packet/AddItemEntityPacket.php | 19 - src/network/protocol/packet/AddMobPacket.php | 19 - .../protocol/packet/AddPaintingPacket.php | 19 - .../protocol/packet/AddPlayerPacket.php | 19 - .../packet/AdventureSettingsPacket.php | 19 - src/network/protocol/packet/AnimatePacket.php | 19 - src/network/protocol/packet/ChatPacket.php | 19 - .../protocol/packet/ChunkDataPacket.php | 19 - .../protocol/packet/ClientConnectPacket.php | 19 - .../protocol/packet/ClientHandshakePacket.php | 19 - .../protocol/packet/ContainerClosePacket.php | 19 - .../protocol/packet/ContainerOpenPacket.php | 19 - .../packet/ContainerSetContentPacket.php | 19 - .../packet/ContainerSetDataPacket.php | 19 - .../packet/ContainerSetSlotPacket.php | 19 - .../protocol/packet/DisconnectPacket.php | 19 - .../protocol/packet/DropItemPacket.php | 19 - .../protocol/packet/EntityDataPacket.php | 19 - .../protocol/packet/EntityEventPacket.php | 19 - src/network/protocol/packet/ExplodePacket.php | 19 - .../protocol/packet/HurtArmorPacket.php | 19 - .../protocol/packet/InteractPacket.php | 19 - .../protocol/packet/LevelEventPacket.php | 19 - src/network/protocol/packet/LoginPacket.php | 19 - .../protocol/packet/LoginStatusPacket.php | 19 - src/network/protocol/packet/MessagePacket.php | 19 - .../protocol/packet/MoveEntityPacket.php | 19 - .../packet/MoveEntityPacket_PosRot.php | 19 - .../protocol/packet/MovePlayerPacket.php | 19 - src/network/protocol/packet/PingPacket.php | 19 - .../protocol/packet/PlayerActionPacket.php | 19 - .../packet/PlayerArmorEquipmentPacket.php | 19 - .../protocol/packet/PlayerEquipmentPacket.php | 19 - src/network/protocol/packet/PongPacket.php | 19 - src/network/protocol/packet/ReadyPacket.php | 19 - .../protocol/packet/RemoveBlockPacket.php | 19 - .../protocol/packet/RemoveEntityPacket.php | 19 - .../protocol/packet/RemovePlayerPacket.php | 19 - .../protocol/packet/RequestChunkPacket.php | 19 - src/network/protocol/packet/RespawnPacket.php | 19 - .../protocol/packet/RotateHeadPacket.php | 19 - .../protocol/packet/SendInventoryPacket.php | 19 - .../protocol/packet/ServerHandshakePacket.php | 19 - .../protocol/packet/SetEntityDataPacket.php | 19 - .../protocol/packet/SetEntityMotionPacket.php | 19 - .../protocol/packet/SetHealthPacket.php | 19 - .../packet/SetSpawnPositionPacket.php | 19 - src/network/protocol/packet/SetTimePacket.php | 19 - .../protocol/packet/StartGamePacket.php | 19 - .../protocol/packet/TakeItemEntityPacket.php | 19 - .../protocol/packet/TileEventPacket.php | 19 - src/network/protocol/packet/UnknownPacket.php | 19 - .../protocol/packet/UpdateBlockPacket.php | 19 - src/network/protocol/packet/UseItemPacket.php | 19 - src/network/query/QueryHandler.php | 60 +- src/network/query/QueryPacket.php | 24 +- src/network/raknet/RakNetCodec.php | 123 +- src/network/raknet/RakNetDataPacket.php | 137 +- src/network/raknet/RakNetInfo.php | 22 +- src/network/raknet/RakNetPacket.php | 29 +- src/network/raknet/RakNetParser.php | 131 +- src/pmf/Level.php | 375 ++-- src/pmf/PMF.php | 126 +- src/pmf/Plugin.php | 39 +- src/recipes/CraftingRecipes.php | 452 ++-- src/recipes/FuelData.php | 26 +- src/recipes/SmeltingData.php | 53 +- src/tests/ServerSuiteTest.php | 113 +- src/utils/Cache.php | 36 +- src/utils/Config.php | 425 ++-- src/utils/Container.php | 29 +- src/utils/Java.php | 38 +- src/utils/LightUtils.php | 14 +- src/utils/MersenneTwister.php | 781 +++---- src/utils/NBT.php | 278 ++- src/utils/Random.php | 82 +- src/utils/TextFormat.php | 22 +- src/utils/UPnP.php | 19 - src/utils/Utils.php | 420 ++-- src/utils/VersionString.php | 51 +- src/utils/pthreads.php | 112 +- src/world/Explosion.php | 63 +- src/world/Level.php | 476 ++-- src/world/LevelImport.php | 79 +- src/world/PocketChunkParser.php | 150 +- src/world/Position.php | 35 +- src/world/Tile.php | 438 ++-- src/world/generator/LevelGenerator.php | 30 +- src/world/generator/Populator.php | 20 +- src/world/generator/SuperflatGenerator.php | 84 +- src/world/generator/TemporalGenerator.php | 62 +- src/world/generator/WorldGenerator.php | 45 +- src/world/generator/noise/NoiseGenerator.php | 19 - .../generator/noise/NoiseGeneratorOctaves.php | 19 - .../generator/noise/NoiseGeneratorPerlin.php | 86 +- .../object/NetherReactorStructure.php | 37 +- src/world/generator/object/OreObject.php | 34 +- src/world/generator/object/OreType.php | 22 +- src/world/generator/object/PondObject.php | 29 +- .../object/grass/TallGrassObject.php | 25 +- .../generator/object/tree/BigTreeObject.php | 27 +- .../generator/object/tree/PineTreeObject.php | 40 +- .../generator/object/tree/SmallTreeObject.php | 66 +- .../object/tree/SpruceTreeObject.php | 36 +- .../generator/object/tree/TreeObject.php | 27 +- .../populator/MineshaftPopulator.php | 24 +- .../generator/populator/OrePopulator.php | 25 +- .../generator/populator/PondPopulator.php | 23 +- 376 files changed, 6528 insertions(+), 13472 deletions(-) diff --git a/src/API/AchievementAPI.php b/src/API/AchievementAPI.php index 1f18fb88..e95bcb55 100644 --- a/src/API/AchievementAPI.php +++ b/src/API/AchievementAPI.php @@ -1,146 +1,101 @@ array( "name" => "Taking Inventory", "requires" => array(), ),*/ - "mineWood" => array( + "mineWood" => [ "name" => "Getting Wood", - "requires" => array( + "requires" => [ //"openInventory", - ), - ), - "buildWorkBench" => array( + ], + ], + "buildWorkBench" => [ "name" => "Benchmarking", - "requires" => array( + "requires" => [ "mineWood", - ), - ), - "buildPickaxe" => array( + ], + ], + "buildPickaxe" => [ "name" => "Time to Mine!", - "requires" => array( + "requires" => [ "buildWorkBench", - ), - ), - "buildFurnace" => array( + ], + ], + "buildFurnace" => [ "name" => "Hot Topic", - "requires" => array( + "requires" => [ "buildPickaxe", - ), - ), - "acquireIron" => array( + ], + ], + "acquireIron" => [ "name" => "Acquire hardware", - "requires" => array( + "requires" => [ "buildFurnace", - ), - ), - "buildHoe" => array( + ], + ], + "buildHoe" => [ "name" => "Time to Farm!", - "requires" => array( + "requires" => [ "buildWorkBench", - ), - ), - "makeBread" => array( + ], + ], + "makeBread" => [ "name" => "Bake Bread", - "requires" => array( + "requires" => [ "buildHoe", - ), - ), - "bakeCake" => array( + ], + ], + "bakeCake" => [ "name" => "The Lie", - "requires" => array( + "requires" => [ "buildHoe", - ), - ), - "buildBetterPickaxe" => array( + ], + ], + "buildBetterPickaxe" => [ "name" => "Getting an Upgrade", - "requires" => array( + "requires" => [ "buildPickaxe", - ), - ), - "buildSword" => array( + ], + ], + "buildSword" => [ "name" => "Time to Strike!", - "requires" => array( + "requires" => [ "buildWorkBench", - ), - ), - "diamonds" => array( + ], + ], + "diamonds" => [ "name" => "DIAMONDS!", - "requires" => array( + "requires" => [ "acquireIron", - ), - ), - "leather" => array( + ], + ], + "leather" => [ "name" => "Cow Tipper", - "requires" => array( + "requires" => [ "buildSword", - ), - ), - - ); + ], + ], + + ]; function __construct(){ } - - public static function broadcastAchievement(Player $player, $achievementId){ - if(isset(self::$achievements[$achievementId])){ - $result = ServerAPI::request()->api->dhandle("achievement.broadcast", array("player" => $player, "achievementId" => $achievementId)); - if($result !== false and $result !== true){ - if(ServerAPI::request()->api->getProperty("announce-player-achievements") == true){ - ServerAPI::request()->api->chat->broadcast($player->username." has just earned the achievement [".self::$achievements[$achievementId]["name"]."]"); - }else{ - $player->sendChat("You have just earned the achievement [".self::$achievements[$achievementId]["name"]."]"); - } - } - return true; - } - return false; - } - - public static function addAchievement($achievementId, $achievementName, array $requires = array()){ + + public static function addAchievement($achievementId, $achievementName, array $requires = []){ if(!isset(self::$achievements[$achievementId])){ - self::$achievements[$achievementId] = array( + self::$achievements[$achievementId] = [ "name" => $achievementName, "requires" => $requires, - ); + ]; return true; } return false; } - - public static function hasAchievement(Player $player, $achievementId){ - if(!isset(self::$achievements[$achievementId]) or !isset($player->achievements)){ - $player->achievements = array(); - return false; - } - - if(!isset($player->achievements[$achievementId]) or $player->achievements[$achievementId] == false){ - return false; - } - return true; - } - + public static function grantAchievement(Player $player, $achievementId){ if(isset(self::$achievements[$achievementId]) and !self::hasAchievement($player, $achievementId)){ foreach(self::$achievements[$achievementId]["requires"] as $requerimentId){ @@ -148,7 +103,7 @@ class AchievementAPI{ return false; } } - if(ServerAPI::request()->api->dhandle("achievement.grant", array("player" => $player, "achievementId" => $achievementId)) !== false){ + if(ServerAPI::request()->api->dhandle("achievement.grant", ["player" => $player, "achievementId" => $achievementId]) !== false){ $player->achievements[$achievementId] = true; self::broadcastAchievement($player, $achievementId); return true; @@ -158,13 +113,40 @@ class AchievementAPI{ } return false; } - + + public static function hasAchievement(Player $player, $achievementId){ + if(!isset(self::$achievements[$achievementId]) or !isset($player->achievements)){ + $player->achievements = []; + return false; + } + + if(!isset($player->achievements[$achievementId]) or $player->achievements[$achievementId] == false){ + return false; + } + return true; + } + + public static function broadcastAchievement(Player $player, $achievementId){ + if(isset(self::$achievements[$achievementId])){ + $result = ServerAPI::request()->api->dhandle("achievement.broadcast", ["player" => $player, "achievementId" => $achievementId]); + if($result !== false and $result !== true){ + if(ServerAPI::request()->api->getProperty("announce-player-achievements") == true){ + ServerAPI::request()->api->chat->broadcast($player->username . " has just earned the achievement [" . self::$achievements[$achievementId]["name"] . "]"); + }else{ + $player->sendChat("You have just earned the achievement [" . self::$achievements[$achievementId]["name"] . "]"); + } + } + return true; + } + return false; + } + public static function removeAchievement(Player $player, $achievementId){ if(self::hasAchievement($player, $achievementId)){ $player->achievements[$achievementId] = false; } } - + public function init(){ } } diff --git a/src/API/BanAPI.php b/src/API/BanAPI.php index 0c5d6f3e..b0269dd7 100644 --- a/src/API/BanAPI.php +++ b/src/API/BanAPI.php @@ -1,93 +1,61 @@ server = ServerAPI::request(); } - + public function init(){ - $this->whitelist = new Config(DATA_PATH."white-list.txt", CONFIG_LIST);//Open whitelist list file - $this->bannedIPs = new Config(DATA_PATH."banned-ips.txt", CONFIG_LIST);//Open Banned IPs list file - $this->banned = new Config(DATA_PATH."banned.txt", CONFIG_LIST);//Open Banned Usernames list file - $this->ops = new Config(DATA_PATH."ops.txt", CONFIG_LIST);//Open list of OPs - $this->server->api->console->register("banip", " [IP|player]", array($this, "commandHandler")); - $this->server->api->console->register("ban", " [username]", array($this, "commandHandler")); - $this->server->api->console->register("kick", " [reason ...]", array($this, "commandHandler")); - $this->server->api->console->register("whitelist", " [username]", array($this, "commandHandler")); - $this->server->api->console->register("op", "", array($this, "commandHandler")); - $this->server->api->console->register("deop", "", array($this, "commandHandler")); - $this->server->api->console->register("sudo", "", array($this, "commandHandler")); + $this->whitelist = new Config(DATA_PATH . "white-list.txt", CONFIG_LIST);//Open whitelist list file + $this->bannedIPs = new Config(DATA_PATH . "banned-ips.txt", CONFIG_LIST);//Open Banned IPs list file + $this->banned = new Config(DATA_PATH . "banned.txt", CONFIG_LIST);//Open Banned Usernames list file + $this->ops = new Config(DATA_PATH . "ops.txt", CONFIG_LIST);//Open list of OPs + $this->server->api->console->register("banip", " [IP|player]", [$this, "commandHandler"]); + $this->server->api->console->register("ban", " [username]", [$this, "commandHandler"]); + $this->server->api->console->register("kick", " [reason ...]", [$this, "commandHandler"]); + $this->server->api->console->register("whitelist", " [username]", [$this, "commandHandler"]); + $this->server->api->console->register("op", "", [$this, "commandHandler"]); + $this->server->api->console->register("deop", "", [$this, "commandHandler"]); + $this->server->api->console->register("sudo", "", [$this, "commandHandler"]); $this->server->api->console->alias("ban-ip", "banip add"); $this->server->api->console->alias("banlist", "ban list"); $this->server->api->console->alias("pardon", "ban remove"); $this->server->api->console->alias("pardon-ip", "banip remove"); - $this->server->addHandler("console.command", array($this, "permissionsCheck"), 1);//Event handler when commands are issued. Used to check permissions of commands that go through the server. - $this->server->addHandler("player.block.break", array($this, "permissionsCheck"), 1);//Event handler for blocks - $this->server->addHandler("player.block.place", array($this, "permissionsCheck"), 1);//Event handler for blocks - $this->server->addHandler("player.flying", array($this, "permissionsCheck"), 1);//Flying Event + $this->server->addHandler("console.command", [$this, "permissionsCheck"], 1);//Event handler when commands are issued. Used to check permissions of commands that go through the server. + $this->server->addHandler("player.block.break", [$this, "permissionsCheck"], 1);//Event handler for blocks + $this->server->addHandler("player.block.place", [$this, "permissionsCheck"], 1);//Event handler for blocks + $this->server->addHandler("player.flying", [$this, "permissionsCheck"], 1);//Flying Event } - /** - * @param string $cmd Command to Whitelist - */ - public function cmdWhitelist($cmd){//Whitelists a CMD so everyone can issue it - Even non OPs. + /** + * @param string $cmd Command to Whitelist + */ + public function cmdWhitelist($cmd){//Whitelists a CMD so everyone can issue it - Even non OPs. $this->cmdWhitelist[strtolower(trim($cmd))] = true; } - /** - * @param string $username - * - * @return boolean - */ - public function isOp($username){//Is a player op? - $username = strtolower($username); - if($this->server->api->dhandle("op.check", $username) === true){ - return true; - }elseif($this->ops->exists($username)){ - return true; - } - return false; - } - - /** - * @param mixed $data - * @param string $event - * - * @return boolean - */ - public function permissionsCheck($data, $event){ + /** + * @param mixed $data + * @param string $event + * + * @return boolean + */ + public function permissionsCheck($data, $event){ switch($event){ case "player.flying"://OPs can fly around the server. if($this->isOp($data->iusername)){ @@ -99,7 +67,7 @@ class BanAPI{ if(!$this->isOp($data["player"]->iusername)){ $t = new Vector2($data["target"]->x, $data["target"]->z); $s = new Vector2($this->server->spawn->x, $this->server->spawn->z); - if($t->distance($s) <= $this->server->api->getProperty("spawn-protection") and $this->server->api->dhandle($event.".spawn", $data) !== true){ + if($t->distance($s) <= $this->server->api->getProperty("spawn-protection") and $this->server->api->dhandle($event . ".spawn", $data) !== true){ return false; } } @@ -109,7 +77,7 @@ class BanAPI{ if(isset($this->cmdWhitelist[$data["cmd"]])){ return; } - + if($data["issuer"] instanceof Player){ if($this->server->api->handle("console.check", $data) === true or $this->isOp($data["issuer"]->iusername)){ return; @@ -118,19 +86,41 @@ class BanAPI{ return; } return false; - break; + break; } } - /** - * @param string $cmd - * @param array $params - * @param string $issuer - * @param string $alias - * - * @return string - */ - public function commandHandler($cmd, $params, $issuer, $alias){ + /** + * @param string $username + * + * @return boolean + */ + public function isOp($username){//Is a player op? + $username = strtolower($username); + if($this->server->api->dhandle("op.check", $username) === true){ + return true; + }elseif($this->ops->exists($username)){ + return true; + } + return false; + } + + /** + * @param string $username + */ + public function ban($username){ + $this->commandHandler("ban", ["add", $username], "console", ""); + } + + /** + * @param string $cmd + * @param array $params + * @param string $issuer + * @param string $alias + * + * @return string + */ + public function commandHandler($cmd, $params, $issuer, $alias){ $output = ""; switch($cmd){ case "sudo": @@ -141,24 +131,24 @@ class BanAPI{ break; } $this->server->api->console->run(implode(" ", $params), $player); - $output .= "Command ran as ".$player->username.".\n"; + $output .= "Command ran as " . $player->username . ".\n"; break; case "op": $user = strtolower($params[0]); - if($user == NULL){ - $output .= "Usage: /op \n"; - break; + if($user == null){ + $output .= "Usage: /op \n"; + break; } $player = $this->server->api->player->get($user); if(!($player instanceof Player)){ $this->ops->set($user); $this->ops->save($user); - $output .= $user." is now op\n"; + $output .= $user . " is now op\n"; break; } $this->ops->set($player->iusername); $this->ops->save(); - $output .= $player->iusername." is now op\n"; + $output .= $player->iusername . " is now op\n"; $this->server->api->chat->sendTo(false, "You are now op.", $player->iusername); break; case "deop": @@ -167,12 +157,12 @@ class BanAPI{ if(!($player instanceof Player)){ $this->ops->remove($user); $this->ops->save(); - $output .= $user." is no longer op\n"; + $output .= $user . " is no longer op\n"; break; } $this->ops->remove($player->iusername); $this->ops->save(); - $output .= $player->iusername." is no longer op\n"; + $output .= $player->iusername . " is no longer op\n"; $this->server->api->chat->sendTo(false, "You are no longer op.", $player->iusername); break; case "kick": @@ -182,17 +172,17 @@ class BanAPI{ $name = strtolower(array_shift($params)); $player = $this->server->api->player->get($name); if($player === false){ - $output .= "Player \"".$name."\" does not exist\n"; + $output .= "Player \"" . $name . "\" does not exist\n"; }else{ $reason = implode(" ", $params); - $reason = $reason == "" ? "No reason":$reason; - - $this->server->schedule(60, array($player, "close"), "You have been kicked: ".$reason); //Forces a kick + $reason = $reason == "" ? "No reason" : $reason; + + $this->server->schedule(60, [$player, "close"], "You have been kicked: " . $reason); //Forces a kick $player->blocked = true; if($issuer instanceof Player){ - $this->server->api->chat->broadcast($player->username." has been kicked by ".$issuer->username.": $reason\n"); + $this->server->api->chat->broadcast($player->username . " has been kicked by " . $issuer->username . ": $reason\n"); }else{ - $this->server->api->chat->broadcast($player->username." has been kicked: $reason\n"); + $this->server->api->chat->broadcast($player->username . " has been kicked: $reason\n"); } } } @@ -213,10 +203,10 @@ class BanAPI{ $output .= "Player \"$user\" added to white-list\n"; break; case "reload": - $this->whitelist = new Config(DATA_PATH."white-list.txt", CONFIG_LIST); + $this->whitelist = new Config(DATA_PATH . "white-list.txt", CONFIG_LIST); break; case "list": - $output .= "White-list: ".implode(", ", $this->whitelist->getAll(true))."\n"; + $output .= "White-list: " . implode(", ", $this->whitelist->getAll(true)) . "\n"; break; case "on": case "true": @@ -258,10 +248,10 @@ class BanAPI{ $output .= "IP \"$ip\" added to ban list\n"; break; case "reload": - $this->bannedIPs = new Config(DATA_PATH."banned-ips.txt", CONFIG_LIST); + $this->bannedIPs = new Config(DATA_PATH . "banned-ips.txt", CONFIG_LIST); break; case "list": - $output .= "IP ban list: ".implode(", ", $this->bannedIPs->getAll(true))."\n"; + $output .= "IP ban list: " . implode(", ", $this->bannedIPs->getAll(true)) . "\n"; break; default: $output .= "Usage: /banip [IP|player]\n"; @@ -288,18 +278,18 @@ class BanAPI{ $player->close("You have been banned"); } if($issuer instanceof Player){ - $this->server->api->chat->broadcast($user." has been banned by ".$issuer->username."\n"); + $this->server->api->chat->broadcast($user . " has been banned by " . $issuer->username . "\n"); }else{ - $this->server->api->chat->broadcast($user." has been banned\n"); + $this->server->api->chat->broadcast($user . " has been banned\n"); } $this->kick($user, "Banned"); $output .= "Player \"$user\" added to ban list\n"; break; case "reload": - $this->banned = new Config(DATA_PATH."banned.txt", CONFIG_LIST); + $this->banned = new Config(DATA_PATH . "banned.txt", CONFIG_LIST); break; case "list": - $output .= "Ban list: ".implode(", ", $this->banned->getAll(true))."\n"; + $output .= "Ban list: " . implode(", ", $this->banned->getAll(true)) . "\n"; break; default: $output .= "Usage: /ban [username]\n"; @@ -310,69 +300,62 @@ class BanAPI{ return $output; } - /** - * @param string $username - */ - public function ban($username){ - $this->commandHandler("ban", array("add", $username), "console", ""); + /** + * @param string $username + * @param string $reason + */ + public function kick($username, $reason = "No Reason"){ + $this->commandHandler("kick", [$username, $reason], "console", ""); } - /** - * @param string $username - */ + /** + * @param string $username + */ public function pardon($username){ - $this->commandHandler("ban", array("pardon", $username), "console", ""); + $this->commandHandler("ban", ["pardon", $username], "console", ""); } - /** - * @param string $ip - */ + /** + * @param string $ip + */ public function banIP($ip){ - $this->commandHandler("banip", array("add", $ip), "console", ""); + $this->commandHandler("banip", ["add", $ip], "console", ""); } - /** - * @param string $ip - */ + /** + * @param string $ip + */ public function pardonIP($ip){ - $this->commandHandler("banip", array("pardon", $ip), "console", ""); + $this->commandHandler("banip", ["pardon", $ip], "console", ""); } - /** - * @param string $username - * @param string $reason - */ - public function kick($username, $reason = "No Reason"){ - $this->commandHandler("kick", array($username, $reason), "console", ""); - } - public function reload(){ - $this->commandHandler("ban", array("reload"), "console", ""); - $this->commandHandler("banip", array("reload"), "console", ""); - $this->commandHandler("whitelist", array("reload"), "console", ""); + $this->commandHandler("ban", ["reload"], "console", ""); + $this->commandHandler("banip", ["reload"], "console", ""); + $this->commandHandler("whitelist", ["reload"], "console", ""); } - /** - * @param string $ip - * - * @return boolean - */ - public function isIPBanned($ip){ + /** + * @param string $ip + * + * @return boolean + */ + public function isIPBanned($ip){ if($this->server->api->dhandle("api.ban.ip.check", $ip) === false){ return true; }elseif($this->bannedIPs->exists($ip, true)){ return true; }else{ return false; - } + } } - /** - * @param string $username - * - * @return boolean - */ - public function isBanned($username){ + /** + * @param string $username + * + * @return boolean + */ + public function isBanned($username){ $username = strtolower($username); if($this->server->api->dhandle("api.ban.check", $username) === false){ return true; @@ -380,15 +363,15 @@ class BanAPI{ return true; }else{ return false; - } + } } - /** - * @param string $username - * - * @return boolean - */ - public function inWhitelist($username){ + /** + * @param string $username + * + * @return boolean + */ + public function inWhitelist($username){ $username = strtolower($username); if($this->isOp($username)){ return true; @@ -397,6 +380,6 @@ class BanAPI{ }elseif($this->whitelist->exists($username, true)){ return true; } - return false; + return false; } } diff --git a/src/API/BlockAPI.php b/src/API/BlockAPI.php index f7527a47..5e18c2f4 100755 --- a/src/API/BlockAPI.php +++ b/src/API/BlockAPI.php @@ -1,233 +1,341 @@ server = ServerAPI::request(); + } + + public static function get($id, $meta = 0, $v = false){ + if(isset(Block::$class[$id])){ + $classname = Block::$class[$id]; + $b = new $classname($meta); + }else{ + $b = new GenericBlock((int) $id, $meta); + } + if($v instanceof Position){ + $b->position($v); + } + return $b; + } + + public function init(){ + $this->server->schedule(1, [$this, "blockUpdateTick"], [], true); + $this->server->api->console->register("setblock", " ", [$this, "commandHandler"]); + $this->server->api->console->register("give", " [amount]", [$this, "commandHandler"]); + } + + public function commandHandler($cmd, $args, $issuer, $alias){ + $output = ""; + switch($cmd){ + case "setblock": + if(!($issuer instanceof Player)){ + $output .= "Please run this command in-game.\n"; + break; + } + + if(count($args) < 4){ + $output .= "Usage: /setblock \n"; + break; + } + + if($args[0] == '~') + $x = round($issuer->entity->x, 0); + elseif((int) $args[0] < 255) + $x = $args[0]; + else{ + $output .= "Usage: /setblock \n"; + break; + } + + if($args[1] == '~') + $y = round($issuer->entity->y, 0); + elseif((int) $args[1] < 255) + $y = $args[1]; + else{ + $output .= "Usage: /setblock \n"; + break; + } + + if($args[2] == '~') + $z = round($issuer->entity->z, 0); + elseif((int) $args[2] < 255) + $z = $args[2]; + else{ + $output .= "Usage: /setblock \n"; + break; + } + + $pos = new Position($x, $y, $z, $issuer->entity->level); + $block = BlockAPI::fromString($args[3])->getBlock(); + if(!($block instanceof Block)){ + $output .= "Usage: /setblock \n"; + break; + }else{ + $issuer->level->setBlock($pos, $block, true, false, true); + $output .= "Placed " . $block . " in " . $x . ", " . $y . ", " . $z; + } + break; + case "give": + if(count($args) == 1 and $issuer instanceof Player){ + $item = BlockAPI::fromString($args[0]); + if(($issuer->gamemode & 0x01) === 0x01){ + $output .= "You are in creative mode.\n"; + break; + } + if($item->getID() == 0){ + $output .= "You cannot give an air block to a player.\n"; + break; + } + + if(!isset($args[1])){ + $item->count = $item->getMaxStackSize(); + }else{ + $item->count = (int) $args[1]; + } + + $issuer->addItem($item->getID(), $item->getMetadata(), $item->count); + $output .= "Giving " . $item->count . " of " . $item->getName() . " (" . $item->getID() . ":" . $item->getMetadata() . ") to " . $issuer->username . "\n"; + break; + } + + $player = $this->server->api->player->get($args[0]); + $item = BlockAPI::fromString($args[1]); + + if(!isset($args[2])){ + $item->count = $item->getMaxStackSize(); + }else{ + $item->count = (int) $args[2]; + } + + if($player instanceof Player){ + if(($player->gamemode & 0x01) === 0x01){ + $output .= "Player is in creative mode.\n"; + break; + } + if($item->getID() == 0){ + $output .= "You cannot give an air block to a player.\n"; + break; + } + $player->addItem($item->getID(), $item->getMetadata(), $item->count); + $output .= "Giving " . $item->count . " of " . $item->getName() . " (" . $item->getID() . ":" . $item->getMetadata() . ") to " . $player->username . "\n"; + }else{ + $output .= "Unknown player.\n"; + } + + break; + } + return $output; + } + public static function fromString($str, $multiple = false){ if($multiple === true){ - $blocks = array(); - foreach(explode(",",$str) as $b){ + $blocks = []; + foreach(explode(",", $str) as $b){ $blocks[] = BlockAPI::fromString($b, false); } return $blocks; @@ -238,7 +346,7 @@ class BlockAPI{ }else{ $meta = ((int) $b[1]) & 0xFFFF; } - + if(defined(strtoupper($b[0]))){ $explodedString = explode(":", constant(strtoupper($b[0]))); if(count($explodedString) == 2){ @@ -255,19 +363,6 @@ class BlockAPI{ } } - public static function get($id, $meta = 0, $v = false){ - if(isset(Block::$class[$id])){ - $classname = Block::$class[$id]; - $b = new $classname($meta); - }else{ - $b = new GenericBlock((int) $id, $meta); - } - if($v instanceof Position){ - $b->position($v); - } - return $b; - } - public static function getItem($id, $meta = 0, $count = 1){ $id = (int) $id; if(isset(Item::$class[$id])){ @@ -278,114 +373,44 @@ class BlockAPI{ } return $i; } - - function __construct(){ - $this->server = ServerAPI::request(); - } - public function init(){ - $this->server->schedule(1, array($this, "blockUpdateTick"), array(), true); - $this->server->api->console->register("setblock", " ", array($this, "commandHandler")); - $this->server->api->console->register("give", " [amount]", array($this, "commandHandler")); - } + public function playerBlockBreak(Player $player, Vector3 $vector){ - public function commandHandler($cmd, $args, $issuer, $alias){ - $output = ""; - switch($cmd){ - case "setblock": - if(!($issuer instanceof Player)){ - $output .= "Please run this command in-game.\n"; - break; - } - - if(count($args) < 4){ - $output .= "Usage: /setblock \n"; - break; - } - - if($args[0] == '~') $x = round($issuer->entity->x, 0); - elseif((int)$args[0] < 255) $x = $args[0]; - else{ - $output .= "Usage: /setblock \n"; - break; - } - - if($args[1] == '~') $y = round($issuer->entity->y, 0); - elseif((int)$args[1] < 255) $y = $args[1]; - else{ - $output .= "Usage: /setblock \n"; - break; - } - - if($args[2] == '~') $z = round($issuer->entity->z, 0); - elseif((int)$args[2] < 255) $z = $args[2]; - else{ - $output .= "Usage: /setblock \n"; - break; - } - - $pos = new Position($x, $y, $z, $issuer->entity->level); - $block = BlockAPI::fromString($args[3])->getBlock(); - if(!($block instanceof Block)){ - $output .= "Usage: /setblock \n"; - break; - } - else{ - $issuer->level->setBlock($pos, $block, true, false, true); - $output .= "Placed ".$block." in ".$x.", ".$y.", ".$z; - } - break; - case "give": - if(count($args) == 1 and $issuer instanceof Player){ - $item = BlockAPI::fromString($args[0]); - if(($issuer->gamemode & 0x01) === 0x01){ - $output .= "You are in creative mode.\n"; - break; - } - if($item->getID() == 0){ - $output .= "You cannot give an air block to a player.\n"; - break; - } - - if(!isset($args[1])){ - $item->count = $item->getMaxStackSize(); - } - else{ - $item->count = (int)$args[1]; - } - - $issuer->addItem($item->getID(), $item->getMetadata(), $item->count); - $output .= "Giving ".$item->count." of ".$item->getName()." (".$item->getID().":".$item->getMetadata().") to ".$issuer->username."\n"; - break; - } - - $player = $this->server->api->player->get($args[0]); - $item = BlockAPI::fromString($args[1]); - - if(!isset($args[2])){ - $item->count = $item->getMaxStackSize(); - }else{ - $item->count = (int) $args[2]; - } + $target = $player->level->getBlock($vector); + $item = $player->getSlot($player->slot); - if($player instanceof Player){ - if(($player->gamemode & 0x01) === 0x01){ - $output .= "Player is in creative mode.\n"; - break; - } - if($item->getID() == 0) { - $output .= "You cannot give an air block to a player.\n"; - break; - } - $player->addItem($item->getID(), $item->getMetadata(), $item->count); - $output .= "Giving ".$item->count." of ".$item->getName()." (".$item->getID().":".$item->getMetadata().") to ".$player->username."\n"; - }else{ - $output .= "Unknown player.\n"; - } - - break; + if($this->server->api->dhandle("player.block.touch", ["type" => "break", "player" => $player, "target" => $target, "item" => $item]) === false){ + if($this->server->api->dhandle("player.block.break.bypass", ["player" => $player, "target" => $target, "item" => $item]) !== true){ + return $this->cancelAction($target, $player, false); + } } - return $output; + + if((!$target->isBreakable($item, $player) and $this->server->api->dhandle("player.block.break.invalid", ["player" => $player, "target" => $target, "item" => $item]) !== true) or ($player->gamemode & 0x02) === 0x02 or (($player->lastBreak - $player->getLag() / 1000) + $target->getBreakTime($item, $player) - 0.2) >= microtime(true)){ + if($this->server->api->dhandle("player.block.break.bypass", ["player" => $player, "target" => $target, "item" => $item]) !== true){ + return $this->cancelAction($target, $player, false); + } + } + $player->lastBreak = microtime(true); + + if($this->server->api->dhandle("player.block.break", ["player" => $player, "target" => $target, "item" => $item]) !== false){ + $drops = $target->getDrops($item, $player); + if($target->onBreak($item, $player) === false){ + return $this->cancelAction($target, $player, false); + } + if(($player->gamemode & 0x01) === 0 and $item->useOn($target) and $item->getMetadata() >= $item->getMaxDurability()){ + $player->setSlot($player->slot, new Item(AIR, 0, 0), false); + } + }else{ + return $this->cancelAction($target, $player, false); + } + + + if(($player->gamemode & 0x01) === 0x00 and count($drops) > 0){ + foreach($drops as $drop){ + $this->server->api->entity->drop(new Position($target->x + 0.5, $target->y, $target->z + 0.5, $target->level), BlockAPI::getItem($drop[0] & 0xFFFF, $drop[1] & 0xFFFF, $drop[2])); + } + } + return false; } private function cancelAction(Block $block, Player $player, $send = true){ @@ -402,76 +427,37 @@ class BlockAPI{ return false; } - public function playerBlockBreak(Player $player, Vector3 $vector){ - - $target = $player->level->getBlock($vector); - $item = $player->getSlot($player->slot); - - if($this->server->api->dhandle("player.block.touch", array("type" => "break", "player" => $player, "target" => $target, "item" => $item)) === false){ - if($this->server->api->dhandle("player.block.break.bypass", array("player" => $player, "target" => $target, "item" => $item)) !== true){ - return $this->cancelAction($target, $player, false); - } - } - - if((!$target->isBreakable($item, $player) and $this->server->api->dhandle("player.block.break.invalid", array("player" => $player, "target" => $target, "item" => $item)) !== true) or ($player->gamemode & 0x02) === 0x02 or (($player->lastBreak - $player->getLag() / 1000) + $target->getBreakTime($item, $player) - 0.2) >= microtime(true)){ - if($this->server->api->dhandle("player.block.break.bypass", array("player" => $player, "target" => $target, "item" => $item)) !== true){ - return $this->cancelAction($target, $player, false); - } - } - $player->lastBreak = microtime(true); - - if($this->server->api->dhandle("player.block.break", array("player" => $player, "target" => $target, "item" => $item)) !== false){ - $drops = $target->getDrops($item, $player); - if($target->onBreak($item, $player) === false){ - return $this->cancelAction($target, $player, false); - } - if(($player->gamemode & 0x01) === 0 and $item->useOn($target) and $item->getMetadata() >= $item->getMaxDurability()){ - $player->setSlot($player->slot, new Item(AIR, 0, 0), false); - } - }else{ - return $this->cancelAction($target, $player, false); - } - - - if(($player->gamemode & 0x01) === 0x00 and count($drops) > 0){ - foreach($drops as $drop){ - $this->server->api->entity->drop(new Position($target->x + 0.5, $target->y, $target->z + 0.5, $target->level), BlockAPI::getItem($drop[0] & 0xFFFF, $drop[1] & 0xFFFF, $drop[2])); - } - } - return false; - } - public function playerBlockAction(Player $player, Vector3 $vector, $face, $fx, $fy, $fz){ if($face < 0 or $face > 5){ return false; } - $target = $player->level->getBlock($vector); + $target = $player->level->getBlock($vector); $block = $target->getSide($face); $item = $player->getSlot($player->slot); - - if($target->getID() === AIR and $this->server->api->dhandle("player.block.place.invalid", array("player" => $player, "block" => $block, "target" => $target, "item" => $item)) !== true){ //If no block exists or not allowed in CREATIVE - if($this->server->api->dhandle("player.block.place.bypass", array("player" => $player, "block" => $block, "target" => $target, "item" => $item)) !== true){ + + if($target->getID() === AIR and $this->server->api->dhandle("player.block.place.invalid", ["player" => $player, "block" => $block, "target" => $target, "item" => $item]) !== true){ //If no block exists or not allowed in CREATIVE + if($this->server->api->dhandle("player.block.place.bypass", ["player" => $player, "block" => $block, "target" => $target, "item" => $item]) !== true){ $this->cancelAction($target, $player); return $this->cancelAction($block, $player); } } - - if($this->server->api->dhandle("player.block.touch", array("type" => "place", "player" => $player, "block" => $block, "target" => $target, "item" => $item)) === false){ - if($this->server->api->dhandle("player.block.place.bypass", array("player" => $player, "block" => $block, "target" => $target, "item" => $item)) !== true){ + + if($this->server->api->dhandle("player.block.touch", ["type" => "place", "player" => $player, "block" => $block, "target" => $target, "item" => $item]) === false){ + if($this->server->api->dhandle("player.block.place.bypass", ["player" => $player, "block" => $block, "target" => $target, "item" => $item]) !== true){ return $this->cancelAction($block, $player); } } $this->blockUpdate($target, BLOCK_UPDATE_TOUCH); if($target->isActivable === true){ - if($this->server->api->dhandle("player.block.activate", array("player" => $player, "block" => $block, "target" => $target, "item" => $item)) !== false and $target->onActivate($item, $player) === true){ + if($this->server->api->dhandle("player.block.activate", ["player" => $player, "block" => $block, "target" => $target, "item" => $item]) !== false and $target->onActivate($item, $player) === true){ return false; } } - + if(($player->gamemode & 0x02) === 0x02){ //Adventure mode!! - if($this->server->api->dhandle("player.block.place.bypass", array("player" => $player, "block" => $block, "target" => $target, "item" => $item)) !== true){ + if($this->server->api->dhandle("player.block.place.bypass", ["player" => $player, "block" => $block, "target" => $target, "item" => $item]) !== true){ return $this->cancelAction($block, $player, false); } } @@ -479,7 +465,7 @@ class BlockAPI{ if($block->y > 127 or $block->y < 0){ return false; } - + if($item->isActivable === true and $item->onActivate($player->level, $player, $block, $target, $face, $fx, $fy, $fz) === true){ if($item->count <= 0){ $player->setSlot($player->slot, BlockAPI::getItem(AIR, 0, 0), false); @@ -496,22 +482,22 @@ class BlockAPI{ }else{ return $this->cancelAction($block, $player, false); } - + if(!($block->isReplaceable === true or ($hand->getID() === SLAB and $block->getID() === SLAB))){ return $this->cancelAction($block, $player, false); } - + if($target->isReplaceable === true){ $block = $target; - $hand->position($block); + $hand->position($block); //$face = -1; } - + if($hand->isSolid === true and $player->entity->inBlock($block)){ return $this->cancelAction($block, $player, false); //Entity in block } - - if($this->server->api->dhandle("player.block.place", array("player" => $player, "block" => $block, "target" => $target, "item" => $item)) === false){ + + if($this->server->api->dhandle("player.block.place", ["player" => $player, "block" => $block, "target" => $target, "item" => $item]) === false){ return $this->cancelAction($block, $player); }elseif($hand->place($item, $player, $block, $target, $face, $fx, $fy, $fz) === false){ return $this->cancelAction($block, $player, false); @@ -531,7 +517,28 @@ class BlockAPI{ return false; } - public function blockUpdateAround(Position $pos, $type = BLOCK_UPDATE_NORMAL, $delay = false){ + public function blockUpdate(Position $pos, $type = BLOCK_UPDATE_NORMAL){ + if(!($pos instanceof Block)){ + $block = $pos->level->getBlock($pos); + }else{ + $pos = new Position($pos->x, $pos->y, $pos->z, $pos->level); + $block = $pos->level->getBlock($pos); + } + if($block === false){ + return false; + } + + $level = $block->onUpdate($type); + if($level === BLOCK_UPDATE_NORMAL){ + $this->blockUpdateAround($block, $level); + $this->server->api->entity->updateRadius($pos, 1); + }elseif($level === BLOCK_UPDATE_RANDOM){ + $this->nextRandomUpdate($pos); + } + return $level; + } + + public function blockUpdateAround(Position $pos, $type = BLOCK_UPDATE_NORMAL, $delay = false){ if($delay !== false){ $this->scheduleBlockUpdate($pos->getSide(0), $delay, $type); $this->scheduleBlockUpdate($pos->getSide(1), $delay, $type); @@ -548,46 +555,25 @@ class BlockAPI{ $this->blockUpdate($pos->getSide(5), $type); } } - - public function blockUpdate(Position $pos, $type = BLOCK_UPDATE_NORMAL){ - if(!($pos instanceof Block)){ - $block = $pos->level->getBlock($pos); - }else{ - $pos = new Position($pos->x, $pos->y, $pos->z, $pos->level); - $block = $pos->level->getBlock($pos); - } - if($block === false){ - return false; - } - - $level = $block->onUpdate($type); - if($level === BLOCK_UPDATE_NORMAL){ - $this->blockUpdateAround($block, $level); - $this->server->api->entity->updateRadius($pos, 1); - }elseif($level === BLOCK_UPDATE_RANDOM){ - $this->nextRandomUpdate($pos); - } - return $level; - } - + public function scheduleBlockUpdate(Position $pos, $delay, $type = BLOCK_UPDATE_SCHEDULED){ $type = (int) $type; if($delay < 0){ return false; } - $index = $pos->x.".".$pos->y.".".$pos->z.".".$pos->level->getName().".".$type; - $delay = microtime(true) + $delay * 0.05; + $index = $pos->x . "." . $pos->y . "." . $pos->z . "." . $pos->level->getName() . "." . $type; + $delay = microtime(true) + $delay * 0.05; if(!isset($this->scheduledUpdates[$index])){ $this->scheduledUpdates[$index] = $pos; - $this->server->query("INSERT INTO blockUpdates (x, y, z, level, type, delay) VALUES (".$pos->x.", ".$pos->y.", ".$pos->z.", '".$pos->level->getName()."', ".$type.", ".$delay.");"); + $this->server->query("INSERT INTO blockUpdates (x, y, z, level, type, delay) VALUES (" . $pos->x . ", " . $pos->y . ", " . $pos->z . ", '" . $pos->level->getName() . "', " . $type . ", " . $delay . ");"); return true; } return false; } - + public function nextRandomUpdate(Position $pos){ - if(!isset($this->scheduledUpdates[$pos->x.".".$pos->y.".".$pos->z.".".$pos->level->getName().".".BLOCK_UPDATE_RANDOM])){ + if(!isset($this->scheduledUpdates[$pos->x . "." . $pos->y . "." . $pos->z . "." . $pos->level->getName() . "." . BLOCK_UPDATE_RANDOM])){ $X = (($pos->x >> 4) << 4); $Y = (($pos->y >> 4) << 4); $Z = (($pos->z >> 4) << 4); @@ -596,7 +582,7 @@ class BlockAPI{ $offset = 0; while(true){ $t = $offset + Utils::getRandomUpdateTicks() * 0.05; - $update = $this->server->query("SELECT COUNT(*) FROM blockUpdates WHERE level = '".$pos->level->getName()."' AND type = ".BLOCK_UPDATE_RANDOM." AND delay >= ".($time + $t - 1)." AND delay <= ".($time + $t + 1).";"); + $update = $this->server->query("SELECT COUNT(*) FROM blockUpdates WHERE level = '" . $pos->level->getName() . "' AND type = " . BLOCK_UPDATE_RANDOM . " AND delay >= " . ($time + $t - 1) . " AND delay <= " . ($time + $t + 1) . ";"); if($update instanceof SQLite3Result){ $update = $update->fetchArray(SQLITE3_NUM); if($update[0] < 3){ @@ -610,21 +596,21 @@ class BlockAPI{ $this->scheduleBlockUpdate($pos, $t / 0.05, BLOCK_UPDATE_RANDOM); } } - + public function blockUpdateTick(){ $time = microtime(true); if(count($this->scheduledUpdates) > 0){ - $update = $this->server->query("SELECT x,y,z,level,type FROM blockUpdates WHERE delay <= ".$time.";"); + $update = $this->server->query("SELECT x,y,z,level,type FROM blockUpdates WHERE delay <= " . $time . ";"); if($update instanceof SQLite3Result){ - $upp = array(); + $upp = []; while(($up = $update->fetchArray(SQLITE3_ASSOC)) !== false){ - $index = $up["x"].".".$up["y"].".".$up["z"].".".$up["level"].".".$up["type"]; + $index = $up["x"] . "." . $up["y"] . "." . $up["z"] . "." . $up["level"] . "." . $up["type"]; if(isset($this->scheduledUpdates[$index])){ - $upp[] = array((int) $up["type"], $this->scheduledUpdates[$index]); + $upp[] = [(int) $up["type"], $this->scheduledUpdates[$index]]; unset($this->scheduledUpdates[$index]); } } - $this->server->query("DELETE FROM blockUpdates WHERE delay <= ".$time.";"); + $this->server->query("DELETE FROM blockUpdates WHERE delay <= " . $time . ";"); foreach($upp as $b){ $this->blockUpdate($b[1], $b[0]); } diff --git a/src/API/ChatAPI.php b/src/API/ChatAPI.php index 3589361f..789f90a3 100644 --- a/src/API/ChatAPI.php +++ b/src/API/ChatAPI.php @@ -1,48 +1,31 @@ server = ServerAPI::request(); } - + public function init(){ - $this->server->api->console->register("tell", " ", array($this, "commandHandler")); - $this->server->api->console->register("me", "", array($this, "commandHandler")); - $this->server->api->console->register("say", "", array($this, "commandHandler")); + $this->server->api->console->register("tell", " ", [$this, "commandHandler"]); + $this->server->api->console->register("me", "", [$this, "commandHandler"]); + $this->server->api->console->register("say", "", [$this, "commandHandler"]); $this->server->api->ban->cmdWhitelist("tell"); $this->server->api->ban->cmdWhitelist("me"); $this->server->api->console->alias("msg", "tell"); } - /** - * @param string $cmd - * @param array $params - * @param string $issuer - * @param string $alias - * - * @return string - */ - public function commandHandler($cmd, $params, $issuer, $alias){ + /** + * @param string $cmd + * @param array $params + * @param string $issuer + * @param string $alias + * + * @return string + */ + public function commandHandler($cmd, $params, $issuer, $alias){ $output = ""; switch($cmd){ case "say": @@ -51,8 +34,8 @@ class ChatAPI{ $output .= "Usage: /say \n"; break; } - $sender = ($issuer instanceof Player) ? "Server":ucfirst($issuer); - $this->server->api->chat->broadcast("[$sender] ".$s); + $sender = ($issuer instanceof Player) ? "Server" : ucfirst($issuer); + $this->server->api->chat->broadcast("[$sender] " . $s); break; case "me": $s = implode(" ", $params); @@ -69,7 +52,7 @@ class ChatAPI{ }else{ $sender = $issuer->username; } - $this->broadcast("* $sender ".implode(" ", $params)); + $this->broadcast("* $sender " . implode(" ", $params)); break; case "tell": if(!isset($params[0]) or !isset($params[1])){ @@ -92,54 +75,45 @@ class ChatAPI{ } } $mes = implode(" ", $params); - $output .= "You're whispering to ".$target.": ".$mes."\n"; + $output .= "You're whispering to " . $target . ": " . $mes . "\n"; if($target !== "Console" and $target !== "Rcon"){ - $this->sendTo(false, $sender." whispers to you: ".$mes, $target); + $this->sendTo(false, $sender . " whispers to you: " . $mes, $target); } if($target === "Console" or $sender === "Console"){ - console("[INFO] ".$sender." whispers to ".$target.": ".$mes); + console("[INFO] " . $sender . " whispers to " . $target . ": " . $mes); } break; } return $output; } - /** - * @param string $message - */ - public function broadcast($message){ + /** + * @param string $message + */ + public function broadcast($message){ $this->send(false, $message); $this->server->send2Discord($message); } - /** - * @param string $owner - * @param string $text - * @param mixed $player Can be either Player object or string username. Boolean false for broadcast. - */ - public function sendTo($owner, $text, $player){ - $this->send($owner, $text, array($player)); - } - - /** - * @param mixed $owner Can be either Player object or string username. Boolean false for broadcast. - * @param string $text - * @param $whitelist - * @param $blacklist - */ - public function send($owner, $text, $whitelist = false, $blacklist = false){ - $message = array( + /** + * @param mixed $owner Can be either Player object or string username. Boolean false for broadcast. + * @param string $text + * @param $whitelist + * @param $blacklist + */ + public function send($owner, $text, $whitelist = false, $blacklist = false){ + $message = [ "player" => $owner, "message" => $text, - ); + ]; if($owner !== false){ if($owner instanceof Player){ if($whitelist === false){ - console("[INFO] <".$owner->username."> ".$text); + console("[INFO] <" . $owner->username . "> " . $text); } }else{ if($whitelist === false){ - console("[INFO] <".$owner."> ".$text); + console("[INFO] <" . $owner . "> " . $text); } } }else{ @@ -151,4 +125,13 @@ class ChatAPI{ $container = new Container($message, $whitelist, $blacklist); $this->server->handle("server.chat", $container); } + + /** + * @param string $owner + * @param string $text + * @param mixed $player Can be either Player object or string username. Boolean false for broadcast. + */ + public function sendTo($owner, $text, $player){ + $this->send($owner, $text, [$player]); + } } diff --git a/src/API/ConsoleAPI.php b/src/API/ConsoleAPI.php index 5e83ffb9..19dc0079 100644 --- a/src/API/ConsoleAPI.php +++ b/src/API/ConsoleAPI.php @@ -1,48 +1,41 @@ help = array(); - $this->cmds = array(); - $this->alias = array(); + $this->help = []; + $this->cmds = []; + $this->alias = []; $this->server = ServerAPI::request(); $this->last = microtime(true); } public function init(){ - $this->server->schedule(2, array($this, "handle"), array(), true); + $this->server->schedule(2, [$this, "handle"], [], true); if(!defined("NO_THREADS")){ $this->loop = new ConsoleLoop(); } - $this->register("help", "[page|command name]", array($this, "defaultCommands")); - $this->register("status", "", array($this, "defaultCommands")); - $this->register("difficulty", "<0|1|2|3>", array($this, "defaultCommands")); - $this->register("stop", "", array($this, "defaultCommands")); - $this->register("defaultgamemode", "", array($this, "defaultCommands")); + $this->register("help", "[page|command name]", [$this, "defaultCommands"]); + $this->register("status", "", [$this, "defaultCommands"]); + $this->register("difficulty", "<0|1|2|3>", [$this, "defaultCommands"]); + $this->register("stop", "", [$this, "defaultCommands"]); + $this->register("defaultgamemode", "", [$this, "defaultCommands"]); $this->server->api->ban->cmdWhitelist("help"); $this->server->api->ban->cmdWhitelist("status"); } + public function register($cmd, $help, $callback){ + if(!is_callable($callback)){ + return false; + } + $cmd = strtolower(trim($cmd)); + $this->cmds[$cmd] = $callback; + $this->help[$cmd] = $help; + ksort($this->help, SORT_NATURAL | SORT_FLAG_CASE); + } + function __destruct(){ $this->server->deleteEvent($this->event); if(!defined("NO_THREADS")){ @@ -55,216 +48,11 @@ class ConsoleAPI{ } } - public function defaultCommands($cmd, $params, $issuer, $alias){ - $output = ""; - switch($cmd){ - case "defaultgamemode": - $gms = array( - "0" => SURVIVAL, - "survival" => SURVIVAL, - "s" => SURVIVAL, - "1" => CREATIVE, - "creative" => CREATIVE, - "c" => CREATIVE, - "2" => ADVENTURE, - "adventure" => ADVENTURE, - "a" => ADVENTURE, - "3" => VIEW, - "view" => VIEW, - "viewer" => VIEW, - "spectator" => VIEW, - "v" => VIEW, - ); - if(!isset($gms[strtolower($params[0])])){ - $output .= "Usage: /$cmd \n"; - break; - } - $this->server->api->setProperty("gamemode", $gms[strtolower($params[0])]); - $output .= "Default Gamemode is now ".strtoupper($this->server->getGamemode()).".\n"; - break; - case "status": - if(!($issuer instanceof Player) and $issuer === "console"){ - $this->server->debugInfo(true); - } - $info = $this->server->debugInfo(); - $output .= "TPS: ".$info["tps"].", Memory usage: ".$info["memory_usage"]." (Peak ".$info["memory_peak_usage"].")\n"; - break; - case "update-done": - $this->server->api->setProperty("last-update", time()); - break; - case "stop": - $this->loop->stop = true; - $output .= "Stopping the server\n"; - $this->server->close(); - break; - case "difficulty": - $s = trim(array_shift($params)); - if($s === "" or (((int) $s) > 3 and ((int) $s) < 0)){ - $output .= "Usage: /difficulty <0|1|2|3>\n"; - break; - } - $this->server->api->setProperty("difficulty", (int) $s); - $output .= "Difficulty changed to ".$this->server->difficulty."\n"; - break; - case "?": - if($issuer !== "console" and $issuer !== "rcon"){ - break; - } - case "help": - if(isset($params[0]) and !is_numeric($params[0])){ - $c = trim(strtolower($params[0])); - if(isset($this->help[$c]) or isset($this->alias[$c])){ - $c = isset($this->help[$c]) ? $c : $this->alias[$c]; - if($this->server->api->dhandle("console.command.".$c, array("cmd" => $c, "parameters" => array(), "issuer" => $issuer, "alias" => false)) === false or $this->server->api->dhandle("console.command", array("cmd" => $c, "parameters" => array(), "issuer" => $issuer, "alias" => false)) === false){ - break; - } - $output .= "Usage: /$c ".$this->help[$c]."\n"; - break; - } - } - $cmds = array(); - foreach($this->help as $c => $h){ - if($this->server->api->dhandle("console.command.".$c, array("cmd" => $c, "parameters" => array(), "issuer" => $issuer, "alias" => false)) === false or $this->server->api->dhandle("console.command", array("cmd" => $c, "parameters" => array(), "issuer" => $issuer, "alias" => false)) === false){ - continue; - } - $cmds[$c] = $h; - } - - $max = ceil(count($cmds) / 5); - $page = (int) (isset($params[0]) ? min($max, max(1, intval($params[0]))):1); - $output .= FORMAT_RED."-".FORMAT_RESET." Showing help page $page of $max (/help ) ".FORMAT_RED."-".FORMAT_RESET."\n"; - $current = 1; - foreach($cmds as $c => $h){ - $curpage = (int) ceil($current / 5); - if($curpage === $page){ - $output .= "/$c ".$h."\n"; - }elseif($curpage > $page){ - break; - } - ++$current; - } - break; - default: - $output .= "Command doesn't exist! Use /help\n"; - break; - } - return $output; - } - public function alias($alias, $cmd){ $this->alias[strtolower(trim($alias))] = trim($cmd); return true; } - public function register($cmd, $help, $callback){ - if(!is_callable($callback)){ - return false; - } - $cmd = strtolower(trim($cmd)); - $this->cmds[$cmd] = $callback; - $this->help[$cmd] = $help; - ksort($this->help, SORT_NATURAL | SORT_FLAG_CASE); - } - - public function run($line = "", $issuer = "console", $alias = false){ - if($line != ""){ - $output = ""; - $end = strpos($line, " "); - if($end === false){ - $end = strlen($line); - } - $cmd = strtolower(substr($line, 0, $end)); - $params = (string) substr($line, $end + 1); - if(isset($this->alias[$cmd])){ - return $this->run($this->alias[$cmd] . ($params !== "" ? " " .$params:""), $issuer, $cmd); - } - - if(preg_match_all('#@([@a-z]{1,})#', $params, $matches, PREG_OFFSET_CAPTURE) > 0){ - $offsetshift = 0; - foreach($matches[1] as $selector){ - if($selector[0][0] === "@"){ //Escape! - $params = substr_replace($params, $selector[0], $selector[1] + $offsetshift - 1, strlen($selector[0]) + 1); - --$offsetshift; - continue; - } - switch(strtolower($selector[0])){ - case "u": - case "player": - case "username": - $p = ($issuer instanceof Player) ? $issuer->username:$issuer; - $params = substr_replace($params, $p, $selector[1] + $offsetshift - 1, strlen($selector[0]) + 1); - $offsetshift -= strlen($selector[0]) - strlen($p) + 1; - break; - case "w": - case "world": - $p = ($issuer instanceof Player) ? $issuer->level->getName():$this->server->api->level->getDefault()->getName(); - $params = substr_replace($params, $p, $selector[1] + $offsetshift - 1, strlen($selector[0]) + 1); - $offsetshift -= strlen($selector[0]) - strlen($p) + 1; - break; - case "a": - case "all": - if($issuer instanceof Player){ - if($this->server->api->ban->isOp($issuer->username)){ - $output = ""; - foreach($this->server->api->player->getAll() as $p){ - $output .= $this->run($cmd . " ". substr_replace($params, $p->username, $selector[1] + $offsetshift - 1, strlen($selector[0]) + 1), $issuer, $alias); - } - }else{ - $issuer->sendChat("You don't have permissions to use this command.\n"); - } - }else{ - $output = ""; - foreach($this->server->api->player->getAll() as $p){ - $output .= $this->run($cmd . " ". substr_replace($params, $p->username, $selector[1] + $offsetshift - 1, strlen($selector[0]) + 1), $issuer, $alias); - } - } - return $output; - case "r": - case "random": - $l = array(); - foreach($this->server->api->player->getAll() as $p){ - if($p !== $issuer){ - $l[] = $p; - } - } - if(count($l) === 0){ - return; - } - - $p = $l[mt_rand(0, count($l) - 1)]->username; - $params = substr_replace($params, $p, $selector[1] + $offsetshift - 1, strlen($selector[0]) + 1); - $offsetshift -= strlen($selector[0]) - strlen($p) + 1; - break; - } - } - } - $params = explode(" ", $params); - if(count($params) === 1 and $params[0] === ""){ - $params = array(); - } - - if(($d1 = $this->server->api->dhandle("console.command.".$cmd, array("cmd" => $cmd, "parameters" => $params, "issuer" => $issuer, "alias" => $alias))) === false - or ($d2 = $this->server->api->dhandle("console.command", array("cmd" => $cmd, "parameters" => $params, "issuer" => $issuer, "alias" => $alias))) === false){ - if(in_array(strtolower($cmd), array_keys($this->cmds))){ - $output = "You don't have permissions to use this command.\n"; - }else{ - $output = "Command doesn't exist! Use /help\n"; - } - }elseif($d1 !== true and (!isset($d2) or $d2 !== true)){ - if(isset($this->cmds[$cmd]) and is_callable($this->cmds[$cmd])){ - $output = @call_user_func($this->cmds[$cmd], $cmd, $params, $issuer, $alias); - }elseif($this->server->api->dhandle("console.command.unknown", array("cmd" => $cmd, "params" => $params, "issuer" => $issuer, "alias" => $alias)) !== false){ - $output = $this->defaultCommands($cmd, $params, $issuer, $alias); - } - } - - if($output != "" and ($issuer instanceof Player)){ - $issuer->sendChat(trim($output)); - } - return $output; - } - } - public function handle($time){ if(defined("NO_THREADS")){ return; @@ -276,7 +64,7 @@ class ConsoleAPI{ if($output != ""){ $mes = explode("\n", trim($output)); foreach($mes as $m){ - console("[CMD] ".$m); + console("[CMD] " . $m); } } }else{ @@ -284,14 +72,211 @@ class ConsoleAPI{ } } + public function run($line = "", $issuer = "console", $alias = false){ + if($line != ""){ + $output = ""; + $end = strpos($line, " "); + if($end === false){ + $end = strlen($line); + } + $cmd = strtolower(substr($line, 0, $end)); + $params = (string) substr($line, $end + 1); + if(isset($this->alias[$cmd])){ + return $this->run($this->alias[$cmd] . ($params !== "" ? " " . $params : ""), $issuer, $cmd); + } + + if(preg_match_all('#@([@a-z]{1,})#', $params, $matches, PREG_OFFSET_CAPTURE) > 0){ + $offsetshift = 0; + foreach($matches[1] as $selector){ + if($selector[0][0] === "@"){ //Escape! + $params = substr_replace($params, $selector[0], $selector[1] + $offsetshift - 1, strlen($selector[0]) + 1); + --$offsetshift; + continue; + } + switch(strtolower($selector[0])){ + case "u": + case "player": + case "username": + $p = ($issuer instanceof Player) ? $issuer->username : $issuer; + $params = substr_replace($params, $p, $selector[1] + $offsetshift - 1, strlen($selector[0]) + 1); + $offsetshift -= strlen($selector[0]) - strlen($p) + 1; + break; + case "w": + case "world": + $p = ($issuer instanceof Player) ? $issuer->level->getName() : $this->server->api->level->getDefault()->getName(); + $params = substr_replace($params, $p, $selector[1] + $offsetshift - 1, strlen($selector[0]) + 1); + $offsetshift -= strlen($selector[0]) - strlen($p) + 1; + break; + case "a": + case "all": + if($issuer instanceof Player){ + if($this->server->api->ban->isOp($issuer->username)){ + $output = ""; + foreach($this->server->api->player->getAll() as $p){ + $output .= $this->run($cmd . " " . substr_replace($params, $p->username, $selector[1] + $offsetshift - 1, strlen($selector[0]) + 1), $issuer, $alias); + } + }else{ + $issuer->sendChat("You don't have permissions to use this command.\n"); + } + }else{ + $output = ""; + foreach($this->server->api->player->getAll() as $p){ + $output .= $this->run($cmd . " " . substr_replace($params, $p->username, $selector[1] + $offsetshift - 1, strlen($selector[0]) + 1), $issuer, $alias); + } + } + return $output; + case "r": + case "random": + $l = []; + foreach($this->server->api->player->getAll() as $p){ + if($p !== $issuer){ + $l[] = $p; + } + } + if(count($l) === 0){ + return; + } + + $p = $l[mt_rand(0, count($l) - 1)]->username; + $params = substr_replace($params, $p, $selector[1] + $offsetshift - 1, strlen($selector[0]) + 1); + $offsetshift -= strlen($selector[0]) - strlen($p) + 1; + break; + } + } + } + $params = explode(" ", $params); + if(count($params) === 1 and $params[0] === ""){ + $params = []; + } + + if(($d1 = $this->server->api->dhandle("console.command." . $cmd, ["cmd" => $cmd, "parameters" => $params, "issuer" => $issuer, "alias" => $alias])) === false + or ($d2 = $this->server->api->dhandle("console.command", ["cmd" => $cmd, "parameters" => $params, "issuer" => $issuer, "alias" => $alias])) === false){ + if(in_array(strtolower($cmd), array_keys($this->cmds))){ + $output = "You don't have permissions to use this command.\n"; + }else{ + $output = "Command doesn't exist! Use /help\n"; + } + }elseif($d1 !== true and (!isset($d2) or $d2 !== true)){ + if(isset($this->cmds[$cmd]) and is_callable($this->cmds[$cmd])){ + $output = @call_user_func($this->cmds[$cmd], $cmd, $params, $issuer, $alias); + }elseif($this->server->api->dhandle("console.command.unknown", ["cmd" => $cmd, "params" => $params, "issuer" => $issuer, "alias" => $alias]) !== false){ + $output = $this->defaultCommands($cmd, $params, $issuer, $alias); + } + } + + if($output != "" and ($issuer instanceof Player)){ + $issuer->sendChat(trim($output)); + } + return $output; + } + } + + public function defaultCommands($cmd, $params, $issuer, $alias){ + $output = ""; + switch($cmd){ + case "defaultgamemode": + $gms = [ + "0" => SURVIVAL, + "survival" => SURVIVAL, + "s" => SURVIVAL, + "1" => CREATIVE, + "creative" => CREATIVE, + "c" => CREATIVE, + "2" => ADVENTURE, + "adventure" => ADVENTURE, + "a" => ADVENTURE, + "3" => VIEW, + "view" => VIEW, + "viewer" => VIEW, + "spectator" => VIEW, + "v" => VIEW, + ]; + if(!isset($gms[strtolower($params[0])])){ + $output .= "Usage: /$cmd \n"; + break; + } + $this->server->api->setProperty("gamemode", $gms[strtolower($params[0])]); + $output .= "Default Gamemode is now " . strtoupper($this->server->getGamemode()) . ".\n"; + break; + case "status": + if(!($issuer instanceof Player) and $issuer === "console"){ + $this->server->debugInfo(true); + } + $info = $this->server->debugInfo(); + $output .= "TPS: " . $info["tps"] . ", Memory usage: " . $info["memory_usage"] . " (Peak " . $info["memory_peak_usage"] . ")\n"; + break; + case "update-done": + $this->server->api->setProperty("last-update", time()); + break; + case "stop": + $this->loop->stop = true; + $output .= "Stopping the server\n"; + $this->server->close(); + break; + case "difficulty": + $s = trim(array_shift($params)); + if($s === "" or (((int) $s) > 3 and ((int) $s) < 0)){ + $output .= "Usage: /difficulty <0|1|2|3>\n"; + break; + } + $this->server->api->setProperty("difficulty", (int) $s); + $output .= "Difficulty changed to " . $this->server->difficulty . "\n"; + break; + case "?": + if($issuer !== "console" and $issuer !== "rcon"){ + break; + } + case "help": + if(isset($params[0]) and !is_numeric($params[0])){ + $c = trim(strtolower($params[0])); + if(isset($this->help[$c]) or isset($this->alias[$c])){ + $c = isset($this->help[$c]) ? $c : $this->alias[$c]; + if($this->server->api->dhandle("console.command." . $c, ["cmd" => $c, "parameters" => [], "issuer" => $issuer, "alias" => false]) === false or $this->server->api->dhandle("console.command", ["cmd" => $c, "parameters" => [], "issuer" => $issuer, "alias" => false]) === false){ + break; + } + $output .= "Usage: /$c " . $this->help[$c] . "\n"; + break; + } + } + $cmds = []; + foreach($this->help as $c => $h){ + if($this->server->api->dhandle("console.command." . $c, ["cmd" => $c, "parameters" => [], "issuer" => $issuer, "alias" => false]) === false or $this->server->api->dhandle("console.command", ["cmd" => $c, "parameters" => [], "issuer" => $issuer, "alias" => false]) === false){ + continue; + } + $cmds[$c] = $h; + } + + $max = ceil(count($cmds) / 5); + $page = (int) (isset($params[0]) ? min($max, max(1, intval($params[0]))) : 1); + $output .= FORMAT_RED . "-" . FORMAT_RESET . " Showing help page $page of $max (/help ) " . FORMAT_RED . "-" . FORMAT_RESET . "\n"; + $current = 1; + foreach($cmds as $c => $h){ + $curpage = (int) ceil($current / 5); + if($curpage === $page){ + $output .= "/$c " . $h . "\n"; + }elseif($curpage > $page){ + break; + } + ++$current; + } + break; + default: + $output .= "Command doesn't exist! Use /help\n"; + break; + } + return $output; + } + } class ConsoleLoop extends Thread{ + public $line; public $stop; public $base; public $ev; public $fp; + public function __construct(){ $this->line = false; $this->stop = false; @@ -302,32 +287,33 @@ class ConsoleLoop extends Thread{ $this->stop = true; } - private function readLine(){ - if($this->fp){ - $line = trim(fgets($this->fp)); - }else{ - $line = trim(readline("")); - if($line != ""){ - readline_add_history( $line ); - } - } - return $line; - } - public function run(){ if(!extension_loaded("readline")){ $this->fp = fopen("php://stdin", "r"); } - while($this->stop === false){ + while(!$this->stop){ $this->line = $this->readLine(); $this->wait(); $this->line = false; } if(!extension_loaded("readline")){ - @fclose($fp); + @fclose($this->fp); } + exit(0); } + + private function readLine(){ + if($this->fp){ + $line = trim(fgets($this->fp)); + }else{ + $line = trim(readline("")); + if($line != ""){ + readline_add_history($line); + } + } + return $line; + } } diff --git a/src/API/EntityAPI.php b/src/API/EntityAPI.php index 1d2660ec..b4b18b0d 100644 --- a/src/API/EntityAPI.php +++ b/src/API/EntityAPI.php @@ -1,34 +1,16 @@ entities = array(); + $this->entities = []; $this->server = ServerAPI::request(); - - $this->hp = array( + + $this->hp = [ 10 => 4, 11 => 10, 12 => 10, @@ -39,9 +21,9 @@ class EntityAPI{ 34 => 20, 35 => 16, 36 => 20, - ); - - $this->mob = array( + ]; + + $this->mob = [ "chicken" => 10, "cow" => 11, "pig" => 12, @@ -52,9 +34,9 @@ class EntityAPI{ "skeleton" => 34, "spider" => 35, "pigman" => 36, - ); - - $this->mobName = array( + ]; + + $this->mobName = [ 10 => "Chicken", 11 => "Cow", 12 => "Pig", @@ -65,29 +47,22 @@ class EntityAPI{ 34 => "Skeleton", 35 => "Spider", 36 => "Pigman", - ); - + ]; + $this->serverSpawnAnimals = $this->server->api->getProperty("spawn-animals"); $this->serverSpawnMobs = $this->server->api->getProperty("spawn-mobs"); } - public function get($eid){ - if(isset($this->entities[$eid])){ - return $this->entities[$eid]; - } - return false; - } - public function init(){ - $this->server->schedule(25, array($this, "updateEntities"), array(), true); - $this->server->api->console->register("summon", "", array($this, "commandHandler")); - $this->server->api->console->register("spawnmob", "", array($this, "commandHandler")); - $this->server->api->console->register("despawn", "", array($this, "CommandHandler")); + $this->server->schedule(25, [$this, "updateEntities"], [], true); + $this->server->api->console->register("summon", "", [$this, "commandHandler"]); + $this->server->api->console->register("spawnmob", "", [$this, "commandHandler"]); + $this->server->api->console->register("despawn", "", [$this, "CommandHandler"]); } - + public function commandHandler($cmd, $args, $issuer, $alias){ $output = ""; - switch ($cmd){ + switch($cmd){ case 'summon': case 'spawnmob': if(!($issuer instanceof Player)){ @@ -98,37 +73,36 @@ class EntityAPI{ $output .= "Usage: /$cmd [amount] [baby]"; break; } - + $type = $this->mob[strtolower($args[0])]; if($type != (10 or 11 or 12 or 13 or 32 or 33 or 34 or 35 or 36)){ $output .= "Unknown mob."; break; } - + if(count($args) == 1){//summon - + $spawnX = round($issuer->entity->x, 1, PHP_ROUND_HALF_UP); $spawnY = round($issuer->entity->y, 1, PHP_ROUND_HALF_UP); $spawnZ = round($issuer->entity->z, 1, PHP_ROUND_HALF_UP); $spawnLevel = $issuer->entity->level; - - $entityit = $this->add($spawnLevel, ENTITY_MOB, $type, array( + + $entityit = $this->add($spawnLevel, ENTITY_MOB, $type, [ "x" => $spawnX, "y" => $spawnY, "z" => $spawnZ, "Health" => $this->hp[$type], - )); + ]); $this->spawnToAll($entityit, $level); - $output .= $this->mobName[$type]." spawned in ".$spawnX.", ".$spawnY.", ".$spawnZ."."; + $output .= $this->mobName[$type] . " spawned in " . $spawnX . ", " . $spawnY . ", " . $spawnZ . "."; break; - } - elseif(is_numeric($args[1])){//summon [amount] - $amount = (int)$args[1]; + }elseif(is_numeric($args[1])){//summon [amount] + $amount = (int) $args[1]; if($amount > 25){ $output .= "Cannot spawn > 25 mobs"; break; } - + $isBaby = 0; if(strtolower($args[2]) == 'baby'){//summon [amount] [baby] if($type > 13){ @@ -137,136 +111,75 @@ class EntityAPI{ } $isBaby = 1; } - + $spawnX = round($issuer->entity->x, 1, PHP_ROUND_HALF_UP); $spawnY = round($issuer->entity->y, 1, PHP_ROUND_HALF_UP); $spawnZ = round($issuer->entity->z, 1, PHP_ROUND_HALF_UP); $spawnLevel = $issuer->entity->level; - + for($cnt = $amount; $cnt > 0; --$cnt){ - $entityit = $this->add($spawnLevel, ENTITY_MOB, $type, array( + $entityit = $this->add($spawnLevel, ENTITY_MOB, $type, [ "x" => $spawnX, "y" => $spawnY, "z" => $spawnZ, "Health" => $this->hp[$type], "IsBaby" => $isBaby, - )); + ]); $this->spawnToAll($entityit, $level); } - - if($type == 13 or $amount == 1) $plural = ''; + + if($type == 13 or $amount == 1) + $plural = ''; else $plural = 's'; - - if($isBaby == 1) $baby = "Baby "; + + if($isBaby == 1) + $baby = "Baby "; else $baby = ''; - - $output .= $amount." ".$baby.$this->mobName[$type].$plural." spawned in ".$spawnX.", ".$spawnY.", ".$spawnZ."."; - + + $output .= $amount . " " . $baby . $this->mobName[$type] . $plural . " spawned in " . $spawnX . ", " . $spawnY . ", " . $spawnZ . "."; + break; - } - elseif(strtolower($args[1]) == 'baby'){//summon [baby] + }elseif(strtolower($args[1]) == 'baby'){//summon [baby] if($type > 13){ $output .= "This mob cant be baby!"; break; - } - else{ + }else{ $spawnX = round($issuer->entity->x, 1, PHP_ROUND_HALF_UP); $spawnY = round($issuer->entity->y, 1, PHP_ROUND_HALF_UP); $spawnZ = round($issuer->entity->z, 1, PHP_ROUND_HALF_UP); - $spawnLevel = $issuer->entity->level; - $entityit = $this->add($spawnLevel, ENTITY_MOB, $type, array( + $spawnLevel = $issuer->entity->level; + $entityit = $this->add($spawnLevel, ENTITY_MOB, $type, [ "x" => $spawnX, "y" => $spawnY, "z" => $spawnZ, "Health" => $this->hp[$type], "isBaby" => 1, - )); + ]); $this->spawnToAll($entityit, $level); - $output .= "Baby ".$this->mobName[$type]." spawned in ".$spawnX.", ".$spawnY.", ".$spawnZ."."; + $output .= "Baby " . $this->mobName[$type] . " spawned in " . $spawnX . ", " . $spawnY . ", " . $spawnZ . "."; break; } break; } case 'despawn': $cnt = 0; - $l = $this->server->query("SELECT EID FROM entities WHERE class = ".ENTITY_MOB.";"); - if ($l !== false and $l !== true){ + $l = $this->server->query("SELECT EID FROM entities WHERE class = " . ENTITY_MOB . ";"); + if($l !== false and $l !== true){ while(($e = $l->fetchArray(SQLITE3_ASSOC)) !== false){ $e = $this->get($e["EID"]); - if ($e instanceof Entity){ + if($e instanceof Entity){ $this->remove($e->eid); $cnt++; } } } - $output .= $cnt." mobs have been despawned!"; + $output .= $cnt . " mobs have been despawned!"; break; } - return $output; - } - - public function updateEntities(){ - $l = $this->server->query("SELECT EID FROM entities WHERE hasUpdate = 1;"); - - if($l !== false and $l !== true){ - while(($e = $l->fetchArray(SQLITE3_ASSOC)) !== false){ - $e = $this->get($e["EID"]); - if($e instanceof Entity){ - $e->update(); - $this->server->query("UPDATE entities SET hasUpdate = 0 WHERE EID = ".$e->eid.";"); - } - } - } - } - - public function updateRadius(Position $center, $radius = 15, $class = false){ - $this->server->query("UPDATE entities SET hasUpdate = 1 WHERE level = '".$center->level->getName()."' ".($class !== false ? "AND class = $class ":"")."AND abs(x - {$center->x}) <= $radius AND abs(y - {$center->y}) <= $radius AND abs(z - {$center->z}) <= $radius;"); + return $output; } - public function getRadius(Position $center, $radius = 15, $class = false){ - $entities = array(); - $l = $this->server->query("SELECT EID FROM entities WHERE level = '".$center->level->getName()."' ".($class !== false ? "AND class = $class ":"")."AND abs(x - {$center->x}) <= $radius AND abs(y - {$center->y}) <= $radius AND abs(z - {$center->z}) <= $radius;"); - if($l !== false and $l !== true){ - while(($e = $l->fetchArray(SQLITE3_ASSOC)) !== false){ - $e = $this->get($e["EID"]); - if($e instanceof Entity){ - $entities[$e->eid] = $e; - } - } - } - return $entities; - } - - public function getAll($level = null){ - if($level instanceof Level){ - $entities = array(); - $l = $this->server->query("SELECT EID FROM entities WHERE level = '".$level->getName()."';"); - if($l !== false and $l !== true){ - while(($e = $l->fetchArray(SQLITE3_ASSOC)) !== false){ - $e = $this->get($e["EID"]); - if($e instanceof Entity){ - $entities[$e->eid] = $e; - } - } - } - return $entities; - } - return $this->entities; - } - - public function heal($eid, $heal = 1, $cause){ - $this->harm($eid, -$heal, $cause); - } - - public function harm($eid, $attack = 1, $cause, $force = false){ - $e = $this->get($eid); - if($e === false or $e->dead === true){ - return false; - } - $e->setHealth($e->getHealth() - $attack, $cause, $force); - } - - public function add(Level $level, $class, $type = 0, $data = array()){ + public function add(Level $level, $class, $type = 0, $data = []){ $eid = $this->eCnt++; $efl = EntityRegistry::$entityList->getEntityFromTypeAndClass($type, $class); if($efl instanceof PropertyEntity){ @@ -286,24 +199,99 @@ class EntityAPI{ } } } - + + public function get($eid){ + if(isset($this->entities[$eid])){ + return $this->entities[$eid]; + } + return false; + } + + public function remove($eid){ + if(isset($this->entities[$eid])){ + $entity = $this->entities[$eid]; + $this->entities[$eid] = null; + unset($this->entities[$eid]); + $entity->closed = true; + $this->server->query("DELETE FROM entities WHERE EID = " . $eid . ";"); + if($entity->class === ENTITY_PLAYER){ + $pk = new RemovePlayerPacket; + $pk->eid = $entity->eid; + $pk->clientID = 0; + $this->server->api->player->broadcastPacket($this->server->api->player->getAll(), $pk); + }else{ + $pk = new RemoveEntityPacket; + $pk->eid = $entity->eid; + $this->server->api->player->broadcastPacket($this->server->api->player->getAll($entity->level), $pk); + } + $this->server->api->dhandle("entity.remove", $entity); + $entity = null; + unset($entity); + } + } + + public function updateEntities(){ + $l = $this->server->query("SELECT EID FROM entities WHERE hasUpdate = 1;"); + + if($l !== false and $l !== true){ + while(($e = $l->fetchArray(SQLITE3_ASSOC)) !== false){ + $e = $this->get($e["EID"]); + if($e instanceof Entity){ + $e->update(); + $this->server->query("UPDATE entities SET hasUpdate = 0 WHERE EID = " . $e->eid . ";"); + } + } + } + } + + public function updateRadius(Position $center, $radius = 15, $class = false){ + $this->server->query("UPDATE entities SET hasUpdate = 1 WHERE level = '" . $center->level->getName() . "' " . ($class !== false ? "AND class = $class " : "") . "AND abs(x - {$center->x}) <= $radius AND abs(y - {$center->y}) <= $radius AND abs(z - {$center->z}) <= $radius;"); + } + + public function getRadius(Position $center, $radius = 15, $class = false){ + $entities = []; + $l = $this->server->query("SELECT EID FROM entities WHERE level = '" . $center->level->getName() . "' " . ($class !== false ? "AND class = $class " : "") . "AND abs(x - {$center->x}) <= $radius AND abs(y - {$center->y}) <= $radius AND abs(z - {$center->z}) <= $radius;"); + if($l !== false and $l !== true){ + while(($e = $l->fetchArray(SQLITE3_ASSOC)) !== false){ + $e = $this->get($e["EID"]); + if($e instanceof Entity){ + $entities[$e->eid] = $e; + } + } + } + return $entities; + } + + public function heal($eid, $heal = 1, $cause){ + $this->harm($eid, -$heal, $cause); + } + + public function harm($eid, $attack = 1, $cause, $force = false){ + $e = $this->get($eid); + if($e === false or $e->dead === true){ + return false; + } + $e->setHealth($e->getHealth() - $attack, $cause, $force); + } + public function drop(Position $pos, Item $item){ if($item->getID() === AIR or $item->count <= 0){ return; } $i = 0; - do { // drop the block to the first supporting block - $i++; - $v = new Vector3($pos->x, $pos->y - $i, $pos->z); - $b = $pos->level->getBlock($v); - if($b->isSolid === true) break; - if(($b instanceof LiquidBlock) or $b->getID() === COBWEB or $b->getID() === LADDER or $b->getID() === FENCE or $b->getID() === STONE_WALL) - break; - - } - while ($i<200); - if ($i==200) $i=0; - $data = array( + do{ // drop the block to the first supporting block + $i++; + $v = new Vector3($pos->x, $pos->y - $i, $pos->z); + $b = $pos->level->getBlock($v); + if($b->isSolid === true) + break; + if(($b instanceof LiquidBlock) or $b->getID() === COBWEB or $b->getID() === LADDER or $b->getID() === FENCE or $b->getID() === STONE_WALL) + break; + + }while($i < 200); + if($i == 200) + $i = 0; + $data = [ "x" => $pos->x + mt_rand(-10, 10) / 50, "y" => $pos->y + 0.19 - $i + 1, "z" => $pos->z + mt_rand(-10, 10) / 50, @@ -312,9 +300,9 @@ class EntityAPI{ "speedY" => mt_rand(5, 8) / 2, //"speedZ" => mt_rand(-3, 3) / 8, "item" => $item, - ); + ]; if($this->server->api->handle("item.drop", $data) !== false){ - for($count = $item->count; $count > 0; ){ + for($count = $item->count; $count > 0;){ $item->count = min($item->getMaxStackSize(), $count); $count -= $item->count; $e = $this->add($pos->level, ENTITY_ITEM, $item->getID(), $data); @@ -332,26 +320,20 @@ class EntityAPI{ } } - public function remove($eid){ - if(isset($this->entities[$eid])){ - $entity = $this->entities[$eid]; - $this->entities[$eid] = null; - unset($this->entities[$eid]); - $entity->closed = true; - $this->server->query("DELETE FROM entities WHERE EID = ".$eid.";"); - if($entity->class === ENTITY_PLAYER){ - $pk = new RemovePlayerPacket; - $pk->eid = $entity->eid; - $pk->clientID = 0; - $this->server->api->player->broadcastPacket($this->server->api->player->getAll(), $pk); - }else{ - $pk = new RemoveEntityPacket; - $pk->eid = $entity->eid; - $this->server->api->player->broadcastPacket($this->server->api->player->getAll($entity->level), $pk); + public function getAll($level = null){ + if($level instanceof Level){ + $entities = []; + $l = $this->server->query("SELECT EID FROM entities WHERE level = '" . $level->getName() . "';"); + if($l !== false and $l !== true){ + while(($e = $l->fetchArray(SQLITE3_ASSOC)) !== false){ + $e = $this->get($e["EID"]); + if($e instanceof Entity){ + $entities[$e->eid] = $e; + } + } } - $this->server->api->dhandle("entity.remove", $entity); - $entity = null; - unset($entity); + return $entities; } + return $this->entities; } } diff --git a/src/API/LevelAPI.php b/src/API/LevelAPI.php index 383f4c48..d3b28c8b 100644 --- a/src/API/LevelAPI.php +++ b/src/API/LevelAPI.php @@ -1,48 +1,20 @@ server = ServerAPI::request(); - $this->levels = array(); - } - - public function get($name){ - if(isset($this->levels[$name])){ - return $this->levels[$name]; - } - return false; - } - - public function getDefault(){ - return $this->levels[$this->default]; + $this->levels = []; } public function init(){ - $this->server->api->console->register("seed", "[world]", array($this, "commandHandler")); - $this->server->api->console->register("save-all", "", array($this, "commandHandler")); - $this->server->api->console->register("save-on", "", array($this, "commandHandler")); - $this->server->api->console->register("save-off", "", array($this, "commandHandler")); - $this->server->api->console->register("setwspawn", "Set the spawn position for your current world. ", array($this, "commandHandler")); + $this->server->api->console->register("seed", "[world]", [$this, "commandHandler"]); + $this->server->api->console->register("save-all", "", [$this, "commandHandler"]); + $this->server->api->console->register("save-on", "", [$this, "commandHandler"]); + $this->server->api->console->register("save-off", "", [$this, "commandHandler"]); + $this->server->api->console->register("setwspawn", "Set the spawn position for your current world. ", [$this, "commandHandler"]); $this->default = $this->server->api->getProperty("level-name"); if($this->loadLevel($this->default) === false){ $this->generateLevel($this->default, $this->server->seed); @@ -50,48 +22,97 @@ class LevelAPI{ } $this->server->spawn = $this->getDefault()->getSafeSpawn(); } - - - public function commandHandler($cmd, $params, $issuer, $alias){ - $output = ""; - switch($cmd){ - case "setwspawn": - if(!($issuer instanceof Player)){return("Please run this command in-game. ");} - $issuer->entity->level->setSpawn(new Vector3($issuer->entity->x, $issuer->entity->y, $issuer->entity->z)); - return("Spawn set!"); - break; - case "save-all": - $save = $this->server->saveEnabled; - $this->server->saveEnabled = true; - $this->saveAll(); - $this->server->saveEnabled = $save; - $this->server->api->chat->broadcast("[NostalgiaCore] All files are saved."); - break; - case "save-on": - $this->server->saveEnabled = true; - break; - case "save-off": - $this->server->saveEnabled = false; - break; - case "seed": - if(!isset($params[0]) and ($issuer instanceof Player)){ - $output .= "Seed: ".$issuer->level->getSeed()."\n"; - }elseif(isset($params[0])){ - if(($lv = $this->server->api->level->get(trim(implode(" ", $params)))) !== false){ - $output .= "Seed: ".$lv->getSeed()."\n"; - } - }else{ - $output .= "Seed: ".$this->server->api->level->getDefault()->getSeed()."\n"; - } + + public function loadLevel($name){ + if($this->get($name) !== false){ + return true; + }elseif($this->levelExists($name) === false){ + console("[NOTICE] Level \"" . $name . "\" not found"); + return false; } - return $output; + $path = DATA_PATH . "worlds/" . $name . "/"; + console("[INFO] Preparing level \"" . $name . "\""); + $level = new PMFLevel($path . "level.pmf"); + if(!$level->isLoaded){ + console("[ERROR] Could not load level \"" . $name . "\""); + return false; + } + $entities = new Config($path . "entities.yml", CONFIG_YAML); + if(file_exists($path . "tileEntities.yml")){ + @rename($path . "tileEntities.yml", $path . "tiles.yml"); + } + $tiles = new Config($path . "tiles.yml", CONFIG_YAML); + $blockUpdates = new Config($path . "bupdates.yml", CONFIG_YAML); + $this->levels[$name] = new Level($level, $entities, $tiles, $blockUpdates, $name); + foreach($entities->getAll() as $entity){ + if(!isset($entity["id"])){ + break; + } + if($entity["id"] === 64){ //Item Drop + $e = $this->server->api->entity->add($this->levels[$name], ENTITY_ITEM, $entity["Item"]["id"], [ + "meta" => $entity["Item"]["Damage"], + "stack" => $entity["Item"]["Count"], + "x" => $entity["Pos"][0], + "y" => $entity["Pos"][1], + "z" => $entity["Pos"][2], + "yaw" => $entity["Rotation"][0], + "pitch" => $entity["Rotation"][1], + ]); + }elseif($entity["id"] === FALLING_SAND){ + $e = $this->server->api->entity->add($this->levels[$name], ENTITY_FALLING, $entity["id"], $entity); + $e->setPosition(new Vector3($entity["Pos"][0], $entity["Pos"][1], $entity["Pos"][2]), $entity["Rotation"][0], $entity["Rotation"][1]); + $e->setHealth($entity["Health"]); + }elseif($entity["id"] === OBJECT_PAINTING or $entity["id"] === OBJECT_ARROW){ //Painting + $e = $this->server->api->entity->add($this->levels[$name], ENTITY_OBJECT, $entity["id"], $entity); + $e->setPosition(new Vector3($entity["Pos"][0], $entity["Pos"][1], $entity["Pos"][2]), $entity["Rotation"][0], $entity["Rotation"][1]); + $e->setHealth(1); + }else{ + $e = $this->server->api->entity->add($this->levels[$name], ENTITY_MOB, $entity["id"], $entity); + $e->setPosition(new Vector3($entity["Pos"][0], $entity["Pos"][1], $entity["Pos"][2]), $entity["Rotation"][0], $entity["Rotation"][1]); + $e->setHealth($entity["Health"]); + } + } + + foreach($tiles->getAll() as $tile){ + if(!isset($tile["id"])){ + break; + } + $t = $this->server->api->tile->add($this->levels[$name], $tile["id"], $tile["x"], $tile["y"], $tile["z"], $tile); + } + + $timeu = microtime(true); + foreach($blockUpdates->getAll() as $bupdate){ + $this->server->api->block->scheduleBlockUpdate(new Position((int) $bupdate["x"], (int) $bupdate["y"], (int) $bupdate["z"], $this->levels[$name]), (float) $bupdate["delay"], (int) $bupdate["type"]); + } + return true; } - + + public function get($name){ + if(isset($this->levels[$name])){ + return $this->levels[$name]; + } + return false; + } + + public function levelExists($name){ + if($name === ""){ + return false; + } + $path = DATA_PATH . "worlds/" . $name . "/"; + if($this->get($name) === false and !file_exists($path . "level.pmf")){ + $level = new LevelImport($path); + if($level->import() === false){ + return false; + } + } + return true; + } + public function generateLevel($name, $seed = false, $generator = false){ if($this->levelExists($name)){ return false; } - $options = array(); + $options = []; if($this->server->api->getProperty("generator-settings") !== false and trim($this->server->api->getProperty("generator-settings")) != ""){ $options["preset"] = $this->server->api->getProperty("generator-settings"); } @@ -105,32 +126,77 @@ class LevelAPI{ $generator = new TemporalGenerator($options); } } - $gen = new WorldGenerator($generator, $name, $seed === false ? Utils::readInt(Utils::getRandomBytes(4, false)):(int) $seed); + $gen = new WorldGenerator($generator, $name, $seed === false ? Utils::readInt(Utils::getRandomBytes(4, false)) : (int) $seed); $gen->generate(); $gen->close(); return true; } - - public function levelExists($name){ - if($name === ""){ - return false; - } - $path = DATA_PATH."worlds/".$name."/"; - if($this->get($name) === false and !file_exists($path."level.pmf")){ - $level = new LevelImport($path); - if($level->import() === false){ - return false; - } - } - return true; + + public function getDefault(){ + return $this->levels[$this->default]; } - + + public function commandHandler($cmd, $params, $issuer, $alias){ + $output = ""; + switch($cmd){ + case "setwspawn": + if(!($issuer instanceof Player)){ + return ("Please run this command in-game. "); + } + $issuer->entity->level->setSpawn(new Vector3($issuer->entity->x, $issuer->entity->y, $issuer->entity->z)); + return ("Spawn set!"); + break; + case "save-all": + $save = $this->server->saveEnabled; + $this->server->saveEnabled = true; + $this->saveAll(); + $this->server->saveEnabled = $save; + $this->server->api->chat->broadcast("[NostalgiaCore] All files are saved."); + break; + case "save-on": + $this->server->saveEnabled = true; + break; + case "save-off": + $this->server->saveEnabled = false; + break; + case "seed": + if(!isset($params[0]) and ($issuer instanceof Player)){ + $output .= "Seed: " . $issuer->level->getSeed() . "\n"; + }elseif(isset($params[0])){ + if(($lv = $this->server->api->level->get(trim(implode(" ", $params)))) !== false){ + $output .= "Seed: " . $lv->getSeed() . "\n"; + } + }else{ + $output .= "Seed: " . $this->server->api->level->getDefault()->getSeed() . "\n"; + } + } + return $output; + } + + public function saveAll(){ + foreach($this->levels as $level){ + $level->save(); + } + } + + public function handle($data, $event){ + switch($event){ + } + } + + public function __destruct(){ + $this->saveAll(); + foreach($this->levels as $level){ + $this->unloadLevel($level, true); + } + } + public function unloadLevel(Level $level, $force = false){ $name = $level->getName(); if($name === $this->default and $force !== true){ return false; } - console("[INFO] Unloading level \"".$name."\""); + console("[INFO] Unloading level \"" . $name . "\""); $level->nextSave = PHP_INT_MAX; $level->save(); foreach($this->server->api->player->getAll($level) as $player){ @@ -148,109 +214,27 @@ class LevelAPI{ unset($this->levels[$name]); return true; } - - public function loadLevel($name){ - if($this->get($name) !== false){ - return true; - }elseif($this->levelExists($name) === false){ - console("[NOTICE] Level \"".$name."\" not found"); - return false; - } - $path = DATA_PATH."worlds/".$name."/"; - console("[INFO] Preparing level \"".$name."\""); - $level = new PMFLevel($path."level.pmf"); - if(!$level->isLoaded){ - console("[ERROR] Could not load level \"".$name."\""); - return false; - } - $entities = new Config($path."entities.yml", CONFIG_YAML); - if(file_exists($path."tileEntities.yml")){ - @rename($path."tileEntities.yml", $path."tiles.yml"); - } - $tiles = new Config($path."tiles.yml", CONFIG_YAML); - $blockUpdates = new Config($path."bupdates.yml", CONFIG_YAML); - $this->levels[$name] = new Level($level, $entities, $tiles, $blockUpdates, $name); - foreach($entities->getAll() as $entity){ - if(!isset($entity["id"])){ - break; - } - if($entity["id"] === 64){ //Item Drop - $e = $this->server->api->entity->add($this->levels[$name], ENTITY_ITEM, $entity["Item"]["id"], array( - "meta" => $entity["Item"]["Damage"], - "stack" => $entity["Item"]["Count"], - "x" => $entity["Pos"][0], - "y" => $entity["Pos"][1], - "z" => $entity["Pos"][2], - "yaw" => $entity["Rotation"][0], - "pitch" => $entity["Rotation"][1], - )); - }elseif($entity["id"] === FALLING_SAND){ - $e = $this->server->api->entity->add($this->levels[$name], ENTITY_FALLING, $entity["id"], $entity); - $e->setPosition(new Vector3($entity["Pos"][0], $entity["Pos"][1], $entity["Pos"][2]), $entity["Rotation"][0], $entity["Rotation"][1]); - $e->setHealth($entity["Health"]); - }elseif($entity["id"] === OBJECT_PAINTING or $entity["id"] === OBJECT_ARROW){ //Painting - $e = $this->server->api->entity->add($this->levels[$name], ENTITY_OBJECT, $entity["id"], $entity); - $e->setPosition(new Vector3($entity["Pos"][0], $entity["Pos"][1], $entity["Pos"][2]), $entity["Rotation"][0], $entity["Rotation"][1]); - $e->setHealth(1); - }else{ - $e = $this->server->api->entity->add($this->levels[$name], ENTITY_MOB, $entity["id"], $entity); - $e->setPosition(new Vector3($entity["Pos"][0], $entity["Pos"][1], $entity["Pos"][2]), $entity["Rotation"][0], $entity["Rotation"][1]); - $e->setHealth($entity["Health"]); - } - } - - foreach($tiles->getAll() as $tile){ - if(!isset($tile["id"])){ - break; - } - $t = $this->server->api->tile->add($this->levels[$name], $tile["id"], $tile["x"], $tile["y"], $tile["z"], $tile); - } - - $timeu = microtime(true); - foreach($blockUpdates->getAll() as $bupdate){ - $this->server->api->block->scheduleBlockUpdate(new Position((int) $bupdate["x"],(int) $bupdate["y"],(int) $bupdate["z"], $this->levels[$name]), (float) $bupdate["delay"], (int) $bupdate["type"]); - } - return true; - } - - public function handle($data, $event){ - switch($event){ - } - } - - public function saveAll(){ - foreach($this->levels as $level){ - $level->save(); - } - } - - public function __destruct(){ - $this->saveAll(); - foreach($this->levels as $level){ - $this->unloadLevel($level, true); - } - } public function getSpawn(){ return $this->server->spawn; } - + public function loadMap(){ if($this->mapName !== false and trim($this->mapName) !== ""){ - if(!file_exists($this->mapDir."level.pmf")){ + if(!file_exists($this->mapDir . "level.pmf")){ $level = new LevelImport($this->mapDir); $level->import(); } - $this->level = new PMFLevel($this->mapDir."level.pmf"); - console("[INFO] Preparing level \"".$this->level->getData("name")."\""); + $this->level = new PMFLevel($this->mapDir . "level.pmf"); + console("[INFO] Preparing level \"" . $this->level->getData("name") . "\""); $this->time = (int) $this->level->getData("time"); $this->seed = (int) $this->level->getData("seed"); $this->spawn = $this->level->getSpawn(); } } - + public function getAll(){ return $this->levels; } - + } diff --git a/src/API/PlayerAPI.php b/src/API/PlayerAPI.php index 2ba4060e..4e70105e 100644 --- a/src/API/PlayerAPI.php +++ b/src/API/PlayerAPI.php @@ -1,326 +1,270 @@ server = ServerAPI::request(); - } - public function init(){ - $this->server->schedule(20 * 15, array($this, "handle"), 1, true, "server.regeneration"); - $this->server->addHandler("player.death", array($this, "handle"), 1); - $this->registerCmd("list"); - $this->registerCmd("kill", ""); - $this->registerCmd("gamemode", " [player]", array($this, "commandHandler")); - $this->registerCmd("tp", "[target player] OR /tp [target player] "); - $this->registerCmd("spawnpoint", "[player] [x] [y] [z]"); - $this->registerCmd("spawn"); - $this->registerCmd("ping"); - $this->server->api->console->alias("lag", "ping"); - $this->server->api->console->alias("suicide", "kill"); - $this->server->api->console->alias("tppos", "tp"); - $this->server->api->ban->cmdWhitelist("list"); - $this->server->api->ban->cmdWhitelist("ping"); - $this->server->api->ban->cmdWhitelist("spawn"); - $this->server->preparedSQL->selectPlayersToHeal = $this->server->database->prepare("SELECT EID FROM entities WHERE class = ".ENTITY_PLAYER." AND health < 20;"); - } - - public function registerCmd($cmd, $help = ""){ - $this->server->api->console->register($cmd, $help, array($this, "commandHandler")); + private $server; + + function __construct(){ + $this->server = ServerAPI::request(); } - public function handle($data, $event){ - switch($event){ - case "server.regeneration": - if($this->server->difficulty === 0){ - $result = $this->server->preparedSQL->selectPlayersToHeal->execute(); - if($result !== false){ - while(($player = $result->fetchArray()) !== false){ - if(($player = $this->server->api->entity->get($player["EID"])) !== false){ - if($player->getHealth() <= 0){ - continue; - } - $player->setHealth(min(20, $player->getHealth() + $data), "regeneration"); - } - } - return true; - } - } - break; - case "player.death": - if(is_numeric($data["cause"])){ - $e = $this->server->api->entity->get($data["cause"]); - if($e instanceof Entity){ - switch($e->class){ - case ENTITY_PLAYER: - $message = " was killed by ".$e->name; - break; - default: - $message = " was killed"; - break; - } - } - }else{ - switch($data["cause"]){ - case "cactus": - $message = " was pricked to death"; - break; - case "lava": - $message = " tried to swim in lava"; - break; - case "fire": - $message = " went up in flames"; - break; - case "burning": - $message = " burned to death"; - break; - case "suffocation": - $message = " suffocated in a wall"; - break; - case "water": - $message = " drowned"; - break; - case "void": - $message = " fell out of the world"; - break; - case "fall": - $message = " hit the ground too hard"; - break; - case "explosion": - $message = " blew up"; - break; - default: - $message = " died"; - break; - } - } - $this->server->api->chat->broadcast($data["player"]->username . $message); - return true; - break; - } - } + public function init(){ + $this->server->schedule(20 * 15, [$this, "handle"], 1, true, "server.regeneration"); + $this->server->addHandler("player.death", [$this, "handle"], 1); + $this->registerCmd("list"); + $this->registerCmd("kill", ""); + $this->registerCmd("gamemode", " [player]", [$this, "commandHandler"]); + $this->registerCmd("tp", "[target player] OR /tp [target player] "); + $this->registerCmd("spawnpoint", "[player] [x] [y] [z]"); + $this->registerCmd("spawn"); + $this->registerCmd("ping"); + $this->server->api->console->alias("lag", "ping"); + $this->server->api->console->alias("suicide", "kill"); + $this->server->api->console->alias("tppos", "tp"); + $this->server->api->ban->cmdWhitelist("list"); + $this->server->api->ban->cmdWhitelist("ping"); + $this->server->api->ban->cmdWhitelist("spawn"); + $this->server->preparedSQL->selectPlayersToHeal = $this->server->database->prepare("SELECT EID FROM entities WHERE class = " . ENTITY_PLAYER . " AND health < 20;"); + } - public function commandHandler($cmd, $args, $issuer, $alias){ - $output = ""; - switch($cmd){ - case "spawnpoint": - if(!($issuer instanceof Player)){ - $output .= "Please run this command in-game.\n"; - break; - } + public function registerCmd($cmd, $help = ""){ + $this->server->api->console->register($cmd, $help, [$this, "commandHandler"]); + } - if(count($args) === 1 or count($args) === 4){ - $target = $this->server->api->player->get(array_shift($args)); - }else{ - $target = $issuer; - } + public function handle($data, $event){ + switch($event){ + case "server.regeneration": + if($this->server->difficulty === 0){ + $result = $this->server->preparedSQL->selectPlayersToHeal->execute(); + if($result !== false){ + while(($player = $result->fetchArray()) !== false){ + if(($player = $this->server->api->entity->get($player["EID"])) !== false){ + if($player->getHealth() <= 0){ + continue; + } + $player->setHealth(min(20, $player->getHealth() + $data), "regeneration"); + } + } + return true; + } + } + break; + case "player.death": + if(is_numeric($data["cause"])){ + $e = $this->server->api->entity->get($data["cause"]); + if($e instanceof Entity){ + switch($e->class){ + case ENTITY_PLAYER: + $message = " was killed by " . $e->name; + break; + default: + $message = " was killed"; + break; + } + } + }else{ + switch($data["cause"]){ + case "cactus": + $message = " was pricked to death"; + break; + case "lava": + $message = " tried to swim in lava"; + break; + case "fire": + $message = " went up in flames"; + break; + case "burning": + $message = " burned to death"; + break; + case "suffocation": + $message = " suffocated in a wall"; + break; + case "water": + $message = " drowned"; + break; + case "void": + $message = " fell out of the world"; + break; + case "fall": + $message = " hit the ground too hard"; + break; + case "explosion": + $message = " blew up"; + break; + default: + $message = " died"; + break; + } + } + $this->server->api->chat->broadcast($data["player"]->username . $message); + return true; + break; + } + } - if(!($target instanceof Player)){ - $output .= "That player cannot be found.\n"; - break; - } + public function commandHandler($cmd, $args, $issuer, $alias){ + $output = ""; + switch($cmd){ + case "spawnpoint": + if(!($issuer instanceof Player)){ + $output .= "Please run this command in-game.\n"; + break; + } - if(count($args) === 3){ - $spawn = new Position(floatval(array_shift($args)), floatval(array_shift($args)), floatval(array_shift($args)), $issuer->level); - }else{ - $spawn = new Position($issuer->entity->x, $issuer->entity->y, $issuer->entity->z, $issuer->entity->level); - } + if(count($args) === 1 or count($args) === 4){ + $target = $this->server->api->player->get(array_shift($args)); + }else{ + $target = $issuer; + } - $target->setSpawn($spawn); - $output .= "Spawnpoint set correctly!\n"; - break; - case "spawn": - if(!($issuer instanceof Player)){ - $output .= "Please run this command in-game.\n"; - break; - } - $issuer->teleport($this->server->spawn); - break; - case "ping": - if(!($issuer instanceof Player)){ - $output .= "Please run this command in-game.\n"; - break; - } - $output .= "ping ".round($issuer->getLag(), 2)."ms, packet loss ".round($issuer->getPacketLoss() * 100, 2)."%, ".round($issuer->getBandwidth() / 1024, 2)." KB/s\n"; - break; - case "gamemode": - $player = false; - $setgm = false; - $gms = array( - "0" => SURVIVAL, - "survival" => SURVIVAL, - "s" => SURVIVAL, - "1" => CREATIVE, - "creative" => CREATIVE, - "c" => CREATIVE, - "2" => ADVENTURE, - "adventure" => ADVENTURE, - "a" => ADVENTURE, - "3" => VIEW, - "view" => VIEW, - "viewer" => VIEW, - "spectator" => VIEW, - "v" => VIEW, - ); - if($issuer instanceof Player){ - $player = $issuer; - } + if(!($target instanceof Player)){ + $output .= "That player cannot be found.\n"; + break; + } + + if(count($args) === 3){ + $spawn = new Position(floatval(array_shift($args)), floatval(array_shift($args)), floatval(array_shift($args)), $issuer->level); + }else{ + $spawn = new Position($issuer->entity->x, $issuer->entity->y, $issuer->entity->z, $issuer->entity->level); + } + + $target->setSpawn($spawn); + $output .= "Spawnpoint set correctly!\n"; + break; + case "spawn": + if(!($issuer instanceof Player)){ + $output .= "Please run this command in-game.\n"; + break; + } + $issuer->teleport($this->server->spawn); + break; + case "ping": + if(!($issuer instanceof Player)){ + $output .= "Please run this command in-game.\n"; + break; + } + $output .= "ping " . round($issuer->getLag(), 2) . "ms, packet loss " . round($issuer->getPacketLoss() * 100, 2) . "%, " . round($issuer->getBandwidth() / 1024, 2) . " KB/s\n"; + break; + case "gamemode": + $player = false; + $setgm = false; + $gms = [ + "0" => SURVIVAL, + "survival" => SURVIVAL, + "s" => SURVIVAL, + "1" => CREATIVE, + "creative" => CREATIVE, + "c" => CREATIVE, + "2" => ADVENTURE, + "adventure" => ADVENTURE, + "a" => ADVENTURE, + "3" => VIEW, + "view" => VIEW, + "viewer" => VIEW, + "spectator" => VIEW, + "v" => VIEW, + ]; + if($issuer instanceof Player){ + $player = $issuer; + } if(count($args) == 1){ $setgm = $args[0]; + }elseif(isset($args[1])){ + if($this->server->api->player->get($args[1]) instanceof Player){ + $player = $this->server->api->player->get($args[1]); + $setgm = $args[0]; + }elseif($this->server->api->player->get($args[0]) instanceof Player){ + $player = $this->server->api->player->get($args[0]); + $setgm = $args[1]; + }else{ + $output .= "Usage: /$cmd [player] or /$cmd [player] \n"; + break; + } } - elseif(isset($args[1])){ - if($this->server->api->player->get($args[1]) instanceof Player){ - $player = $this->server->api->player->get($args[1]); - $setgm = $args[0]; - }elseif($this->server->api->player->get($args[0]) instanceof Player){ - $player = $this->server->api->player->get($args[0]); - $setgm = $args[1]; - }else{ - $output .= "Usage: /$cmd [player] or /$cmd [player] \n"; - break; - } - } - if(!($player instanceof Player) or !isset($gms[strtolower($setgm)])){ - $output .= "Usage: /$cmd [player] or /$cmd [player] \n"; - break; - } - if($player->setGamemode($gms[strtolower($setgm)])){ - $output .= "Gamemode of ".$player->username." changed to ".$player->getGamemode()."\n"; - } - break; - case "tp": + if(!($player instanceof Player) or !isset($gms[strtolower($setgm)])){ + $output .= "Usage: /$cmd [player] or /$cmd [player] \n"; + break; + } + if($player->setGamemode($gms[strtolower($setgm)])){ + $output .= "Gamemode of " . $player->username . " changed to " . $player->getGamemode() . "\n"; + } + break; + case "tp": if(count($args) <= 2 or substr($args[0], 0, 2) === "w:" or substr($args[1], 0, 2) === "w:"){ - if((!isset($args[1]) or substr($args[0], 0, 2) === "w:") and isset($args[0]) and ($issuer instanceof Player)){ - $name = $issuer->username; - $target = implode(" ", $args); - }elseif(isset($args[1]) and isset($args[0])){ - $name = array_shift($args); - $target = implode(" ", $args); - }else{ - $output .= "Usage: /$cmd [target player] \n"; - break; - } - if($this->teleport($name, $target) !== false){ - $output .= "\"$name\" teleported to \"$target\"\n"; - }else{ - $output .= "Couldn't teleport.\n"; - } - }else{ - if(!isset($args[3]) and isset($args[2]) and isset($args[1]) and isset($args[0]) and ($issuer instanceof Player)){ - $name = $issuer->username; - $x = $args[0]; - $y = $args[1]; - $z = $args[2]; - }elseif(isset($args[3]) and isset($args[2]) and isset($args[1]) and isset($args[0])){ - $name = $args[0]; - $x = $args[1]; - $y = $args[2]; - $z = $args[3]; - }else{ - $output .= "Usage: /$cmd [player] \n"; - break; - } - if($this->tppos($name, $x, $y, $z)){ - $output .= "\"$name\" teleported to ($x, $y, $z)\n"; - }else{ - $output .= "Couldn't teleport.\n"; - } - } - break; - case "kill": - case "suicide": - if(!isset($args[0]) and ($issuer instanceof Player)){ - $player = $issuer; - }else{ - $player = $this->get($args[0]); - } - if($player instanceof Player){ - $player->entity->harm(PHP_INT_MAX, "console", true); - $player->sendChat("Ouch. That looks like it hurt.\n"); - }else{ - $output .= "Usage: /$cmd [player]\n"; - } - break; - case "list": - $output .= "There are ".count($this->server->clients)."/".$this->server->maxClients." players online:\n"; - if(count($this->server->clients) == 0){ - break; - } - foreach($this->server->clients as $c){ - $output .= $c->username.", "; - } - $output = substr($output, 0, -2)."\n"; - break; - } - return $output; - } + if((!isset($args[1]) or substr($args[0], 0, 2) === "w:") and isset($args[0]) and ($issuer instanceof Player)){ + $name = $issuer->username; + $target = implode(" ", $args); + }elseif(isset($args[1]) and isset($args[0])){ + $name = array_shift($args); + $target = implode(" ", $args); + }else{ + $output .= "Usage: /$cmd [target player] \n"; + break; + } + if($this->teleport($name, $target) !== false){ + $output .= "\"$name\" teleported to \"$target\"\n"; + }else{ + $output .= "Couldn't teleport.\n"; + } + }else{ + if(!isset($args[3]) and isset($args[2]) and isset($args[1]) and isset($args[0]) and ($issuer instanceof Player)){ + $name = $issuer->username; + $x = $args[0]; + $y = $args[1]; + $z = $args[2]; + }elseif(isset($args[3]) and isset($args[2]) and isset($args[1]) and isset($args[0])){ + $name = $args[0]; + $x = $args[1]; + $y = $args[2]; + $z = $args[3]; + }else{ + $output .= "Usage: /$cmd [player] \n"; + break; + } + if($this->tppos($name, $x, $y, $z)){ + $output .= "\"$name\" teleported to ($x, $y, $z)\n"; + }else{ + $output .= "Couldn't teleport.\n"; + } + } + break; + case "kill": + case "suicide": + if(!isset($args[0]) and ($issuer instanceof Player)){ + $player = $issuer; + }else{ + $player = $this->get($args[0]); + } + if($player instanceof Player){ + $player->entity->harm(PHP_INT_MAX, "console", true); + $player->sendChat("Ouch. That looks like it hurt.\n"); + }else{ + $output .= "Usage: /$cmd [player]\n"; + } + break; + case "list": + $output .= "There are " . count($this->server->clients) . "/" . $this->server->maxClients . " players online:\n"; + if(count($this->server->clients) == 0){ + break; + } + foreach($this->server->clients as $c){ + $output .= $c->username . ", "; + } + $output = substr($output, 0, -2) . "\n"; + break; + } + return $output; + } - public function teleport(&$name, &$target){ - if(substr($target, 0, 2) === "w:"){ - $lv = $this->server->api->level->get(substr($target, 2)); - if($lv instanceof Level){ - $origin = $this->get($name); - if($origin instanceof Player){ - $name = $origin->username; - return $origin->teleport($lv->getSafeSpawn()); - } - }else{ - return false; - } - } - $player = $this->get($target); - if(($player instanceof Player) and ($player->entity instanceof Entity)){ - $target = $player->username; - $origin = $this->get($name); - if($origin instanceof Player){ - $name = $origin->username; - return $origin->teleport($player->entity); - } - } - return false; - } - - public function tppos(&$name, &$x, &$y, &$z){ - $player = $this->get($name); - if(($player instanceof Player) and ($player->entity instanceof Entity)){ - $name = $player->username; - $x = $x[0] === "~" ? $player->entity->x + floatval(substr($x, 1)):floatval($x); - $y = $y[0] === "~" ? $player->entity->y + floatval(substr($y, 1)):floatval($y); - $z = $z[0] === "~" ? $player->entity->z + floatval(substr($z, 1)):floatval($z); - $player->teleport(new Vector3($x, $y, $z)); - return true; - } - return false; - } - - public function get($name, $alike = true, $multiple = false){ - $name = trim(strtolower($name)); - if($name === ""){ - return false; - } - $query = $this->server->query("SELECT ip,port,name FROM players WHERE name ".($alike === true ? "LIKE '%".$name."%'":"= '".$name."'").";"); - $players = array(); - if($query !== false and $query !== true){ - while(($d = $query->fetchArray(SQLITE3_ASSOC)) !== false){ + public function get($name, $alike = true, $multiple = false){ + $name = trim(strtolower($name)); + if($name === ""){ + return false; + } + $query = $this->server->query("SELECT ip,port,name FROM players WHERE name " . ($alike === true ? "LIKE '%" . $name . "%'" : "= '" . $name . "'") . ";"); + $players = []; + if($query !== false and $query !== true){ + while(($d = $query->fetchArray(SQLITE3_ASSOC)) !== false){ $CID = PocketMinecraftServer::clientID($d["ip"], $d["port"]); if(isset($this->server->clients[$CID])){ $players[$CID] = $this->server->clients[$CID]; @@ -328,9 +272,9 @@ class PlayerAPI{ return $players[$CID]; } } - } + } } - + if($multiple === false){ if(count($players) > 0){ return array_shift($players); @@ -340,74 +284,128 @@ class PlayerAPI{ }else{ return $players; } - } + } - public function getAll($level = null){ - if($level instanceof Level){ - $clients = array(); - $l = $this->server->query("SELECT EID FROM entities WHERE level = '".$level->getName()."' AND class = '".ENTITY_PLAYER."';"); - if($l !== false and $l !== true){ - while(($e = $l->fetchArray(SQLITE3_ASSOC)) !== false){ - $e = $this->getByEID($e["EID"]); - if($e instanceof Player){ - $clients[$e->CID] = $e; - } - } - } - return $clients; - } - return $this->server->clients; - } + public function teleport(&$name, &$target){ + if(substr($target, 0, 2) === "w:"){ + $lv = $this->server->api->level->get(substr($target, 2)); + if($lv instanceof Level){ + $origin = $this->get($name); + if($origin instanceof Player){ + $name = $origin->username; + return $origin->teleport($lv->getSafeSpawn()); + } + }else{ + return false; + } + } + $player = $this->get($target); + if(($player instanceof Player) and ($player->entity instanceof Entity)){ + $target = $player->username; + $origin = $this->get($name); + if($origin instanceof Player){ + $name = $origin->username; + return $origin->teleport($player->entity); + } + } + return false; + } - public function broadcastPacket(array $players, RakNetDataPacket $packet){ - foreach($players as $p){ - $p->dataPacket(clone $packet); - } - } + public function tppos(&$name, &$x, &$y, &$z){ + $player = $this->get($name); + if(($player instanceof Player) and ($player->entity instanceof Entity)){ + $name = $player->username; + $x = $x[0] === "~" ? $player->entity->x + floatval(substr($x, 1)) : floatval($x); + $y = $y[0] === "~" ? $player->entity->y + floatval(substr($y, 1)) : floatval($y); + $z = $z[0] === "~" ? $player->entity->z + floatval(substr($z, 1)) : floatval($z); + $player->teleport(new Vector3($x, $y, $z)); + return true; + } + return false; + } - public function getByEID($eid){ - $eid = (int) $eid; - $CID = $this->server->query("SELECT ip,port FROM players WHERE EID = '".$eid."';", true); - $CID = PocketMinecraftServer::clientID($CID["ip"], $CID["port"]); - if(isset($this->server->clients[$CID])){ - return $this->server->clients[$CID]; - } - return false; - } + public function broadcastPacket(array $players, RakNetDataPacket $packet){ + foreach($players as $p){ + $p->dataPacket(clone $packet); + } + } - public function online(){ - $o = array(); - foreach($this->server->clients as $p){ - if($p->auth === true){ - $o[] = $p->username; - } - } - return $o; - } + public function online(){ + $o = []; + foreach($this->server->clients as $p){ + if($p->auth === true){ + $o[] = $p->username; + } + } + return $o; + } - public function add($CID){ - if(isset($this->server->clients[$CID])){ - $player = $this->server->clients[$CID]; - $player->data = $this->getOffline($player->username); - $player->gamemode = $player->data->get("gamemode"); - if(($player->level = $this->server->api->level->get($player->data->get("position")["level"])) === false){ - $player->level = $this->server->api->level->getDefault(); - $player->data->set("position", array( - "level" => $player->level->getName(), - "x" => $player->level->getSpawn()->x, - "y" => $player->level->getSpawn()->y, - "z" => $player->level->getSpawn()->z, - )); - } - $this->server->query("INSERT OR REPLACE INTO players (CID, ip, port, name) VALUES (".$player->CID.", '".$player->ip."', ".$player->port.", '".strtolower($player->username)."');"); - } - } + public function add($CID){ + if(isset($this->server->clients[$CID])){ + $player = $this->server->clients[$CID]; + $player->data = $this->getOffline($player->username); + $player->gamemode = $player->data->get("gamemode"); + if(($player->level = $this->server->api->level->get($player->data->get("position")["level"])) === false){ + $player->level = $this->server->api->level->getDefault(); + $player->data->set("position", [ + "level" => $player->level->getName(), + "x" => $player->level->getSpawn()->x, + "y" => $player->level->getSpawn()->y, + "z" => $player->level->getSpawn()->z, + ]); + } + $this->server->query("INSERT OR REPLACE INTO players (CID, ip, port, name) VALUES (" . $player->CID . ", '" . $player->ip . "', " . $player->port . ", '" . strtolower($player->username) . "');"); + } + } - public function spawnAllPlayers(Player $player){ - foreach($this->getAll() as $p){ - if($p !== $player and ($p->entity instanceof Entity)){ - $p->entity->spawn($player); - if($p->level !== $player->level){ + public function getOffline($name){ + $iname = strtolower($name); + $default = [ + "caseusername" => $name, + "position" => [ + "level" => $this->server->spawn->level->getName(), + "x" => $this->server->spawn->x, + "y" => $this->server->spawn->y, + "z" => $this->server->spawn->z, + ], + "spawn" => [ + "level" => $this->server->spawn->level->getName(), + "x" => $this->server->spawn->x, + "y" => $this->server->spawn->y, + "z" => $this->server->spawn->z, + ], + "inventory" => array_fill(0, PLAYER_SURVIVAL_SLOTS, [AIR, 0, 0]), + "hotbar" => [0, -1, -1, -1, -1, -1, -1, -1, -1], + "armor" => array_fill(0, 4, [AIR, 0]), + "gamemode" => $this->server->gamemode, + "health" => 20, + "lastIP" => "", + "lastID" => 0, + "achievements" => [], + ]; + + if(!file_exists(DATA_PATH . "players/" . $iname . ".yml")){ + if($this->server->extraprops->get("save-player-data")){ + console("[NOTICE] Player data not found for \"" . $iname . "\", creating new profile"); + $data = new Config(DATA_PATH . "players/" . $iname . ".yml", CONFIG_YAML, $default); + $data->save(); + } + } + + $data = new Config(DATA_PATH . "players/" . $iname . ".yml", CONFIG_YAML, $default); + + if(($data->get("gamemode") & 0x01) === 1){ + $data->set("health", 20); + } + $this->server->handle("player.offline.get", $data); + return $data; + } + + public function spawnAllPlayers(Player $player){ + foreach($this->getAll() as $p){ + if($p !== $player and ($p->entity instanceof Entity)){ + $p->entity->spawn($player); + if($p->level !== $player->level){ $pk = new MoveEntityPacket_PosRot; $pk->eid = $p->entity->eid; $pk->x = -256; @@ -415,17 +413,44 @@ class PlayerAPI{ $pk->z = -256; $pk->yaw = 0; $pk->pitch = 0; - $player->dataPacket($pk); - } - } - } - } + $player->dataPacket($pk); + } + } + } + } - public function spawnToAllPlayers(Player $player){ - foreach($this->getAll() as $p){ - if($p !== $player and ($p->entity instanceof Entity) and ($player->entity instanceof Entity)){ - $player->entity->spawn($p); - if($p->level !== $player->level){ + public function getAll($level = null){ + if($level instanceof Level){ + $clients = []; + $l = $this->server->query("SELECT EID FROM entities WHERE level = '" . $level->getName() . "' AND class = '" . ENTITY_PLAYER . "';"); + if($l !== false and $l !== true){ + while(($e = $l->fetchArray(SQLITE3_ASSOC)) !== false){ + $e = $this->getByEID($e["EID"]); + if($e instanceof Player){ + $clients[$e->CID] = $e; + } + } + } + return $clients; + } + return $this->server->clients; + } + + public function getByEID($eid){ + $eid = (int) $eid; + $CID = $this->server->query("SELECT ip,port FROM players WHERE EID = '" . $eid . "';", true); + $CID = PocketMinecraftServer::clientID($CID["ip"], $CID["port"]); + if(isset($this->server->clients[$CID])){ + return $this->server->clients[$CID]; + } + return false; + } + + public function spawnToAllPlayers(Player $player){ + foreach($this->getAll() as $p){ + if($p !== $player and ($p->entity instanceof Entity) and ($player->entity instanceof Entity)){ + $player->entity->spawn($p); + if($p->level !== $player->level){ $pk = new MoveEntityPacket_PosRot; $pk->eid = $player->entity->eid; $pk->x = -256; @@ -433,78 +458,35 @@ class PlayerAPI{ $pk->z = -256; $pk->yaw = 0; $pk->pitch = 0; - $p->dataPacket($pk); - } - } - } - } + $p->dataPacket($pk); + } + } + } + } - public function remove($CID){ - if(isset($this->server->clients[$CID])){ - $player = $this->server->clients[$CID]; - unset($this->server->clients[$CID]); - $player->close(); - if($player->username != "" and ($player->data instanceof Config)){ - $this->saveOffline($player->data); - } - $this->server->query("DELETE FROM players WHERE name = '".$player->username."';"); - if($player->entity instanceof Entity){ - unset($player->entity->player); - //unset($player->entity); - } - $this->server->api->entity->remove($player->eid); - $player = null; - unset($player); - } - } + public function remove($CID){ + if(isset($this->server->clients[$CID])){ + $player = $this->server->clients[$CID]; + unset($this->server->clients[$CID]); + $player->close(); + if($player->username != "" and ($player->data instanceof Config)){ + $this->saveOffline($player->data); + } + $this->server->query("DELETE FROM players WHERE name = '" . $player->username . "';"); + if($player->entity instanceof Entity){ + unset($player->entity->player); + //unset($player->entity); + } + $this->server->api->entity->remove($player->eid); + $player = null; + unset($player); + } + } - public function getOffline($name){ - $iname = strtolower($name); - $default = array( - "caseusername" => $name, - "position" => array( - "level" => $this->server->spawn->level->getName(), - "x" => $this->server->spawn->x, - "y" => $this->server->spawn->y, - "z" => $this->server->spawn->z, - ), - "spawn" => array( - "level" => $this->server->spawn->level->getName(), - "x" => $this->server->spawn->x, - "y" => $this->server->spawn->y, - "z" => $this->server->spawn->z, - ), - "inventory" => array_fill(0, PLAYER_SURVIVAL_SLOTS, array(AIR, 0, 0)), - "hotbar" => array(0, -1, -1, -1, -1, -1, -1, -1, -1), - "armor" => array_fill(0, 4, array(AIR, 0)), - "gamemode" => $this->server->gamemode, - "health" => 20, - "lastIP" => "", - "lastID" => 0, - "achievements" => array(), - ); - - if(!file_exists(DATA_PATH."players/".$iname.".yml")){ - if($this->server->extraprops->get("save-player-data")) { - console("[NOTICE] Player data not found for \"".$iname."\", creating new profile"); - $data = new Config(DATA_PATH."players/".$iname.".yml", CONFIG_YAML, $default); - $data->save(); - } - } - - $data = new Config(DATA_PATH."players/".$iname.".yml", CONFIG_YAML, $default); - - if(($data->get("gamemode") & 0x01) === 1){ - $data->set("health", 20); - } - $this->server->handle("player.offline.get", $data); - return $data; - } - - public function saveOffline(Config $data){ - if($this->server->extraprops->get("save-player-data")) { - $this->server->handle("player.offline.save", $data); - $data->save(); - } - } + public function saveOffline(Config $data){ + if($this->server->extraprops->get("save-player-data")){ + $this->server->handle("player.offline.save", $data); + $data->save(); + } + } } diff --git a/src/API/PluginAPI.php b/src/API/PluginAPI.php index 93620876..ceb2d1c2 100644 --- a/src/API/PluginAPI.php +++ b/src/API/PluginAPI.php @@ -1,53 +1,50 @@ server = ServerAPI::request(); $this->randomNonce = Utils::getRandomBytes(16, false); - $this->server->api->console->register("plugins", "", array($this, "commandHandler")); - $this->server->api->console->register("version", "", array($this, "commandHandler")); + $this->server->api->console->register("plugins", "", [$this, "commandHandler"]); + $this->server->api->console->register("version", "", [$this, "commandHandler"]); $this->server->api->ban->cmdWhitelist("version"); $this->server->api->console->alias("pl", "plugins"); $this->server->api->console->alias("ver", "version"); $this->server->api->console->alias("about", "version"); } - public function commandHandler($cmd, $params, $issuer, $alias){ + public function commandHandler($cmd, $params, $issuer, $alias){ $output = ""; switch($cmd){ case "plugins": $output = "Plugins (" . count($this->plugins) . "): "; foreach($this->getList() as $plugin){ - $output .= $plugin["name"] . " v".$plugin["version"] .", "; + $output .= $plugin["name"] . " v" . $plugin["version"] . ", "; } - $output = $output === "Plugins (0): " ? "No plugins installed.\n" : substr($output, 0, -2)."\n"; + $output = $output === "Plugins (0): " ? "No plugins installed.\n" : substr($output, 0, -2) . "\n"; break; case "version": $output = "This server is running NostalgiaCore version " . MAJOR_VERSION . "\nCODENAME: 「 " . CODENAME . " 」\n(Implementing API version #" . CURRENT_API_VERSION . " for Minecraft: PE " . CURRENT_MINECRAFT_VERSION . ")"; if(GIT_COMMIT !== str_repeat("00", 20)){ - $output .= " (git ".GIT_COMMIT.")"; + $output .= " (git " . GIT_COMMIT . ")"; } $output .= "\n"; break; @@ -55,6 +52,14 @@ class PluginAPI extends stdClass{ return $output; } + public function getList(){ + $list = []; + foreach($this->plugins as $p){ + $list[] = $p[1]; + } + return $list; + } + public function __destruct(){ foreach($this->plugins as $p){ $p[0]->__destruct(); @@ -62,21 +67,87 @@ class PluginAPI extends stdClass{ unset($plugins); } - public function getList(){ - $list = array(); - foreach($this->plugins as $p){ - $list[] = $p[1]; - } - return $list; - } - public function getAll(){ return $this->plugins; } + public function createConfig(Plugin $plugin, $default = []){ + $p = $this->get($plugin); + if($p === false){ + return false; + } + $path = $this->configPath($plugin); + $cnf = new Config($path . "config.yml", CONFIG_YAML, $default); + $cnf->save(); + return $path; + } + + public function get($identifier){ + if($identifier instanceof Plugin){ + foreach($this->plugins as $p){ + if($p[0] === $identifier){ + return $p; + } + } + return false; + } + if(isset($this->plugins[$identifier])){ + return $this->plugins[$identifier]; + } + return false; + } + + public function configPath(Plugin $plugin){ + $p = $this->get($plugin); + $identifier = $this->getIdentifier($p[1]["name"], $p[1]["author"]); + if($p === false){ + return false; + } + $path = $this->pluginsPath() . $p[1]["name"] . DIRECTORY_SEPARATOR; + $this->plugins[$identifier][1]["path"] = $path; + if(!file_exists($path)){ + mkdir($path, 0777); + } + return $path; + } + + public function pluginsPath(){ + $path = join(DIRECTORY_SEPARATOR, [DATA_PATH . "plugins", ""]); + if(!file_exists($path)){ + mkdir($path, 0777); + } + + return $path; + } + + public function readYAML($file){ + return yaml_parse(preg_replace("#^([ ]*)([a-zA-Z_]{1}[^\:]*)\:#m", "$1\"$2\":", file_get_contents($file))); + } + + public function writeYAML($file, $data){ + return file_put_contents($file, yaml_emit($data, YAML_UTF8_ENCODING)); + } + + public function init(){ + $this->server->event("server.start", [$this, "initAll"]); + $this->loadAll(); + } + + private function loadAll(){ + $dir = dir($this->pluginsPath()); + while(false !== ($file = $dir->read())){ + if($file[0] !== "."){ + $ext = strtolower(substr($file, -3)); + if($ext === "php" or $ext === "pmf"){ + $this->load($dir->path . $file); + } + } + } + } + public function load($file){ if(is_link($file) or is_dir($file) or !file_exists($file)){ - console("[ERROR] ".basename($file)." is not a file"); + console("[ERROR] " . basename($file) . " is not a file"); return false; } if(strtolower(substr($file, -3)) === "pmf"){ @@ -85,12 +156,12 @@ class PluginAPI extends stdClass{ }else{ $content = file_get_contents($file); $info = strstr($content, "*/", true); - $content = str_repeat(PHP_EOL, substr_count($info, "\n")).substr(strstr($content, "*/"),2); + $content = str_repeat(PHP_EOL, substr_count($info, "\n")) . substr(strstr($content, "*/"), 2); if(preg_match_all('#([a-zA-Z0-9\-_]*)=([^\r\n]*)#u', $info, $matches) == 0){ //false or 0 matches - console("[ERROR] Failed parsing of ".basename($file)); + console("[ERROR] Failed parsing of " . basename($file)); return false; } - $info = array(); + $info = []; foreach($matches[1] as $k => $i){ $v = $matches[2][$k]; switch(strtolower($v)){ @@ -111,10 +182,10 @@ class PluginAPI extends stdClass{ $info["class"] = trim(strtolower($info["class"])); } if(!isset($info["name"]) or !isset($info["version"]) or !isset($info["class"]) or !isset($info["author"])){ - console("[ERROR] Failed parsing of ".basename($file)); + console("[ERROR] Failed parsing of " . basename($file)); return false; } - console("[INFO] Loading plugin \"".FORMAT_GREEN.$info["name"].FORMAT_RESET."\" ".FORMAT_AQUA.$info["version"].FORMAT_RESET." by ".FORMAT_AQUA.$info["author"].FORMAT_RESET); + console("[INFO] Loading plugin \"" . FORMAT_GREEN . $info["name"] . FORMAT_RESET . "\" " . FORMAT_AQUA . $info["version"] . FORMAT_RESET . " by " . FORMAT_AQUA . $info["author"] . FORMAT_RESET); if($info["class"] !== "none" and class_exists($info["class"])){ console("[ERROR] Failed loading plugin: class already exists"); return false; @@ -123,29 +194,29 @@ class PluginAPI extends stdClass{ console("[ERROR] Failed loading {$info['name']}: evaluation error"); return false; } - + $className = $info["class"]; $apiversion = array_map("floatval", explode(",", (string) $info["apiversion"])); if(!in_array((string) CURRENT_API_VERSION, $apiversion)){ - console("[WARNING] Plugin \"".$info["name"]."\" may not be compatible with the API (".$info["apiversion"]." != ".CURRENT_API_VERSION.")! It can crash or corrupt the server!"); + console("[WARNING] Plugin \"" . $info["name"] . "\" may not be compatible with the API (" . $info["apiversion"] . " != " . CURRENT_API_VERSION . ")! It can crash or corrupt the server!"); } - + $identifier = $this->getIdentifier($info["name"], $info["author"]); - - if($info["class"] !== "none"){ + + if($info["class"] !== "none"){ $object = new $className($this->server->api, false); if(!($object instanceof Plugin)){ - console("[ERROR] Plugin \"".$info["name"]."\" doesn't use the Plugin Interface"); + console("[ERROR] Plugin \"" . $info["name"] . "\" doesn't use the Plugin Interface"); if(method_exists($object, "__destruct")){ $object->__destruct(); } $object = null; unset($object); }else{ - $this->plugins[$identifier] = array($object, $info); + $this->plugins[$identifier] = [$object, $info]; } }else{ - $this->plugins[$identifier] = array(new DummyPlugin($this->server->api, false), $info); + $this->plugins[$identifier] = [new DummyPlugin($this->server->api, false), $info]; } return true; } @@ -154,93 +225,10 @@ class PluginAPI extends stdClass{ return sha1(trim(strtolower($name)), true) ^ sha1(trim(strtolower($author)), true) ^ sha1($this->randomNonce, true); } - public function get($identifier){ - if($identifier instanceof Plugin){ - foreach($this->plugins as $p){ - if($p[0] === $identifier){ - return $p; - } - } - return false; - } - if(isset($this->plugins[$identifier])){ - return $this->plugins[$identifier]; - } - return false; - } - - public function pluginsPath(){ - $path = join(DIRECTORY_SEPARATOR, array(DATA_PATH."plugins", "")); - @mkdir($path); - return $path; - } - - - public function configPath(Plugin $plugin){ - $p = $this->get($plugin); - $identifier = $this->getIdentifier($p[1]["name"], $p[1]["author"]); - if($p === false){ - return false; - } - $path = $this->pluginsPath() . $p[1]["name"] . DIRECTORY_SEPARATOR; - $this->plugins[$identifier][1]["path"] = $path; - @mkdir($path); - return $path; - } - - public function createConfig(Plugin $plugin, $default = array()){ - $p = $this->get($plugin); - if($p === false){ - return false; - } - $path = $this->configPath($plugin); - $cnf = new Config($path."config.yml", CONFIG_YAML, $default); - $cnf->save(); - return $path; - } - - private function fillDefaults($default, &$yaml){ - foreach($default as $k => $v){ - if(is_array($v)){ - if(!isset($yaml[$k]) or !is_array($yaml[$k])){ - $yaml[$k] = array(); - } - $this->fillDefaults($v, $yaml[$k]); - }elseif(!isset($yaml[$k])){ - $yaml[$k] = $v; - } - } - } - - public function readYAML($file){ - return yaml_parse(preg_replace("#^([ ]*)([a-zA-Z_]{1}[^\:]*)\:#m", "$1\"$2\":", file_get_contents($file))); - } - - public function writeYAML($file, $data){ - return file_put_contents($file, yaml_emit($data, YAML_UTF8_ENCODING)); - } - - public function init(){ - $this->server->event("server.start", array($this, "initAll")); - $this->loadAll(); - } - - private function loadAll(){ - $dir = dir($this->pluginsPath()); - while(false !== ($file = $dir->read())){ - if($file[0] !== "."){ - $ext = strtolower(substr($file, -3)); - if($ext === "php" or $ext === "pmf"){ - $this->load($dir->path . $file); - } - } - } - } - public function initAll(){ console("[INFO] Starting plugins..."); - $names = array(); - $versions = array(); + $names = []; + $versions = []; foreach($this->plugins as $p){ $names[] = $p[1]["name"]; $versions[] = $p[1]["version"]; @@ -250,46 +238,52 @@ class PluginAPI extends stdClass{ foreach($p[0]->getRequiredPlugins() as $required){ if(in_array($required->pluginName, $names)){ if(!in_array($required->version, $versions) && $required->version !== false){ - console("[WARNING] Plugin \"".$required->pluginName."\" needed by \"".$p[1]["name"]."\" is incorrect version."); + console("[WARNING] Plugin \"" . $required->pluginName . "\" needed by \"" . $p[1]["name"] . "\" is incorrect version."); } }else{ - console("[ERROR] Plugin \"".$required->pluginName."\" needed by \"".$p[1]["name"]."\" is not found."); + console("[ERROR] Plugin \"" . $required->pluginName . "\" needed by \"" . $p[1]["name"] . "\" is not found."); ServerAPI::request()->close(); - + } } } $p[0]->init(); //ARGHHH!!! Plugin loading randomly fails!! } } + + private function fillDefaults($default, &$yaml){ + foreach($default as $k => $v){ + if(is_array($v)){ + if(!isset($yaml[$k]) or !is_array($yaml[$k])){ + $yaml[$k] = []; + } + $this->fillDefaults($v, $yaml[$k]); + }elseif(!isset($yaml[$k])){ + $yaml[$k] = $v; + } + } + } } class RequiredPluginEntry{ //Use this as object of requirements array + public $pluginName; public $version; + public function __construct($name, $version = false){ $this->pluginName = $name; $this->version = $version; } } -interface OtherPluginRequirement{ - public function getRequiredPlugins(); -} - -interface Plugin{ - public function __construct(ServerAPI $api, $server = false); - public function init(); - public function __destruct(); -} - class DummyPlugin implements Plugin{ - public function __construct(ServerAPI $api, $server = false){ + + public function __construct(ServerAPI $api, $server = false){ } - + public function init(){ } - + public function __destruct(){ } } diff --git a/src/API/QueryAPI.php b/src/API/QueryAPI.php index ac367880..46357c6f 100644 --- a/src/API/QueryAPI.php +++ b/src/API/QueryAPI.php @@ -1,38 +1,42 @@ server = ServerAPI::request(); QueryAPI::$NOT_FOUND_VALUE = new NFV(); $this->updateQueryData("splitnum", chr(128)); $this->updateQueryData("hostname", $this->server->name); - $this->updateQueryData("gametype", ($this->server->gamemode & 0x01) === 0 ? "SMP":"CMP"); + $this->updateQueryData("gametype", ($this->server->gamemode & 0x01) === 0 ? "SMP" : "CMP"); $this->updateQueryData("game_id", "MINECRAFTPE"); $this->updateQueryData("version", CURRENT_MINECRAFT_VERSION); - $this->updateQueryData("server_engine", "NostalgiaCore ".MAJOR_VERSION); + $this->updateQueryData("server_engine", "NostalgiaCore " . MAJOR_VERSION); $this->addToQuery("plugins"); $this->addToQuery("map"); $this->addToQuery("numplayers"); $this->updateQueryData("maxplayers", $this->server->maxClients); - $this->updateQueryData("whitelist", $this->server->api->getProperty("white-list") === true ? "on":"off"); + $this->updateQueryData("whitelist", $this->server->api->getProperty("white-list") === true ? "on" : "off"); $this->updateQueryData("hostport", $this->server->api->getProperty("server-port")); $this->addToQuery("tps"); } - - public function getQueryData(){ - return $this->queryData; - } - - public function addToQuery($name){ - $this->updateQueryData($name, QueryAPI::$NOT_FOUND_VALUE); - } - + public function updateQueryData($name, $value){ $this->queryData[$name] = $value; } + + public function addToQuery($name){ + $this->updateQueryData($name, QueryAPI::$NOT_FOUND_VALUE); + } + + public function getQueryData(){ + return $this->queryData; + } } -class NFV{} \ No newline at end of file +class NFV{ + +} \ No newline at end of file diff --git a/src/API/ServerAPI.php b/src/API/ServerAPI.php index 85493de4..13625f0a 100644 --- a/src/API/ServerAPI.php +++ b/src/API/ServerAPI.php @@ -1,81 +1,55 @@ run(); } - + public function run(){ $this->load(); return $this->init(); } - + public function load(){ - @mkdir(DATA_PATH."players/", 0755); - @mkdir(DATA_PATH."worlds/", 0755); - @mkdir(DATA_PATH."plugins/", 0755); - + if(!file_exists(DATA_PATH . "worlds/")){ + mkdir(DATA_PATH . "worlds/", 0777); + } + + if(!file_exists(DATA_PATH . "players/")){ + mkdir(DATA_PATH . "players/", 0777); + } + + if(!file_exists(DATA_PATH . "plugins/")){ + mkdir(DATA_PATH . "plugins/", 0777); + } + //Init all the events foreach(get_declared_classes() as $class){ if(is_subclass_of($class, "BaseEvent") and property_exists($class, "handlers") and property_exists($class, "handlerPriority")){ $class::unregisterAll(); } } - + $version = new VersionString(); - console("[INFO] Starting Minecraft PE server version ".FORMAT_AQUA.CURRENT_MINECRAFT_VERSION); - + console("[INFO] Starting Minecraft PE server version " . FORMAT_AQUA . CURRENT_MINECRAFT_VERSION); + console("[INFO] Loading properties..."); - $this->config = new Config(DATA_PATH . "server.properties", CONFIG_PROPERTIES, array( + $this->config = new Config(DATA_PATH . "server.properties", CONFIG_PROPERTIES, [ "server-name" => "Minecraft: PE Server", "description" => "Server made using NostalgiaCore", "motd" => "Welcome @player to this server!", @@ -137,10 +119,10 @@ class ServerAPI{ "enable-rcon" => false, "rcon.password" => substr(base64_encode(Utils::getRandomBytes(20, false)), 3, 10), "auto-save" => true, - )); - + ]); + $this->parseProperties(); - + //Load advanced properties define("DEBUG", $this->getProperty("debug", 1)); define("ADVANCED_CACHE", $this->getProperty("enable-advanced-cache", false)); @@ -148,96 +130,40 @@ class ServerAPI{ if(ADVANCED_CACHE == true){ console("[INFO] Advanced cache enabled"); } - + if($this->getProperty("upnp-forwarding") == true){ console("[INFO] [UPnP] Trying to port forward..."); UPnP_PortForward($this->getProperty("server-port")); } - $this->server = new PocketMinecraftServer($this->getProperty("server-name"), $this->getProperty("gamemode"), ($seed = $this->getProperty("level-seed")) != "" ? (int) $seed:false, $this->getProperty("server-port"), ($ip = $this->getProperty("server-ip")) != "" ? $ip:"0.0.0.0"); + $this->server = new PocketMinecraftServer($this->getProperty("server-name"), $this->getProperty("gamemode"), ($seed = $this->getProperty("level-seed")) != "" ? (int) $seed : false, $this->getProperty("server-port"), ($ip = $this->getProperty("server-ip")) != "" ? $ip : "0.0.0.0"); $this->server->api = $this; self::$serverRequest = $this->server; - $this->server->send2Discord("[INFO] Starting Minecraft PE server version ".CURRENT_MINECRAFT_VERSION); - console("[INFO] This server is running NostalgiaCore version ".($version->isDev() ? FORMAT_YELLOW:"").MAJOR_VERSION.FORMAT_RESET." \"".CODENAME."\" (MCPE: ".CURRENT_MINECRAFT_VERSION.") (API ".CURRENT_API_VERSION.") (PHP ".PHP_VERSION.")", true, true, 0); + $this->server->send2Discord("[INFO] Starting Minecraft PE server version " . CURRENT_MINECRAFT_VERSION); + console("[INFO] This server is running NostalgiaCore version " . ($version->isDev() ? FORMAT_YELLOW : "") . MAJOR_VERSION . FORMAT_RESET . " \"" . CODENAME . "\" (MCPE: " . CURRENT_MINECRAFT_VERSION . ") (API " . CURRENT_API_VERSION . ") (PHP " . PHP_VERSION . ")", true, true, 0); console("[INFO] NostalgiaCore is distributed under the LGPL License", true, true, 0); $this->loadProperties(); - - + + $this->loadAPI("console", "ConsoleAPI"); $this->loadAPI("level", "LevelAPI"); $this->loadAPI("block", "BlockAPI"); $this->loadAPI("chat", "ChatAPI"); - $this->loadAPI("ban", "BanAPI"); - $this->loadAPI("entity", "EntityAPI"); + $this->loadAPI("ban", "BanAPI"); + $this->loadAPI("entity", "EntityAPI"); $this->loadAPI("tile", "TileAPI"); $this->loadAPI("player", "PlayerAPI"); $this->loadAPI("time", "TimeAPI"); $this->loadAPI("queryAPI", "QueryAPI"); foreach($this->apiList as $ob){ - if(is_callable(array($ob, "init"))){ + if(is_callable([$ob, "init"])){ $ob->init(); //Fails sometimes!!! } } $this->loadAPI("plugin", "PluginAPI"); //fix :( $this->plugin->init(); - - } - - public function async(callable $callable, $params = array(), $remove = false){ - $cnt = $this->asyncCnt++; - $this->asyncCalls[$cnt] = new Async($callable, $params); - return $remove === true ? $this->getAsync($cnt):$cnt; - } - - public function getAsync($id){ - if(!isset($this->asyncCalls[$id])){ - return false; - } - $ob = $this->asyncCalls[$id]; - unset($this->asyncCalls[$id]); - return $ob; - } - public function autoSave(){ - console("[DEBUG] Saving....", true, true, 2); - $this->server->api->level->saveAll(); - } - public function __destruct(){ - foreach($this->apiList as $i => $ob){ - if(method_exists($ob, "__destruct")){ - $ob->__destruct(); - unset($this->apiList[$i]); - } - } - } - - - private function loadProperties(){ - if(($memory = str_replace("B", "", strtoupper($this->getProperty("memory-limit")))) !== false){ - $value = array("M" => 1, "G" => 1024); - $real = ((int) substr($memory, 0, -1)) * $value[substr($memory, -1)]; - if($real < 128){ - console("[WARNING] NostalgiaCore may not work right with less than 128MB of RAM", true, true, 0); - } - @ini_set("memory_limit", $memory); - }else{ - $this->setProperty("memory-limit", "128M"); - } - - if($this->server instanceof PocketMinecraftServer){ - $this->server->setType($this->getProperty("server-type")); - $this->server->maxClients = $this->getProperty("max-players"); - $this->server->description = $this->getProperty("description"); - $this->server->motd = $this->getProperty("motd"); - $this->server->gamemode = $this->getProperty("gamemode"); - $this->server->difficulty = $this->getProperty("difficulty"); - $this->server->whitelist = $this->getProperty("white-list"); - } - } - - private function writeProperties(){ - $this->config->save(); } private function parseProperties(){ @@ -252,7 +178,7 @@ class ServerAPI{ break; case "server-id": if($v !== false){ - $v = preg_match("/[^0-9\-]/", $v) > 0 ? Utils::readInt(substr(md5($v, true), 0, 4)):$v; + $v = preg_match("/[^0-9\-]/", $v) > 0 ? Utils::readInt(substr(md5($v, true), 0, 4)) : $v; } break; } @@ -263,74 +189,6 @@ class ServerAPI{ } } - public function init(){ - if(!(self::$serverRequest instanceof PocketMinecraftServer)){ - self::$serverRequest = $this->server; - } - - if($this->getProperty("auto-save") === true){ - $this->server->schedule(18000, array($this, "autoSave"), array(), true); - } - if(!defined("NO_THREADS") and $this->getProperty("enable-rcon") === true){ - $this->rcon = new RCON($this->getProperty("rcon.password", ""), $this->getProperty("rcon.port", $this->getProperty("server-port")), ($ip = $this->getProperty("server-ip")) != "" ? $ip:"0.0.0.0", $this->getProperty("rcon.threads", 1), $this->getProperty("rcon.clients-per-thread", 50)); - } - - if($this->getProperty("enable-query") === true){ - $this->query = new QueryHandler(); - } - CraftingRecipes::init(); - $this->server->init(); - unregister_tick_function(array($this->server, "tick")); - $this->console->__destruct(); - if($this->rcon instanceof RCON){ - $this->rcon->stop(); - } - $this->__destruct(); - if($this->getProperty("upnp-forwarding") === true ){ - console("[INFO] [UPnP] Removing port forward..."); - UPnP_RemovePortForward($this->getProperty("server-port")); - } - return $this->restart; - } - - /*-------------------------------------------------------------*/ - - public function asyncOperation($t, $d, $c = null){ - return $this->server->asyncOperation($t, $d, $c); - } - - public function addHandler($e, $c, $p = 5){ - return $this->server->addHandler($e, $c, $p); - } - - public function dhandle($e, $d){ - return $this->server->handle($e, $d); - } - - public function handle($e, &$d){ - return $this->server->handle($e, $d); - } - - public function schedule($t, $c, $d, $r = false, $e = "server.schedule"){ - return $this->server->schedule($t, $c, $d, $r, $e); - } - - public function event($e, $d){ - return $this->server->event($e, $d); - } - - public function trigger($e, $d){ - return $this->server->trigger($e, $d); - } - - public function deleteEvent($id){ - return $this->server->deleteEvent($id); - } - - public function getProperties(){ - return $this->config->getAll(); - } - public function getProperty($name, $default = false){ if(($v = arg($name)) !== false){ //Allow for command-line arguments switch(strtolower(trim($v))){ @@ -356,13 +214,13 @@ class ServerAPI{ break; case "server-id": if($v !== false){ - $v = preg_match("/[^0-9\-]/", $v) > 0 ? Utils::readInt(substr(md5($v, true), 0, 4)):$v; + $v = preg_match("/[^0-9\-]/", $v) > 0 ? Utils::readInt(substr(md5($v, true), 0, 4)) : $v; } break; } return $v; } - return ($this->config->exists($name) ? $this->config->get($name):$default); + return ($this->config->exists($name) ? $this->config->get($name) : $default); } public function setProperty($name, $value, $save = true){ @@ -373,8 +231,31 @@ class ServerAPI{ $this->loadProperties(); } - public function getList(){ - return $this->apiList; + private function writeProperties(){ + $this->config->save(); + } + + private function loadProperties(){ + if(($memory = str_replace("B", "", strtoupper($this->getProperty("memory-limit")))) !== false){ + $value = ["M" => 1, "G" => 1024]; + $real = ((int) substr($memory, 0, -1)) * $value[substr($memory, -1)]; + if($real < 128){ + console("[WARNING] NostalgiaCore may not work right with less than 128MB of RAM", true, true, 0); + } + @ini_set("memory_limit", $memory); + }else{ + $this->setProperty("memory-limit", "128M"); + } + + if($this->server instanceof PocketMinecraftServer){ + $this->server->setType($this->getProperty("server-type")); + $this->server->maxClients = $this->getProperty("max-players"); + $this->server->description = $this->getProperty("description"); + $this->server->motd = $this->getProperty("motd"); + $this->server->gamemode = $this->getProperty("gamemode"); + $this->server->difficulty = $this->getProperty("difficulty"); + $this->server->whitelist = $this->getProperty("white-list"); + } } public function loadAPI($name, $class, $dir = false){ @@ -384,11 +265,11 @@ class ServerAPI{ $internal = false; if($dir === false){ $internal = true; - $dir = FILE_PATH."src/API/"; + $dir = FILE_PATH . "src/API/"; } - $file = $dir.$class.".php"; + $file = $dir . $class . ".php"; if(!file_exists($file)){ - console("[ERROR] API ".$name." [".$class."] in ".$dir." doesn't exist", true, true, 0); + console("[ERROR] API " . $name . " [" . $class . "] in " . $dir . " doesn't exist", true, true, 0); return false; } require_once($file); @@ -397,7 +278,108 @@ class ServerAPI{ } $this->$name = new $class(); $this->apiList[] = $this->$name; - console("[".($internal === true ? "INTERNAL":"DEBUG")."] API \x1b[36m".$name."\x1b[0m [\x1b[30;1m".$class."\x1b[0m] loaded", true, true, ($internal === true ? 3:2)); + console("[" . ($internal === true ? "INTERNAL" : "DEBUG") . "] API \x1b[36m" . $name . "\x1b[0m [\x1b[30;1m" . $class . "\x1b[0m] loaded", true, true, ($internal === true ? 3 : 2)); + } + + public function init(){ + if(!(self::$serverRequest instanceof PocketMinecraftServer)){ + self::$serverRequest = $this->server; + } + + if($this->getProperty("auto-save") === true){ + $this->server->schedule(18000, [$this, "autoSave"], [], true); + } + if(!defined("NO_THREADS") and $this->getProperty("enable-rcon") === true){ + $this->rcon = new RCON($this->getProperty("rcon.password", ""), $this->getProperty("rcon.port", $this->getProperty("server-port")), ($ip = $this->getProperty("server-ip")) != "" ? $ip : "0.0.0.0", $this->getProperty("rcon.threads", 1), $this->getProperty("rcon.clients-per-thread", 50)); + } + + if($this->getProperty("enable-query") === true){ + $this->query = new QueryHandler(); + } + CraftingRecipes::init(); + $this->server->init(); + unregister_tick_function([$this->server, "tick"]); + $this->console->__destruct(); + if($this->rcon instanceof RCON){ + $this->rcon->stop(); + } + $this->__destruct(); + if($this->getProperty("upnp-forwarding") === true){ + console("[INFO] [UPnP] Removing port forward..."); + UPnP_RemovePortForward($this->getProperty("server-port")); + } + return $this->restart; + } + + public function __destruct(){ + foreach($this->apiList as $i => $ob){ + if(method_exists($ob, "__destruct")){ + $ob->__destruct(); + unset($this->apiList[$i]); + } + } + } + + /*-------------------------------------------------------------*/ + + public function async(callable $callable, $params = [], $remove = false){ + $cnt = $this->asyncCnt++; + $this->asyncCalls[$cnt] = new Async($callable, $params); + return $remove === true ? $this->getAsync($cnt) : $cnt; + } + + public function getAsync($id){ + if(!isset($this->asyncCalls[$id])){ + return false; + } + $ob = $this->asyncCalls[$id]; + unset($this->asyncCalls[$id]); + return $ob; + } + + public function autoSave(){ + console("[DEBUG] Saving....", true, true, 2); + $this->server->api->level->saveAll(); + } + + public function asyncOperation($t, $d, $c = null){ + return $this->server->asyncOperation($t, $d, $c); + } + + public function addHandler($e, $c, $p = 5){ + return $this->server->addHandler($e, $c, $p); + } + + public function dhandle($e, $d){ + return $this->server->handle($e, $d); + } + + public function handle($e, &$d){ + return $this->server->handle($e, $d); + } + + public function schedule($t, $c, $d, $r = false, $e = "server.schedule"){ + return $this->server->schedule($t, $c, $d, $r, $e); + } + + public function event($e, $d){ + return $this->server->event($e, $d); + } + + public function trigger($e, $d){ + return $this->server->trigger($e, $d); + } + + public function deleteEvent($id){ + return $this->server->deleteEvent($id); + } + + public function getProperties(){ + return $this->config->getAll(); + } + + public function getList(){ + return $this->apiList; } } diff --git a/src/API/TileAPI.php b/src/API/TileAPI.php index c0313ae8..000b70a5 100644 --- a/src/API/TileAPI.php +++ b/src/API/TileAPI.php @@ -1,36 +1,19 @@ tiles = array(); + $this->tiles = []; $this->server = ServerAPI::request(); } - + public function get(Position $pos){ - $tile = $this->server->query("SELECT * FROM tiles WHERE level = '".$pos->level->getName()."' AND x = {$pos->x} AND y = {$pos->y} AND z = {$pos->z};", true); - if($tile !== false and $tile !== true and ($tile = $this->getByID($tile["ID"])) !== false){ + $tile = $this->server->query("SELECT * FROM tiles WHERE level = '" . $pos->level->getName() . "' AND x = {$pos->x} AND y = {$pos->y} AND z = {$pos->z};", true); + if($tile !== false and $tile !== true and ($tile = $this->getByID($tile["ID"])) !== false){ return $tile; } return false; @@ -44,37 +27,13 @@ class TileAPI{ } return false; } - + public function init(){ - + } - public function getAll($level = null){ - if($level instanceof Level){ - $tiles = array(); - $l = $this->server->query("SELECT ID FROM tiles WHERE level = '".$level->getName()."';"); - if($l !== false and $l !== true){ - while(($t = $l->fetchArray(SQLITE3_ASSOC)) !== false){ - $t = $this->getByID($t["ID"]); - if($t instanceof Tile){ - $tiles[$t->id] = $t; - } - } - } - return $tiles; - } - return $this->tiles; - } - - public function add(Level $level, $class, $x, $y, $z, $data = array()){ - $id = $this->tCnt++; - $this->tiles[$id] = new Tile($level, $id, $class, $x, $y, $z, $data); - $this->spawnToAll($this->tiles[$id]); - return $this->tiles[$id]; - } - - public function addSign(Level $level, $x, $y, $z, $lines = array("", "", "", "")){ - return $this->add($level, TILE_SIGN, $x, $y, $z, $data = array( + public function addSign(Level $level, $x, $y, $z, $lines = ["", "", "", ""]){ + return $this->add($level, TILE_SIGN, $x, $y, $z, $data = [ "id" => "Sign", "x" => $x, "y" => $y, @@ -83,7 +42,14 @@ class TileAPI{ "Text2" => $lines[1], "Text3" => $lines[2], "Text4" => $lines[3], - )); + ]); + } + + public function add(Level $level, $class, $x, $y, $z, $data = []){ + $id = $this->tCnt++; + $this->tiles[$id] = new Tile($level, $id, $class, $x, $y, $z, $data); + $this->spawnToAll($this->tiles[$id]); + return $this->tiles[$id]; } public function spawnToAll(Tile $t){ @@ -100,6 +66,23 @@ class TileAPI{ } } + public function getAll($level = null){ + if($level instanceof Level){ + $tiles = []; + $l = $this->server->query("SELECT ID FROM tiles WHERE level = '" . $level->getName() . "';"); + if($l !== false and $l !== true){ + while(($t = $l->fetchArray(SQLITE3_ASSOC)) !== false){ + $t = $this->getByID($t["ID"]); + if($t instanceof Tile){ + $tiles[$t->id] = $t; + } + } + } + return $tiles; + } + return $this->tiles; + } + public function remove($id){ if(isset($this->tiles[$id])){ $t = $this->tiles[$id]; @@ -107,10 +90,10 @@ class TileAPI{ unset($this->tiles[$id]); $t->closed = true; $t->close(); - $this->server->query("DELETE FROM tiles WHERE ID = ".$id.";"); + $this->server->query("DELETE FROM tiles WHERE ID = " . $id . ";"); $this->server->api->dhandle("tile.remove", $t); $t = null; - unset($t); + unset($t); } } } \ No newline at end of file diff --git a/src/API/TimeAPI.php b/src/API/TimeAPI.php index c320ef9d..da4786b7 100644 --- a/src/API/TimeAPI.php +++ b/src/API/TimeAPI.php @@ -1,38 +1,21 @@ 0, "sunset" => 9500, "night" => 10900, "sunrise" => 17800, - ); + ]; private $server; + function __construct(){ $this->server = ServerAPI::request(); } public function init(){ - $this->server->api->console->register("time", " [time]", array($this, "commandHandler")); + $this->server->api->console->register("time", " [time]", [$this, "commandHandler"]); } public function commandHandler($cmd, $args, $issuer, $alias){ @@ -42,8 +25,7 @@ class TimeAPI{ $level = false; if($issuer instanceof Player){ $level = $issuer->level; - } - else{ + }else{ $level = $this->server->api->level->getDefault(); } $p = strtolower(array_shift($args)); @@ -54,14 +36,12 @@ class TimeAPI{ $level = $this->server->api->level->get($levelName); if($level instanceof Level){ $world = " in world \"$levelName\""; - } - else{ + }else{ $output .= "World \"$levelName\" doesn't exist or loaded!"; break; } - } - else $world = " in world \"".$level->getName()."\""; - $output .= "Time".$world.": ".$this->getDate($level).", ".$this->getPhase($level)." (".$this->get(true, $level)." ticks)\n"; + }else $world = " in world \"" . $level->getName() . "\""; + $output .= "Time" . $world . ": " . $this->getDate($level) . ", " . $this->getPhase($level) . " (" . $this->get(true, $level) . " ticks)\n"; break; case "add": if(substr($args[1], 0, 2) === "w:"){ @@ -69,22 +49,20 @@ class TimeAPI{ $level = $this->server->api->level->get($levelName); if($level instanceof Level){ $world = " to the time of world \"$levelName\""; - } - else{ + }else{ $output .= "World \"$levelName\" doesn't exist or loaded!"; break; } - } - else $world = " to the time of world \"".$level->getName()."\""; - + }else $world = " to the time of world \"" . $level->getName() . "\""; + $addTime = array_shift($args); if(!is_numeric($addTime)){ $output .= "Time must be an integer!"; break; } - $addTime = (int)$addTime; + $addTime = (int) $addTime; $this->add($addTime, $level); - $output .= "Added $addTime ticks".$world."\n"; + $output .= "Added $addTime ticks" . $world . "\n"; break; case "set": if(substr($args[1], 0, 2) === "w:"){ @@ -92,24 +70,22 @@ class TimeAPI{ $level = $this->server->api->level->get($levelName); if($level instanceof Level){ $world = " in world \"$levelName\""; - } - else{ + }else{ $output .= "World \"$levelName\" doesn't exist or loaded!"; break; } - } - else $world = " in world \"".$level->getName()."\""; - + }else $world = " in world \"" . $level->getName() . "\""; + $setTime = array_shift($args); if(is_numeric($setTime)){ - $setTime = (int)$setTime; - } - elseif($setTime == 'sunrise' or $setTime == 'day' or $setTime == 'sunset' or $setTime == 'night'); + $setTime = (int) $setTime; + }elseif($setTime == 'sunrise' or $setTime == 'day' or $setTime == 'sunset' or $setTime == 'night') + ; else{ $output .= "Wrong time!"; } $this->set($setTime, $level); - $output .= "Set the time to ".$setTime.$world."\n"; + $output .= "Set the time to " . $setTime . $world . "\n"; break; case "sunrise": case "day": @@ -120,16 +96,14 @@ class TimeAPI{ $level = $this->server->api->level->get($levelName); if($level instanceof Level){ $world = " in world \"$levelName\""; - } - else{ + }else{ $output .= "World \"$levelName\" doesn't exist or loaded!"; break; } - } - else $world = " in world \"".$level->getName()."\""; - + }else $world = " in world \"" . $level->getName() . "\""; + $this->set($p, $level); - $output .= "Set the time to ".$p.$world."\n"; + $output .= "Set the time to " . $p . $world . "\n"; break; default: $output .= "Usage: /time [time] [w:world]\n"; @@ -140,40 +114,20 @@ class TimeAPI{ return $output; } - public function night(){ - return $this->set("night"); - } - public function day(){ - return $this->set("day"); - } - public function sunrise(){ - return $this->set("sunrise"); - } - public function sunset(){ - return $this->set("sunset"); + public function getDate($time = false){ + $time = !is_integer($time) ? $this->get(false, $time) : $time; + return str_pad(strval((floor($time / 800) + 6) % 24), 2, "0", STR_PAD_LEFT) . ":" . str_pad(strval(floor(($time % 800) / 13.33)), 2, "0", STR_PAD_LEFT); } public function get($raw = false, $level = false){ if(!($level instanceof Level)){ $level = $this->server->api->level->getDefault(); } - return $raw === true ? $level->getTime():abs($level->getTime()) % 19200; - } - - public function add($time, $level = false){ - if(!($level instanceof Level)){ - $level = $this->server->api->level->getDefault(); - } - $level->setTime($level->getTime() + (int) $time); - } - - public function getDate($time = false){ - $time = !is_integer($time) ? $this->get(false, $time):$time; - return str_pad(strval((floor($time /800) + 6) % 24), 2, "0", STR_PAD_LEFT).":".str_pad(strval(floor(($time % 800) / 13.33)), 2, "0", STR_PAD_LEFT); + return $raw === true ? $level->getTime() : abs($level->getTime()) % 19200; } public function getPhase($time = false){ - $time = !is_integer($time) ? $this->get(false, $time):$time; + $time = !is_integer($time) ? $this->get(false, $time) : $time; if($time < TimeAPI::$phases["sunset"]){ $time = "day"; }elseif($time < TimeAPI::$phases["night"]){ @@ -186,6 +140,13 @@ class TimeAPI{ return $time; } + public function add($time, $level = false){ + if(!($level instanceof Level)){ + $level = $this->server->api->level->getDefault(); + } + $level->setTime($level->getTime() + (int) $time); + } + public function set($time, $level = false){ if(!($level instanceof Level)){ $level = $this->server->api->level->getDefault(); @@ -198,5 +159,21 @@ class TimeAPI{ return $level->getTime(); } + public function night(){ + return $this->set("night"); + } + + public function day(){ + return $this->set("day"); + } + + public function sunrise(){ + return $this->set("sunrise"); + } + + public function sunset(){ + return $this->set("sunset"); + } + } diff --git a/src/BaseEvent.php b/src/BaseEvent.php index 35182030..0244e7ce 100644 --- a/src/BaseEvent.php +++ b/src/BaseEvent.php @@ -1,30 +1,12 @@ eventName !== null ? get_class($this) : $this->eventName; - } - - final public function setPrioritySlot($slot){ - $this->prioritySlot = (int) $slot; - } - - final public function getPrioritySlot(){ - return (int) $this->prioritySlot; - } - - - public function isAllowed(){ - return ($this->status & 0x7FFFFFFF) === BaseEvent::ALLOW; - } - - public function setAllowed($forceAllow = false){ - $this->status = BaseEvent::ALLOW | ($forceAllow === true ? BaseEvent::FORCE : 0); - } - - public function isCancelled(){ - return ($this->status & 0x7FFFFFFF) === BaseEvent::DENY; - } - - public function setCancelled($forceCancel = false){ - if($this instanceof CancellableEvent){ - $this->status = BaseEvent::DENY | ($forceCancel === true ? BaseEvent::FORCE : 0); - } - return false; - } - - public function isNormal(){ - return $this->status === BaseEvent::NORMAL; - } - - public function setNormal(){ - $this->status = BaseEvent::NORMAL; - } - - public function isForced(){ - return ($this->status & BaseEvent::FORCE) > 0; - } - + public static function getHandlerList(){ return static::$handlers; } - + public static function getPriorityList(){ return static::$handlerPriority; } - + public static function unregisterAll(){ - static::$handlers = array(); - static::$handlerPriority = array(); + static::$handlers = []; + static::$handlerPriority = []; } - + public static function register(callable $handler, $priority = EventPriority::NORMAL){ if($priority < EventPriority::MONITOR or $priority > EventPriority::LOWEST){ return false; @@ -105,14 +43,14 @@ abstract class BaseEvent{ }else{ static::$handlers[$identifier] = $handler; if(!isset(static::$handlerPriority[(int) $priority])){ - static::$handlerPriority[(int) $priority] = array(); + static::$handlerPriority[(int) $priority] = []; krsort(static::$handlerPriority); } static::$handlerPriority[(int) $priority][$identifier] = $handler; return true; } } - + public static function unregister(callable $handler, $priority = EventPriority::NORMAL){ $identifier = Utils::getCallableIdentifier($handler); if(isset(static::$handlers[$identifier])){ @@ -131,6 +69,48 @@ abstract class BaseEvent{ }else{ return false; } - } - + } + + final public function getEventName(){ + return $this->eventName !== null ? get_class($this) : $this->eventName; + } + + final public function getPrioritySlot(){ + return (int) $this->prioritySlot; + } + + final public function setPrioritySlot($slot){ + $this->prioritySlot = (int) $slot; + } + + public function isAllowed(){ + return ($this->status & 0x7FFFFFFF) === BaseEvent::ALLOW; + } + + public function setAllowed($forceAllow = false){ + $this->status = BaseEvent::ALLOW | ($forceAllow === true ? BaseEvent::FORCE : 0); + } + + public function isCancelled(){ + return ($this->status & 0x7FFFFFFF) === BaseEvent::DENY; + } + + public function setCancelled($forceCancel = false){ + if($this instanceof CancellableEvent){ + $this->status = BaseEvent::DENY | ($forceCancel === true ? BaseEvent::FORCE : 0); + } + return false; + } + + public function isNormal(){ + return $this->status === BaseEvent::NORMAL; + } + + public function setNormal(){ + $this->status = BaseEvent::NORMAL; + } + + public function isForced(){ + return ($this->status & BaseEvent::FORCE) > 0; + } } diff --git a/src/Deprecation.php b/src/Deprecation.php index da685020..7d8e66cd 100644 --- a/src/Deprecation.php +++ b/src/Deprecation.php @@ -1,27 +1,9 @@ "ServerAPI::schedule()", "server.time" => "time.change", "world.block.change" => "block.change", @@ -29,7 +11,5 @@ class Deprecation{ "api.op.check" => "op.check", "api.player.offline.get" => "player.offline.get", "api.player.offline.save" => "player.offline.save", - ); - - + ]; } \ No newline at end of file diff --git a/src/Player.php b/src/Player.php index 790495cb..b79332b6 100755 --- a/src/Player.php +++ b/src/Player.php @@ -1,50 +1,9 @@ {$name})){ - return ($this->{$name}); - } - return null; - } + private $chunkCount = []; + private $received = []; /** * @param integer $clientID @@ -107,55 +82,344 @@ class Player{ $this->port = $port; $this->spawnPosition = $this->server->spawn; $this->timeout = microtime(true) + 20; - $this->inventory = array(); - $this->armor = array(); + $this->inventory = []; + $this->armor = []; $this->gamemode = $this->server->gamemode; $this->level = $this->server->api->level->getDefault(); $this->slot = 0; - $this->hotbar = array(0, -1, -1, -1, -1, -1, -1, -1, -1); - $this->packetStats = array(0,0); + $this->hotbar = [0, -1, -1, -1, -1, -1, -1, -1, -1]; + $this->packetStats = [0, 0]; $this->buffer = new RakNetPacket(RakNetInfo::DATA_PACKET_0); - $this->buffer->data = array(); - $this->server->schedule(2, array($this, "handlePacketQueues"), array(), true); - $this->server->schedule(20 * 60, array($this, "clearQueue"), array(), true); - $this->evid[] = $this->server->event("server.close", array($this, "close")); - console("[DEBUG] New Session started with ".$ip.":".$port.". MTU ".$this->MTU.", Client ID ".$this->clientID, true, true, 2); + $this->buffer->data = []; + $this->server->schedule(2, [$this, "handlePacketQueues"], [], true); + $this->server->schedule(20 * 60, [$this, "clearQueue"], [], true); + $this->evid[] = $this->server->event("server.close", [$this, "close"]); + console("[DEBUG] New Session started with " . $ip . ":" . $port . ". MTU " . $this->MTU . ", Client ID " . $this->clientID, true, true, 2); } - + + public function __get($name){ + if(isset($this->{$name})){ + return ($this->{$name}); + } + return null; + } + public function getSpawn(){ return $this->spawnPosition; } /** * @param Vector3 $pos + * + * @return boolean */ - public function setSpawn(Vector3 $pos){ - if(!($pos instanceof Position)){ - $level = $this->level; - }else{ - $level = $pos->level; + public function sleepOn(Vector3 $pos){ + foreach($this->server->api->player->getAll($this->level) as $p){ + if($p->isSleeping instanceof Vector3){ + if($pos->distance($p->isSleeping) <= 0.1){ + return false; + } + } } - $this->spawnPosition = new Position($pos->x, $pos->y, $pos->z, $level); - $pk = new SetSpawnPositionPacket; - $pk->x = (int) $this->spawnPosition->x; - $pk->y = (int) $this->spawnPosition->y; - $pk->z = (int) $this->spawnPosition->z; + $this->isSleeping = $pos; + $this->teleport(new Position($pos->x + 0.5, $pos->y + 1, $pos->z + 0.5, $this->level), false, false, false, false); + if($this->entity instanceof Entity){ + $this->entity->updateMetadata(); + } + $this->setSpawn($pos); + $this->server->schedule(60, [$this, "checkSleep"]); + return true; + } + + /** + * @param Vector3 $pos + * @param float|boolean $yaw + * @param float|boolean $pitch + * @param float|boolean $terrain + * @param float|boolean $force + * + * @return boolean + */ + public function teleport(Vector3 $pos, $yaw = false, $pitch = false, $terrain = true, $force = true){ + if($this->entity instanceof Entity and $this->level instanceof Level){ + $this->entity->check = false; + if($yaw === false){ + $yaw = $this->entity->yaw; + } + if($pitch === false){ + $pitch = $this->entity->pitch; + } + if($this->server->api->dhandle("player.teleport", ["player" => $this, "target" => $pos]) === false){ + $this->entity->check = true; + return false; + } + + if($pos instanceof Position and $pos->level instanceof Level and $pos->level !== $this->level){ + if($this->server->api->dhandle("player.teleport.level", ["player" => $this, "origin" => $this->level, "target" => $pos->level]) === false){ + $this->entity->check = true; + return false; + } + + foreach($this->server->api->entity->getAll($this->level) as $e){ + if($e !== $this->entity){ + if($e->player instanceof Player){ + $pk = new MoveEntityPacket_PosRot; + $pk->eid = $this->entity->eid; + $pk->x = -256; + $pk->y = 128; + $pk->z = -256; + $pk->yaw = 0; + $pk->pitch = 0; + $e->player->dataPacket($pk); + + $pk = new MoveEntityPacket_PosRot; + $pk->eid = $e->eid; + $pk->x = -256; + $pk->y = 128; + $pk->z = -256; + $pk->yaw = 0; + $pk->pitch = 0; + $this->dataPacket($pk); + }else{ + $pk = new RemoveEntityPacket; + $pk->eid = $e->eid; + $this->dataPacket($pk); + } + } + } + + $this->level->freeAllChunks($this); + $this->level = $pos->level; + $this->chunksLoaded = []; + $this->server->api->entity->spawnToAll($this->entity); + $this->server->api->entity->spawnAll($this); + + $pk = new SetTimePacket; + $pk->time = $this->level->getTime(); + $this->dataPacket($pk); + $terrain = true; + + foreach($this->server->api->player->getAll($this->level) as $player){ + if($player !== $this and $player->entity instanceof Entity){ + $pk = new MoveEntityPacket_PosRot; + $pk->eid = $player->entity->eid; + $pk->x = $player->entity->x; + $pk->y = $player->entity->y; + $pk->z = $player->entity->z; + $pk->yaw = $player->entity->yaw; + $pk->pitch = $player->entity->pitch; + $this->dataPacket($pk); + + $pk = new PlayerEquipmentPacket; + $pk->eid = $this->eid; + $pk->item = $this->getSlot($this->slot)->getID(); + $pk->meta = $this->getSlot($this->slot)->getMetadata(); + $pk->slot = 0; + $player->dataPacket($pk); + $this->sendArmor($player); + + $pk = new PlayerEquipmentPacket; + $pk->eid = $player->eid; + $pk->item = $player->getSlot($player->slot)->getID(); + $pk->meta = $player->getSlot($player->slot)->getMetadata(); + $pk->slot = 0; + $this->dataPacket($pk); + $player->sendArmor($this); + } + } + } + + $this->lastCorrect = $pos; + $this->entity->fallY = false; + $this->entity->fallStart = false; + $this->entity->setPosition($pos, $yaw, $pitch); + $this->entity->resetSpeed(); + $this->entity->updateLast(); + $this->entity->calculateVelocity(); + if($terrain === true){ + $this->orderChunks(); + $this->getNextChunk(); + } + $this->entity->check = true; + if($force === true){ + $this->forceMovement = $pos; + } + } + + $pk = new MovePlayerPacket; + $pk->eid = 0; + $pk->x = $pos->x; + $pk->y = $pos->y; + $pk->z = $pos->z; + $pk->bodyYaw = $yaw; + $pk->pitch = $pitch; + $pk->yaw = $yaw; $this->dataPacket($pk); } - + + /** + * @param integer $id + * @param array $data + * + * @return array|bool + */ + public function dataPacket(RakNetDataPacket $packet){ + if($this->connected === false){ + return false; + } + + if(EventHandler::callEvent(new DataPacketSendEvent($this, $packet)) === BaseEvent::DENY){ + return; + } + + $packet->encode(); + $len = strlen($packet->buffer) + 1; + $MTU = $this->MTU - 24; + if($len > $MTU){ + return $this->directBigRawPacket($packet); + } + + if(($this->bufferLen + $len) >= $MTU){ + $this->sendBuffer(); + } + + $packet->messageIndex = $this->counter[3]++; + $packet->reliability = 2; + $this->buffer->data[] = $packet; + $this->bufferLen += 6 + $len; + return []; + } + + private function directBigRawPacket(RakNetDataPacket $packet){ + if($this->connected === false){ + return false; + } + + $sendtime = microtime(true); + + $size = $this->MTU - 34; + $buffer = str_split($packet->buffer, $size); + $bigCnt = $this->bigCnt; + $this->bigCnt = ($this->bigCnt + 1) % 0x10000; + $cnts = []; + $bufCount = count($buffer); + foreach($buffer as $i => $buf){ + $cnts[] = $count = $this->counter[0]++; + + $pk = new UnknownPacket; + $pk->packetID = $packet->pid(); + $pk->reliability = 2; + $pk->hasSplit = true; + $pk->splitCount = $bufCount; + $pk->splitID = $bigCnt; + $pk->splitIndex = $i; + $pk->buffer = $buf; + $pk->messageIndex = $this->counter[3]++; + + $rk = new RakNetPacket(RakNetInfo::DATA_PACKET_0); + $rk->data[] = $pk; + $rk->seqNumber = $count; + $rk->sendtime = $sendtime; + $this->recoveryQueue[$count] = $rk; + $this->send($rk); + } + return $cnts; + } + + public function send(RakNetPacket $packet){ + if($this->connected === true){ + $packet->ip = $this->ip; + $packet->port = $this->port; + $this->bandwidthRaw += $this->server->send($packet); + } + } + + public function sendBuffer(){ + if($this->bufferLen > 0 and $this->buffer instanceof RakNetPacket){ + $this->buffer->seqNumber = $this->counter[0]++; + $this->send($this->buffer); + } + $this->bufferLen = 0; + $this->buffer = new RakNetPacket(RakNetInfo::DATA_PACKET_0); + $this->buffer->data = []; + $this->nextBuffer = microtime(true) + 0.1; + } + + /** + * @param integer $slot + * + * @return Item + */ + public function getSlot($slot){ + if(isset($this->inventory[(int) $slot])){ + return $this->inventory[(int) $slot]; + }else{ + return BlockAPI::getItem(AIR, 0, 0); + } + } + + /** + * @param integer $slot + * @param Item $item + * @param boolean $send + * + * @return boolean + */ + public function setSlot($slot, Item $item, $send = true){ + $this->inventory[(int) $slot] = $item; + if($send === true){ + $this->sendInventorySlot((int) $slot); + } + return true; + } + + /** + * @param Player|string|boolean|void $player + */ + public function sendArmor($player = false){ + $data = [ + "player" => $this, + "eid" => $this->eid, + "slots" => [] + ]; + for($i = 0; $i < 4; ++$i){ + if(isset($this->armor[$i]) and ($this->armor[$i] instanceof Item) and $this->armor[$i]->getID() > AIR){ + $data["slots"][$i] = $this->armor[$i]->getID() !== AIR ? $this->armor[$i]->getID() - 256 : 0; + }else{ + $this->armor[$i] = BlockAPI::getItem(AIR, 0, 0); + $data["slots"][$i] = 255; + } + } + if($player instanceof Player){ + if($player === $this){ + $pk = new ContainerSetContentPacket; + $pk->windowid = 0x78; //Armor window id + $pk->slots = $this->armor; + $this->dataPacket($pk); + }else{ + $pk = new PlayerArmorEquipmentPacket; + $pk->eid = $this->eid; + $pk->slots = $data["slots"]; + $player->dataPacket($pk); + } + }else{ + $this->server->api->dhandle("player.armor", $data); + } + } + public function orderChunks(){ if(!($this->entity instanceof Entity) or $this->connected === false){ return false; } $X = $this->entity->x >> 4; $Z = $this->entity->z >> 4; - $v = new Vector2($X, $Z); - $this->chunksOrder = array(); + $v = new Vector2($X, $Z); + $this->chunksOrder = []; for($x = 0; $x < 16; ++$x){ for($z = 0; $z < 16; ++$z){ $dist = $v->distance(new Vector2($x, $z)); for($y = 0; $y < 8; ++$y){ - $d = $x.":".$y.":".$z; + $d = $x . ":" . $y . ":" . $z; if(!isset($this->chunksLoaded[$d])){ $this->chunksOrder[$d] = $dist; } @@ -164,7 +428,7 @@ class Player{ } asort($this->chunksOrder); } - + public function getNextChunk(){ if($this->connected === false){ return false; @@ -172,15 +436,15 @@ class Player{ foreach($this->chunkCount as $count => $t){ if(isset($this->recoveryQueue[$count]) or isset($this->resendQueue[$count])){ - $this->server->schedule(MAX_CHUNK_RATE, array($this, "getNextChunk")); + $this->server->schedule(MAX_CHUNK_RATE, [$this, "getNextChunk"]); return; }else{ unset($this->chunkCount[$count]); } } - + if(is_array($this->lastChunk)){ - $tiles = $this->server->query("SELECT ID FROM tiles WHERE spawnable = 1 AND level = '".$this->level->getName()."' AND x >= ".($this->lastChunk[0] - 1)." AND x < ".($this->lastChunk[0] + 17)." AND z >= ".($this->lastChunk[1] - 1)." AND z < ".($this->lastChunk[1] + 17).";"); + $tiles = $this->server->query("SELECT ID FROM tiles WHERE spawnable = 1 AND level = '" . $this->level->getName() . "' AND x >= " . ($this->lastChunk[0] - 1) . " AND x < " . ($this->lastChunk[0] + 17) . " AND z >= " . ($this->lastChunk[1] - 1) . " AND z < " . ($this->lastChunk[1] + 17) . ";"); $this->lastChunk = false; if($tiles !== false and $tiles !== true){ while(($tile = $tiles->fetchArray(SQLITE3_ASSOC)) !== false){ @@ -189,15 +453,16 @@ class Player{ $tile->spawn($this); } } - } + } } $c = key($this->chunksOrder); - $d = @$this->chunksOrder[$c]; + $d = $this->chunksOrder[$c] ?? null; if($c === null or $d === null){ - $this->server->schedule(40, array($this, "getNextChunk")); + $this->server->schedule(40, [$this, "getNextChunk"]); return false; } + unset($this->chunksOrder[$c]); $this->chunksLoaded[$c] = true; $id = explode(":", $c); @@ -224,129 +489,70 @@ class Player{ if($cnt === false){ return false; } - $this->chunkCount = array(); + $this->chunkCount = []; foreach($cnt as $i => $count){ $this->chunkCount[$count] = true; } - - $this->lastChunk = array($x, $z); - - $this->server->schedule(MAX_CHUNK_RATE, array($this, "getNextChunk")); - } - public function save(){ - if($this->entity instanceof Entity){ - $this->data->set("achievements", $this->achievements); - $this->data->set("position", array( - "level" => $this->entity->level->getName(), - "x" => (float) $this->entity->x, - "y" => $this->entity->y, - "z" => (float) $this->entity->z, - )); - $this->data->set("spawn", array( - "level" => $this->spawnPosition->level->getName(), - "x" => $this->spawnPosition->x, - "y" => $this->spawnPosition->y, - "z" => $this->spawnPosition->z, - )); - $inv = array(); - foreach($this->inventory as $slot => $item){ - if($item instanceof Item){ - if($slot < (($this->gamemode & 0x01) === 0 ? PLAYER_SURVIVAL_SLOTS:PLAYER_CREATIVE_SLOTS)){ - $inv[$slot] = array($item->getID(), $item->getMetadata(), $item->count); - } - } - } - $this->data->set("inventory", $inv); - $this->data->set("hotbar", $this->hotbar); - - $armor = array(); - foreach($this->armor as $slot => $item){ - if($item instanceof Item){ - $armor[$slot] = array($item->getID(), $item->getMetadata()); - } - } - $this->data->set("armor", $armor); - if($this->entity instanceof Entity){ - $this->data->set("health", $this->entity->getHealth()); - } - $this->data->set("gamemode", $this->gamemode); - } + $this->lastChunk = [$x, $z]; + + $this->server->schedule(MAX_CHUNK_RATE, [$this, "getNextChunk"]); } /** - * @param string $reason Reason for closing connection - * @param boolean $msg Set to false to silently disconnect player. No broadcast. + * @param Vector3 $pos */ - public function close($reason = "", $msg = true){ - if($this->connected === true){ - foreach($this->evid as $ev){ - $this->server->deleteEvent($ev); - } - if($this->username != ""){ - $this->server->api->handle("player.quit", $this); - $this->save(); - } - $reason = $reason == "" ? "server stop":$reason; - $this->sendChat("You have been kicked. Reason: ".$reason."\n"); - $this->sendBuffer(); - $this->directDataPacket(new DisconnectPacket); - $this->connected = false; - $this->level->freeAllChunks($this); - $this->loggedIn = false; - $this->buffer = null; - unset($this->buffer); - $this->recoveryQueue = array(); - $this->receiveQueue = array(); - $this->resendQueue = array(); - $this->ackQueue = array(); - $this->server->api->player->remove($this->CID); - if($msg === true and $this->username != "" and $this->spawned !== false){ - $this->server->api->chat->broadcast($this->username." left the game: ".$reason); - } - $this->spawned = false; - console("[INFO] ".FORMAT_AQUA.$this->username.FORMAT_RESET."[/".$this->ip.":".$this->port."] logged out due to ".$reason); - $this->windows = array(); - $this->armor = array(); - $this->inventory = array(); - $this->chunksLoaded = array(); - $this->chunksOrder = array(); - $this->chunkCount = array(); - $this->cratingItems = array(); - $this->received = array(); + public function setSpawn(Vector3 $pos){ + if(!($pos instanceof Position)){ + $level = $this->level; + }else{ + $level = $pos->level; } + $this->spawnPosition = new Position($pos->x, $pos->y, $pos->z, $level); + $pk = new SetSpawnPositionPacket; + $pk->x = (int) $this->spawnPosition->x; + $pk->y = (int) $this->spawnPosition->y; + $pk->z = (int) $this->spawnPosition->z; + $this->dataPacket($pk); } - /** - * @param Vector3 $pos - * - * @return boolean - */ - public function sleepOn(Vector3 $pos){ - foreach($this->server->api->player->getAll($this->level) as $p){ - if($p->isSleeping instanceof Vector3){ - if($pos->distance($p->isSleeping) <= 0.1){ - return false; - } - } + public function sendInventorySlot($s){ + $this->sendInventory(); + return; + $s = (int) $s; + if(!isset($this->inventory[$s])){ + $pk = new ContainerSetSlotPacket; + $pk->windowid = 0; + $pk->slot = (int) $s; + $pk->item = BlockAPI::getItem(AIR, 0, 0); + $this->dataPacket($pk); } - $this->isSleeping = $pos; - $this->teleport(new Position($pos->x + 0.5, $pos->y + 1, $pos->z + 0.5, $this->level), false, false, false, false); - if($this->entity instanceof Entity){ - $this->entity->updateMetadata(); - } - $this->setSpawn($pos); - $this->server->schedule(60, array($this, "checkSleep")); + + $slot = $this->inventory[$s]; + $pk = new ContainerSetSlotPacket; + $pk->windowid = 0; + $pk->slot = (int) $s; + $pk->item = $slot; + $this->dataPacket($pk); return true; } - - public function stopSleep(){ - $this->isSleeping = false; - if($this->entity instanceof Entity){ - $this->entity->updateMetadata(); + + public function sendInventory(){ + if(($this->gamemode & 0x01) === CREATIVE){ + return; } + $hotbar = []; + foreach($this->hotbar as $slot){ + $hotbar[] = $slot <= -1 ? -1 : $slot + 9; + } + + $pk = new ContainerSetContentPacket; + $pk->windowid = 0; + $pk->slots = $this->inventory; + $pk->hotbar = $hotbar; + $this->dataPacket($pk); } - + public function checkSleep(){ if($this->isSleeping !== false){ if($this->server->api->time->getPhase($this->level) === "night"){ @@ -363,14 +569,14 @@ class Player{ } } - /** - * @param $type - * @param $damage - * @param $count - * - * @return boolean - */ - public function hasSpace($type, $damage, $count){ + /** + * @param $type + * @param $damage + * @param $count + * + * @return boolean + */ + public function hasSpace($type, $damage, $count){ $inv = $this->inventory; while($count > 0){ $add = 0; @@ -396,119 +602,19 @@ class Player{ return true; } - /** - * @param $type - * @param $damage - * @param integer $count - * @param boolean $send - * - * @return boolean - */ - public function addItem($type, $damage, $count, $send = true){ - while($count > 0){ - $add = 0; - foreach($this->inventory as $s => $item){ - if($item->getID() === AIR){ - $add = min($item->getMaxStackSize(), $count); - $this->inventory[$s] = BlockAPI::getItem($type, $damage, $add); - if($send === true){ - $this->sendInventorySlot($s); - } - break; - }elseif($item->getID() === $type and $item->getMetadata() === $damage){ - $add = min($item->getMaxStackSize() - $item->count, $count); - if($add <= 0){ - continue; - } - $item->count += $add; - if($send === true){ - $this->sendInventorySlot($s); - } - break; - } - } - if($add <= 0){ - return false; - } - $count -= $add; - } - return true; - } - - public function removeItem($type, $damage, $count, $send = true){ - while($count > 0){ - $remove = 0; - foreach($this->inventory as $s => $item){ - if($item->getID() === $type and $item->getMetadata() === $damage){ - $remove = min($count, $item->count); - if($remove < $item->count){ - $item->count -= $remove; - }else{ - $this->inventory[$s] = BlockAPI::getItem(AIR, 0, 0); - } - if($send === true){ - $this->sendInventorySlot($s); - } - break; - } - } - if($remove <= 0){ - return false; - } - $count -= $remove; - } - return true; - } - - /** - * @param integer $slot - * @param Item $item - * @param boolean $send - * - * @return boolean - */ - public function setSlot($slot, Item $item, $send = true){ - $this->inventory[(int) $slot] = $item; - if($send === true){ - $this->sendInventorySlot((int) $slot); - } - return true; - } - - /** - * @param integer $slot - * - * @return Item - */ - public function getSlot($slot){ - if(isset($this->inventory[(int) $slot])){ - return $this->inventory[(int) $slot]; + /** + * @param integer $slot + * + * @return Item + */ + public function getArmor($slot){ + if(isset($this->armor[(int) $slot])){ + return $this->armor[(int) $slot]; }else{ return BlockAPI::getItem(AIR, 0, 0); } } - - public function sendInventorySlot($s){ - $this->sendInventory(); - return; - $s = (int) $s; - if(!isset($this->inventory[$s])){ - $pk = new ContainerSetSlotPacket; - $pk->windowid = 0; - $pk->slot = (int) $s; - $pk->item = BlockAPI::getItem(AIR, 0, 0); - $this->dataPacket($pk); - } - - $slot = $this->inventory[$s]; - $pk = new ContainerSetSlotPacket; - $pk->windowid = 0; - $pk->slot = (int) $s; - $pk->item = $slot; - $this->dataPacket($pk); - return true; - } - + public function setArmor($slot, Item $armor, $send = true){ $this->armor[(int) $slot] = $armor; if($send === true){ @@ -517,33 +623,11 @@ class Player{ return true; } - /** - * @param integer $slot - * - * @return Item - */ - public function getArmor($slot){ - if(isset($this->armor[(int) $slot])){ - return $this->armor[(int) $slot]; - }else{ - return BlockAPI::getItem(AIR, 0, 0); - } - } - - public function hasItem($type, $damage = false){ - foreach($this->inventory as $s => $item){ - if($item->getID() === $type and ($item->getMetadata() === $damage or $damage === false) and $item->count > 0){ - return $s; - } - } - return false; - } - - /** - * @param mixed $data - * @param string $event - */ - public function eventHandler($data, $event){ + /** + * @param mixed $data + * @param string $event + */ + public function eventHandler($data, $event){ switch($event){ case "tile.update": if($data->level === $this->level){ @@ -572,7 +656,7 @@ class Player{ if($w === $data["tile"]){ $pk = new ContainerSetSlotPacket; $pk->windowid = $id; - $pk->slot = $data["slot"] + (isset($data["offset"]) ? $data["offset"]:0); + $pk->slot = $data["slot"] + (isset($data["offset"]) ? $data["offset"] : 0); $pk->item = $data["slotdata"]; $this->dataPacket($pk); } @@ -695,11 +779,50 @@ class Player{ } } - /** - * @param string $message - * @param string $author - */ - public function sendChat($message, $author = ""){ + /** + * @param $type + * @param $damage + * @param integer $count + * @param boolean $send + * + * @return boolean + */ + public function addItem($type, $damage, $count, $send = true){ + while($count > 0){ + $add = 0; + foreach($this->inventory as $s => $item){ + if($item->getID() === AIR){ + $add = min($item->getMaxStackSize(), $count); + $this->inventory[$s] = BlockAPI::getItem($type, $damage, $add); + if($send === true){ + $this->sendInventorySlot($s); + } + break; + }elseif($item->getID() === $type and $item->getMetadata() === $damage){ + $add = min($item->getMaxStackSize() - $item->count, $count); + if($add <= 0){ + continue; + } + $item->count += $add; + if($send === true){ + $this->sendInventorySlot($s); + } + break; + } + } + if($add <= 0){ + return false; + } + $count -= $add; + } + return true; + } + + /** + * @param string $message + * @param string $author + */ + public function sendChat($message, $author = ""){ $mes = explode("\n", $message); foreach($mes as $m){ if(preg_match_all('#@([@A-Za-z_]{1,})#', $m, $matches, PREG_OFFSET_CAPTURE) > 0){ @@ -719,16 +842,72 @@ class Player{ } } } - + if($m !== ""){ $pk = new MessagePacket; - $pk->source = ($author instanceof Player) ? $author->username:$author; + $pk->source = ($author instanceof Player) ? $author->username : $author; $pk->message = TextFormat::clean($m); //Colors not implemented :( $this->dataPacket($pk); } } } - + + public function getGamemode(){ + switch($this->gamemode){ + case SURVIVAL: + return "survival"; + case CREATIVE: + return "creative"; + case ADVENTURE: + return "adventure"; + case VIEW: + return "view"; + } + } + + public function setGamemode($gm){ + if($gm < 0 or $gm > 3 or $this->gamemode === $gm){ + return false; + } + + if($this->server->api->dhandle("player.gamemode.change", ["player" => $this, "gamemode" => $gm]) === false){ + return false; + } + + $inv =& $this->inventory; + if($gm === VIEW){ + $this->armor = []; + $this->sendArmor(); + } + if(($this->gamemode & 0x01) === ($gm & 0x01)){ + if(($gm & 0x01) === 0x01 and ($gm & 0x02) === 0x02){ + $inv = []; + foreach(BlockAPI::$creative as $item){ + $inv[] = BlockAPI::getItem(0, 0, 1); + } + }elseif(($gm & 0x01) === 0x01){ + $inv = []; + foreach(BlockAPI::$creative as $item){ + $inv[] = BlockAPI::getItem($item[0], $item[1], 1); + } + } + $this->gamemode = $gm; + $this->sendChat("Your gamemode has been changed to " . $this->getGamemode() . ".\n"); + }else{ + foreach($this->inventory as $slot => $item){ + $inv[$slot] = BlockAPI::getItem(AIR, 0, 0); + } + $this->blocked = true; + $this->gamemode = $gm; + $this->sendChat("Your gamemode has been changed to " . $this->getGamemode() . ", you've to do a forced reconnect.\n"); + $this->server->schedule(30, [$this, "close"], "gamemode change"); //Forces a kick + } + $this->inventory = $inv; + $this->sendSettings(); + $this->sendInventory(); + return true; + } + public function sendSettings($nametags = true){ /* bit mask | flag name @@ -769,301 +948,16 @@ class Player{ if(($this->gamemode & 0x02) === 0x02){ $flags |= 0x01; //Do not allow placing/breaking blocks, adventure mode } - + if($nametags !== false){ $flags |= 0x20; //Show Nametags } - + $pk = new AdventureSettingsPacket; $pk->flags = $flags; $this->dataPacket($pk); } - /** - * @param array $craft - * @param array $recipe - * @param $type - * - * @return array|bool - */ - public function craftItems(array $craft, array $recipe, $type){ - $craftItem = array(0, true, 0); - unset($craft[-1]); - foreach($craft as $slot => $item){ - if($item instanceof Item){ - $craftItem[0] = $item->getID(); - if($item->getMetadata() !== $craftItem[1] and $craftItem[1] !== true){ - $craftItem[1] = false; - }else{ - $craftItem[1] = $item->getMetadata(); - } - $craftItem[2] += $item->count; - } - - } - - $recipeItems = array(); - foreach($recipe as $slot => $item){ - if(!isset($recipeItems[$item->getID()])){ - $recipeItems[$item->getID()] = array($item->getID(), $item->getMetadata(), $item->count); - }else{ - if($item->getMetadata() !== $recipeItems[$item->getID()][1]){ - $recipeItems[$item->getID()][1] = false; - } - $recipeItems[$item->getID()][2] += $item->count; - } - } - - $res = CraftingRecipes::canCraft($craftItem, $recipeItems, $type); - - if(!is_array($res) and $type === 1){ - $res2 = CraftingRecipes::canCraft($craftItem, $recipeItems, 0); - if(is_array($res2)){ - $res = $res2; - } - } - - if(is_array($res)){ - - if($this->server->api->dhandle("player.craft", array("player" => $this, "recipe" => $recipe, "craft" => $craft, "type" => $type)) === false){ - return false; - } - foreach($recipe as $slot => $item){ - $s = $this->getSlot($slot); - $s->count -= $item->count; - if($s->count <= 0){ - $this->setSlot($slot, BlockAPI::getItem(AIR, 0, 0), false); - } - } - foreach($craft as $slot => $item){ - $s = $this->getSlot($slot); - if($s->count <= 0 or $s->getID() === AIR){ - $this->setSlot($slot, BlockAPI::getItem($item->getID(), $item->getMetadata(), $item->count), false); - }else{ - $this->setSlot($slot, BlockAPI::getItem($item->getID(), $item->getMetadata(), $s->count + $item->count), false); - } - console($item->getID()); - switch($item->getID()){ - case WORKBENCH: - AchievementAPI::grantAchievement($this, "buildWorkBench"); - break; - case WOODEN_PICKAXE: - AchievementAPI::grantAchievement($this, "buildPickaxe"); - break; - case FURNACE: - AchievementAPI::grantAchievement($this, "buildFurnace"); - break; - case WOODEN_HOE: - AchievementAPI::grantAchievement($this, "buildHoe"); - break; - case BREAD: - AchievementAPI::grantAchievement($this, "makeBread"); - break; - case CAKE: - AchievementAPI::grantAchievement($this, "bakeCake"); - $this->addItem(BUCKET, 0, 3); - break; - case STONE_PICKAXE: - case GOLDEN_PICKAXE: - case IRON_PICKAXE: - case DIAMOND_PICKAXE: - AchievementAPI::grantAchievement($this, "buildBetterPickaxe"); - break; - case WOODEN_SWORD: - AchievementAPI::grantAchievement($this, "buildSword"); - break; - case DIAMOND: - AchievementAPI::grantAchievement($this, "diamond"); - break; - - } - } - } - return $res; - } - - /** - * @param Vector3 $pos - * @param float|boolean $yaw - * @param float|boolean $pitch - * @param float|boolean $terrain - * @param float|boolean $force - * - * @return boolean - */ - public function teleport(Vector3 $pos, $yaw = false, $pitch = false, $terrain = true, $force = true){ - if($this->entity instanceof Entity and $this->level instanceof Level){ - $this->entity->check = false; - if($yaw === false){ - $yaw = $this->entity->yaw; - } - if($pitch === false){ - $pitch = $this->entity->pitch; - } - if($this->server->api->dhandle("player.teleport", array("player" => $this, "target" => $pos)) === false){ - $this->entity->check = true; - return false; - } - - if($pos instanceof Position and $pos->level instanceof Level and $pos->level !== $this->level){ - if($this->server->api->dhandle("player.teleport.level", array("player" => $this, "origin" => $this->level, "target" => $pos->level)) === false){ - $this->entity->check = true; - return false; - } - - foreach($this->server->api->entity->getAll($this->level) as $e){ - if($e !== $this->entity){ - if($e->player instanceof Player){ - $pk = new MoveEntityPacket_PosRot; - $pk->eid = $this->entity->eid; - $pk->x = -256; - $pk->y = 128; - $pk->z = -256; - $pk->yaw = 0; - $pk->pitch = 0; - $e->player->dataPacket($pk); - - $pk = new MoveEntityPacket_PosRot; - $pk->eid = $e->eid; - $pk->x = -256; - $pk->y = 128; - $pk->z = -256; - $pk->yaw = 0; - $pk->pitch = 0; - $this->dataPacket($pk); - }else{ - $pk = new RemoveEntityPacket; - $pk->eid = $e->eid; - $this->dataPacket($pk); - } - } - } - - $this->level->freeAllChunks($this); - $this->level = $pos->level; - $this->chunksLoaded = array(); - $this->server->api->entity->spawnToAll($this->entity); - $this->server->api->entity->spawnAll($this); - - $pk = new SetTimePacket; - $pk->time = $this->level->getTime(); - $this->dataPacket($pk); - $terrain = true; - - foreach($this->server->api->player->getAll($this->level) as $player){ - if($player !== $this and $player->entity instanceof Entity){ - $pk = new MoveEntityPacket_PosRot; - $pk->eid = $player->entity->eid; - $pk->x = $player->entity->x; - $pk->y = $player->entity->y; - $pk->z = $player->entity->z; - $pk->yaw = $player->entity->yaw; - $pk->pitch = $player->entity->pitch; - $this->dataPacket($pk); - - $pk = new PlayerEquipmentPacket; - $pk->eid = $this->eid; - $pk->item = $this->getSlot($this->slot)->getID(); - $pk->meta = $this->getSlot($this->slot)->getMetadata(); - $pk->slot = 0; - $player->dataPacket($pk); - $this->sendArmor($player); - - $pk = new PlayerEquipmentPacket; - $pk->eid = $player->eid; - $pk->item = $player->getSlot($player->slot)->getID(); - $pk->meta = $player->getSlot($player->slot)->getMetadata(); - $pk->slot = 0; - $this->dataPacket($pk); - $player->sendArmor($this); - } - } - } - - $this->lastCorrect = $pos; - $this->entity->fallY = false; - $this->entity->fallStart = false; - $this->entity->setPosition($pos, $yaw, $pitch); - $this->entity->resetSpeed(); - $this->entity->updateLast(); - $this->entity->calculateVelocity(); - if($terrain === true){ - $this->orderChunks(); - $this->getNextChunk(); - } - $this->entity->check = true; - if($force === true){ - $this->forceMovement = $pos; - } - } - - $pk = new MovePlayerPacket; - $pk->eid = 0; - $pk->x = $pos->x; - $pk->y = $pos->y; - $pk->z = $pos->z; - $pk->bodyYaw = $yaw; - $pk->pitch = $pitch; - $pk->yaw = $yaw; - $this->dataPacket($pk); - } - - public function getGamemode(){ - switch($this->gamemode){ - case SURVIVAL: - return "survival"; - case CREATIVE: - return "creative"; - case ADVENTURE: - return "adventure"; - case VIEW: - return "view"; - } - } - - public function setGamemode($gm){ - if($gm < 0 or $gm > 3 or $this->gamemode === $gm){ - return false; - } - - if($this->server->api->dhandle("player.gamemode.change", array("player" => $this, "gamemode" => $gm)) === false){ - return false; - } - - $inv =& $this->inventory; - if($gm === VIEW){ - $this->armor = array(); - $this->sendArmor(); - } - if(($this->gamemode & 0x01) === ($gm & 0x01)){ - if(($gm & 0x01) === 0x01 and ($gm & 0x02) === 0x02){ - $inv = array(); - foreach(BlockAPI::$creative as $item){ - $inv[] = BlockAPI::getItem(0, 0, 1); - } - }elseif(($gm & 0x01) === 0x01){ - $inv = array(); - foreach(BlockAPI::$creative as $item){ - $inv[] = BlockAPI::getItem($item[0], $item[1], 1); - } - } - $this->gamemode = $gm; - $this->sendChat("Your gamemode has been changed to ".$this->getGamemode().".\n"); - }else{ - foreach($this->inventory as $slot => $item){ - $inv[$slot] = BlockAPI::getItem(AIR, 0, 0); - } - $this->blocked = true; - $this->gamemode = $gm; - $this->sendChat("Your gamemode has been changed to ".$this->getGamemode().", you've to do a forced reconnect.\n"); - $this->server->schedule(30, array($this, "close"), "gamemode change"); //Forces a kick - } - $this->inventory = $inv; - $this->sendSettings(); - $this->sendInventory(); - return true; - } - public function measureLag(){ if($this->connected === false){ return false; @@ -1073,24 +967,24 @@ class Player{ }else{ $this->packetLoss = 0; } - $this->packetStats = array(0, 0); + $this->packetStats = [0, 0]; array_shift($this->bandwidthStats); $this->bandwidthStats[] = $this->bandwidthRaw / max(0.00001, microtime(true) - $this->lastMeasure); $this->bandwidthRaw = 0; $this->lagStat = array_sum($this->lag) / max(1, count($this->lag)); - $this->lag = array(); + $this->lag = []; $this->sendBuffer(); $this->lastMeasure = microtime(true); } - + public function getLag(){ return $this->lagStat * 1000; } - + public function getPacketLoss(){ return $this->packetLoss; } - + public function getBandwidth(){ return array_sum($this->bandwidthStats) / max(1, count($this->bandwidthStats)); } @@ -1110,7 +1004,7 @@ class Player{ } } } - + public function handlePacketQueues(){ if($this->connected === false){ return false; @@ -1127,7 +1021,7 @@ class Player{ $packetCnt = (int) ($ackCnt / $safeCount + 1); for($p = 0; $p < $packetCnt; ++$p){ $pk = new RakNetPacket(RakNetInfo::ACK); - $pk->packets = array(); + $pk->packets = []; for($c = 0; $c < $safeCount; ++$c){ if(($k = array_pop($this->ackQueue)) === null){ break; @@ -1136,9 +1030,9 @@ class Player{ } $this->send($pk); } - $this->ackQueue = array(); + $this->ackQueue = []; } - + if(($receiveCnt = count($this->receiveQueue)) > 0){ ksort($this->receiveQueue); foreach($this->receiveQueue as $count => $packets){ @@ -1175,7 +1069,7 @@ class Player{ if($this->nextBuffer <= $time and $this->bufferLen > 0){ $this->sendBuffer(); } - + $limit = $time - 5; //max lag foreach($this->recoveryQueue as $count => $data){ if($data->sendtime > $limit){ @@ -1186,7 +1080,7 @@ class Player{ } if(($resendCnt = count($this->resendQueue)) > 0){ - foreach($this->resendQueue as $count => $data){ + foreach($this->resendQueue as $count => $data){ unset($this->resendQueue[$count]); $this->packetStats[1]++; $this->lag[] = microtime(true) - $data->sendtime; @@ -1195,73 +1089,126 @@ class Player{ if(isset($this->chunkCount[$count])){ unset($this->chunkCount[$count]); if(!is_null($cnt) and !is_null($cnt[0])) - $this->chunkCount[$cnt[0]] = true; + $this->chunkCount[$cnt[0]] = true; } } } } - - public function handlePacket(RakNetPacket $packet){ + + /** + * @param string $reason Reason for closing connection + * @param boolean $msg Set to false to silently disconnect player. No broadcast. + */ + public function close($reason = "", $msg = true){ if($this->connected === true){ - $this->timeout = microtime(true) + 20; - switch($packet->pid()){ - case RakNetInfo::NACK: - foreach($packet->packets as $count){ - if(isset($this->recoveryQueue[$count])){ - $this->resendQueue[$count] =& $this->recoveryQueue[$count]; - $this->lag[] = microtime(true) - $this->recoveryQueue[$count]->sendtime; - unset($this->recoveryQueue[$count]); - } - ++$this->packetStats[1]; - } - break; - - case RakNetInfo::ACK: - foreach($packet->packets as $count){ - if(isset($this->recoveryQueue[$count])){ - $this->lag[] = microtime(true) - $this->recoveryQueue[$count]->sendtime; - unset($this->recoveryQueue[$count]); - unset($this->resendQueue[$count]); - } - ++$this->packetStats[0]; - } - break; - - case RakNetInfo::DATA_PACKET_0: - case RakNetInfo::DATA_PACKET_1: - case RakNetInfo::DATA_PACKET_2: - case RakNetInfo::DATA_PACKET_3: - case RakNetInfo::DATA_PACKET_4: - case RakNetInfo::DATA_PACKET_5: - case RakNetInfo::DATA_PACKET_6: - case RakNetInfo::DATA_PACKET_7: - case RakNetInfo::DATA_PACKET_8: - case RakNetInfo::DATA_PACKET_9: - case RakNetInfo::DATA_PACKET_A: - case RakNetInfo::DATA_PACKET_B: - case RakNetInfo::DATA_PACKET_C: - case RakNetInfo::DATA_PACKET_D: - case RakNetInfo::DATA_PACKET_E: - case RakNetInfo::DATA_PACKET_F: - $this->ackQueue[] = $packet->seqNumber; - $this->receiveQueue[$packet->seqNumber] = array(); - foreach($packet->data as $pk){ - $this->receiveQueue[$packet->seqNumber][] = $pk; - } - break; + foreach($this->evid as $ev){ + $this->server->deleteEvent($ev); } + if($this->username != ""){ + $this->server->api->handle("player.quit", $this); + $this->save(); + } + $reason = $reason == "" ? "server stop" : $reason; + $this->sendChat("You have been kicked. Reason: " . $reason . "\n"); + $this->sendBuffer(); + $this->directDataPacket(new DisconnectPacket); + $this->connected = false; + $this->level->freeAllChunks($this); + $this->loggedIn = false; + $this->buffer = null; + unset($this->buffer); + $this->recoveryQueue = []; + $this->receiveQueue = []; + $this->resendQueue = []; + $this->ackQueue = []; + $this->server->api->player->remove($this->CID); + if($msg === true and $this->username != "" and $this->spawned !== false){ + $this->server->api->chat->broadcast($this->username . " left the game: " . $reason); + } + $this->spawned = false; + console("[INFO] " . FORMAT_AQUA . $this->username . FORMAT_RESET . "[/" . $this->ip . ":" . $this->port . "] logged out due to " . $reason); + $this->windows = []; + $this->armor = []; + $this->inventory = []; + $this->chunksLoaded = []; + $this->chunksOrder = []; + $this->chunkCount = []; + $this->cratingItems = []; + $this->received = []; } } + public function save(){ + if($this->entity instanceof Entity){ + $this->data->set("achievements", $this->achievements); + $this->data->set("position", [ + "level" => $this->entity->level->getName(), + "x" => (float) $this->entity->x, + "y" => $this->entity->y, + "z" => (float) $this->entity->z, + ]); + $this->data->set("spawn", [ + "level" => $this->spawnPosition->level->getName(), + "x" => $this->spawnPosition->x, + "y" => $this->spawnPosition->y, + "z" => $this->spawnPosition->z, + ]); + $inv = []; + foreach($this->inventory as $slot => $item){ + if($item instanceof Item){ + if($slot < (($this->gamemode & 0x01) === 0 ? PLAYER_SURVIVAL_SLOTS : PLAYER_CREATIVE_SLOTS)){ + $inv[$slot] = [$item->getID(), $item->getMetadata(), $item->count]; + } + } + } + $this->data->set("inventory", $inv); + $this->data->set("hotbar", $this->hotbar); + + $armor = []; + foreach($this->armor as $slot => $item){ + if($item instanceof Item){ + $armor[$slot] = [$item->getID(), $item->getMetadata()]; + } + } + $this->data->set("armor", $armor); + if($this->entity instanceof Entity){ + $this->data->set("health", $this->entity->getHealth()); + } + $this->data->set("gamemode", $this->gamemode); + } + } + + public function directDataPacket(RakNetDataPacket $packet, $reliability = 0, $recover = true){ + if($this->connected === false){ + return false; + } + + if(EventHandler::callEvent(new DataPacketSendEvent($this, $packet)) === BaseEvent::DENY){ + return []; + } + + $packet->encode(); + $pk = new RakNetPacket(RakNetInfo::DATA_PACKET_0); + $pk->data[] = $packet; + $pk->seqNumber = $this->counter[0]++; + $pk->sendtime = microtime(true); + if($recover !== false){ + $this->recoveryQueue[$pk->seqNumber] = $pk; + } + + $this->send($pk); + return [$pk->seqNumber]; + } + public function handleDataPacket(RakNetDataPacket $packet){ if($this->connected === false){ return; } - + if(EventHandler::callEvent(new DataPacketReceiveEvent($this, $packet)) === BaseEvent::DENY){ return; } - + switch($packet->pid()){ case 0x01: break; @@ -1297,7 +1244,7 @@ class Player{ } $this->username = $packet->username; $this->iusername = strtolower($this->username); - $this->loginData = array("clientId" => $packet->clientId, "loginData" => $packet->loginData); + $this->loginData = ["clientId" => $packet->clientId, "loginData" => $packet->loginData]; if(count($this->server->clients) > $this->server->maxClients and !$this->server->api->ban->isOp($this->iusername)){ $this->close("server is full!", false); return; @@ -1312,7 +1259,7 @@ class Player{ $pk->status = 2; $this->directDataPacket($pk); } - $this->close("Incorrect protocol #".$packet->protocol1, false); + $this->close("Incorrect protocol #" . $packet->protocol1, false); return; } if(preg_match('#[^a-zA-Z0-9_]#', $this->username) > 0 or $this->username === "" or $this->iusername === "rcon" or $this->iusername === "console" or $this->iusername === "server"){ @@ -1323,7 +1270,7 @@ class Player{ $this->close("Unknown reason", false); return; } - + if($this->server->whitelist === true and !$this->server->api->ban->inWhitelist($this->iusername)){ $this->close("Server is white-listed", false); return; @@ -1332,9 +1279,9 @@ class Player{ return; } $this->loggedIn = true; - + if(!isset($this->CID) or $this->CID == null){ - console("[DEBUG] Player ".$this->username." does not have a CID", true, true, 2); + console("[DEBUG] Player " . $this->username . " does not have a CID", true, true, 2); $this->CID = Utils::readLong(Utils::getRandomBytes(8, false)); } $u = $this->server->api->player->get($this->iusername, false); @@ -1348,25 +1295,25 @@ class Player{ $this->close("join cancelled", false); return; } - + if(!($this->data instanceof Config)){ $this->close("no config created", false); return; } - - $this->server->send2Discord($this->username." joined the game"); - + + $this->server->send2Discord($this->username . " joined the game"); + $this->auth = true; if(!$this->data->exists("inventory") or ($this->gamemode & 0x01) === 0x01){ if(($this->gamemode & 0x01) === 0x01){ - $inv = array(); + $inv = []; if(($this->gamemode & 0x02) === 0x02){ foreach(BlockAPI::$creative as $item){ - $inv[] = array(0, 0, 1); + $inv[] = [0, 0, 1]; } }else{ foreach(BlockAPI::$creative as $item){ - $inv[] = array($item[0], $item[1], 1); + $inv[] = [$item[0], $item[1], 1]; } } } @@ -1374,19 +1321,19 @@ class Player{ } $this->achievements = $this->data->get("achievements"); $this->data->set("caseusername", $this->username); - $this->inventory = array(); + $this->inventory = []; foreach($this->data->get("inventory") as $slot => $item){ if(!is_array($item) or count($item) < 3){ - $item = array(AIR, 0, 0); + $item = [AIR, 0, 0]; } $this->inventory[$slot] = BlockAPI::getItem($item[0], $item[1], $item[2]); } - $this->armor = array(); + $this->armor = []; foreach($this->data->get("armor") as $slot => $item){ - $this->armor[$slot] = BlockAPI::getItem($item[0], $item[1], $item[0] === 0 ? 0:1); + $this->armor[$slot] = BlockAPI::getItem($item[0], $item[1], $item[0] === 0 ? 0 : 1); } - + $this->data->set("lastIP", $this->ip); $this->data->set("lastID", $this->clientID); @@ -1396,7 +1343,7 @@ class Player{ $pk = new LoginStatusPacket; $pk->status = 0; $this->dataPacket($pk); - + $pk = new StartGamePacket; $pk->seed = $this->level->getSeed(); $pk->x = $this->data->get("position")["x"]; @@ -1406,26 +1353,26 @@ class Player{ $pk->gamemode = $this->gamemode & 0x01; $pk->eid = 0; $this->dataPacket($pk); - + if(($this->gamemode & 0x01) === 0x01){ $this->slot = 0; - $this->hotbar = array(); + $this->hotbar = []; }elseif($this->data->exists("hotbar")){ $this->hotbar = $this->data->get("hotbar"); $this->slot = $this->hotbar[0]; }else{ $this->slot = -1;//0 - $this->hotbar = array(-1, -1, -1, -1, -1, -1, -1, -1, -1); + $this->hotbar = [-1, -1, -1, -1, -1, -1, -1, -1, -1]; } - $this->entity = $this->server->api->entity->add($this->level, ENTITY_PLAYER, 0, array("player" => $this)); + $this->entity = $this->server->api->entity->add($this->level, ENTITY_PLAYER, 0, ["player" => $this]); $this->eid = $this->entity->eid; - $this->server->query("UPDATE players SET EID = ".$this->eid." WHERE CID = ".$this->CID.";"); + $this->server->query("UPDATE players SET EID = " . $this->eid . " WHERE CID = " . $this->CID . ";"); $this->entity->x = $this->data->get("position")["x"]; $this->entity->y = $this->data->get("position")["y"]; $this->entity->z = $this->data->get("position")["z"]; if(($level = $this->server->api->level->get($this->data->get("spawn")["level"])) !== false){ $this->spawnPosition = new Position($this->data->get("spawn")["x"], $this->data->get("spawn")["y"], $this->data->get("spawn")["z"], $level); - + $pk = new SetSpawnPositionPacket; $pk->x = (int) $this->spawnPosition->x; $pk->y = (int) $this->spawnPosition->y; @@ -1435,19 +1382,19 @@ class Player{ $this->entity->check = false; $this->entity->setName($this->username); $this->entity->data["CID"] = $this->CID; - $this->evid[] = $this->server->event("server.chat", array($this, "eventHandler")); - $this->evid[] = $this->server->event("entity.motion", array($this, "eventHandler")); - $this->evid[] = $this->server->event("entity.animate", array($this, "eventHandler")); - $this->evid[] = $this->server->event("entity.event", array($this, "eventHandler")); - $this->evid[] = $this->server->event("entity.metadata", array($this, "eventHandler")); - $this->evid[] = $this->server->event("player.equipment.change", array($this, "eventHandler")); - $this->evid[] = $this->server->event("player.armor", array($this, "eventHandler")); - $this->evid[] = $this->server->event("player.pickup", array($this, "eventHandler")); - $this->evid[] = $this->server->event("tile.container.slot", array($this, "eventHandler")); - $this->evid[] = $this->server->event("tile.update", array($this, "eventHandler")); + $this->evid[] = $this->server->event("server.chat", [$this, "eventHandler"]); + $this->evid[] = $this->server->event("entity.motion", [$this, "eventHandler"]); + $this->evid[] = $this->server->event("entity.animate", [$this, "eventHandler"]); + $this->evid[] = $this->server->event("entity.event", [$this, "eventHandler"]); + $this->evid[] = $this->server->event("entity.metadata", [$this, "eventHandler"]); + $this->evid[] = $this->server->event("player.equipment.change", [$this, "eventHandler"]); + $this->evid[] = $this->server->event("player.armor", [$this, "eventHandler"]); + $this->evid[] = $this->server->event("player.pickup", [$this, "eventHandler"]); + $this->evid[] = $this->server->event("tile.container.slot", [$this, "eventHandler"]); + $this->evid[] = $this->server->event("tile.update", [$this, "eventHandler"]); $this->lastMeasure = microtime(true); - $this->server->schedule(50, array($this, "measureLag"), array(), true); - console("[INFO] ".FORMAT_AQUA.$this->username.FORMAT_RESET."[/".$this->ip.":".$this->port."] logged in with entity id ".$this->eid." at (".$this->entity->level->getName().", ".round($this->entity->x, 2).", ".round($this->entity->y, 2).", ".round($this->entity->z, 2).")"); + $this->server->schedule(50, [$this, "measureLag"], [], true); + console("[INFO] " . FORMAT_AQUA . $this->username . FORMAT_RESET . "[/" . $this->ip . ":" . $this->port . "] logged in with entity id " . $this->eid . " at (" . $this->entity->level->getName() . ", " . round($this->entity->x, 2) . ", " . round($this->entity->y, 2) . ", " . round($this->entity->z, 2) . ")"); break; case ProtocolInfo::READY_PACKET: if($this->loggedIn === false){ @@ -1459,32 +1406,32 @@ class Player{ break; } $this->entity->setHealth($this->data->get("health"), "spawn", true); - $this->spawned = true; + $this->spawned = true; $this->server->api->player->spawnAllPlayers($this); $this->server->api->player->spawnToAllPlayers($this); $this->server->api->entity->spawnAll($this); $this->server->api->entity->spawnToAll($this->entity); - - $this->server->schedule(5, array($this->entity, "update"), array(), true); - $this->server->schedule(2, array($this->entity, "updateMovement"), array(), true); + + $this->server->schedule(5, [$this->entity, "update"], [], true); + $this->server->schedule(2, [$this->entity, "updateMovement"], [], true); $this->sendArmor(); - $this->sendChat($this->server->motd."\n"); - + $this->sendChat($this->server->motd . "\n"); + $this->sendInventory(); $this->sendSettings(); - $this->server->schedule(50, array($this, "orderChunks"), array(), true); + $this->server->schedule(50, [$this, "orderChunks"], [], true); $this->blocked = false; - + $pk = new SetTimePacket; $pk->time = $this->level->getTime(); $this->dataPacket($pk); - + $pos = new Position($this->data->get("position")["x"], $this->data->get("position")["y"], $this->data->get("position")["z"], $this->level); $pos = $this->level->getSafeSpawn($pos); $this->teleport($pos); - $this->server->schedule(10, array($this, "teleport"), $pos); - $this->server->schedule(20, array($this, "teleport"), $pos); - $this->server->schedule(30, array($this, "teleport"), $pos); + $this->server->schedule(10, [$this, "teleport"], $pos); + $this->server->schedule(20, [$this, "teleport"], $pos); + $this->server->schedule(30, [$this, "teleport"], $pos); $this->server->handle("player.spawn", $this); break; case 2://Chunk loaded? @@ -1528,11 +1475,11 @@ class Player{ break; } $packet->eid = $this->eid; - - $data = array(); + + $data = []; $data["eid"] = $packet->eid; $data["player"] = $this; - + if($packet->slot === 0x28 or $packet->slot === 0){ //0 for 0.8.0 compatibility $data["slot"] = -1; $data["item"] = BlockAPI::getItem(AIR, 0, 0); @@ -1543,8 +1490,8 @@ class Player{ }else{ $packet->slot -= 9; } - - + + if(($this->gamemode & 0x01) === SURVIVAL){ $data["item"] = $this->getSlot($packet->slot); if(!($data["item"] instanceof Item)){ @@ -1565,9 +1512,9 @@ class Player{ }else{ break;//????? } - + $data["slot"] = $packet->slot; - + if($this->server->handle("player.equipment.change", $data) !== false){ $this->slot = $packet->slot; if(($this->gamemode & 0x01) === SURVIVAL){ @@ -1593,11 +1540,11 @@ class Player{ } $blockVector = new Vector3($packet->x, $packet->y, $packet->z); - + if(($this->spawned === false or $this->blocked === true) and $packet->face >= 0 and $packet->face <= 5){ $target = $this->level->getBlock($blockVector); $block = $target->getSide($packet->face); - + $pk = new UpdateBlockPacket; $pk->x = $target->x; $pk->y = $target->y; @@ -1605,7 +1552,7 @@ class Player{ $pk->block = $target->getID(); $pk->meta = $target->getMetadata(); $this->dataPacket($pk); - + $pk = new UpdateBlockPacket; $pk->x = $block->x; $pk->y = $block->y; @@ -1615,10 +1562,10 @@ class Player{ $this->dataPacket($pk); break; } - $this->craftingItems = array(); - $this->toCraft = array(); + $this->craftingItems = []; + $this->toCraft = []; $packet->eid = $this->eid; - $data = array(); + $data = []; $data["eid"] = $packet->eid; $data["player"] = $this; $data["face"] = $packet->face; @@ -1639,9 +1586,9 @@ class Player{ $this->entity->inAction = false; $this->entity->updateMetadata(); } - + if($this->blocked === true or ($this->entity->position instanceof Vector3 and $blockVector->distance($this->entity->position) > 10)){ - + }elseif($this->getSlot($this->slot)->getID() !== $packet->item or ($this->getSlot($this->slot)->isTool() === false and $this->getSlot($this->slot)->getMetadata() !== $packet->meta)){ $this->sendInventorySlot($this->slot); }else{ @@ -1650,7 +1597,7 @@ class Player{ } $target = $this->level->getBlock($blockVector); $block = $target->getSide($packet->face); - + $pk = new UpdateBlockPacket; $pk->x = $target->x; $pk->y = $target->y; @@ -1658,7 +1605,7 @@ class Player{ $pk->block = $target->getID(); $pk->meta = $target->getMetadata(); $this->dataPacket($pk); - + $pk = new UpdateBlockPacket; $pk->x = $block->x; $pk->y = $block->y; @@ -1678,22 +1625,22 @@ class Player{ break; } $packet->eid = $this->eid; - $this->craftingItems = array(); - $this->toCraft = array(); - + $this->craftingItems = []; + $this->toCraft = []; + switch($packet->action){ case 5: //Shot arrow if($this->entity->inAction === true){ if($this->getSlot($this->slot)->getID() === BOW){ if($this->startAction !== false){ $time = microtime(true) - $this->startAction; - $d = array( + $d = [ "x" => $this->entity->x, "y" => $this->entity->y + 1.6, "z" => $this->entity->z, "yaw" => $this->entity->yaw, "pitch" => $this->entity->pitch - ); + ]; $e = $this->server->api->entity->add($this->level, ENTITY_OBJECT, OBJECT_ARROW, $d); $e->speedX = -sin(($e->yaw / 180) * M_PI) * cos(($e->pitch / 180) * M_PI); $e->speedZ = cos(($e->yaw / 180) * M_PI) * cos(($e->pitch / 180) * M_PI); @@ -1715,7 +1662,7 @@ class Player{ $blockVector = new Vector3($packet->x, $packet->y, $packet->z); if($this->spawned === false or $this->blocked === true or $this->entity->distance($blockVector) > 8){ $target = $this->level->getBlock($blockVector); - + $pk = new UpdateBlockPacket; $pk->x = $target->x; $pk->y = $target->y; @@ -1725,16 +1672,16 @@ class Player{ $this->dataPacket($pk); break; } - $this->craftingItems = array(); - $this->toCraft = array(); + $this->craftingItems = []; + $this->toCraft = []; $this->server->api->block->playerBlockBreak($this, $blockVector); break; case ProtocolInfo::PLAYER_ARMOR_EQUIPMENT_PACKET: if($this->spawned === false or $this->blocked === true){ break; } - $this->craftingItems = array(); - $this->toCraft = array(); + $this->craftingItems = []; + $this->toCraft = []; $packet->eid = $this->eid; for($i = 0; $i < 4; ++$i){ @@ -1760,7 +1707,7 @@ class Player{ $packet->slots[$i] = 255; } - } + } $this->sendArmor(); if($this->entity->inAction === true){ $this->entity->inAction = false; @@ -1773,12 +1720,12 @@ class Player{ } $needsBreak = false; $packet->eid = $this->eid; - $data = array(); + $data = []; $data["target"] = $packet->target; $data["eid"] = $packet->eid; $data["action"] = $packet->action; - $this->craftingItems = array(); - $this->toCraft = array(); + $this->craftingItems = []; + $this->toCraft = []; $target = $this->server->api->entity->get($packet->target); if($target instanceof Entity and $this->entity instanceof Entity and $this->gamemode !== VIEW and $this->blocked === false and ($target instanceof Entity) and $this->entity->distance($target) <= 8){ $data["targetentity"] = $target; @@ -1797,7 +1744,7 @@ class Player{ $pk->riding = $this->entity->eid; $pk->type = 2; $this->server->api->player->broadcastPacket([$this], $pk); - + $target->linkedEntity = $this->entity; $this->entity->isInMinecart = true; $pk = new SetEntityLinkPacket(); @@ -1806,7 +1753,7 @@ class Player{ $pk->type = 2; $this->dataPacket($pk); $needsBreak = true; - + } case ENTITY_MOB: $slot = $this->getSlot($this->slot); @@ -1820,7 +1767,7 @@ class Player{ break; case MOB_SHEEP: if($slot->getID() === SHEARS && $target->data["Sheared"] === 0){ //not sheared - ServerAPI::request()->api->entity->drop(new Position($target->x + 0.5, $target->y, $target->z + 0.5, $target->level), BlockAPI::getItem(WOOL, $target->data["Color"], mt_rand(1,3))); + ServerAPI::request()->api->entity->drop(new Position($target->x + 0.5, $target->y, $target->z + 0.5, $target->level), BlockAPI::getItem(WOOL, $target->data["Color"], mt_rand(1, 3))); $target->data["Sheared"] = 1; //i hope it means sheared right? $target->updateMetadata(); if($slot->getMetadata() >= $slot->getMaxDurability()){ @@ -1838,8 +1785,8 @@ class Player{ case OBJECT_MINECART: $players = $this->server->api->player->getAll($this->level); $pk = new SetEntityLinkPacket(); - $pk->rider = targetEntity.getId(); - $pk->riding = this.id; + $pk->rider = targetEntity . getId(); + $pk->riding = this . id; $pk->type = 3; $this->server->api->player->broadcastPacket([$this], $pk); $this->entity->isInMinecart = false; @@ -1873,7 +1820,7 @@ class Player{ case DIAMOND_SWORD: $damage = 10; break; - + case WOODEN_AXE: case GOLDEN_AXE: $damage = 3; @@ -1927,14 +1874,14 @@ class Player{ } } } - + break; case ProtocolInfo::ANIMATE_PACKET: if($this->spawned === false){ break; } $packet->eid = $this->eid; - $this->server->api->dhandle("entity.animate", array("eid" => $packet->eid, "entity" => $this->entity, "action" => $packet->action)); + $this->server->api->dhandle("entity.animate", ["eid" => $packet->eid, "entity" => $this->entity, "action" => $packet->action]); break; case ProtocolInfo::RESPAWN_PACKET: if($this->spawned === false){ @@ -1943,8 +1890,8 @@ class Player{ if(@$this->entity->dead === false){ break; } - $this->craftingItems = array(); - $this->toCraft = array(); + $this->craftingItems = []; + $this->toCraft = []; $this->teleport($this->spawnPosition); if($this->entity instanceof Entity){ $this->entity->fire = 0; @@ -1964,8 +1911,8 @@ class Player{ if($this->spawned === false or $this->blocked === true){ break; } - $this->craftingItems = array(); - $this->toCraft = array(); + $this->craftingItems = []; + $this->toCraft = []; $packet->eid = $this->eid; if($this->entity->inAction === true){ $this->entity->inAction = false; @@ -1973,7 +1920,7 @@ class Player{ } switch($packet->event){ case 9: //Eating - $items = array( + $items = [ APPLE => 4, MUSHROOM_STEW => 10, BEETROOT_SOUP => 10, @@ -1990,15 +1937,15 @@ class Player{ CARROT => 4, POTATO => 1, BAKED_POTATO => 6, - ); + ]; $slot = $this->getSlot($this->slot); if($this->entity->getHealth() < 20 and isset($items[$slot->getID()])){ - + $pk = new EntityEventPacket; $pk->eid = 0; - $pk->event = 9; + $pk->event = 9; $this->dataPacket($pk); - + $this->entity->heal($items[$slot->getID()], "eating"); --$slot->count; if($slot->count <= 0){ @@ -2017,8 +1964,8 @@ class Player{ } $packet->eid = $this->eid; $packet->item = $this->getSlot($this->slot); - $this->craftingItems = array(); - $this->toCraft = array(); + $this->craftingItems = []; + $this->toCraft = []; $data["eid"] = $packet->eid; $data["unknown"] = $packet->unknown; $data["item"] = $packet->item; @@ -2036,19 +1983,19 @@ class Player{ if($this->spawned === false){ break; } - $this->craftingItems = array(); - $this->toCraft = array(); + $this->craftingItems = []; + $this->toCraft = []; if(trim($packet->message) != "" and strlen($packet->message) <= 255){ $message = $packet->message; if($message[0] === "/"){ //Command if($this instanceof Player){ - console("[DEBUG] ".FORMAT_AQUA.$this->username.FORMAT_RESET." issued server command: ".$message); + console("[DEBUG] " . FORMAT_AQUA . $this->username . FORMAT_RESET . " issued server command: " . $message); }else{ - console("[DEBUG] ".FORMAT_YELLOW."*".$this.FORMAT_RESET." issued server command: ".$message); + console("[DEBUG] " . FORMAT_YELLOW . "*" . $this . FORMAT_RESET . " issued server command: " . $message); } $this->server->api->console->run(substr($message, 1), $this); }else{ - $data = array("player" => $this, "message" => $message); + $data = ["player" => $this, "message" => $message]; if($this->server->api->handle("player.chat", $data) !== false){ $this->server->send2Discord("<" . $this->username . "> " . $message); if(isset($data["message"])){ @@ -2064,8 +2011,8 @@ class Player{ if($this->spawned === false){ break; } - $this->craftingItems = array(); - $this->toCraft = array(); + $this->craftingItems = []; + $this->toCraft = []; if(isset($this->windows[$packet->windowid])){ if(is_array($this->windows[$packet->windowid])){ foreach($this->windows[$packet->windowid] as $ob){ @@ -2100,13 +2047,13 @@ class Player{ if($this->lastCraft <= (microtime(true) - 1)){ if(isset($this->toCraft[-1])){ - $this->toCraft = array(-1 => $this->toCraft[-1]); + $this->toCraft = [-1 => $this->toCraft[-1]]; }else{ - $this->toCraft = array(); + $this->toCraft = []; } - $this->craftingItems = array(); + $this->craftingItems = []; } - + if($packet->windowid === 0){ $craft = false; $slot = $this->getSlot($packet->slot); @@ -2131,7 +2078,7 @@ class Player{ $this->toCraft[$packet->slot] = $craftItem; $craft = true; } - + if($craft === true){ $this->lastCraft = microtime(true); } @@ -2139,15 +2086,15 @@ class Player{ if($craft === true and count($this->craftingItems) > 0 and count($this->toCraft) > 0 and ($recipe = $this->craftItems($this->toCraft, $this->craftingItems, $this->toCraft[-1])) !== true){ if($recipe === false){ $this->sendInventory(); - $this->toCraft = array(); + $this->toCraft = []; }else{ - $this->toCraft = array(-1 => $this->toCraft[-1]); + $this->toCraft = [-1 => $this->toCraft[-1]]; } - $this->craftingItems = array(); + $this->craftingItems = []; } }else{ - $this->toCraft = array(); - $this->craftingItems = array(); + $this->toCraft = []; + $this->craftingItems = []; } if(!isset($this->windows[$packet->windowid])){ break; @@ -2168,16 +2115,16 @@ class Player{ } $item = BlockAPI::getItem($packet->item->getID(), $packet->item->getMetadata(), $packet->item->count); - + $slot = $tile->getSlot($slotn); - if($this->server->api->dhandle("player.container.slot", array( - "tile" => $tile, - "slot" => $packet->slot, - "offset" => $offset, - "slotdata" => $slot, - "itemdata" => $item, - "player" => $this, - )) === false){ + if($this->server->api->dhandle("player.container.slot", [ + "tile" => $tile, + "slot" => $packet->slot, + "offset" => $offset, + "slotdata" => $slot, + "itemdata" => $item, + "player" => $this, + ]) === false){ $pk = new ContainerSetSlotPacket; $pk->windowid = $packet->windowid; $pk->slot = $packet->slot; @@ -2206,15 +2153,15 @@ class Player{ break; } $item = BlockAPI::getItem($packet->item->getID(), $packet->item->getMetadata(), $packet->item->count); - + $slot = $tile->getSlot($packet->slot); - if($this->server->api->dhandle("player.container.slot", array( - "tile" => $tile, - "slot" => $packet->slot, - "slotdata" => $slot, - "itemdata" => $item, - "player" => $this, - )) === false){ + if($this->server->api->dhandle("player.container.slot", [ + "tile" => $tile, + "slot" => $packet->slot, + "slotdata" => $slot, + "itemdata" => $item, + "player" => $this, + ]) === false){ $pk = new ContainerSetSlotPacket; $pk->windowid = $packet->windowid; $pk->slot = $packet->slot; @@ -2230,7 +2177,7 @@ class Player{ break; } } - + if($item->getID() !== AIR and $slot->getID() == $item->getID()){ if($slot->count < $item->count){ if($this->removeItem($item->getID(), $item->getMetadata(), $item->count - $slot->count, false) === false){ @@ -2257,8 +2204,8 @@ class Player{ if($this->spawned === false or $this->blocked === true){ break; } - $this->craftingItems = array(); - $this->toCraft = array(); + $this->craftingItems = []; + $this->toCraft = []; $t = $this->server->api->tile->get(new Position($packet->x, $packet->y, $packet->z, $this->level)); if(($t instanceof Tile) and $t->class === TILE_SIGN){ if($t->data["creator"] !== $this->username){ @@ -2276,10 +2223,207 @@ class Player{ } break; default: - console("[DEBUG] Unhandled 0x".dechex($packet->pid())." data packet for ".$this->username." (".$this->clientID."): ".print_r($packet, true), true, true, 2); + console("[DEBUG] Unhandled 0x" . dechex($packet->pid()) . " data packet for " . $this->username . " (" . $this->clientID . "): " . print_r($packet, true), true, true, 2); break; } } + + public function stopSleep(){ + $this->isSleeping = false; + if($this->entity instanceof Entity){ + $this->entity->updateMetadata(); + } + } + + public function hasItem($type, $damage = false){ + foreach($this->inventory as $s => $item){ + if($item->getID() === $type and ($item->getMetadata() === $damage or $damage === false) and $item->count > 0){ + return $s; + } + } + return false; + } + + public function removeItem($type, $damage, $count, $send = true){ + while($count > 0){ + $remove = 0; + foreach($this->inventory as $s => $item){ + if($item->getID() === $type and $item->getMetadata() === $damage){ + $remove = min($count, $item->count); + if($remove < $item->count){ + $item->count -= $remove; + }else{ + $this->inventory[$s] = BlockAPI::getItem(AIR, 0, 0); + } + if($send === true){ + $this->sendInventorySlot($s); + } + break; + } + } + if($remove <= 0){ + return false; + } + $count -= $remove; + } + return true; + } + + /** + * @param array $craft + * @param array $recipe + * @param $type + * + * @return array|bool + */ + public function craftItems(array $craft, array $recipe, $type){ + $craftItem = [0, true, 0]; + unset($craft[-1]); + foreach($craft as $slot => $item){ + if($item instanceof Item){ + $craftItem[0] = $item->getID(); + if($item->getMetadata() !== $craftItem[1] and $craftItem[1] !== true){ + $craftItem[1] = false; + }else{ + $craftItem[1] = $item->getMetadata(); + } + $craftItem[2] += $item->count; + } + + } + + $recipeItems = []; + foreach($recipe as $slot => $item){ + if(!isset($recipeItems[$item->getID()])){ + $recipeItems[$item->getID()] = [$item->getID(), $item->getMetadata(), $item->count]; + }else{ + if($item->getMetadata() !== $recipeItems[$item->getID()][1]){ + $recipeItems[$item->getID()][1] = false; + } + $recipeItems[$item->getID()][2] += $item->count; + } + } + + $res = CraftingRecipes::canCraft($craftItem, $recipeItems, $type); + + if(!is_array($res) and $type === 1){ + $res2 = CraftingRecipes::canCraft($craftItem, $recipeItems, 0); + if(is_array($res2)){ + $res = $res2; + } + } + + if(is_array($res)){ + + if($this->server->api->dhandle("player.craft", ["player" => $this, "recipe" => $recipe, "craft" => $craft, "type" => $type]) === false){ + return false; + } + foreach($recipe as $slot => $item){ + $s = $this->getSlot($slot); + $s->count -= $item->count; + if($s->count <= 0){ + $this->setSlot($slot, BlockAPI::getItem(AIR, 0, 0), false); + } + } + foreach($craft as $slot => $item){ + $s = $this->getSlot($slot); + if($s->count <= 0 or $s->getID() === AIR){ + $this->setSlot($slot, BlockAPI::getItem($item->getID(), $item->getMetadata(), $item->count), false); + }else{ + $this->setSlot($slot, BlockAPI::getItem($item->getID(), $item->getMetadata(), $s->count + $item->count), false); + } + console($item->getID()); + switch($item->getID()){ + case WORKBENCH: + AchievementAPI::grantAchievement($this, "buildWorkBench"); + break; + case WOODEN_PICKAXE: + AchievementAPI::grantAchievement($this, "buildPickaxe"); + break; + case FURNACE: + AchievementAPI::grantAchievement($this, "buildFurnace"); + break; + case WOODEN_HOE: + AchievementAPI::grantAchievement($this, "buildHoe"); + break; + case BREAD: + AchievementAPI::grantAchievement($this, "makeBread"); + break; + case CAKE: + AchievementAPI::grantAchievement($this, "bakeCake"); + $this->addItem(BUCKET, 0, 3); + break; + case STONE_PICKAXE: + case GOLDEN_PICKAXE: + case IRON_PICKAXE: + case DIAMOND_PICKAXE: + AchievementAPI::grantAchievement($this, "buildBetterPickaxe"); + break; + case WOODEN_SWORD: + AchievementAPI::grantAchievement($this, "buildSword"); + break; + case DIAMOND: + AchievementAPI::grantAchievement($this, "diamond"); + break; + + } + } + } + return $res; + } + + public function handlePacket(RakNetPacket $packet){ + if($this->connected === true){ + $this->timeout = microtime(true) + 20; + switch($packet->pid()){ + case RakNetInfo::NACK: + foreach($packet->packets as $count){ + if(isset($this->recoveryQueue[$count])){ + $this->resendQueue[$count] =& $this->recoveryQueue[$count]; + $this->lag[] = microtime(true) - $this->recoveryQueue[$count]->sendtime; + unset($this->recoveryQueue[$count]); + } + ++$this->packetStats[1]; + } + break; + + case RakNetInfo::ACK: + foreach($packet->packets as $count){ + if(isset($this->recoveryQueue[$count])){ + $this->lag[] = microtime(true) - $this->recoveryQueue[$count]->sendtime; + unset($this->recoveryQueue[$count]); + unset($this->resendQueue[$count]); + } + ++$this->packetStats[0]; + } + break; + + case RakNetInfo::DATA_PACKET_0: + case RakNetInfo::DATA_PACKET_1: + case RakNetInfo::DATA_PACKET_2: + case RakNetInfo::DATA_PACKET_3: + case RakNetInfo::DATA_PACKET_4: + case RakNetInfo::DATA_PACKET_5: + case RakNetInfo::DATA_PACKET_6: + case RakNetInfo::DATA_PACKET_7: + case RakNetInfo::DATA_PACKET_8: + case RakNetInfo::DATA_PACKET_9: + case RakNetInfo::DATA_PACKET_A: + case RakNetInfo::DATA_PACKET_B: + case RakNetInfo::DATA_PACKET_C: + case RakNetInfo::DATA_PACKET_D: + case RakNetInfo::DATA_PACKET_E: + case RakNetInfo::DATA_PACKET_F: + $this->ackQueue[] = $packet->seqNumber; + $this->receiveQueue[$packet->seqNumber] = []; + foreach($packet->data as $pk){ + $this->receiveQueue[$packet->seqNumber][] = $pk; + } + break; + } + } + } + public function damageArmorPart($slot, $part){ $part->useOn($this->entity, true); //PocketMine is forced to do it =<. Even if PocketMine doesnt want, he have to damage your armor. if($part->getMetadata() >= $part->getMaxDurability()){ @@ -2288,170 +2432,11 @@ class Player{ } $this->setArmor($slot, $part, false); } - /** - * @param Player|string|boolean|void $player - */ - public function sendArmor($player = false){ - $data = array( - "player" => $this, - "eid" => $this->eid, - "slots" => array() - ); - for($i = 0; $i < 4; ++$i){ - if(isset($this->armor[$i]) and ($this->armor[$i] instanceof Item) and $this->armor[$i]->getID() > AIR){ - $data["slots"][$i] = $this->armor[$i]->getID() !== AIR ? $this->armor[$i]->getID() - 256:0; - }else{ - $this->armor[$i] = BlockAPI::getItem(AIR, 0, 0); - $data["slots"][$i] = 255; - } - } - if($player instanceof Player){ - if($player === $this){ - $pk = new ContainerSetContentPacket; - $pk->windowid = 0x78; //Armor window id - $pk->slots = $this->armor; - $this->dataPacket($pk); - }else{ - $pk = new PlayerArmorEquipmentPacket; - $pk->eid = $this->eid; - $pk->slots = $data["slots"]; - $player->dataPacket($pk); - } - }else{ - $this->server->api->dhandle("player.armor", $data); - } - } - - public function sendInventory(){ - if(($this->gamemode & 0x01) === CREATIVE){ - return; - } - $hotbar = array(); - foreach($this->hotbar as $slot){ - $hotbar[] = $slot <= -1 ? -1 : $slot + 9; - } - $pk = new ContainerSetContentPacket; - $pk->windowid = 0; - $pk->slots = $this->inventory; - $pk->hotbar = $hotbar; - $this->dataPacket($pk); - } - - public function send(RakNetPacket $packet){ - if($this->connected === true){ - $packet->ip = $this->ip; - $packet->port = $this->port; - $this->bandwidthRaw += $this->server->send($packet); - } - } - - public function sendBuffer(){ - if($this->bufferLen > 0 and $this->buffer instanceof RakNetPacket){ - $this->buffer->seqNumber = $this->counter[0]++; - $this->send($this->buffer); - } - $this->bufferLen = 0; - $this->buffer = new RakNetPacket(RakNetInfo::DATA_PACKET_0); - $this->buffer->data = array(); - $this->nextBuffer = microtime(true) + 0.1; - } - - private function directBigRawPacket(RakNetDataPacket $packet){ - if($this->connected === false){ - return false; - } - - $sendtime = microtime(true); - - $size = $this->MTU - 34; - $buffer = str_split($packet->buffer, $size); - $bigCnt = $this->bigCnt; - $this->bigCnt = ($this->bigCnt + 1) % 0x10000; - $cnts = array(); - $bufCount = count($buffer); - foreach($buffer as $i => $buf){ - $cnts[] = $count = $this->counter[0]++; - - $pk = new UnknownPacket; - $pk->packetID = $packet->pid(); - $pk->reliability = 2; - $pk->hasSplit = true; - $pk->splitCount = $bufCount; - $pk->splitID = $bigCnt; - $pk->splitIndex = $i; - $pk->buffer = $buf; - $pk->messageIndex = $this->counter[3]++; - - $rk = new RakNetPacket(RakNetInfo::DATA_PACKET_0); - $rk->data[] = $pk; - $rk->seqNumber = $count; - $rk->sendtime = $sendtime; - $this->recoveryQueue[$count] = $rk; - $this->send($rk); - } - return $cnts; - } - - public function directDataPacket(RakNetDataPacket $packet, $reliability = 0, $recover = true){ - if($this->connected === false){ - return false; - } - - if(EventHandler::callEvent(new DataPacketSendEvent($this, $packet)) === BaseEvent::DENY){ - return array(); - } - - $packet->encode(); - $pk = new RakNetPacket(RakNetInfo::DATA_PACKET_0); - $pk->data[] = $packet; - $pk->seqNumber = $this->counter[0]++; - $pk->sendtime = microtime(true); - if($recover !== false){ - $this->recoveryQueue[$pk->seqNumber] = $pk; - } - - $this->send($pk); - return array($pk->seqNumber); - } - - /** - * @param integer $id - * @param array $data - * - * @return array|bool - */ - public function dataPacket(RakNetDataPacket $packet){ - if($this->connected === false){ - return false; - } - - if(EventHandler::callEvent(new DataPacketSendEvent($this, $packet)) === BaseEvent::DENY){ - return; - } - - $packet->encode(); - $len = strlen($packet->buffer) + 1; - $MTU = $this->MTU - 24; - if($len > $MTU){ - return $this->directBigRawPacket($packet); - } - - if(($this->bufferLen + $len) >= $MTU){ - $this->sendBuffer(); - } - - $packet->messageIndex = $this->counter[3]++; - $packet->reliability = 2; - $this->buffer->data[] = $packet; - $this->bufferLen += 6 + $len; - return array(); - } - - /** - * @return string - */ - function __toString(){ + /** + * @return string + */ + function __toString(){ if($this->username != ""){ return $this->username; } @@ -2461,7 +2446,8 @@ class Player{ } class PlayerNull extends Player{ + public function __construct(){ - + } } diff --git a/src/PocketMinecraftServer.php b/src/PocketMinecraftServer.php index 026b526f..f6b0f674 100644 --- a/src/PocketMinecraftServer.php +++ b/src/PocketMinecraftServer.php @@ -1,34 +1,27 @@ port = (int) $port; + $this->doTick = true; + $this->gamemode = (int) $gamemode; + $this->name = $name; + $this->motd = "Welcome to " . $name; + $this->serverID = false; + $this->seed = $seed; + $this->serverip = $serverip; + $this->load(); + } + private function load(){ global $dolog; EntityRegistry::registerEntities(); @@ -36,32 +29,32 @@ class PocketMinecraftServer{ /*if(defined("DEBUG") and DEBUG >= 0){ @cli_set_process_title("NostalgiaCore ".MAJOR_VERSION); }*/ - console("[INFO] Starting Minecraft PE server on ".($this->serverip === "0.0.0.0" ? "*":$this->serverip).":".$this->port); + console("[INFO] Starting Minecraft PE server on " . ($this->serverip === "0.0.0.0" ? "*" : $this->serverip) . ":" . $this->port); define("BOOTUP_RANDOM", Utils::getRandomBytes(16)); - $this->serverID = $this->serverID === false ? Utils::readLong(substr(Utils::getUniqueID(true, $this->serverip . $this->port), 8)):$this->serverID; - $this->seed = $this->seed === false ? Utils::readInt(Utils::getRandomBytes(4, false)):$this->seed; + $this->serverID = $this->serverID === false ? Utils::readLong(substr(Utils::getUniqueID(true, $this->serverip . $this->port), 8)) : $this->serverID; + $this->seed = $this->seed === false ? Utils::readInt(Utils::getRandomBytes(4, false)) : $this->seed; $this->startDatabase(); $this->api = false; $this->tCnt = 1; - $this->events = array(); - $this->eventsID = array(); - $this->handlers = array(); + $this->events = []; + $this->eventsID = []; + $this->handlers = []; $this->invisible = false; $this->levelData = false; $this->difficulty = 1; - $this->tiles = array(); - $this->entities = array(); - $this->custom = array(); + $this->tiles = []; + $this->entities = []; + $this->custom = []; $this->evCnt = 1; $this->handCnt = 1; $this->eidCnt = 1; $this->maxClients = 20; - $this->schedule = array(); + $this->schedule = []; $this->scheduleCnt = 1; $this->description = ""; $this->whitelist = false; - $this->memoryStats = array(); - $this->clients = array(); + $this->memoryStats = []; + $this->clients = []; $this->spawn = false; $this->saveEnabled = true; $this->tickMeasure = array_fill(0, 40, 0); @@ -73,92 +66,34 @@ class PocketMinecraftServer{ $this->asyncThread = new AsyncMultipleQueue(); } console("[INFO] Loading extra.properties..."); - $this->extraprops = new Config(DATA_PATH . "extra.properties", CONFIG_PROPERTIES, array( - "version" => "5", - "enable-nether-reactor" => true, - "enable-explosions" => true, - "enable-rail-connection" => false, - "save-player-data" => true, - "save-console-data" => true, - "query-plugins" => false, - "discord-msg" => false, - "discord-ru-smiles" => false, - "discord-webhook-url" => "none", - "discord-bot-name" => "NostalgiaCore Logger" - )); - Explosion::$enableExplosions = $this->extraprops->get("enable-explosions"); - RailBlock::$shouldconnectrails = $this->extraprops->get("enable-rail-connection"); //Rail connection in config - NetherReactorBlock::$enableReactor = $this->extraprops->get("enable-nether-reactor"); - if($this->extraprops->get("discord-msg") == true){ - if($this->extraprops->get("discord-webhook-url") !== "none"){ - console("[INFO] Discord Logger is enabled."); - } else { - console("[WARNING] Discord Logger is enabled in extra.properties,"); - console("[WARNING] but you didn't put the webhook url, so it won't work."); - } - } elseif($this->extraprops->get("version") == null){ - console("[WARNING] Your extra.properties file is corrupted!"); - console("To fix it - just remove it! Server will generate it again automatically."); + $this->extraprops = new Config(DATA_PATH . "extra.properties", CONFIG_PROPERTIES, [ + "version" => "5", + "enable-nether-reactor" => true, + "enable-explosions" => true, + "enable-rail-connection" => false, + "save-player-data" => true, + "save-console-data" => true, + "query-plugins" => false, + "discord-msg" => false, + "discord-ru-smiles" => false, + "discord-webhook-url" => "none", + "discord-bot-name" => "NostalgiaCore Logger" + ]); + Explosion::$enableExplosions = $this->extraprops->get("enable-explosions"); + RailBlock::$shouldconnectrails = $this->extraprops->get("enable-rail-connection"); //Rail connection in config + NetherReactorBlock::$enableReactor = $this->extraprops->get("enable-nether-reactor"); + if($this->extraprops->get("discord-msg") == true){ + if($this->extraprops->get("discord-webhook-url") !== "none"){ + console("[INFO] Discord Logger is enabled."); + }else{ + console("[WARNING] Discord Logger is enabled in extra.properties,"); + console("[WARNING] but you didn't put the webhook url, so it won't work."); } - $dolog = $this->extraprops->get("save-console-data"); - } - - function __construct($name, $gamemode = SURVIVAL, $seed = false, $port = 19132, $serverip = "0.0.0.0"){ - $this->port = (int) $port; - $this->doTick = true; - $this->gamemode = (int) $gamemode; - $this->name = $name; - $this->motd = "Welcome to ".$name; - $this->serverID = false; - $this->seed = $seed; - $this->serverip = $serverip; - $this->load(); - } - - /** - * @return float - */ - public function getTPS(){ - $v = array_values($this->tickMeasure); - $divval = ($v[39] - $v[0]); - if($divval === 0){ - return 0; - } - $tps = 40 / $divval; - return round($tps, 4); - } - - public function titleTick(){ - $time = microtime(true); - if(defined("DEBUG") and DEBUG >= 0 and ENABLE_ANSI === true){ - echo "\x1b]0;NostalgiaCore ".MAJOR_VERSION." | Online ". count($this->clients)."/".$this->maxClients." | RAM ".round((memory_get_usage() / 1024) / 1024, 2)."MB | U ".round(($this->interface->bandwidth[1] / max(1, $time - $this->interface->bandwidth[2])) / 1024, 2)." D ".round(($this->interface->bandwidth[0] / max(1, $time - $this->interface->bandwidth[2])) / 1024, 2)." kB/s | TPS ".$this->getTPS()."\x07"; - } - $this->interface->bandwidth = array(0, 0, $time); - } - - public function loadEvents(){ - if(ENABLE_ANSI === true){ - $this->schedule(30, array($this, "titleTick"), array(), true); - } - $this->schedule(20 * 15, array($this, "checkTicks"), array(), true); - $this->schedule(20 * 60, array($this, "checkMemory"), array(), true); - $this->schedule(20 * 45, "Cache::cleanup", array(), true); - $this->schedule(20, array($this, "asyncOperationChecker"), array(), true); - } - - public function checkTicks(){ - if($this->getTPS() < 12){ - console("[WARNING] Can't keep up! Is the server overloaded?"); - } - } - - public function checkMemory(){ - $info = $this->debugInfo(); - $data = $info["memory_usage"].",".$info["players"].",".$info["entities"]; - $i = count($this->memoryStats) - 1; - if($i < 0 or $this->memoryStats[$i] !== $data){ - $this->memoryStats[] = $data; + }elseif($this->extraprops->get("version") == null){ + console("[WARNING] Your extra.properties file is corrupted!"); + console("To fix it - just remove it! Server will generate it again automatically."); } + $dolog = $this->extraprops->get("save-console-data"); } public function startDatabase(){ @@ -184,60 +119,13 @@ class PocketMinecraftServer{ } public function query($sql, $fetch = false){ - $result = $this->database->query($sql) or console("[ERROR] [SQL Error] ".$this->database->lastErrorMsg().". Query: ".$sql, true, true, 0); + $result = $this->database->query($sql) or console("[ERROR] [SQL Error] " . $this->database->lastErrorMsg() . ". Query: " . $sql, true, true, 0); if($fetch === true and ($result instanceof SQLite3Result)){ $result = $result->fetchArray(SQLITE3_ASSOC); } return $result; } - public function debugInfo($console = false){ - $info = array(); - $info["tps"] = $this->getTPS(); - $info["memory_usage"] = round((memory_get_usage() / 1024) / 1024, 2)."MB"; - $info["memory_peak_usage"] = round((memory_get_peak_usage() / 1024) / 1024, 2)."MB"; - $info["entities"] = $this->query("SELECT count(EID) as count FROM entities;", true); - $info["entities"] = $info["entities"]["count"]; - $info["players"] = $this->query("SELECT count(CID) as count FROM players;", true); - $info["players"] = $info["players"]["count"]; - $info["events"] = count($this->eventsID); - $info["handlers"] = $this->query("SELECT count(ID) as count FROM handlers;", true); - $info["handlers"] = $info["handlers"]["count"]; - $info["actions"] = $this->query("SELECT count(ID) as count FROM actions;", true); - $info["actions"] = $info["actions"]["count"]; - $info["garbage"] = gc_collect_cycles(); - $this->handle("server.debug", $info); - if($console === true){ - console("[DEBUG] TPS: ".$info["tps"].", Memory usage: ".$info["memory_usage"]." (Peak ".$info["memory_peak_usage"]."), Entities: ".$info["entities"].", Events: ".$info["events"].", Handlers: ".$info["handlers"].", Actions: ".$info["actions"].", Garbage: ".$info["garbage"], true, true, 2); - } - return $info; - } - - /** - * @param string $reason - */ - public function close($reason = "server stop"){ - $this->send2Discord('[INFO] Server stopped!'); - usleep(2); - if($this->stop !== true){ - if(is_int($reason)){ - $reason = "signal stop"; - } - if(($this->api instanceof ServerAPI) === true){ - if(($this->api->chat instanceof ChatAPI) === true){ - $this->api->chat->broadcast("Stopping server..."); - } - } - $this->stop = true; - $this->trigger("server.close", $reason); - $this->interface->close(); - - if(!defined("NO_THREADS")){ - @$this->asyncThread->stop = true; - } - } - } - public function setType($type = "normal"){ switch(trim(strtolower($type))){ case "normal": @@ -250,7 +138,74 @@ class PocketMinecraftServer{ } } - + + public function titleTick(){ + $time = microtime(true); + if(defined("DEBUG") and DEBUG >= 0 and ENABLE_ANSI === true){ + echo "\x1b]0;NostalgiaCore " . MAJOR_VERSION . " | Online " . count($this->clients) . "/" . $this->maxClients . " | RAM " . round((memory_get_usage() / 1024) / 1024, 2) . "MB | U " . round(($this->interface->bandwidth[1] / max(1, $time - $this->interface->bandwidth[2])) / 1024, 2) . " D " . round(($this->interface->bandwidth[0] / max(1, $time - $this->interface->bandwidth[2])) / 1024, 2) . " kB/s | TPS " . $this->getTPS() . "\x07"; + } + + $this->interface->bandwidth = [0, 0, $time]; + } + + /** + * @return float + */ + public function getTPS(){ + $v = array_values($this->tickMeasure); + $divval = ($v[39] - $v[0]); + if($divval === 0){ + return 0; + } + $tps = 40 / $divval; + return round($tps, 4); + } + + public function checkTicks(){ + if($this->getTPS() < 12){ + console("[WARNING] Can't keep up! Is the server overloaded?"); + } + } + + /** + * @param string $reason + */ + public function close($reason = "server stop"){ + $this->send2Discord('[INFO] Server stopped!'); + usleep(2); + if($this->stop !== true){ + if(is_int($reason)){ + $reason = "signal stop"; + } + if(($this->api instanceof ServerAPI) === true){ + if(($this->api->chat instanceof ChatAPI) === true){ + $this->api->chat->broadcast("Stopping server..."); + } + } + $this->stop = true; + $this->trigger("server.close", $reason); + $this->interface->close(); + + if(!defined("NO_THREADS")){ + @$this->asyncThread->stop = true; + } + } + } + + public function send2Discord($msg){ + if($this->extraprops->get("discord-msg") == true and $this->extraprops->get("discord-webhook-url") !== "none"){ + $url = $this->extraprops->get("discord-webhook-url"); + $name = $this->extraprops->get("discord-bot-name"); + $this->asyncOperation(ASYNC_CURL_POST, [ + "url" => $url, + "data" => [ + "username" => $name, + "content" => $this->extraprops->get("discord-ru-smiles") ? str_replace("@", " ", str_replace("Ы", "<:ru_cool:960113011383738369>", str_replace("Ь", "<:ru_cry:960112920346390548>", str_replace("Ъ", "<:ru_happy:960112868601237504>", $msg)))) : str_replace("@", "", $msg) + ], + ], null); + } + } + public function asyncOperation($type, array $data, callable $callable = null){ if(defined("NO_THREADS")){ return false; @@ -259,13 +214,13 @@ class PocketMinecraftServer{ $type = (int) $type; switch($type){ case ASYNC_CURL_GET: - $d .= Utils::writeShort(strlen($data["url"])).$data["url"].(isset($data["timeout"]) ? Utils::writeShort($data["timeout"]) : Utils::writeShort(10)); + $d .= Utils::writeShort(strlen($data["url"])) . $data["url"] . (isset($data["timeout"]) ? Utils::writeShort($data["timeout"]) : Utils::writeShort(10)); break; case ASYNC_CURL_POST: - $d .= Utils::writeShort(strlen($data["url"])).$data["url"].(isset($data["timeout"]) ? Utils::writeShort($data["timeout"]) : Utils::writeShort(10)); + $d .= Utils::writeShort(strlen($data["url"])) . $data["url"] . (isset($data["timeout"]) ? Utils::writeShort($data["timeout"]) : Utils::writeShort(10)); $d .= Utils::writeShort(count($data["data"])); foreach($data["data"] as $key => $value){ - $d .= Utils::writeShort(strlen($key)).$key . Utils::writeInt(strlen($value)).$value; + $d .= Utils::writeShort(strlen($key)) . $key . Utils::writeInt(strlen($value)) . $value; } break; default: @@ -273,10 +228,47 @@ class PocketMinecraftServer{ } $ID = $this->asyncID++; $this->async[$ID] = $callable; - $this->asyncThread->input .= Utils::writeInt($ID).Utils::writeShort($type).$d; + $this->asyncThread->input .= Utils::writeInt($ID) . Utils::writeShort($type) . $d; return $ID; } - + + public function trigger($event, $data = ""){ + if(isset($this->events[$event])){ + foreach($this->events[$event] as $evid => $ev){ + if(!is_callable($ev)){ + $this->deleteEvent($evid); + continue; + } + if(is_array($ev)){ + $method = $ev[1]; + $ev[0]->$method($data, $event); + }else{ + $ev($data, $event); + } + } + }elseif(isset(Deprecation::$events[$event])){ + $sub = ""; + if(Deprecation::$events[$event] !== false){ + $sub = " Substitute \"" . Deprecation::$events[$event] . "\" found."; + } + console("[ERROR] Event \"$event\" has been deprecated.$sub [Trigger]"); + } + } + + public function deleteEvent($id){ + $id = (int) $id; + if(isset($this->eventsID[$id])){ + $ev = $this->eventsID[$id]; + $this->eventsID[$id] = null; + unset($this->eventsID[$id]); + $this->events[$ev][$id] = null; + unset($this->events[$ev][$id]); + if(count($this->events[$ev]) === 0){ + unset($this->events[$ev]); + } + } + } + public function asyncOperationChecker(){ if(defined("NO_THREADS")){ return false; @@ -287,7 +279,7 @@ class PocketMinecraftServer{ $offset += 4; $type = Utils::readShort(substr($this->asyncThread->output, $offset, 2)); $offset += 2; - $data = array(); + $data = []; switch($type){ case ASYNC_CURL_GET: case ASYNC_CURL_POST: @@ -297,6 +289,7 @@ class PocketMinecraftServer{ $offset += $len; break; } + $this->asyncThread->output = substr($this->asyncThread->output, $offset); if(isset($this->async[$ID]) and $this->async[$ID] !== null and is_callable($this->async[$ID])){ if(is_array($this->async[$ID])){ @@ -310,31 +303,31 @@ class PocketMinecraftServer{ } } - /** - * @param string $event - * @param callable $callable - * @param integer $priority - * - * @return boolean - */ - public function addHandler($event,callable $callable, $priority = 5){ + /** + * @param string $event + * @param callable $callable + * @param integer $priority + * + * @return boolean + */ + public function addHandler($event, callable $callable, $priority = 5){ if(!is_callable($callable)){ return false; }elseif(isset(Deprecation::$events[$event])){ $sub = ""; if(Deprecation::$events[$event] !== false){ - $sub = " Substitute \"".Deprecation::$events[$event]."\" found."; + $sub = " Substitute \"" . Deprecation::$events[$event] . "\" found."; } - console("[ERROR] Event \"$event\" has been deprecated.$sub [Adding handle to ".(is_array($callable) ? get_class($callable[0])."::".$callable[1]:$callable)."]"); + console("[ERROR] Event \"$event\" has been deprecated.$sub [Adding handle to " . (is_array($callable) ? get_class($callable[0]) . "::" . $callable[1] : $callable) . "]"); } $priority = (int) $priority; $hnid = $this->handCnt++; $this->handlers[$hnid] = $callable; - $this->query("INSERT INTO handlers (ID, name, priority) VALUES (".$hnid.", '".str_replace("'", "\\'", $event)."', ".$priority.");"); - console("[INTERNAL] New handler ".(is_array($callable) ? get_class($callable[0])."::".$callable[1]:$callable)." to special event ".$event." (ID ".$hnid.")", true, true, 3); + $this->query("INSERT INTO handlers (ID, name, priority) VALUES (" . $hnid . ", '" . str_replace("'", "\\'", $event) . "', " . $priority . ");"); + console("[INTERNAL] New handler " . (is_array($callable) ? get_class($callable[0]) . "::" . $callable[1] : $callable) . " to special event " . $event . " (ID " . $hnid . ")", true, true, 3); return $hnid; } - + public function dhandle($e, $d){ return $this->handle($e, $d); } @@ -346,7 +339,7 @@ class PocketMinecraftServer{ $handlers = $this->preparedSQL->selectHandlers->execute(); $result = null; if($handlers instanceof SQLite3Result){ - $call = array(); + $call = []; while(($hn = $handlers->fetchArray(SQLITE3_ASSOC)) !== false){ $call[(int) $hn["ID"]] = true; } @@ -368,7 +361,7 @@ class PocketMinecraftServer{ }elseif(isset(Deprecation::$events[$event])){ $sub = ""; if(Deprecation::$events[$event] !== false){ - $sub = " Substitute \"".Deprecation::$events[$event]."\" found."; + $sub = " Substitute \"" . Deprecation::$events[$event] . "\" found."; } console("[ERROR] Event \"$event\" has been deprecated.$sub [Handler]"); } @@ -385,10 +378,49 @@ class PocketMinecraftServer{ } } - /** - * @return string - */ - public function getGamemode(){ + public function init(){ + register_tick_function([$this, "tick"]); + declare(ticks=5000); //Minimum TPS for main thread locks + + $this->loadEvents(); + register_shutdown_function([$this, "dumpError"]); + register_shutdown_function([$this, "close"]); + if(function_exists("pcntl_signal")){ + pcntl_signal(SIGTERM, [$this, "close"]); + pcntl_signal(SIGINT, [$this, "close"]); + pcntl_signal(SIGHUP, [$this, "close"]); + } + console("[INFO] Default game type: " . strtoupper($this->getGamemode())); + $this->trigger("server.start", microtime(true)); + console('[INFO] Done (' . round(microtime(true) - START_TIME, 3) . 's)! For help, type "help" or "?"'); + $this->process(); + } + + public function loadEvents(){ + if(ENABLE_ANSI === true){ + $this->schedule(30, [$this, "titleTick"], [], true); + } + $this->schedule(20 * 15, [$this, "checkTicks"], [], true); + $this->schedule(20 * 60, [$this, "checkMemory"], [], true); + $this->schedule(20 * 45, "Cache::cleanup", [], true); + $this->schedule(20, [$this, "asyncOperationChecker"], [], true); + } + + public function schedule($ticks, callable $callback, $data = [], $repeat = false, $eventName = "server.schedule"){ + if(!is_callable($callback)){ + return false; + } + + $chcnt = $this->scheduleCnt++; + $this->schedule[$chcnt] = [$callback, $data, $eventName]; + $this->query("INSERT INTO actions (ID, interval, last, repeat) VALUES(" . $chcnt . ", " . ($ticks / 20) . ", " . microtime(true) . ", " . (((bool) $repeat) === true ? 1 : 0) . ");"); + return $chcnt; + } + + /** + * @return string + */ + public function getGamemode(){ switch($this->gamemode){ case SURVIVAL: return "survival"; @@ -401,206 +433,6 @@ class PocketMinecraftServer{ } } - - - public function init(){ - register_tick_function(array($this, "tick")); - declare(ticks=5000); //Minimum TPS for main thread locks - - $this->loadEvents(); - register_shutdown_function(array($this, "dumpError")); - register_shutdown_function(array($this, "close")); - if(function_exists("pcntl_signal")){ - pcntl_signal(SIGTERM, array($this, "close")); - pcntl_signal(SIGINT, array($this, "close")); - pcntl_signal(SIGHUP, array($this, "close")); - } - console("[INFO] Default game type: ".strtoupper($this->getGamemode())); - $this->trigger("server.start", microtime(true)); - console('[INFO] Done ('.round(microtime(true) - START_TIME, 3).'s)! For help, type "help" or "?"'); - $this->process(); - } - - public function dumpError(){ - if($this->stop === true){ - return; - } - ini_set("memory_limit", "-1"); //Fix error dump not dumped on memory problems - console("[SEVERE] An unrecovereable has ocurred and the server has crashed. Creating an error dump"); - $dump = "```\r\n# NostalgiaCore Error Dump ".date("D M j H:i:s T Y")."\r\n"; - $er = error_get_last(); - $errorConversion = array( - E_ERROR => "E_ERROR", - E_WARNING => "E_WARNING", - E_PARSE => "E_PARSE", - E_NOTICE => "E_NOTICE", - E_CORE_ERROR => "E_CORE_ERROR", - E_CORE_WARNING => "E_CORE_WARNING", - E_COMPILE_ERROR => "E_COMPILE_ERROR", - E_COMPILE_WARNING => "E_COMPILE_WARNING", - E_USER_ERROR => "E_USER_ERROR", - E_USER_WARNING => "E_USER_WARNING", - E_USER_NOTICE => "E_USER_NOTICE", - E_STRICT => "E_STRICT", - E_RECOVERABLE_ERROR => "E_RECOVERABLE_ERROR", - E_DEPRECATED => "E_DEPRECATED", - E_USER_DEPRECATED => "E_USER_DEPRECATED", - ); - $er["type"] = isset($errorConversion[$er["type"]]) ? $errorConversion[$er["type"]]:$er["type"]; - $dump .= "Error: ".var_export($er, true)."\r\n\r\n"; - if(stripos($er["file"], "plugin") !== false){ - $dump .= "THIS ERROR WAS CAUSED BY A PLUGIN. REPORT IT TO THE PLUGIN DEVELOPER.\r\n"; - } - - $dump .= "Code: \r\n"; - $file = @file($er["file"], FILE_IGNORE_NEW_LINES); - for($l = max(0, $er["line"] - 10); $l < $er["line"] + 10; ++$l){ - $dump .= "[".($l + 1)."] ".@$file[$l]."\r\n"; - } - $dump .= "\r\n\r\n"; - $dump .= "Backtrace: \r\n"; - foreach(getTrace() as $line){ - $dump .= "$line\r\n"; - } - $dump .= "\r\n\r\n"; - $version = new VersionString(); - $dump .= "NostalgiaCore version: ".$version." #".$version->getNumber()." [Protocol ".ProtocolInfo::CURRENT_PROTOCOL."; API ".CURRENT_API_VERSION."]\r\n"; - $dump .= "Git commit: ".GIT_COMMIT."\r\n"; - $dump .= "Source SHA1 sum: ".SOURCE_SHA1SUM."\r\n"; - $dump .= "uname -a: ".php_uname("a")."\r\n"; - $dump .= "PHP Version: " .phpversion()."\r\n"; - $dump .= "Zend version: ".zend_version()."\r\n"; - $dump .= "OS : " .PHP_OS.", ".Utils::getOS()."\r\n"; - $dump .= "Debug Info: ".var_export($this->debugInfo(false), true)."\r\n\r\n\r\n"; - global $arguments; - $dump .= "Parameters: ".var_export($arguments, true)."\r\n\r\n\r\n"; - $p = $this->api->getProperties(); - if($p["rcon.password"] != ""){ - $p["rcon.password"] = "******"; - } - $dump .= "server.properties: ".var_export($p, true)."\r\n\r\n\r\n"; - if($this->api->plugin instanceof PluginAPI){ - $plist = $this->api->plugin->getList(); - $dump .= "Loaded plugins:\r\n"; - foreach($plist as $p){ - $dump .= $p["name"]." ".$p["version"]." by ".$p["author"]."\r\n"; - } - $dump .= "\r\n\r\n"; - } - - $extensions = array(); - foreach(get_loaded_extensions() as $ext){ - $extensions[$ext] = phpversion($ext); - } - - $dump .= "Loaded Modules: ".var_export($extensions, true)."\r\n"; - $this->checkMemory(); - $dump .= "Memory Usage Tracking: \r\n".chunk_split(base64_encode(gzdeflate(implode(";", $this->memoryStats), 9)))."\r\n"; - ob_start(); - phpinfo(); - $dump .= "\r\nphpinfo(): \r\n".chunk_split(base64_encode(gzdeflate(ob_get_contents(), 9)))."\r\n"; - ob_end_clean(); - $dump .= "\r\n```"; - $name = "Error_Dump_".date("D_M_j-H.i.s-T_Y"); - logg($dump, $name, true, 0, true); - console("[SEVERE] Please submit the \"{$name}.log\" file to the Bug Reporting page. Give as much info as you can.", true, true, 0); - } - - public function tick(){ - $time = microtime(true); - if($this->lastTick <= ($time - 0.05)){ - $this->tickMeasure[] = $this->lastTick = $time; - unset($this->tickMeasure[key($this->tickMeasure)]); - ++$this->ticks; - return $this->tickerFunction($time); - } - return 0; - } - - public static function clientID($ip, $port){ - return crc32($ip . $port) ^ crc32($port . $ip . BOOTUP_RANDOM); - //return $ip . ":" . $port; - } - - public function packetHandler(Packet $packet){ - $data =& $packet; - $CID = PocketMinecraftServer::clientID($packet->ip, $packet->port); - if(isset($this->clients[$CID])){ - $this->clients[$CID]->handlePacket($packet); - }else{ - if($this->handle("server.noauthpacket.".$packet->pid(), $packet) === false){ - return; - } - switch($packet->pid()){ - case RakNetInfo::UNCONNECTED_PING: - case RakNetInfo::UNCONNECTED_PING_OPEN_CONNECTIONS: - if($this->invisible === true){ - $pk = new RakNetPacket(RakNetInfo::UNCONNECTED_PONG); - $pk->pingID = $packet->pingID; - $pk->serverID = $this->serverID; - $pk->serverType = $this->serverType; - $pk->ip = $packet->ip; - $pk->port = $packet->port; - $this->send($pk); - break; - } - if(!isset($this->custom["times_".$CID])){ - $this->custom["times_".$CID] = 0; - } - $ln = 15; - if($this->description == "" or substr($this->description, -1) != " "){ - $this->description .= " "; - } - $txt = substr($this->description, $this->custom["times_".$CID], $ln); - $txt .= substr($this->description, 0, $ln - strlen($txt)); - $pk = new RakNetPacket(RakNetInfo::UNCONNECTED_PONG); - $pk->pingID = $packet->pingID; - $pk->serverID = $this->serverID; - $pk->serverType = $this->serverType . $this->name . " [".count($this->clients)."/".$this->maxClients."] ".$txt; - $pk->ip = $packet->ip; - $pk->port = $packet->port; - $this->send($pk); - $this->custom["times_".$CID] = ($this->custom["times_".$CID] + 1) % strlen($this->description); - break; - case RakNetInfo::OPEN_CONNECTION_REQUEST_1: - if($packet->structure !== RakNetInfo::STRUCTURE){ - console("[DEBUG] Incorrect structure #".$packet->structure." from ".$packet->ip.":".$packet->port, true, true, 2); - $pk = new RakNetPacket(RakNetInfo::INCOMPATIBLE_PROTOCOL_VERSION); - $pk->serverID = $this->serverID; - $pk->ip = $packet->ip; - $pk->port = $packet->port; - $this->send($pk); - }else{ - $pk = new RakNetPacket(RakNetInfo::OPEN_CONNECTION_REPLY_1); - $pk->serverID = $this->serverID; - $pk->mtuSize = strlen($packet->buffer); - $pk->ip = $packet->ip; - $pk->port = $packet->port; - $this->send($pk); - } - break; - case RakNetInfo::OPEN_CONNECTION_REQUEST_2: - if($this->invisible === true){ - break; - } - - $this->clients[$CID] = new Player($packet->clientID, $packet->ip, $packet->port, $packet->mtuSize); //New Session! - $pk = new RakNetPacket(RakNetInfo::OPEN_CONNECTION_REPLY_2); - $pk->serverID = $this->serverID; - $pk->port = $this->port; - $pk->mtuSize = $packet->mtuSize; - $pk->ip = $packet->ip; - $pk->port = $packet->port; - $this->send($pk); - break; - } - } - } - - public function send(Packet $packet){ - return $this->interface->writePacket($packet); - } - public function process(){ $lastLoop = 0; while($this->stop === false){ @@ -626,37 +458,99 @@ class PocketMinecraftServer{ } } - public function trigger($event, $data = ""){ - if(isset($this->events[$event])){ - foreach($this->events[$event] as $evid => $ev){ - if(!is_callable($ev)){ - $this->deleteEvent($evid); - continue; - } - if(is_array($ev)){ - $method = $ev[1]; - $ev[0]->$method($data, $event); - }else{ - $ev($data, $event); - } + public function packetHandler(Packet $packet){ + $data =& $packet; + $CID = PocketMinecraftServer::clientID($packet->ip, $packet->port); + if(isset($this->clients[$CID])){ + $this->clients[$CID]->handlePacket($packet); + }else{ + if($this->handle("server.noauthpacket." . $packet->pid(), $packet) === false){ + return; } - }elseif(isset(Deprecation::$events[$event])){ - $sub = ""; - if(Deprecation::$events[$event] !== false){ - $sub = " Substitute \"".Deprecation::$events[$event]."\" found."; + switch($packet->pid()){ + case RakNetInfo::UNCONNECTED_PING: + case RakNetInfo::UNCONNECTED_PING_OPEN_CONNECTIONS: + if($this->invisible === true){ + $pk = new RakNetPacket(RakNetInfo::UNCONNECTED_PONG); + $pk->pingID = $packet->pingID; + $pk->serverID = $this->serverID; + $pk->serverType = $this->serverType; + $pk->ip = $packet->ip; + $pk->port = $packet->port; + $this->send($pk); + break; + } + if(!isset($this->custom["times_" . $CID])){ + $this->custom["times_" . $CID] = 0; + } + $ln = 15; + if($this->description == "" or substr($this->description, -1) != " "){ + $this->description .= " "; + } + $txt = substr($this->description, $this->custom["times_" . $CID], $ln); + $txt .= substr($this->description, 0, $ln - strlen($txt)); + $pk = new RakNetPacket(RakNetInfo::UNCONNECTED_PONG); + $pk->pingID = $packet->pingID; + $pk->serverID = $this->serverID; + $pk->serverType = $this->serverType . $this->name . " [" . count($this->clients) . "/" . $this->maxClients . "] " . $txt; + $pk->ip = $packet->ip; + $pk->port = $packet->port; + $this->send($pk); + $this->custom["times_" . $CID] = ($this->custom["times_" . $CID] + 1) % strlen($this->description); + break; + case RakNetInfo::OPEN_CONNECTION_REQUEST_1: + if($packet->structure !== RakNetInfo::STRUCTURE){ + console("[DEBUG] Incorrect structure #" . $packet->structure . " from " . $packet->ip . ":" . $packet->port, true, true, 2); + $pk = new RakNetPacket(RakNetInfo::INCOMPATIBLE_PROTOCOL_VERSION); + $pk->serverID = $this->serverID; + $pk->ip = $packet->ip; + $pk->port = $packet->port; + $this->send($pk); + }else{ + $pk = new RakNetPacket(RakNetInfo::OPEN_CONNECTION_REPLY_1); + $pk->serverID = $this->serverID; + $pk->mtuSize = strlen($packet->buffer); + $pk->ip = $packet->ip; + $pk->port = $packet->port; + $this->send($pk); + } + break; + case RakNetInfo::OPEN_CONNECTION_REQUEST_2: + if($this->invisible === true){ + break; + } + + $this->clients[$CID] = new Player($packet->clientID, $packet->ip, $packet->port, $packet->mtuSize); //New Session! + $pk = new RakNetPacket(RakNetInfo::OPEN_CONNECTION_REPLY_2); + $pk->serverID = $this->serverID; + $pk->port = $this->port; + $pk->mtuSize = $packet->mtuSize; + $pk->ip = $packet->ip; + $pk->port = $packet->port; + $this->send($pk); + break; } - console("[ERROR] Event \"$event\" has been deprecated.$sub [Trigger]"); } } - public function schedule($ticks, callable $callback, $data = array(), $repeat = false, $eventName = "server.schedule"){ - if(!is_callable($callback)){ - return false; + public static function clientID($ip, $port){ + return crc32($ip . $port) ^ crc32($port . $ip . BOOTUP_RANDOM); + //return $ip . ":" . $port; + } + + public function send(Packet $packet){ + return $this->interface->writePacket($packet); + } + + public function tick(){ + $time = microtime(true); + if($this->lastTick <= ($time - 0.05)){ + $this->tickMeasure[] = $this->lastTick = $time; + unset($this->tickMeasure[key($this->tickMeasure)]); + ++$this->ticks; + return $this->tickerFunction($time); } - $chcnt = $this->scheduleCnt++; - $this->schedule[$chcnt] = array($callback, $data, $eventName); - $this->query("INSERT INTO actions (ID, interval, last, repeat) VALUES(".$chcnt.", ".($ticks / 20).", ".microtime(true).", ".(((bool) $repeat) === true ? 1:0).");"); - return $chcnt; + return 0; } public function tickerFunction($time){ @@ -681,7 +575,7 @@ class PocketMinecraftServer{ } if($action["repeat"] == 0 or $return === false){ - $this->query("DELETE FROM actions WHERE ID = ".$action["ID"].";"); + $this->query("DELETE FROM actions WHERE ID = " . $action["ID"] . ";"); $this->schedule[$cid] = null; unset($this->schedule[$cid]); } @@ -691,51 +585,139 @@ class PocketMinecraftServer{ return $actionCount; } - public function event($event,callable $func){ + public function dumpError(){ + if($this->stop === true){ + return; + } + ini_set("memory_limit", "-1"); //Fix error dump not dumped on memory problems + console("[SEVERE] An unrecovereable has ocurred and the server has crashed. Creating an error dump"); + $dump = "```\r\n# NostalgiaCore Error Dump " . date("D M j H:i:s T Y") . "\r\n"; + $er = error_get_last(); + $errorConversion = [ + E_ERROR => "E_ERROR", + E_WARNING => "E_WARNING", + E_PARSE => "E_PARSE", + E_NOTICE => "E_NOTICE", + E_CORE_ERROR => "E_CORE_ERROR", + E_CORE_WARNING => "E_CORE_WARNING", + E_COMPILE_ERROR => "E_COMPILE_ERROR", + E_COMPILE_WARNING => "E_COMPILE_WARNING", + E_USER_ERROR => "E_USER_ERROR", + E_USER_WARNING => "E_USER_WARNING", + E_USER_NOTICE => "E_USER_NOTICE", + E_STRICT => "E_STRICT", + E_RECOVERABLE_ERROR => "E_RECOVERABLE_ERROR", + E_DEPRECATED => "E_DEPRECATED", + E_USER_DEPRECATED => "E_USER_DEPRECATED", + ]; + $er["type"] = isset($errorConversion[$er["type"]]) ? $errorConversion[$er["type"]] : $er["type"]; + $dump .= "Error: " . var_export($er, true) . "\r\n\r\n"; + if(stripos($er["file"], "plugin") !== false){ + $dump .= "THIS ERROR WAS CAUSED BY A PLUGIN. REPORT IT TO THE PLUGIN DEVELOPER.\r\n"; + } + + $dump .= "Code: \r\n"; + $file = @file($er["file"], FILE_IGNORE_NEW_LINES); + for($l = max(0, $er["line"] - 10); $l < $er["line"] + 10; ++$l){ + $dump .= "[" . ($l + 1) . "] " . @$file[$l] . "\r\n"; + } + $dump .= "\r\n\r\n"; + $dump .= "Backtrace: \r\n"; + foreach(getTrace() as $line){ + $dump .= "$line\r\n"; + } + $dump .= "\r\n\r\n"; + $version = new VersionString(); + $dump .= "NostalgiaCore version: " . $version . " #" . $version->getNumber() . " [Protocol " . ProtocolInfo::CURRENT_PROTOCOL . "; API " . CURRENT_API_VERSION . "]\r\n"; + $dump .= "Git commit: " . GIT_COMMIT . "\r\n"; + $dump .= "Source SHA1 sum: " . SOURCE_SHA1SUM . "\r\n"; + $dump .= "uname -a: " . php_uname("a") . "\r\n"; + $dump .= "PHP Version: " . phpversion() . "\r\n"; + $dump .= "Zend version: " . zend_version() . "\r\n"; + $dump .= "OS : " . PHP_OS . ", " . Utils::getOS() . "\r\n"; + $dump .= "Debug Info: " . var_export($this->debugInfo(false), true) . "\r\n\r\n\r\n"; + global $arguments; + $dump .= "Parameters: " . var_export($arguments, true) . "\r\n\r\n\r\n"; + $p = $this->api->getProperties(); + if($p["rcon.password"] != ""){ + $p["rcon.password"] = "******"; + } + $dump .= "server.properties: " . var_export($p, true) . "\r\n\r\n\r\n"; + if($this->api->plugin instanceof PluginAPI){ + $plist = $this->api->plugin->getList(); + $dump .= "Loaded plugins:\r\n"; + foreach($plist as $p){ + $dump .= $p["name"] . " " . $p["version"] . " by " . $p["author"] . "\r\n"; + } + $dump .= "\r\n\r\n"; + } + + $extensions = []; + foreach(get_loaded_extensions() as $ext){ + $extensions[$ext] = phpversion($ext); + } + + $dump .= "Loaded Modules: " . var_export($extensions, true) . "\r\n"; + $this->checkMemory(); + $dump .= "Memory Usage Tracking: \r\n" . chunk_split(base64_encode(gzdeflate(implode(";", $this->memoryStats), 9))) . "\r\n"; + ob_start(); + phpinfo(); + $dump .= "\r\nphpinfo(): \r\n" . chunk_split(base64_encode(gzdeflate(ob_get_contents(), 9))) . "\r\n"; + ob_end_clean(); + $dump .= "\r\n```"; + $name = "Error_Dump_" . date("D_M_j-H.i.s-T_Y"); + logg($dump, $name, true, 0, true); + console("[SEVERE] Please submit the \"{$name}.log\" file to the Bug Reporting page. Give as much info as you can.", true, true, 0); + } + + public function debugInfo($console = false){ + $info = []; + $info["tps"] = $this->getTPS(); + $info["memory_usage"] = round((memory_get_usage() / 1024) / 1024, 2) . "MB"; + $info["memory_peak_usage"] = round((memory_get_peak_usage() / 1024) / 1024, 2) . "MB"; + $info["entities"] = $this->query("SELECT count(EID) as count FROM entities;", true); + $info["entities"] = $info["entities"]["count"]; + $info["players"] = $this->query("SELECT count(CID) as count FROM players;", true); + $info["players"] = $info["players"]["count"]; + $info["events"] = count($this->eventsID); + $info["handlers"] = $this->query("SELECT count(ID) as count FROM handlers;", true); + $info["handlers"] = $info["handlers"]["count"]; + $info["actions"] = $this->query("SELECT count(ID) as count FROM actions;", true); + $info["actions"] = $info["actions"]["count"]; + $info["garbage"] = gc_collect_cycles(); + $this->handle("server.debug", $info); + if($console === true){ + console("[DEBUG] TPS: " . $info["tps"] . ", Memory usage: " . $info["memory_usage"] . " (Peak " . $info["memory_peak_usage"] . "), Entities: " . $info["entities"] . ", Events: " . $info["events"] . ", Handlers: " . $info["handlers"] . ", Actions: " . $info["actions"] . ", Garbage: " . $info["garbage"], true, true, 2); + } + return $info; + } + + public function checkMemory(){ + $info = $this->debugInfo(); + $data = $info["memory_usage"] . "," . $info["players"] . "," . $info["entities"]; + $i = count($this->memoryStats) - 1; + if($i < 0 or $this->memoryStats[$i] !== $data){ + $this->memoryStats[] = $data; + } + } + + public function event($event, callable $func){ if(!is_callable($func)){ return false; }elseif(isset(Deprecation::$events[$event])){ $sub = ""; if(Deprecation::$events[$event] !== false){ - $sub = " Substitute \"".Deprecation::$events[$event]."\" found."; + $sub = " Substitute \"" . Deprecation::$events[$event] . "\" found."; } - console("[ERROR] Event \"$event\" has been deprecated.$sub [Attach to ".(is_array($func) ? get_class($func[0])."::".$func[1]:$func)."]"); + console("[ERROR] Event \"$event\" has been deprecated.$sub [Attach to " . (is_array($func) ? get_class($func[0]) . "::" . $func[1] : $func) . "]"); } $evid = $this->evCnt++; if(!isset($this->events[$event])){ - $this->events[$event] = array(); + $this->events[$event] = []; } $this->events[$event][$evid] = $func; $this->eventsID[$evid] = $event; - console("[INTERNAL] Attached ".(is_array($func) ? get_class($func[0])."::".$func[1]:$func)." to event ".$event." (ID ".$evid.")", true, true, 3); + console("[INTERNAL] Attached " . (is_array($func) ? get_class($func[0]) . "::" . $func[1] : $func) . " to event " . $event . " (ID " . $evid . ")", true, true, 3); return $evid; } - - public function deleteEvent($id){ - $id = (int) $id; - if(isset($this->eventsID[$id])){ - $ev = $this->eventsID[$id]; - $this->eventsID[$id] = null; - unset($this->eventsID[$id]); - $this->events[$ev][$id] = null; - unset($this->events[$ev][$id]); - if(count($this->events[$ev]) === 0){ - unset($this->events[$ev]); - } - } - } - - public function send2Discord($msg){ - if($this->extraprops->get("discord-msg") == true and $this->extraprops->get("discord-webhook-url") !== "none"){ - $url = $this->extraprops->get("discord-webhook-url"); - $name = $this->extraprops->get("discord-bot-name"); - $this->asyncOperation(ASYNC_CURL_POST, array( - "url" => $url, - "data" => array( - "username" => $name, - "content" => $this->extraprops->get("discord-ru-smiles") ? str_replace("@", " ", str_replace("Ы", "<:ru_cool:960113011383738369>", str_replace("Ь", "<:ru_cry:960112920346390548>", str_replace("Ъ","<:ru_happy:960112868601237504>", $msg)))) : str_replace("@", "", $msg) - ), - ), NULL); - } - } } \ No newline at end of file diff --git a/src/config.php b/src/config.php index bd234c48..efd25237 100644 --- a/src/config.php +++ b/src/config.php @@ -1,29 +1,10 @@ = 0.1.0 is required, while you have $pthreads_version.", true, true, 0); ++$errors; - } + } } -if(!extension_loaded("curl") and @dl((PHP_SHLIB_SUFFIX === "dll" ? "php_":"") . "curl." . PHP_SHLIB_SUFFIX) === false){ +if(!extension_loaded("curl") and @dl((PHP_SHLIB_SUFFIX === "dll" ? "php_" : "") . "curl." . PHP_SHLIB_SUFFIX) === false){ console("[ERROR] Unable to find the cURL extension.", true, true, 0); ++$errors; } -if(!extension_loaded("sqlite3") and @dl((PHP_SHLIB_SUFFIX === "dll" ? "php_":"") . "sqlite3." . PHP_SHLIB_SUFFIX) === false){ +if(!extension_loaded("sqlite3") and @dl((PHP_SHLIB_SUFFIX === "dll" ? "php_" : "") . "sqlite3." . PHP_SHLIB_SUFFIX) === false){ console("[ERROR] Unable to find the SQLite3 extension.", true, true, 0); ++$errors; } -if(!extension_loaded("yaml") and @dl((PHP_SHLIB_SUFFIX === "dll" ? "php_":"") . "yaml." . PHP_SHLIB_SUFFIX) === false){ +if(!extension_loaded("yaml") and @dl((PHP_SHLIB_SUFFIX === "dll" ? "php_" : "") . "yaml." . PHP_SHLIB_SUFFIX) === false){ console("[ERROR] Unable to find the YAML extension.", true, true, 0); ++$errors; } -if(!extension_loaded("zlib") and @dl((PHP_SHLIB_SUFFIX === "dll" ? "php_":"") . "zlib." . PHP_SHLIB_SUFFIX) === false){ +if(!extension_loaded("zlib") and @dl((PHP_SHLIB_SUFFIX === "dll" ? "php_" : "") . "zlib." . PHP_SHLIB_SUFFIX) === false){ console("[ERROR] Unable to find the Zlib extension.", true, true, 0); ++$errors; } @@ -92,22 +73,22 @@ if($errors > 0){ $sha1sum = "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"; /***REM_START***/ -require_once(FILE_PATH."/src/math/Vector3.php"); -require_once(FILE_PATH."/src/world/Position.php"); -require_once(FILE_PATH."/src/pmf/PMF.php"); -require_once(FILE_PATH."/src/entity/Entity.php"); -require_once(FILE_PATH."/src/entity/Damageable.php"); -require_once(FILE_PATH."/src/entity/Breedable.php"); -require_once(FILE_PATH."/src/entity/Living.php"); -require_once(FILE_PATH."/src/entity/Creature.php"); -require_once(FILE_PATH."/src/entity/Ageable.php"); -require_once(FILE_PATH."/src/entity/Animal.php"); +require_once(FILE_PATH . "/src/math/Vector3.php"); +require_once(FILE_PATH . "/src/world/Position.php"); +require_once(FILE_PATH . "/src/pmf/PMF.php"); +require_once(FILE_PATH . "/src/entity/Entity.php"); +require_once(FILE_PATH . "/src/entity/Damageable.php"); +require_once(FILE_PATH . "/src/entity/Breedable.php"); +require_once(FILE_PATH . "/src/entity/Living.php"); +require_once(FILE_PATH . "/src/entity/Creature.php"); +require_once(FILE_PATH . "/src/entity/Ageable.php"); +require_once(FILE_PATH . "/src/entity/Animal.php"); require_all(FILE_PATH . "src/"); $inc = get_included_files(); $inc[] = array_shift($inc); -$srcdir = realpath(FILE_PATH."src/"); +$srcdir = realpath(FILE_PATH . "src/"); foreach($inc as $s){ if(strpos(realpath(dirname($s)), $srcdir) === false and strtolower(basename($s)) !== "pocketmine-mp.php"){ continue; @@ -119,7 +100,7 @@ ini_set("opcache.mmap_base", bin2hex(Utils::getRandomBytes(8, false))); //Fix OP define("SOURCE_SHA1SUM", bin2hex($sha1sum)); /***REM_START***/ -if(!file_exists(DATA_PATH."server.properties") and arg("no-wizard", false) != true){ +if(!file_exists(DATA_PATH . "server.properties") and arg("no-wizard", false) != true){ $installer = new Installer(); } /***REM_END***/ diff --git a/src/entity/Entity.php b/src/entity/Entity.php index 84978546..acca1493 100644 --- a/src/entity/Entity.php +++ b/src/entity/Entity.php @@ -1,24 +1,5 @@ $value){ - echo str_repeat(" ", $cnt + 1)."[".(is_integer($key) ? $key:'"'.$key.'"')."]=>".PHP_EOL; + echo str_repeat(" ", $cnt + 1) . "[" . (is_integer($key) ? $key : '"' . $key . '"') . "]=>" . PHP_EOL; safe_var_dump($value, $cnt + 1); } - echo str_repeat(" ", $cnt)."}".PHP_EOL; + echo str_repeat(" ", $cnt) . "}" . PHP_EOL; break; case is_integer($var): - echo str_repeat(" ", $cnt)."int(".$var.")".PHP_EOL; + echo str_repeat(" ", $cnt) . "int(" . $var . ")" . PHP_EOL; break; case is_float($var): - echo str_repeat(" ", $cnt)."float(".$var.")".PHP_EOL; + echo str_repeat(" ", $cnt) . "float(" . $var . ")" . PHP_EOL; break; case is_bool($var): - echo str_repeat(" ", $cnt)."bool(".($var === true ? "true":"false").")".PHP_EOL; + echo str_repeat(" ", $cnt) . "bool(" . ($var === true ? "true" : "false") . ")" . PHP_EOL; break; case is_string($var): - echo str_repeat(" ", $cnt)."string(".strlen($var).") \"$var\"".PHP_EOL; + echo str_repeat(" ", $cnt) . "string(" . strlen($var) . ") \"$var\"" . PHP_EOL; break; case is_resource($var): - echo str_repeat(" ", $cnt)."resource() of type (".get_resource_type($var).")".PHP_EOL; + echo str_repeat(" ", $cnt) . "resource() of type (" . get_resource_type($var) . ")" . PHP_EOL; break; case is_object($var): - echo str_repeat(" ", $cnt)."object(".get_class($var).")".PHP_EOL; + echo str_repeat(" ", $cnt) . "object(" . get_class($var) . ")" . PHP_EOL; break; case is_null($var): - echo str_repeat(" ", $cnt)."NULL".PHP_EOL; + echo str_repeat(" ", $cnt) . "NULL" . PHP_EOL; break; } } @@ -71,26 +52,26 @@ function safe_var_dump($var, $cnt = 0){ function kill($pid){ switch(Utils::getOS()){ case "win": - exec("taskkill.exe /F /PID ".((int) $pid)." > NUL"); + exec("taskkill.exe /F /PID " . ((int) $pid) . " > NUL"); break; case "mac": case "linux": default: - exec("kill -9 ".((int) $pid)." > /dev/null 2>&1"); + exec("kill -9 " . ((int) $pid) . " > /dev/null 2>&1"); } } function require_all($path, &$count = 0){ - $dir = dir($path."/"); - $dirs = array(); + $dir = dir($path . "/"); + $dirs = []; while(false !== ($file = $dir->read())){ if($file !== "." and $file !== ".."){ - if(!is_dir($path.$file) and strtolower(substr($file, -3)) === "php"){ - require_once($path.$file); + if(!is_dir($path . $file) and strtolower(substr($file, -3)) === "php"){ + require_once($path . $file); ++$count; - }elseif(is_dir($path.$file)){ - $dirs[] = $path.$file."/"; + }elseif(is_dir($path . $file)){ + $dirs[] = $path . $file . "/"; } } } @@ -135,57 +116,57 @@ function arg($name, $default = false){ } } -function arguments ( $args ){ +function arguments($args){ if(!is_array($args)){ - $args = array(); + $args = []; } - array_shift( $args ); - $args = join(' ', $args); + array_shift($args); + $args = join(' ', $args); - preg_match_all('/ (--[\w\-]+ (?:[= ] [^-\s]+ )? ) | (-\w+) | (\w+) /x', $args, $match ); - $args = array_shift( $match ); + preg_match_all('/ (--[\w\-]+ (?:[= ] [^-\s]+ )? ) | (-\w+) | (\w+) /x', $args, $match); + $args = array_shift($match); - $ret = array( - 'input' => array(), - 'commands' => array(), - 'flags' => array() - ); + $ret = [ + 'input' => [], + 'commands' => [], + 'flags' => [] + ]; - foreach ( $args as $arg ) { + foreach($args as $arg){ - // Is it a command? (prefixed with --) - if ( substr( $arg, 0, 2 ) === '--' ) { + // Is it a command? (prefixed with --) + if(substr($arg, 0, 2) === '--'){ - $value = preg_split( '/[= ]/', $arg, 2 ); - $com = substr( array_shift($value), 2 ); - $value = join($value); + $value = preg_split('/[= ]/', $arg, 2); + $com = substr(array_shift($value), 2); + $value = join($value); - $ret['commands'][$com] = !empty($value) ? $value : true; - continue; + $ret['commands'][$com] = !empty($value) ? $value : true; + continue; - } + } - // Is it a flag? (prefixed with -) - if ( substr( $arg, 0, 1 ) === '-' ) { - $ret['flags'][] = substr( $arg, 1 ); - continue; - } + // Is it a flag? (prefixed with -) + if(substr($arg, 0, 1) === '-'){ + $ret['flags'][] = substr($arg, 1); + continue; + } - $ret['input'][] = $arg; - continue; + $ret['input'][] = $arg; + continue; - } + } - return $ret; + return $ret; } function console($message, $EOL = true, $log = true, $level = 1){ if(!defined("DEBUG") or DEBUG >= $level){ - $message .= $EOL === true ? PHP_EOL:""; - $time = (ENABLE_ANSI === true ? FORMAT_AQUA . date("H:i:s") . FORMAT_RESET:date("H:i:s")) . " "; + $message .= $EOL === true ? PHP_EOL : ""; + $time = (ENABLE_ANSI === true ? FORMAT_AQUA . date("H:i:s") . FORMAT_RESET : date("H:i:s")) . " "; $replaced = TextFormat::clean(preg_replace('/\x1b\[[0-9;]*m/', "", $time . $message)); if($log === true and (!defined("LOG") or LOG === true)){ - logg(date("Y-m-d")." ".$replaced, "console", false, $level); + logg(date("Y-m-d") . " " . $replaced, "console", false, $level); } if(ENABLE_ANSI === true){ $add = ""; @@ -221,14 +202,14 @@ function console($message, $EOL = true, $log = true, $level = 1){ function getTrace($start = 1){ $e = new Exception(); $trace = $e->getTrace(); - $messages = array(); + $messages = []; $j = 0; for($i = (int) $start; isset($trace[$i]); ++$i, ++$j){ $params = ""; foreach($trace[$i]["args"] as $name => $value){ - $params .= (is_object($value) ? get_class($value)." ".(method_exists($value, "__toString") ? $value->__toString() : "object"):gettype($value)." ".@strval($value)).", "; + $params .= (is_object($value) ? get_class($value) . " " . (method_exists($value, "__toString") ? $value->__toString() : "object") : gettype($value) . " " . @strval($value)) . ", "; } - $messages[] = "#$j ".(isset($trace[$i]["file"]) ? $trace[$i]["file"]:"")."(".(isset($trace[$i]["line"]) ? $trace[$i]["line"]:"")."): ".(isset($trace[$i]["class"]) ? $trace[$i]["class"].$trace[$i]["type"]:"").$trace[$i]["function"]."(".substr($params, 0, -2).")"; + $messages[] = "#$j " . (isset($trace[$i]["file"]) ? $trace[$i]["file"] : "") . "(" . (isset($trace[$i]["line"]) ? $trace[$i]["line"] : "") . "): " . (isset($trace[$i]["class"]) ? $trace[$i]["class"] . $trace[$i]["type"] : "") . $trace[$i]["function"] . "(" . substr($params, 0, -2) . ")"; } return $messages; } @@ -237,7 +218,7 @@ function error_handler($errno, $errstr, $errfile, $errline){ if(error_reporting() === 0){ //@ error-control return false; } - $errorConversion = array( + $errorConversion = [ E_ERROR => "E_ERROR", E_WARNING => "E_WARNING", E_PARSE => "E_PARSE", @@ -253,9 +234,9 @@ function error_handler($errno, $errstr, $errfile, $errline){ E_RECOVERABLE_ERROR => "E_RECOVERABLE_ERROR", E_DEPRECATED => "E_DEPRECATED", E_USER_DEPRECATED => "E_USER_DEPRECATED", - ); - $errno = isset($errorConversion[$errno]) ? $errorConversion[$errno]:$errno; - console("[ERROR] A ".$errno." error happened: \"$errstr\" in \"$errfile\" at line $errline", true, true, 0); + ]; + $errno = isset($errorConversion[$errno]) ? $errorConversion[$errno] : $errno; + console("[ERROR] A " . $errno . " error happened: \"$errstr\" in \"$errfile\" at line $errline", true, true, 0); foreach(getTrace() as $i => $line){ console("[TRACE] $line"); } @@ -265,16 +246,16 @@ function error_handler($errno, $errstr, $errfile, $errline){ function logg($message, $name, $EOL = true, $level = 2, $close = false){ global $fpointers, $dolog; if((!defined("DEBUG") or DEBUG >= $level) and (!defined("LOG") or LOG === true)){ - $message .= $EOL === true ? PHP_EOL:""; + $message .= $EOL === true ? PHP_EOL : ""; if(!isset($fpointers)){ - $fpointers = array(); + $fpointers = []; } if(!isset($fpointers[$name]) or $fpointers[$name] === false){ - $fpointers[$name] = @fopen(DATA_PATH."/".$name.".log", "ab"); + $fpointers[$name] = @fopen(DATA_PATH . "/" . $name . ".log", "ab"); + } + if($dolog){ + @fwrite($fpointers[$name], $message); } - if($dolog) { - @fwrite($fpointers[$name], $message); - } if($close === true){ fclose($fpointers[$name]); unset($fpointers[$name]); diff --git a/src/installer/Installer.php b/src/installer/Installer.php index acb71551..c228cda6 100644 --- a/src/installer/Installer.php +++ b/src/installer/Installer.php @@ -1,24 +1,5 @@ server = ServerAPI::request(); } diff --git a/src/material/Block.php b/src/material/Block.php index 38bb40e0..fa920dcd 100755 --- a/src/material/Block.php +++ b/src/material/Block.php @@ -1,24 +1,5 @@ "AirBlock", diff --git a/src/material/Item.php b/src/material/Item.php index a294566c..9a48fc07 100755 --- a/src/material/Item.php +++ b/src/material/Item.php @@ -1,24 +1,5 @@ block = BlockAPI::get(CAKE_BLOCK); diff --git a/src/material/item/food/Carrot.php b/src/material/item/food/Carrot.php index 4f431ada..8a29a17c 100755 --- a/src/material/item/food/Carrot.php +++ b/src/material/item/food/Carrot.php @@ -1,24 +1,5 @@ block = BlockAPI::get(CARROT_BLOCK); diff --git a/src/material/item/food/CookedChicken.php b/src/material/item/food/CookedChicken.php index 8af880e6..a543697f 100644 --- a/src/material/item/food/CookedChicken.php +++ b/src/material/item/food/CookedChicken.php @@ -1,24 +1,5 @@ block = BlockAPI::get(POTATO_BLOCK); diff --git a/src/material/item/food/PumpkinPie.php b/src/material/item/food/PumpkinPie.php index eede9b71..3c3ca3e2 100644 --- a/src/material/item/food/PumpkinPie.php +++ b/src/material/item/food/PumpkinPie.php @@ -1,24 +1,5 @@ block = BlockAPI::get(BED_BLOCK); diff --git a/src/material/item/generic/BeetrootSeeds.php b/src/material/item/generic/BeetrootSeeds.php index e94e934b..f0a1ddab 100644 --- a/src/material/item/generic/BeetrootSeeds.php +++ b/src/material/item/generic/BeetrootSeeds.php @@ -1,24 +1,5 @@ block = BlockAPI::get(BEETROOT_BLOCK); diff --git a/src/material/item/generic/Bone.php b/src/material/item/generic/Bone.php index 63797491..3a30ebfa 100755 --- a/src/material/item/generic/Bone.php +++ b/src/material/item/generic/Bone.php @@ -1,24 +1,5 @@ "Bucket", diff --git a/src/material/item/generic/CameraItem.php b/src/material/item/generic/CameraItem.php index 0d01cff6..289f56a5 100755 --- a/src/material/item/generic/CameraItem.php +++ b/src/material/item/generic/CameraItem.php @@ -1,24 +1,5 @@ block = BlockAPI::get(IRON_DOOR_BLOCK); diff --git a/src/material/item/generic/IronIngot.php b/src/material/item/generic/IronIngot.php index c430911a..8e9e4e2f 100755 --- a/src/material/item/generic/IronIngot.php +++ b/src/material/item/generic/IronIngot.php @@ -1,24 +1,5 @@ block = BlockAPI::get(MELON_STEM); diff --git a/src/material/item/generic/Minecart.php b/src/material/item/generic/Minecart.php index 08f1aa1f..14575a6f 100755 --- a/src/material/item/generic/Minecart.php +++ b/src/material/item/generic/Minecart.php @@ -1,24 +1,5 @@ block = BlockAPI::get(PUMPKIN_STEM); diff --git a/src/material/item/generic/Quartz.php b/src/material/item/generic/Quartz.php index 557009bd..989559d4 100755 --- a/src/material/item/generic/Quartz.php +++ b/src/material/item/generic/Quartz.php @@ -1,24 +1,5 @@ block = BlockAPI::get(SIGN_POST); diff --git a/src/material/item/generic/Slimeball.php b/src/material/item/generic/Slimeball.php index 3a1dfb19..c5d1a4fb 100755 --- a/src/material/item/generic/Slimeball.php +++ b/src/material/item/generic/Slimeball.php @@ -1,24 +1,5 @@ block = BlockAPI::get(SUGARCANE_BLOCK); diff --git a/src/material/item/generic/Wheat.php b/src/material/item/generic/Wheat.php index 6b8d9333..0c8e0eac 100644 --- a/src/material/item/generic/Wheat.php +++ b/src/material/item/generic/Wheat.php @@ -1,24 +1,5 @@ block = BlockAPI::get(WHEAT_BLOCK); diff --git a/src/material/item/generic/WoodenDoor.php b/src/material/item/generic/WoodenDoor.php index d7a3f95c..a9f50031 100644 --- a/src/material/item/generic/WoodenDoor.php +++ b/src/material/item/generic/WoodenDoor.php @@ -1,24 +1,5 @@ block = BlockAPI::get(WOODEN_DOOR_BLOCK); diff --git a/src/material/item/tool/Bow.php b/src/material/item/tool/Bow.php index e9bc36eb..0d985c58 100644 --- a/src/material/item/tool/Bow.php +++ b/src/material/item/tool/Bow.php @@ -1,24 +1,5 @@ matrix[(int) $offset]); - } - - public function offsetGet($offset){ - return $this->matrix[(int) $offset]; - } - - public function offsetSet($offset, $value){ - $this->matrix[(int) $offset] = $value; - } - - public function offsetUnset($offset){ - unset($this->matrix[(int) $offset]); - } - - public function __construct($rows, $columns, array $set = array()){ + + public function __construct($rows, $columns, array $set = []){ $this->rows = max(1, (int) $rows); $this->columns = max(1, (int) $columns); $this->set($set); } - + public function set(array $m){ for($r = 0; $r < $this->rows; ++$r){ - $this->matrix[$r] = array(); + $this->matrix[$r] = []; for($c = 0; $c < $this->columns; ++$c){ $this->matrix[$r][$c] = isset($m[$r][$c]) ? $m[$r][$c] : 0; } } } - - public function getRows(){ - return ($this->rows); + + public function offsetExists($offset){ + return isset($this->matrix[(int) $offset]); } - - public function getColumns(){ - return ($this->columns); + + public function offsetGet($offset){ + return $this->matrix[(int) $offset]; } - - public function setElement($row, $column, $value){ - if($row > $this->rows or $row < 0 or $column > $this->columns or $column < 0){ - return false; - } - $this->matrix[(int) $row][(int) $column] = $value; - return true; + + public function offsetSet($offset, $value){ + $this->matrix[(int) $offset] = $value; } - - public function getElement($row, $column){ - if($row > $this->rows or $row < 0 or $column > $this->columns or $column < 0){ - return false; - } - return $this->matrix[(int) $row][(int) $column]; + + public function offsetUnset($offset){ + unset($this->matrix[(int) $offset]); } - - public function isSquare(){ - return $this->rows === $this->columns; - } - + public function add(Matrix $matrix){ if($this->rows !== $matrix->getRows() or $this->columns !== $matrix->getColumns()){ return false; @@ -94,7 +49,30 @@ class Matrix implements ArrayAccess{ } return $result; } - + + public function getRows(){ + return ($this->rows); + } + + public function getColumns(){ + return ($this->columns); + } + + public function setElement($row, $column, $value){ + if($row > $this->rows or $row < 0 or $column > $this->columns or $column < 0){ + return false; + } + $this->matrix[(int) $row][(int) $column] = $value; + return true; + } + + public function getElement($row, $column){ + if($row > $this->rows or $row < 0 or $column > $this->columns or $column < 0){ + return false; + } + return $this->matrix[(int) $row][(int) $column]; + } + public function substract(Matrix $matrix){ if($this->rows !== $matrix->getRows() or $this->columns !== $matrix->getColumns()){ return false; @@ -107,7 +85,7 @@ class Matrix implements ArrayAccess{ } return $result; } - + public function multiplyScalar($number){ $result = clone $this; for($r = 0; $r < $this->rows; ++$r){ @@ -117,8 +95,7 @@ class Matrix implements ArrayAccess{ } return $result; } - - + public function divideScalar($number){ $result = clone $this; for($r = 0; $r < $this->rows; ++$r){ @@ -128,7 +105,7 @@ class Matrix implements ArrayAccess{ } return $result; } - + public function transpose(){ $result = new Matrix($this->columns, $this->rows); for($r = 0; $r < $this->rows; ++$r){ @@ -138,8 +115,7 @@ class Matrix implements ArrayAccess{ } return $result; } - - //Naive Matrix product, O(n^3) + public function product(Matrix $matrix){ if($this->columns !== $matrix->getRows()){ return false; @@ -157,9 +133,9 @@ class Matrix implements ArrayAccess{ } return $result; } - - - //Computation of the determinant of 2x2 and 3x3 matrices + + //Naive Matrix product, O(n^3) + public function determinant(){ if($this->isSquare() !== true){ return false; @@ -174,14 +150,20 @@ class Matrix implements ArrayAccess{ } return false; } - - + + + //Computation of the determinant of 2x2 and 3x3 matrices + + public function isSquare(){ + return $this->rows === $this->columns; + } + public function __toString(){ $s = ""; for($r = 0; $r < $this->rows; ++$r){ - $s .= implode(",", $this->matrix[$r]).";"; + $s .= implode(",", $this->matrix[$r]) . ";"; } - return "Matrix({$this->rows}x{$this->columns};".substr($s, 0, -1).")"; + return "Matrix({$this->rows}x{$this->columns};" . substr($s, 0, -1) . ")"; } } \ No newline at end of file diff --git a/src/math/Vector2.php b/src/math/Vector2.php index 5713f30e..8ce96c4d 100644 --- a/src/math/Vector2.php +++ b/src/math/Vector2.php @@ -1,25 +1,7 @@ y; } + public function subtract($x = 0, $y = 0){ + if(($x instanceof Vector2) === true){ + return $this->add(-$x->x, -$x->y); + }else{ + return $this->add(-$x, -$y); + } + } + public function add($x = 0, $y = 0){ if(($x instanceof Vector2) === true){ return $this->add($x->x, $x->y); @@ -53,14 +43,6 @@ class Vector2{ } } - public function subtract($x = 0, $y = 0){ - if(($x instanceof Vector2) === true){ - return $this->add(-$x->x, -$x->y); - }else{ - return $this->add(-$x, -$y); - } - } - public function ceil(){ return new Vector2((int) ($this->x + 1), (int) ($this->y + 1)); } @@ -76,14 +58,10 @@ class Vector2{ public function abs(){ return new Vector2(abs($this->x), abs($this->y)); } - + public function multiply($number){ return new Vector2($this->x * $number, $this->y * $number); } - - public function divide($number){ - return new Vector2($this->x / $number, $this->y / $number); - } public function distance($x = 0, $y = 0){ if(($x instanceof Vector2) === true){ @@ -100,15 +78,7 @@ class Vector2{ return pow($this->x - $x, 2) + pow($this->y - $y, 2); } } - - public function length(){ - return sqrt($this->lengthSquared()); - } - - public function lengthSquared(){ - return $this->x * $this->x + $this->y * $this->y; - } - + public function normalize(){ $len = $this->length(); if($len != 0){ @@ -116,13 +86,24 @@ class Vector2{ } return new Vector2(0, 0); } - + + public function length(){ + return sqrt($this->lengthSquared()); + } + + public function lengthSquared(){ + return $this->x * $this->x + $this->y * $this->y; + } + + public function divide($number){ + return new Vector2($this->x / $number, $this->y / $number); + } + public function dot(Vector2 $v){ return $this->x * $v->x + $this->y * $v->y; } public function __toString(){ - return "Vector2(x=".$this->x.",y=".$this->y.")"; + return "Vector2(x=" . $this->x . ",y=" . $this->y . ")"; } - } \ No newline at end of file diff --git a/src/math/Vector3.php b/src/math/Vector3.php index 7b8b8761..2cfc331e 100644 --- a/src/math/Vector3.php +++ b/src/math/Vector3.php @@ -1,25 +1,7 @@ z = $z; } - public function getX(){ - return $this->x; - } - - public function getY(){ - return $this->y; - } - - public function getZ(){ - return $this->z; - } - public function getFloorX(){ return (int) $this->x; } @@ -56,14 +26,26 @@ class Vector3{ return $this->getX(); } + public function getX(){ + return $this->x; + } + public function getUp(){ return $this->getY(); } + public function getY(){ + return $this->y; + } + public function getForward(){ return $this->getZ(); } + public function getZ(){ + return $this->z; + } + public function getSouth(){ return $this->getX(); } @@ -72,6 +54,14 @@ class Vector3{ return $this->getZ(); } + public function subtract($x = 0, $y = 0, $z = 0){ + if(($x instanceof Vector3) === true){ + return $this->add(-$x->x, -$x->y, -$x->z); + }else{ + return $this->add(-$x, -$y, -$z); + } + } + public function add($x = 0, $y = 0, $z = 0){ if(($x instanceof Vector3) === true){ return $this->add($x->x, $x->y, $x->z); @@ -80,21 +70,9 @@ class Vector3{ } } - public function subtract($x = 0, $y = 0, $z = 0){ - if(($x instanceof Vector3) === true){ - return $this->add(-$x->x, -$x->y, -$x->z); - }else{ - return $this->add(-$x, -$y, -$z); - } - } - public function multiply($number){ return new Vector3($this->x * $number, $this->y * $number, $this->z * $number); } - - public function divide($number){ - return new Vector3($this->x / $number, $this->y / $number, $this->z / $number); - } public function ceil(){ return new Vector3((int) ($this->x + 1), (int) ($this->y + 1), (int) ($this->z + 1)); @@ -111,7 +89,7 @@ class Vector3{ public function abs(){ return new Vector3(abs($this->x), abs($this->y), abs($this->z)); } - + public function getSide($side, $step = 1){ switch((int) $side){ case 0: @@ -125,7 +103,7 @@ class Vector3{ case 4: return new Vector3($this->x - $step, $this->y, $this->z); case 5: - return new Vector3($this->x + $step, $this->y, $this->z); + return new Vector3($this->x + $step, $this->y, $this->z); default: return $this; } @@ -146,23 +124,15 @@ class Vector3{ return pow($this->x - $x, 2) + pow($this->y - $y, 2) + pow($this->z - $z, 2); } } - + public function maxPlainDistance($x = 0, $z = 0){ if(($x instanceof Vector3) === true){ return $this->maxPlainDistance($x->x, $x->z); }else{ return max(abs($this->x - $x), abs($this->z - $z)); - } + } } - - public function length(){ - return sqrt($this->lengthSquared()); - } - - public function lengthSquared(){ - return $this->x * $this->x + $this->y * $this->y + $this->z * $this->z; - } - + public function normalize(){ $len = $this->length(); if($len != 0){ @@ -170,11 +140,23 @@ class Vector3{ } return new Vector3(0, 0, 0); } - + + public function length(){ + return sqrt($this->lengthSquared()); + } + + public function lengthSquared(){ + return $this->x * $this->x + $this->y * $this->y + $this->z * $this->z; + } + + public function divide($number){ + return new Vector3($this->x / $number, $this->y / $number, $this->z / $number); + } + public function dot(Vector3 $v){ return $this->x * $v->x + $this->y * $v->y + $this->z * $v->z; } - + public function cross(Vector3 $v){ return new Vector3( $this->y * $v->z - $this->z * $v->y, @@ -184,7 +166,6 @@ class Vector3{ } public function __toString(){ - return "Vector3(x=".$this->x.",y=".$this->y.",z=".$this->z.")"; + return "Vector3(x=" . $this->x . ",y=" . $this->y . ",z=" . $this->z . ")"; } - } \ No newline at end of file diff --git a/src/math/VectorMath.php b/src/math/VectorMath.php index 4457bf81..ba65b941 100644 --- a/src/math/VectorMath.php +++ b/src/math/VectorMath.php @@ -1,28 +1,8 @@ socket = new UDPSocket($server, $port, true, $serverip); if($this->socket->connected === false){ - console("[SEVERE] Couldn't bind to $serverip:".$port, true, true, 0); + console("[SEVERE] Couldn't bind to $serverip:" . $port, true, true, 0); exit(1); } - $this->bandwidth = array(0, 0, microtime(true)); + $this->bandwidth = [0, 0, microtime(true)]; $this->start = microtime(true); - $this->packets = array(); + $this->packets = []; } public function close(){ @@ -52,7 +35,7 @@ class MinecraftInterface{ $this->bandwidth[0] += $len; return $this->parsePacket($buf, $source, $port); } - + private function parsePacket($buffer, $source, $port){ $pid = ord($buffer[0]); @@ -85,7 +68,7 @@ class MinecraftInterface{ return false; } } - + public function writePacket(Packet $packet){ if(EventHandler::callEvent(new PacketSendEvent($packet)) === BaseEvent::DENY){ return 0; @@ -96,7 +79,4 @@ class MinecraftInterface{ $this->bandwidth[1] += $write; return $write; } - -} - -?> \ No newline at end of file +} \ No newline at end of file diff --git a/src/network/Packet.php b/src/network/Packet.php index abfa75f9..9499ca69 100644 --- a/src/network/Packet.php +++ b/src/network/Packet.php @@ -1,25 +1,7 @@ workers = array(); + $this->workers = []; $this->password = (string) $password; console("[INFO] Starting remote control listener"); if($this->password === ""){ @@ -39,7 +21,7 @@ class RCON{ $this->clientsPerThread = (int) max(1, $clientsPerThread); $this->socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); if($this->socket === false or !socket_bind($this->socket, $interface, (int) $port) or !socket_listen($this->socket)){ - console("[ERROR] RCON can't be started: ".socket_strerror(socket_last_error())); + console("[ERROR] RCON can't be started: " . socket_strerror(socket_last_error())); return; } @socket_set_block($this->socket); @@ -48,9 +30,9 @@ class RCON{ } @socket_getsockname($this->socket, $addr, $port); console("[INFO] RCON running on $addr:$port"); - ServerAPI::request()->schedule(2, array($this, "check"), array(), true); + ServerAPI::request()->schedule(2, [$this, "check"], [], true); } - + public function stop(){ for($n = 0; $n < $this->threads; ++$n){ $this->workers[$n]->close(); @@ -61,10 +43,10 @@ class RCON{ @socket_close($this->socket); $this->threads = 0; } - + public function check(){ for($n = 0; $n < $this->threads; ++$n){ - if($this->workers[$n]->isTerminated() === true){ + if($this->workers[$n]->isTerminated()){ $this->workers[$n] = new RCONInstance($this->socket, $this->password, $this->clientsPerThread); }elseif($this->workers[$n]->isWaiting()){ if($this->workers[$n]->response !== ""){ @@ -81,6 +63,7 @@ class RCON{ } class RCONInstance extends Thread{ + public $stop; public $cmd; public $response; @@ -96,25 +79,113 @@ class RCONInstance extends Thread{ $this->password = $password; $this->maxClients = (int) $maxClients; for($n = 0; $n < $this->maxClients; ++$n){ - $this->{"client".$n} = null; - $this->{"status".$n} = 0; - $this->{"timeout".$n} = 0; + $this->{"client" . $n} = null; + $this->{"status" . $n} = 0; + $this->{"timeout" . $n} = 0; } $this->start(); } - - private function writePacket($client, $requestID, $packetType, $payload){ - $pk = Utils::writeLInt((int) $requestID) - . Utils::writeLInt((int) $packetType) - . $payload - . "\x00\x00"; //Terminate payload and packet - return socket_write($client, Utils::writeLInt(strlen($pk)).$pk); + + public function close(){ + $this->stop = true; } - + + public function run(){ + while($this->stop !== true){ + usleep(2000); + $r = [$socket = $this->socket]; + $w = null; + $e = null; + if(socket_select($r, $w, $e, 0) === 1){ + if(($client = socket_accept($this->socket)) !== false){ + socket_set_block($client); + socket_set_option($client, SOL_SOCKET, SO_KEEPALIVE, 1); + $done = false; + for($n = 0; $n < $this->maxClients; ++$n){ + if($this->{"client" . $n} === null){ + $this->{"client" . $n} = $client; + $this->{"status" . $n} = 0; + $this->{"timeout" . $n} = microtime(true) + 5; + $done = true; + break; + } + } + if($done === false){ + @socket_close($client); + } + } + } + + for($n = 0; $n < $this->maxClients; ++$n){ + $client = &$this->{"client" . $n}; + if($client !== null){ + if($this->{"status" . $n} !== -1 and $this->stop !== true){ + if($this->{"status" . $n} === 0 and $this->{"timeout" . $n} < microtime(true)){ //Timeout + $this->{"status" . $n} = -1; + break; + } + $p = $this->readPacket($client, $size, $requestID, $packetType, $payload); + if($p === false){ + $this->{"status" . $n} = -1; + break; + }elseif($p === null){ + break; + } + + switch($packetType){ + case 3: //Login + if($this->{"status" . $n} !== 0){ + $this->{"status" . $n} = -1; + break; + } + if($payload === $this->password){ + @socket_getpeername($client, $addr, $port); + $this->response = "[INFO] Successful Rcon connection from: /$addr:$port"; + $this->wait(); + $this->response = ""; + $this->writePacket($client, $requestID, 2, ""); + $this->{"status" . $n} = 1; + }else{ + $this->{"status" . $n} = -1; + $this->writePacket($client, -1, 2, ""); + break; + } + break; + case 2: //Command + if($this->{"status" . $n} !== 1){ + $this->{"status" . $n} = -1; + break; + } + if(strlen($payload) > 0){ + $this->cmd = ltrim($payload); + $this->wait(); + $this->writePacket($client, $requestID, 0, str_replace("\n", "\r\n", trim($this->response))); + $this->response = ""; + $this->cmd = ""; + } + break; + } + usleep(1); + }else{ + @socket_set_option($client, SOL_SOCKET, SO_LINGER, ["l_onoff" => 1, "l_linger" => 1]); + @socket_shutdown($client, 2); + @socket_set_block($client); + @socket_read($client, 1); + @socket_close($client); + $this->{"status" . $n} = 0; + $this->{"client" . $n} = null; + } + } + } + } + unset($this->socket, $this->cmd, $this->response, $this->stop); + exit(0); + } + private function readPacket($client, &$size, &$requestID, &$packetType, &$payload){ @socket_set_nonblock($client); $d = socket_read($client, 4); - if($this->stop === true){ + if($this->stop){ return false; }elseif($d === false){ return null; @@ -131,100 +202,12 @@ class RCONInstance extends Thread{ $payload = rtrim(socket_read($client, $size + 2)); //Strip two null bytes return true; } - - public function close(){ - $this->stop = true; - } - - public function run(){ - while($this->stop !== true){ - usleep(2000); - $r = array($socket = $this->socket); - $w = null; - $e = null; - if(socket_select($r, $w, $e, 0) === 1){ - if(($client = socket_accept($this->socket)) !== false){ - socket_set_block($client); - socket_set_option($client, SOL_SOCKET, SO_KEEPALIVE, 1); - $done = false; - for($n = 0; $n < $this->maxClients; ++$n){ - if($this->{"client".$n} === null){ - $this->{"client".$n} = $client; - $this->{"status".$n} = 0; - $this->{"timeout".$n} = microtime(true) + 5; - $done = true; - break; - } - } - if($done === false){ - @socket_close($client); - } - } - } - for($n = 0; $n < $this->maxClients; ++$n){ - $client = &$this->{"client".$n}; - if($client !== null){ - if($this->{"status".$n} !== -1 and $this->stop !== true){ - if($this->{"status".$n} === 0 and $this->{"timeout".$n} < microtime(true)){ //Timeout - $this->{"status".$n} = -1; - break; - } - $p = $this->readPacket($client, $size, $requestID, $packetType, $payload); - if($p === false){ - $this->{"status".$n} = -1; - break; - }elseif($p === null){ - break; - } - - switch($packetType){ - case 3: //Login - if($this->{"status".$n} !== 0){ - $this->{"status".$n} = -1; - break; - } - if($payload === $this->password){ - @socket_getpeername($client, $addr, $port); - $this->response = "[INFO] Successful Rcon connection from: /$addr:$port"; - $this->wait(); - $this->response = ""; - $this->writePacket($client, $requestID, 2, ""); - $this->{"status".$n} = 1; - }else{ - $this->{"status".$n} = -1; - $this->writePacket($client, -1, 2, ""); - break; - } - break; - case 2: //Command - if($this->{"status".$n} !== 1){ - $this->{"status".$n} = -1; - break; - } - if(strlen($payload) > 0){ - $this->cmd = ltrim($payload); - $this->wait(); - $this->writePacket($client, $requestID, 0, str_replace("\n", "\r\n", trim($this->response))); - $this->response = ""; - $this->cmd = ""; - } - break; - } - usleep(1); - }else{ - @socket_set_option($client, SOL_SOCKET, SO_LINGER, array("l_onoff" => 1, "l_linger" => 1)); - @socket_shutdown($client, 2); - @socket_set_block($client); - @socket_read($client, 1); - @socket_close($client); - $this->{"status".$n} = 0; - $this->{"client".$n} = null; - } - } - } - } - unset($this->socket, $this->cmd, $this->response, $this->stop); - exit(0); + private function writePacket($client, $requestID, $packetType, $payload){ + $pk = Utils::writeLInt((int) $requestID) + . Utils::writeLInt((int) $packetType) + . $payload + . "\x00\x00"; //Terminate payload and packet + return socket_write($client, Utils::writeLInt(strlen($pk)) . $pk); } } diff --git a/src/network/UDPSocket.php b/src/network/UDPSocket.php index 72355beb..7eb70c72 100644 --- a/src/network/UDPSocket.php +++ b/src/network/UDPSocket.php @@ -1,28 +1,9 @@ server = $server; $this->port = $port; @@ -44,6 +25,10 @@ class UDPSocket{ } } + public function unblock(){ + socket_set_nonblock($this->sock); + } + public function close($error = 125){ $this->connected = false; return @socket_close($this->sock); @@ -53,10 +38,6 @@ class UDPSocket{ socket_set_block($this->sock); } - public function unblock(){ - socket_set_nonblock($this->sock); - } - public function read(&$buf, &$source, &$port){ if($this->connected === false){ return false; @@ -68,9 +49,7 @@ class UDPSocket{ if($this->connected === false){ return false; } + return @socket_sendto($this->sock, $data, strlen($data), 0, $dest, $port); } - -} - -?> \ No newline at end of file +} \ No newline at end of file diff --git a/src/network/protocol/ProtocolInfo.php b/src/network/protocol/ProtocolInfo.php index 98edc082..f6d13dd4 100644 --- a/src/network/protocol/ProtocolInfo.php +++ b/src/network/protocol/ProtocolInfo.php @@ -1,30 +1,9 @@ server = ServerAPI::request(); - $addr = ($ip = $this->server->api->getProperty("server-ip")) != "" ? $ip:"0.0.0.0"; + $addr = ($ip = $this->server->api->getProperty("server-ip")) != "" ? $ip : "0.0.0.0"; $port = $this->server->api->getProperty("server-port"); console("[INFO] Setting query port to $port"); /* @@ -41,23 +23,28 @@ class QueryHandler{ Then, the Query class handles itself sending the packets in raw form, because packets can conflict with the MCPE ones. */ - - $this->server->schedule(20 * 30, array($this, "regenerateToken"), array(), true); + + $this->server->schedule(20 * 30, [$this, "regenerateToken"], [], true); $this->regenerateToken(); $this->lastToken = $this->token; $this->regenerateInfo(); console("[INFO] Query running on $addr:$port"); } - + + public function regenerateToken(){ + $this->lastToken = $this->token; + $this->token = Utils::readInt("\x00" . Utils::getRandomBytes(3, false)); + } + public function regenerateInfo(){ $str = ""; - $plist = "NostalgiaCore ".MAJOR_VERSION; + $plist = "NostalgiaCore " . MAJOR_VERSION; if($this->server->extraprops->get("query-plugins") == true){ $pl = $this->server->api->plugin->getList(); if(count($pl) > 0){ $plist .= ":"; foreach($pl as $p){ - $plist .= " ".str_replace(array(";", ":", " "), array("", "", "_"), $p["name"])." ".str_replace(array(";", ":", " "), array("", "", "_"), $p["version"]).";"; + $plist .= " " . str_replace([";", ":", " "], ["", "", "_"], $p["name"]) . " " . str_replace([";", ":", " "], ["", "", "_"], $p["version"]) . ";"; } $plist = substr($plist, 0, -1); } @@ -68,27 +55,22 @@ class QueryHandler{ $this->server->api->queryAPI->updateQueryData("tps", $this->server->debugInfo()["tps"]); $this->server->api->dhandle("query.update", null); $KVdata = $this->server->api->queryAPI->getQueryData(); - + foreach($KVdata as $key => $value){ - $str .= $key."\x00".$value."\x00"; + $str .= $key . "\x00" . $value . "\x00"; } $str .= "\x00\x01player_\x00\x00"; foreach($this->server->clients as $player){ if($player->username != ""){ - $str .= $player->username."\x00"; + $str .= $player->username . "\x00"; } } $str .= "\x00"; $this->longData = $str; $this->timeout = microtime(true) + 5; } - - public function regenerateToken(){ - $this->lastToken = $this->token; - $this->token = Utils::readInt("\x00".Utils::getRandomBytes(3, false)); - } - - public function handle(QueryPacket $packet){ + + public function handle(QueryPacket $packet){ $packet->decode(); switch($packet->packetType){ case QueryPacket::HANDSHAKE: //Handshake @@ -97,7 +79,7 @@ class QueryHandler{ $pk->port = $packet->port; $pk->packetType = QueryPacket::HANDSHAKE; $pk->sessionID = $packet->sessionID; - $pk->payload = $this->token."\x00"; + $pk->payload = $this->token . "\x00"; $pk->encode(); $this->server->send($pk); break; @@ -115,9 +97,9 @@ class QueryHandler{ if($this->timeout < microtime(true)){ $this->regenerateInfo(); } - $pk->payload = $this->longData; + $pk->payload = $this->longData; }else{ - $pk->payload = $this->server->name."\x00".(($this->server->gamemode & 0x01) === 0 ? "SMP":"CMP")."\x00".$this->server->api->level->getDefault()->getName()."\x00".count($this->server->clients)."\x00".$this->server->maxClients."\x00".Utils::writeLShort($this->server->api->getProperty("server-port")).$this->server->api->getProperty("server-ip", "0.0.0.0")."\x00"; + $pk->payload = $this->server->name . "\x00" . (($this->server->gamemode & 0x01) === 0 ? "SMP" : "CMP") . "\x00" . $this->server->api->level->getDefault()->getName() . "\x00" . count($this->server->clients) . "\x00" . $this->server->maxClients . "\x00" . Utils::writeLShort($this->server->api->getProperty("server-port")) . $this->server->api->getProperty("server-ip", "0.0.0.0") . "\x00"; } $pk->encode(); $this->server->send($pk); diff --git a/src/network/query/QueryPacket.php b/src/network/query/QueryPacket.php index 4c162dea..be8a674d 100644 --- a/src/network/query/QueryPacket.php +++ b/src/network/query/QueryPacket.php @@ -1,38 +1,20 @@ packetType = ord($this->buffer[2]); $this->sessionID = Utils::readInt(substr($this->buffer, 3, 4)); $this->payload = substr($this->buffer, 7); } - + public function encode(){ $this->buffer .= chr($this->packetType); $this->buffer .= Utils::writeInt($this->sessionID); diff --git a/src/network/raknet/RakNetCodec.php b/src/network/raknet/RakNetCodec.php index a009f63d..ba1ae8ef 100644 --- a/src/network/raknet/RakNetCodec.php +++ b/src/network/raknet/RakNetCodec.php @@ -1,32 +1,15 @@ packet = $packet; $this->buffer =& $this->packet->buffer; $this->encode(); } - + private function encode(){ if(strlen($this->packet->buffer) > 0){ return; @@ -87,7 +70,7 @@ class RakNetCodec{ $pointer = 0; sort($this->packet->packets, SORT_NUMERIC); $max = count($this->packet->packets); - + while($pointer < $max){ $type = true; $curr = $start = $this->packet->packets[$pointer]; @@ -116,69 +99,69 @@ class RakNetCodec{ $this->buffer .= $payload; break; default: - + } - + } - - private function encodeDataPacket(RakNetDataPacket $pk){ - $this->putByte(($pk->reliability << 5) | ($pk->hasSplit > 0 ? 0b00010000:0)); - $this->putShort(strlen($pk->buffer) << 3); - if($pk->reliability === 2 - or $pk->reliability === 3 - or $pk->reliability === 4 - or $pk->reliability === 6 - or $pk->reliability === 7){ - $this->putLTriad($pk->messageIndex); - } - - if($pk->reliability === 1 - or $pk->reliability === 3 - or $pk->reliability === 4 - or $pk->reliability === 7){ - $this->putLTriad($pk->orderIndex); - $this->putByte($pk->orderChannel); - } - - if($pk->hasSplit === true){ - $this->putInt($pk->splitCount); - $this->putShort($pk->splitID); - $this->putInt($pk->splitIndex); - } - - $this->buffer .= $pk->buffer; + + protected function putLong($v){ + $this->buffer .= Utils::writeLong($v); + } + + protected function putByte($v){ + $this->buffer .= chr($v); + } + + protected function putShort($v){ + $this->buffer .= Utils::writeShort($v); + } + + protected function putString($v){ + $this->putShort(strlen($v)); + $this->put($v); } protected function put($str){ $this->buffer .= $str; } - protected function putLong($v){ - $this->buffer .= Utils::writeLong($v); + protected function putLTriad($v){ + $this->buffer .= strrev(Utils::writeTriad($v)); } - + + private function encodeDataPacket(RakNetDataPacket $pk){ + $this->putByte(($pk->reliability << 5) | ($pk->hasSplit > 0 ? 0b00010000 : 0)); + $this->putShort(strlen($pk->buffer) << 3); + if($pk->reliability === 2 + or $pk->reliability === 3 + or $pk->reliability === 4 + or $pk->reliability === 6 + or $pk->reliability === 7){ + $this->putLTriad($pk->messageIndex); + } + + if($pk->reliability === 1 + or $pk->reliability === 3 + or $pk->reliability === 4 + or $pk->reliability === 7){ + $this->putLTriad($pk->orderIndex); + $this->putByte($pk->orderChannel); + } + + if($pk->hasSplit === true){ + $this->putInt($pk->splitCount); + $this->putShort($pk->splitID); + $this->putInt($pk->splitIndex); + } + + $this->buffer .= $pk->buffer; + } + protected function putInt($v){ $this->buffer .= Utils::writeInt($v); } - - protected function putShort($v){ - $this->buffer .= Utils::writeShort($v); - } protected function putTriad($v){ $this->buffer .= Utils::writeTriad($v); } - - protected function putLTriad($v){ - $this->buffer .= strrev(Utils::writeTriad($v)); - } - - protected function putByte($v){ - $this->buffer .= chr($v); - } - - protected function putString($v){ - $this->putShort(strlen($v)); - $this->put($v); - } } \ No newline at end of file diff --git a/src/network/raknet/RakNetDataPacket.php b/src/network/raknet/RakNetDataPacket.php index e4ab0c40..882480e6 100755 --- a/src/network/raknet/RakNetDataPacket.php +++ b/src/network/raknet/RakNetDataPacket.php @@ -1,28 +1,8 @@ setBuffer(chr($this->pid())); + public function getBuffer(){ + return $this->buffer; } - + public function setBuffer($buffer = ""){ $this->buffer = $buffer; $this->offset = 0; } - - public function getBuffer(){ - return $this->buffer; + + protected function reset(){ + $this->setBuffer(chr($this->pid())); } - + + abstract public function pid(); + + protected function getLong($unsigned = false){ + return Utils::readLong($this->get(8), $unsigned); + } + protected function get($len){ if($len <= 0){ $this->offset = strlen($this->buffer) - 1; @@ -62,35 +46,19 @@ abstract class RakNetDataPacket extends stdClass{ $this->offset += $len; return substr($this->buffer, $this->offset - $len, $len); } - - protected function put($str){ - $this->buffer .= $str; - } - - protected function getLong($unsigned = false){ - return Utils::readLong($this->get(8), $unsigned); - } protected function putLong($v){ $this->buffer .= Utils::writeLong($v); } - + protected function getInt($unsigned = false){ return Utils::readInt($this->get(4), $unsigned); } - + protected function putInt($v){ $this->buffer .= Utils::writeInt($v); } - - protected function getShort($unsigned = false){ - return Utils::readShort($this->get(2), $unsigned); - } - - protected function putShort($v){ - $this->buffer .= Utils::writeShort($v); - } - + protected function getFloat(){ return Utils::readFloat($this->get(4)); } @@ -99,46 +67,45 @@ abstract class RakNetDataPacket extends stdClass{ $this->buffer .= Utils::writeFloat($v); } - protected function getTriad(){ - return Utils::readTriad($this->get(3)); - } - - protected function putTriad($v){ - $this->buffer .= Utils::writeTriad($v); - } - - protected function getLTriad(){ return Utils::readTriad(strrev($this->get(3))); } - + protected function putLTriad($v){ $this->buffer .= strrev(Utils::writeTriad($v)); } - - protected function getByte(){ - return ord($this->get(1)); - } - - protected function putByte($v){ - $this->buffer .= chr($v); - } protected function getDataArray($len = 10){ - $data = array(); + $data = []; for($i = 1; $i <= $len and !$this->feof(); ++$i){ $data[] = $this->get($this->getTriad()); } return $data; } - protected function putDataArray(array $data = array()){ + protected function feof(){ + return !isset($this->buffer[$this->offset]); + } + + protected function getTriad(){ + return Utils::readTriad($this->get(3)); + } + + protected function putDataArray(array $data = []){ foreach($data as $v){ $this->putTriad(strlen($v)); $this->put($v); } } - + + protected function putTriad($v){ + $this->buffer .= Utils::writeTriad($v); + } + + protected function put($str){ + $this->buffer .= $str; + } + protected function getSlot(){ $id = $this->getShort(); $cnt = $this->getByte(); @@ -148,23 +115,35 @@ abstract class RakNetDataPacket extends stdClass{ $cnt ); } - + + protected function getShort($unsigned = false){ + return Utils::readShort($this->get(2), $unsigned); + } + + protected function getByte(){ + return ord($this->get(1)); + } + protected function putSlot(Item $item){ $this->putShort($item->getID()); $this->putByte($item->count); $this->putShort($item->getMetadata()); } - + + protected function putShort($v){ + $this->buffer .= Utils::writeShort($v); + } + + protected function putByte($v){ + $this->buffer .= chr($v); + } + protected function getString(){ return $this->get($this->getShort(true)); } - + protected function putString($v){ $this->putShort(strlen($v)); $this->put($v); } - - protected function feof(){ - return !isset($this->buffer[$this->offset]); - } } diff --git a/src/network/raknet/RakNetInfo.php b/src/network/raknet/RakNetInfo.php index 2823ee43..0093a4ce 100644 --- a/src/network/raknet/RakNetInfo.php +++ b/src/network/raknet/RakNetInfo.php @@ -1,25 +1,7 @@ packetID = (int) $packetID; } - + public function pid(){ return $this->packetID; } - - public function __destruct(){} + + public function __destruct(){ + } } \ No newline at end of file diff --git a/src/network/raknet/RakNetParser.php b/src/network/raknet/RakNetParser.php index 0e82f4fd..d0738753 100644 --- a/src/network/raknet/RakNetParser.php +++ b/src/network/raknet/RakNetParser.php @@ -1,29 +1,11 @@ buffer =& $buffer; $this->offset = 0; @@ -33,44 +15,7 @@ class RakNetParser{ $this->packet = false; } } - - private function get($len){ - if($len <= 0){ - $this->offset = strlen($this->buffer) - 1; - return ""; - } - if($len === true){ - return substr($this->buffer, $this->offset); - } - $this->offset += $len; - return substr($this->buffer, $this->offset - $len, $len); - } - - private function getLong($unsigned = false){ - return Utils::readLong($this->get(8), $unsigned); - } - - private function getInt($unsigned = false){ - return Utils::readInt($this->get(4), $unsigned); - } - - private function getShort($unsigned = false){ - return Utils::readShort($this->get(2), $unsigned); - } - - private function getLTriad(){ - return Utils::readTriad(strrev($this->get(3))); - } - - private function getByte(){ - return ord($this->get(1)); - } - - - private function feof(){ - return !isset($this->buffer[$this->offset]); - } - + private function parse(){ $this->packet = new RakNetPacket(ord($this->get(1))); $this->packet->buffer =& $this->buffer; @@ -110,15 +55,15 @@ class RakNetParser{ case RakNetInfo::DATA_PACKET_E: case RakNetInfo::DATA_PACKET_F: $this->packet->seqNumber = $this->getLTriad(); - $this->packet->data = array(); + $this->packet->data = []; while(!$this->feof() and ($pk = $this->parseDataPacket()) instanceof RakNetDataPacket){ - $this->packet->data[] = $pk; + $this->packet->data[] = $pk; } break; case RakNetInfo::NACK: case RakNetInfo::ACK: $count = $this->getShort(); - $this->packet->packets = array(); + $this->packet->packets = []; for($i = 0; $i < $count and !$this->feof(); ++$i){ if($this->getByte() === 0){ $start = $this->getLTriad(); @@ -139,33 +84,65 @@ class RakNetParser{ break; } } - + + private function get($len){ + if($len <= 0){ + $this->offset = strlen($this->buffer) - 1; + return ""; + } + if($len === true){ + return substr($this->buffer, $this->offset); + } + $this->offset += $len; + return substr($this->buffer, $this->offset - $len, $len); + } + + private function getLong($unsigned = false){ + return Utils::readLong($this->get(8), $unsigned); + } + + private function getByte(){ + return ord($this->get(1)); + } + + private function getShort($unsigned = false){ + return Utils::readShort($this->get(2), $unsigned); + } + + private function getLTriad(){ + return Utils::readTriad(strrev($this->get(3))); + } + + private function feof(){ + return !isset($this->buffer[$this->offset]); + } + private function parseDataPacket(){ $packetFlags = $this->getByte(); $reliability = ($packetFlags & 0b11100000) >> 5; $hasSplit = ($packetFlags & 0b00010000) > 0; $length = (int) ceil($this->getShort() / 8); if($reliability === 2 - or $reliability === 3 - or $reliability === 4 - or $reliability === 6 - or $reliability === 7){ + or $reliability === 3 + or $reliability === 4 + or $reliability === 6 + or $reliability === 7){ $messageIndex = $this->getLTriad(); }else{ $messageIndex = false; } - + if($reliability === 1 - or $reliability === 3 - or $reliability === 4 - or $reliability === 7){ + or $reliability === 3 + or $reliability === 4 + or $reliability === 7){ $orderIndex = $this->getLTriad(); $orderChannel = $this->getByte(); }else{ $orderIndex = false; $orderChannel = false; } - + if($hasSplit == true){ $splitCount = $this->getInt(); $splitID = $this->getShort(); @@ -175,10 +152,10 @@ class RakNetParser{ $splitID = false; $splitIndex = false; } - + if($length <= 0 - or $orderChannel >= 32 - or ($hasSplit === true and $splitIndex >= $splitCount)){ + or $orderChannel >= 32 + or ($hasSplit === true and $splitIndex >= $splitCount)){ return false; }else{ $pid = $this->getByte(); @@ -366,4 +343,8 @@ class RakNetParser{ return $data; } + private function getInt($unsigned = false){ + return Utils::readInt($this->get(4), $unsigned); + } + } \ No newline at end of file diff --git a/src/pmf/Level.php b/src/pmf/Level.php index 53189ac7..fa73c3d5 100644 --- a/src/pmf/Level.php +++ b/src/pmf/Level.php @@ -1,56 +1,17 @@ levelData[$index])){ - return false; - } - return ($this->levelData[$index]); - } - - public function setData($index, $data){ - if(!isset($this->levelData[$index])){ - return false; - } - $this->levelData[$index] = $data; - return true; - } - - public function close(){ - $chunks = null; - unset($chunks, $chunkChange, $locationTable); - parent::close(); - } - + private $chunks = []; + private $chunkChange = []; + public function __construct($file, $blank = false){ if(is_array($blank)){ $this->create($file, 0); @@ -72,13 +33,39 @@ class PMFLevel extends PMF{ } } } - + + private function createBlank(){ + $this->saveData(false); + $this->locationTable = []; + $cnt = pow($this->levelData["width"], 2); + @mkdir(dirname($this->file) . "/chunks/", 0755); + for($index = 0; $index < $cnt; ++$index){ + $this->chunks[$index] = false; + $this->chunkChange[$index] = false; + $this->locationTable[$index] = [ + 0 => 0, + ]; + $this->write(Utils::writeShort(0)); + $X = $Z = null; + $this->getXZ($index, $X, $Z); + @file_put_contents($this->getChunkPath($X, $Z), gzdeflate("", PMF_LEVEL_DEFLATE_LEVEL)); + } + if(!file_exists(dirname($this->file) . "/entities.yml")){ + $entities = new Config(dirname($this->file) . "/entities.yml", CONFIG_YAML); + $entities->save(); + } + if(!file_exists(dirname($this->file) . "/tiles.yml")){ + $tiles = new Config(dirname($this->file) . "/tiles.yml", CONFIG_YAML); + $tiles->save(); + } + } + public function saveData($locationTable = true){ $this->levelData["version"] = PMF_CURRENT_LEVEL_VERSION; @ftruncate($this->fp, 5); $this->seek(5); $this->write(chr($this->levelData["version"])); - $this->write(Utils::writeShort(strlen($this->levelData["name"])).$this->levelData["name"]); + $this->write(Utils::writeShort(strlen($this->levelData["name"])) . $this->levelData["name"]); $this->write(Utils::writeInt($this->levelData["seed"])); $this->write(Utils::writeInt($this->levelData["time"])); $this->write(Utils::writeFloat($this->levelData["spawnX"])); @@ -87,40 +74,33 @@ class PMFLevel extends PMF{ $this->write(chr($this->levelData["width"])); $this->write(chr($this->levelData["height"])); $extra = gzdeflate($this->levelData["extra"], PMF_LEVEL_DEFLATE_LEVEL); - $this->write(Utils::writeShort(strlen($extra)).$extra); + $this->write(Utils::writeShort(strlen($extra)) . $extra); $this->payloadOffset = ftell($this->fp); - + if($locationTable !== false){ $this->writeLocationTable(); } } - - private function createBlank(){ - $this->saveData(false); - $this->locationTable = array(); + + private function writeLocationTable(){ $cnt = pow($this->levelData["width"], 2); - @mkdir(dirname($this->file)."/chunks/", 0755); + @ftruncate($this->fp, $this->payloadOffset); + $this->seek($this->payloadOffset); for($index = 0; $index < $cnt; ++$index){ - $this->chunks[$index] = false; - $this->chunkChange[$index] = false; - $this->locationTable[$index] = array( - 0 => 0, - ); - $this->write(Utils::writeShort(0)); - $X = $Z = null; - $this->getXZ($index, $X, $Z); - @file_put_contents($this->getChunkPath($X, $Z), gzdeflate("", PMF_LEVEL_DEFLATE_LEVEL)); - } - if(!file_exists(dirname($this->file)."/entities.yml")){ - $entities = new Config(dirname($this->file)."/entities.yml", CONFIG_YAML); - $entities->save(); - } - if(!file_exists(dirname($this->file)."/tiles.yml")){ - $tiles = new Config(dirname($this->file)."/tiles.yml", CONFIG_YAML); - $tiles->save(); + $this->write(Utils::writeShort($this->locationTable[$index][0])); } } - + + public function getXZ($index, &$X = null, &$Z = null){ + $X = $index >> $this->log; + $Z = $index & (pow($this->log, 2) - 1); + return [$X, $Z]; + } + + private function getChunkPath($X, $Z){ + return dirname($this->file) . "/chunks/" . $Z . "." . $X . ".pmc"; + } + protected function parseLevel(){ if($this->getType() !== 0x00){ return false; @@ -146,10 +126,10 @@ class PMFLevel extends PMF{ console("[NOTICE] Empty/corrupt location table detected, forcing recovery"); fseek($this->fp, $lastseek); $c = gzdeflate(""); - $this->write(Utils::writeShort(strlen($c)).$c); + $this->write(Utils::writeShort(strlen($c)) . $c); $this->payloadOffset = ftell($this->fp); $this->levelData["extra"] = ""; - $cnt = pow($this->levelData["width"], 2); + $cnt = pow($this->levelData["width"], 2); for($index = 0; $index < $cnt; ++$index){ $this->write("\x00\xFF"); //Force index recreation } @@ -159,57 +139,132 @@ class PMFLevel extends PMF{ } return $this->readLocationTable(); } - - public function getIndex($X, $Z){ - $X = (int) $X; - $Z = (int) $Z; - return ($Z << $this->log) + $X; - } - - public function getXZ($index, &$X = null, &$Z = null){ - $X = $index >> $this->log; - $Z = $index & (pow($this->log, 2) - 1); - return array($X, $Z); - } - + private function readLocationTable(){ - $this->locationTable = array(); + $this->locationTable = []; $cnt = pow($this->levelData["width"], 2); $this->seek($this->payloadOffset); for($index = 0; $index < $cnt; ++$index){ $this->chunks[$index] = false; $this->chunkChange[$index] = false; - $this->locationTable[$index] = array( + $this->locationTable[$index] = [ 0 => Utils::readShort($this->read(2)), //16 bit flags - ); + ]; } return true; } - - private function writeLocationTable(){ - $cnt = pow($this->levelData["width"], 2); - @ftruncate($this->fp, $this->payloadOffset); - $this->seek($this->payloadOffset); - for($index = 0; $index < $cnt; ++$index){ - $this->write(Utils::writeShort($this->locationTable[$index][0])); + + public function getData($index){ + if(!isset($this->levelData[$index])){ + return false; } + return ($this->levelData[$index]); } - - private function getChunkPath($X, $Z){ - return dirname($this->file)."/chunks/".$Z.".".$X.".pmc"; + + public function setData($index, $data){ + if(!isset($this->levelData[$index])){ + return false; + } + $this->levelData[$index] = $data; + return true; } - + + public function close(){ + $chunks = null; + unset($chunks, $chunkChange, $locationTable); + parent::close(); + } + + public function unloadChunk($X, $Z, $save = true){ + $X = (int) $X; + $Z = (int) $Z; + if(!$this->isChunkLoaded($X, $Z)){ + return false; + }elseif($save !== false){ + $this->saveChunk($X, $Z); + } + $index = $this->getIndex($X, $Z); + $this->chunks[$index] = null; + $this->chunkChange[$index] = null; + unset($this->chunks[$index], $this->chunkChange[$index]); + return true; + } + + public function isChunkLoaded($X, $Z){ + $index = $this->getIndex($X, $Z); + if(!isset($this->chunks[$index]) or $this->chunks[$index] === false){ + return false; + } + return true; + } + + public function getIndex($X, $Z){ + $X = (int) $X; + $Z = (int) $Z; + return ($Z << $this->log) + $X; + } + + public function saveChunk($X, $Z){ + $X = (int) $X; + $Z = (int) $Z; + if(!$this->isChunkLoaded($X, $Z)){ + return false; + } + $index = $this->getIndex($X, $Z); + if(!isset($this->chunkChange[$index]) or $this->chunkChange[$index][-1] === false){//No changes in chunk + return true; + } + + $chunk = @gzopen($this->getChunkPath($X, $Z), "wb" . PMF_LEVEL_DEFLATE_LEVEL); + $bitmap = 0; + for($Y = 0; $Y < $this->levelData["height"]; ++$Y){ + if($this->chunks[$index][$Y] !== false and ((isset($this->chunkChange[$index][$Y]) and $this->chunkChange[$index][$Y] === 0) or !$this->isMiniChunkEmpty($X, $Z, $Y))){ + gzwrite($chunk, $this->chunks[$index][$Y]); + $bitmap |= 1 << $Y; + }else{ + $this->chunks[$index][$Y] = false; + } + $this->chunkChange[$index][$Y] = 0; + } + $this->chunkChange[$index][-1] = false; + $this->locationTable[$index][0] = $bitmap; + $this->seek($this->payloadOffset + ($index << 1)); + $this->write(Utils::writeShort($this->locationTable[$index][0])); + return true; + } + + protected function isMiniChunkEmpty($X, $Z, $Y){ + $index = $this->getIndex($X, $Z); + if($this->chunks[$index][$Y] !== false){ + if(substr_count($this->chunks[$index][$Y], "\x00") < 8192){ + return false; + } + } + return true; + } + + public function getMiniChunk($X, $Z, $Y){ + if($this->loadChunk($X, $Z) === false){ + return str_repeat("\x00", 8192); + } + $index = $this->getIndex($X, $Z); + if(!isset($this->chunks[$index][$Y]) or $this->chunks[$index][$Y] === false){ + return str_repeat("\x00", 8192); + } + return $this->chunks[$index][$Y]; + } + public function loadChunk($X, $Z){ $index = self::getIndex($X, $Z); if($this->isChunkLoaded($X, $Z)){ return true; - + }elseif(!isset($this->locationTable[$index])){ return false; } - + $info = $this->locationTable[$index]; $this->seek($info[0]); @@ -217,8 +272,8 @@ class PMFLevel extends PMF{ if($chunk === false){ return false; } - $this->chunks[$index] = array(); - $this->chunkChange[$index] = array(-1 => false); + $this->chunks[$index] = []; + $this->chunkChange[$index] = [-1 => false]; for($Y = 0; $Y < $this->levelData["height"]; ++$Y){ $t = 1 << $Y; if(($info[0] & $t) === $t){ @@ -234,40 +289,7 @@ class PMFLevel extends PMF{ @gzclose($chunk); return true; } - - public function unloadChunk($X, $Z, $save = true){ - $X = (int) $X; - $Z = (int) $Z; - if(!$this->isChunkLoaded($X, $Z)){ - return false; - }elseif($save !== false){ - $this->saveChunk($X, $Z); - } - $index = $this->getIndex($X, $Z); - $this->chunks[$index] = null; - $this->chunkChange[$index] = null; - unset($this->chunks[$index], $this->chunkChange[$index]); - return true; - } - - public function isChunkLoaded($X, $Z){ - $index = $this->getIndex($X, $Z); - if(!isset($this->chunks[$index]) or $this->chunks[$index] === false){ - return false; - } - return true; - } - - protected function isMiniChunkEmpty($X, $Z, $Y){ - $index = $this->getIndex($X, $Z); - if($this->chunks[$index][$Y] !== false){ - if(substr_count($this->chunks[$index][$Y], "\x00") < 8192){ - return false; - } - } - return true; - } - + protected function fillMiniChunk($X, $Z, $Y){ if($this->isChunkLoaded($X, $Z) === false){ return false; @@ -279,18 +301,7 @@ class PMFLevel extends PMF{ $this->locationTable[$index][0] |= 1 << $Y; return true; } - - public function getMiniChunk($X, $Z, $Y){ - if($this->loadChunk($X, $Z) === false){ - return str_repeat("\x00", 8192); - } - $index = $this->getIndex($X, $Z); - if(!isset($this->chunks[$index][$Y]) or $this->chunks[$index][$Y] === false){ - return str_repeat("\x00", 8192); - } - return $this->chunks[$index][$Y]; - } - + public function setMiniChunk($X, $Z, $Y, $data){ if($this->isChunkLoaded($X, $Z) === false){ $this->loadChunk($X, $Z); @@ -305,7 +316,7 @@ class PMFLevel extends PMF{ $this->locationTable[$index][0] |= 1 << $Y; return true; } - + public function getBlockID($x, $y, $z){ if($y > 127 or $y < 0 or $x < 0 or $z < 0 or $x > 255 or $z > 255){ return 0; @@ -318,9 +329,9 @@ class PMFLevel extends PMF{ $aZ = $z - ($Z << 4); $aY = $y - ($Y << 4); $b = ord($this->chunks[$index][$Y][(int) ($aY + ($aX << 5) + ($aZ << 9))]); - return $b; + return $b; } - + public function setBlockID($x, $y, $z, $block){ if($y > 127 or $y < 0 or $x < 0 or $z < 0 or $x > 255 or $z > 255){ return false; @@ -345,7 +356,7 @@ class PMFLevel extends PMF{ $this->chunkChange[$index][-1] = true; return true; } - + public function getBlockDamage($x, $y, $z){ if($y > 127 or $y < 0 or $x < 0 or $z < 0 or $x > 255 or $z > 255){ return 0; @@ -363,9 +374,9 @@ class PMFLevel extends PMF{ }else{ $m = $m >> 4; } - return $m; + return $m; } - + public function setBlockDamage($x, $y, $z, $damage){ if($y > 127 or $y < 0 or $x < 0 or $z < 0 or $x > 255 or $z > 255){ return false; @@ -407,15 +418,15 @@ class PMFLevel extends PMF{ $Z = $z >> 4; $Y = $y >> 4; if($x < 0 or $z < 0 or $X >= $this->levelData["width"] or $Z >= $this->levelData["width"] or $Y >= $this->levelData["height"] or $y < 0){ - return array(AIR, 0); + return [AIR, 0]; } $index = $this->getIndex($X, $Z); if(!isset($this->chunks[$index]) or $this->chunks[$index] === false){ if($this->loadChunk($X, $Z) === false){ - return array(AIR, 0); + return [AIR, 0]; } }elseif($this->chunks[$index][$Y] === false){ - return array(AIR, 0); + return [AIR, 0]; } $aX = $x - ($X << 4); $aZ = $z - ($Z << 4); @@ -428,9 +439,9 @@ class PMFLevel extends PMF{ }else{ $m = $m >> 4; } - return array($b, $m); + return [$b, $m]; } - + public function setBlock($x, $y, $z, $block, $meta = 0){ $X = $x >> 4; $Z = $z >> 4; @@ -470,13 +481,12 @@ class PMFLevel extends PMF{ ++$this->chunkChange[$index][$Y]; } $this->chunkChange[$index][-1] = true; - if($old_b instanceof LiquidBlock) - { + if($old_b instanceof LiquidBlock){ $pos = new Position($x, $y, $z, $this->level); - for($side = 0; $side <= 5; ++$side) - { + for($side = 0; $side <= 5; ++$side){ $b = $pos->getSide($side); - if($b instanceof LavaBlock) ServerAPI::request()->api->block->scheduleBlockUpdate(new Position($b, 0, 0, $this->level), 40, BLOCK_UPDATE_NORMAL); + if($b instanceof LavaBlock) + ServerAPI::request()->api->block->scheduleBlockUpdate(new Position($b, 0, 0, $this->level), 40, BLOCK_UPDATE_NORMAL); else ServerAPI::request()->api->block->scheduleBlockUpdate(new Position($b, 0, 0, $this->level), 10, BLOCK_UPDATE_NORMAL); } } @@ -484,36 +494,7 @@ class PMFLevel extends PMF{ } return false; } - - public function saveChunk($X, $Z){ - $X = (int) $X; - $Z = (int) $Z; - if(!$this->isChunkLoaded($X, $Z)){ - return false; - } - $index = $this->getIndex($X, $Z); - if(!isset($this->chunkChange[$index]) or $this->chunkChange[$index][-1] === false){//No changes in chunk - return true; - } - - $chunk = @gzopen($this->getChunkPath($X, $Z), "wb".PMF_LEVEL_DEFLATE_LEVEL); - $bitmap = 0; - for($Y = 0; $Y < $this->levelData["height"]; ++$Y){ - if($this->chunks[$index][$Y] !== false and ((isset($this->chunkChange[$index][$Y]) and $this->chunkChange[$index][$Y] === 0) or !$this->isMiniChunkEmpty($X, $Z, $Y))){ - gzwrite($chunk, $this->chunks[$index][$Y]); - $bitmap |= 1 << $Y; - }else{ - $this->chunks[$index][$Y] = false; - } - $this->chunkChange[$index][$Y] = 0; - } - $this->chunkChange[$index][-1] = false; - $this->locationTable[$index][0] = $bitmap; - $this->seek($this->payloadOffset + ($index << 1)); - $this->write(Utils::writeShort($this->locationTable[$index][0])); - return true; - } - + public function doSaveRound(){ foreach($this->chunks as $index => $chunk){ $this->getXZ($index, $X, $Z); diff --git a/src/pmf/PMF.php b/src/pmf/PMF.php index 87ed1a78..447ef6d5 100644 --- a/src/pmf/PMF.php +++ b/src/pmf/PMF.php @@ -1,32 +1,14 @@ create($file, $type, $version); @@ -36,15 +18,33 @@ class PMF{ } } } - - public function getVersion(){ - return $this->version; + + public function create($file, $type, $version = PMF_CURRENT_VERSION){ + $this->file = $file; + @mkdir(dirname($this->file), 0755, true); + if(!is_resource($this->fp)){ + if(($this->fp = @fopen($file, "c+b")) === false){ + return false; + } + } + $this->seek(0); + $this->write("PMF" . chr((int) $version) . chr((int) $type)); } - - public function getType(){ - return $this->type; + + public function seek($offset, $whence = SEEK_SET){ + if(is_resource($this->fp)){ + return fseek($this->fp, (int) $offset, (int) $whence); + } + return false; } - + + public function write($string, $length = false){ + if(is_resource($this->fp)){ + return ($length === false ? fwrite($this->fp, $string) : fwrite($this->fp, $string, $length)); + } + return false; + } + public function load($file){ $this->close(); $this->file = $file; @@ -58,28 +58,7 @@ class PMF{ } return false; } - - public function parseInfo(){ - $this->seek(0); - if(fread($this->fp, 3) !== "PMF"){ - return false; - } - $this->version = ord($this->read(1)); - switch($this->version){ - case 0x01: - $this->type = ord($this->read(1)); - break; - default: - console("[ERROR] Tried loading non-supported PMF version ".$this->version." on file ".$this->file); - return false; - } - return true; - } - - public function getFile(){ - return $this->file; - } - + public function close(){ unset($this->version, $this->type, $this->file); if(is_object($this->fp)){ @@ -87,19 +66,24 @@ class PMF{ fclose($this->fp); } } - - public function create($file, $type, $version = PMF_CURRENT_VERSION){ - $this->file = $file; - @mkdir(dirname($this->file), 0755, true); - if(!is_resource($this->fp)){ - if(($this->fp = @fopen($file, "c+b")) === false){ - return false; - } - } + + public function parseInfo(){ $this->seek(0); - $this->write("PMF" . chr((int) $version) . chr((int) $type)); + if(fread($this->fp, 3) !== "PMF"){ + return false; + } + $this->version = ord($this->read(1)); + switch($this->version){ + case 0x01: + $this->type = ord($this->read(1)); + break; + default: + console("[ERROR] Tried loading non-supported PMF version " . $this->version . " on file " . $this->file); + return false; + } + return true; } - + public function read($length){ if($length <= 0){ return ""; @@ -109,19 +93,17 @@ class PMF{ } return false; } - - public function write($string, $length = false){ - if(is_resource($this->fp)){ - return ($length === false ? fwrite($this->fp, $string) : fwrite($this->fp, $string, $length)); - } - return false; + + public function getVersion(){ + return $this->version; } - - public function seek($offset, $whence = SEEK_SET){ - if(is_resource($this->fp)){ - return fseek($this->fp, (int) $offset, (int) $whence); - } - return false; + + public function getType(){ + return $this->type; + } + + public function getFile(){ + return $this->file; } } \ No newline at end of file diff --git a/src/pmf/Plugin.php b/src/pmf/Plugin.php index e46ed200..d5f12692 100644 --- a/src/pmf/Plugin.php +++ b/src/pmf/Plugin.php @@ -1,42 +1,21 @@ load($file); $this->parseInfo(); $this->parsePlugin(); } - - public function getPluginInfo(){ - return $this->pluginData; - } - + protected function parsePlugin(){ if($this->getType() !== 0x01){ return false; @@ -58,7 +37,7 @@ class PMFPlugin extends PMF{ $this->pluginData["identifier"] = $this->read(Utils::readShort($this->read(2), false)); //Will be used to check for updates if($this->pluginData["fversion"] >= 0x02){ $data = explode(";", gzinflate($this->read(Utils::readInt($this->read(4))))); - $this->pluginData["extra"] = array(); + $this->pluginData["extra"] = []; foreach($data as $v){ $v = trim($v); if($v != ""){ @@ -67,7 +46,7 @@ class PMFPlugin extends PMF{ $this->pluginData["extra"][substr($v, 0, $kl)] = substr($v, $kl + 1); } } - + }else{ $this->pluginData["extra"] = gzinflate($this->read(Utils::readShort($this->read(2), false))); } @@ -78,4 +57,8 @@ class PMFPlugin extends PMF{ $this->pluginData["code"] = gzinflate($this->pluginData["code"]); } + public function getPluginInfo(){ + return $this->pluginData; + } + } \ No newline at end of file diff --git a/src/recipes/CraftingRecipes.php b/src/recipes/CraftingRecipes.php index 4f072756..6854317b 100644 --- a/src/recipes/CraftingRecipes.php +++ b/src/recipes/CraftingRecipes.php @@ -1,196 +1,178 @@ CLAY_BLOCK:0x1", - "WOODEN_PLANKS:?x4=>WORKBENCH:0x1", - "GLOWSTONE_DUST:?x4=>GLOWSTONE_BLOCK:0x1", - "PUMPKIN:?x1,TORCH:?x1=>LIT_PUMPKIN:0x1", - "SNOWBALL:?x4=>SNOW_BLOCK:0x1", - "WOODEN_PLANKS:?x2=>STICK:0x4", - "COBBLESTONE:?x4=>STONECUTTER:0x1", - "WOOD:0x1=>WOODEN_PLANKS:0x4", - "WOOD:1x1=>WOODEN_PLANKS:1x4", - "WOOD:2x1=>WOODEN_PLANKS:2x4", - //"WOOD:3x1=>WOODEN_PLANKS:3x4", - "WOOL:0x1,DYE:0x1=>WOOL:15x1", - "WOOL:0x1,DYE:1x1=>WOOL:14x1", - "WOOL:0x1,DYE:2x1=>WOOL:13x1", - "WOOL:0x1,DYE:3x1=>WOOL:12x1", - "WOOL:0x1,DYE:4x1=>WOOL:11x1", - "WOOL:0x1,DYE:5x1=>WOOL:10x1", - "WOOL:0x1,DYE:6x1=>WOOL:9x1", - "WOOL:0x1,DYE:7x1=>WOOL:8x1", - "WOOL:0x1,DYE:8x1=>WOOL:7x1", - "WOOL:0x1,DYE:9x1=>WOOL:6x1", - "WOOL:0x1,DYE:10x1=>WOOL:5x1", - "WOOL:0x1,DYE:11x1=>WOOL:4x1", - "WOOL:0x1,DYE:12x1=>WOOL:3x1", - "WOOL:0x1,DYE:13x1=>WOOL:2x1", - "WOOL:0x1,DYE:14x1=>WOOL:1x1", - "STRING:?x4=>WOOL:0x1", - - //Tools - "IRON_INGOT:?x1,FLINT:?x1=>FLINT_STEEL:0x1", - "IRON_INGOT:?x2=>SHEARS:0x1", - "COAL:0x1,STICK:?x1=>TORCH:0x4", - "COAL:1x1,STICK:?x1=>TORCH:0x4", - - //Food & protection - "MELON_SLICE:?x1=>MELON_SEEDS:0x1", - "PUMPKIN:?x1=>PUMPKIN_SEEDS:0x4", - "PUMPKIN:?x1,EGG:?x1,SUGAR:?x1=>PUMPKIN_PIE:0x1", - "BROWN_MUSHROOM:?x1,RED_MUSHROOM:?x1,BOWL:?x1=>MUSHROOM_STEW:0x1", - "SUGARCANE:?x1=>SUGAR:0x1", - "MELON_SLICE:?x1=>MELON_SEEDS:0x1", - "HAY_BALE:?x1=>WHEAT:0x9", - - //Items - "DIAMOND_BLOCK:?x1=>DIAMOND:0x9", - "GOLD_BLOCK:?x1=>GOLD_INGOT:0x9", - "IRON_BLOCK:?x1=>IRON_INGOT:0x9", - "LAPIS_BLOCK:?x1=>DYE:4x9",//Lapis Lazuli - "DANDELION:?x1=>DYE:11x2",//Dandelion Yellow - "BONE:?x1=>DYE:15x3",//Bone Meal - "DYE:0x1,DYE:14x1=>DYE:3x2",//Cocoa Beans - "DYE:0x1,DYE:1x1,DYE:11x1=>DYE:3x3",//Cocoa Beans - "DYE:1x1,DYE:15x1=>DYE:9x2",//Pink Dye - "DYE:1x1,DYE:11x1=>DYE:14x2",//Orange Dye - "DYE:2x1,DYE:15x1=>DYE:10x2",//Lime Dye - "DYE:4x1,DYE:15x1=>DYE:12x2",//Light Blue Dye - "DYE:2x1,DYE:4x1=>DYE:6x2",//Cyan Dye - "DYE:1x1,DYE:4x1=>DYE:5x2",//Purple Dye - "DYE:1x1,DYE:4x1,DYE:15x1=>DYE:13x3",//Magenta Dye - "BEETROOT:?x1=>DYE:1x2",//Rose Red - "DYE:15x1,DYE:1x2,DYE:4x1=>DYE:13x4",//Magenta Dye - "DYE:5x1,DYE:9x1=>DYE:13x2",//Magenta Dye - "DYE:0x1,DYE:15x1=>DYE:8x2",//Gray Dye - "DYE:0x1,DYE:15x2=>DYE:7x3",//Light Gray Dye - "DYE:0x1,DYE:8x1=>DYE:7x2",//Light Gray Dye - "WOOL:14x2=>CARPET:14x3", - ); - - private static $big = array(//Probably means only craftable on crafting bench. Name it better! - //Building - "WOOL:?x3,WOODEN_PLANKS:?x3=>BED:0x1", - "WOODEN_PLANKS:?x8=>CHEST:0x1", - "STICK:?x6=>FENCE:0x2", - "STICK:?x4,WOODEN_PLANKS:?x2=>FENCE_GATE:0x1", - "COBBLESTONE:?x8=>FURNACE:0x1", - "GLASS:?x6=>GLASS_PANE:0x16", - "STICK:?x7=>LADDER:0x2", - "DIAMOND:?x3,IRON_INGOT:?x6=>NETHER_REACTOR:0x1", - "WOODEN_PLANKS:?x6=>TRAPDOOR:0x2", - "WOODEN_PLANKS:?x6=>WOODEN_DOOR:0x1", - "WOODEN_PLANKS:0x6=>WOODEN_STAIRS:0x4", - "WOODEN_PLANKS:0x3=>WOOD_SLAB:0x6", - "WOODEN_PLANKS:1x6=>SPRUCE_WOOD_STAIRS:0x4", - "WOODEN_PLANKS:1x3=>WOOD_SLAB:1x6", - "WOODEN_PLANKS:2x6=>BIRCH_WOOD_STAIRS:0x4", - "WOODEN_PLANKS:2x3=>WOOD_SLAB:2x6", - //"WOODEN_PLANKS:3x6=>JUNGLE_WOOD_STAIRS:0x4", - //"WOODEN_PLANKS:3x3=>WOOD_SLAB:3x6", - - //Tools - "STICK:?x1,FEATHER:?x1,FLINT:?x1=>ARROW:0x4", - "STICK:?x3,STRING:?x3=>BOW:0x1", - "IRON_INGOT:?x3=>BUCKET:0x1", - "GOLD_INGOT:?x4,REDSTONE_DUST:?x1=>CLOCK:0x1", - "IRON_INGOT:?x4,REDSTONE_DUST:?x1=>COMPASS:0x1", - "DIAMOND:?x3,STICK:?x2=>DIAMOND_AXE:0x1", - "DIAMOND:?x2,STICK:?x2=>DIAMOND_HOE:0x1", - "DIAMOND:?x3,STICK:?x2=>DIAMOND_PICKAXE:0x1", - "DIAMOND:?x1,STICK:?x2=>DIAMOND_SHOVEL:0x1", - "DIAMOND:?x2,STICK:?x1=>DIAMOND_SWORD:0x1", - "GOLD_INGOT:?x3,STICK:?x2=>GOLDEN_AXE:0x1", - "GOLD_INGOT:?x2,STICK:?x2=>GOLDEN_HOE:0x1", - "GOLD_INGOT:?x3,STICK:?x2=>GOLDEN_PICKAXE:0x1", - "GOLD_INGOT:?x1,STICK:?x2=>GOLDEN_SHOVEL:0x1", - "GOLD_INGOT:?x2,STICK:?x1=>GOLDEN_SWORD:0x1", - "IRON_INGOT:?x3,STICK:?x2=>IRON_AXE:0x1", - "IRON_INGOT:?x2,STICK:?x2=>IRON_HOE:0x1", - "IRON_INGOT:?x3,STICK:?x2=>IRON_PICKAXE:0x1", - "IRON_INGOT:?x1,STICK:?x2=>IRON_SHOVEL:0x1", - "IRON_INGOT:?x2,STICK:?x1=>IRON_SWORD:0x1", - "COBBLESTONE:?x3,STICK:?x2=>STONE_AXE:0x1", - "COBBLESTONE:?x2,STICK:?x2=>STONE_HOE:0x1", - "COBBLESTONE:?x3,STICK:?x2=>STONE_PICKAXE:0x1", - "COBBLESTONE:?x1,STICK:?x2=>STONE_SHOVEL:0x1", - "COBBLESTONE:?x2,STICK:?x1=>STONE_SWORD:0x1", - "SAND:?x4,GUNPOWDER:?x5=>TNT:0x1", - "WOODEN_PLANKS:?x3,STICK:?x2=>WOODEN_AXE:0x1", - "WOODEN_PLANKS:?x2,STICK:?x2=>WOODEN_HOE:0x1", - "WOODEN_PLANKS:?x3,STICK:?x2=>WOODEN_PICKAXE:0x1", - "WOODEN_PLANKS:?x1,STICK:?x2=>WOODEN_SHOVEL:0x1", - "WOODEN_PLANKS:?x2,STICK:?x1=>WOODEN_SWORD:0x1", - "IRON_INGOT:?x6,STICK:?x1=>RAIL:0x16", - "GOLD_INGOT:?x6,STICK:?x1,REDSTONE:?x1=>POWERED_RAIL:0x6", - - //Food & protection - "BEETROOT:?x4,BOWL:?x1=>BEETROOT_SOUP:0x1", - "WOODEN_PLANKS:?x3=>BOWL:0x4", - "WHEAT:?x3=>BREAD:0x1", - "WHEAT:?x3,BUCKET:1x3,EGG:?x1,SUGAR:?x2=>CAKE:0x1", - "DIAMOND:?x4=>DIAMOND_BOOTS:0x1", - "DIAMOND:?x8=>DIAMOND_CHESTPLATE:0x1", - "DIAMOND:?x5=>DIAMOND_HELMET:0x1", - "DIAMOND:?x7=>DIAMOND_LEGGINGS:0x1", - "GOLD_INGOT:?x4=>GOLDEN_BOOTS:0x1", - "GOLD_INGOT:?x8=>GOLDEN_CHESTPLATE:0x1", - "GOLD_INGOT:?x5=>GOLDEN_HELMET:0x1", - "GOLD_INGOT:?x7=>GOLDEN_LEGGINGS:0x1", - "IRON_INGOT:?x4=>IRON_BOOTS:0x1", - "IRON_INGOT:?x8=>IRON_CHESTPLATE:0x1", - "IRON_INGOT:?x5=>IRON_HELMET:0x1", - "IRON_INGOT:?x7=>IRON_LEGGINGS:0x1", - "LEATHER:?x4=>LEATHER_BOOTS:0x1", - "LEATHER:?x8=>LEATHER_TUNIC:0x1", - "LEATHER:?x5=>LEATHER_CAP:0x1", - "LEATHER:?x7=>LEATHER_PANTS:0x1", - //"FIRE:?x4=>CHAIN_BOOTS:0x1", - //"FIRE:?x8=>CHAIN_CHESTPLATE:0x1", - //"FIRE:?x5=>CHAIN_HELMET:0x1", - //"FIRE:?x7=>CHAIN_LEGGINGS:0x1", - - //Items - "DIAMOND:?x9=>DIAMOND_BLOCK:0x1", - "GOLD_INGOT:?x9=>GOLD_BLOCK:0x1", - "IRON_INGOT:?x9=>IRON_BLOCK:0x1", - "IRON_INGOT:?x5=>MINECART:0x1", - "WHEAT:?x9=>HAY_BALE:0x1", - "PAPER:?x3=>BOOK:0x1", - "WOODEN_PLANKS:?x6,BOOK:?x3=>BOOKSHELF:0x1", - "DYE:4x9=>LAPIS_BLOCK:0x1", - "WOOL:?x1,STICK:?x8=>PAINTING:0x1", - "SUGARCANE:?x3=>PAPER:0x3", - "WOODEN_PLANKS:?x6,STICK:?x1=>SIGN:0x1", - "IRON_INGOT:?x6=>IRON_BARS:0x16", - "COAL:0x9=>COAL_BLOCK:0x1", - "COAL_BLOCK:?x1=>COAL:0x9", - "MELON_SLICE:?x9=>MELON_BLOCK:0x1", - ); - - private static $stone = array( + + private static $small = [//Probably means craftable on crafting bench and in inventory. Name it better! + //Building + "CLAY:?x4=>CLAY_BLOCK:0x1", + "WOODEN_PLANKS:?x4=>WORKBENCH:0x1", + "GLOWSTONE_DUST:?x4=>GLOWSTONE_BLOCK:0x1", + "PUMPKIN:?x1,TORCH:?x1=>LIT_PUMPKIN:0x1", + "SNOWBALL:?x4=>SNOW_BLOCK:0x1", + "WOODEN_PLANKS:?x2=>STICK:0x4", + "COBBLESTONE:?x4=>STONECUTTER:0x1", + "WOOD:0x1=>WOODEN_PLANKS:0x4", + "WOOD:1x1=>WOODEN_PLANKS:1x4", + "WOOD:2x1=>WOODEN_PLANKS:2x4", + //"WOOD:3x1=>WOODEN_PLANKS:3x4", + "WOOL:0x1,DYE:0x1=>WOOL:15x1", + "WOOL:0x1,DYE:1x1=>WOOL:14x1", + "WOOL:0x1,DYE:2x1=>WOOL:13x1", + "WOOL:0x1,DYE:3x1=>WOOL:12x1", + "WOOL:0x1,DYE:4x1=>WOOL:11x1", + "WOOL:0x1,DYE:5x1=>WOOL:10x1", + "WOOL:0x1,DYE:6x1=>WOOL:9x1", + "WOOL:0x1,DYE:7x1=>WOOL:8x1", + "WOOL:0x1,DYE:8x1=>WOOL:7x1", + "WOOL:0x1,DYE:9x1=>WOOL:6x1", + "WOOL:0x1,DYE:10x1=>WOOL:5x1", + "WOOL:0x1,DYE:11x1=>WOOL:4x1", + "WOOL:0x1,DYE:12x1=>WOOL:3x1", + "WOOL:0x1,DYE:13x1=>WOOL:2x1", + "WOOL:0x1,DYE:14x1=>WOOL:1x1", + "STRING:?x4=>WOOL:0x1", + + //Tools + "IRON_INGOT:?x1,FLINT:?x1=>FLINT_STEEL:0x1", + "IRON_INGOT:?x2=>SHEARS:0x1", + "COAL:0x1,STICK:?x1=>TORCH:0x4", + "COAL:1x1,STICK:?x1=>TORCH:0x4", + + //Food & protection + "MELON_SLICE:?x1=>MELON_SEEDS:0x1", + "PUMPKIN:?x1=>PUMPKIN_SEEDS:0x4", + "PUMPKIN:?x1,EGG:?x1,SUGAR:?x1=>PUMPKIN_PIE:0x1", + "BROWN_MUSHROOM:?x1,RED_MUSHROOM:?x1,BOWL:?x1=>MUSHROOM_STEW:0x1", + "SUGARCANE:?x1=>SUGAR:0x1", + "MELON_SLICE:?x1=>MELON_SEEDS:0x1", + "HAY_BALE:?x1=>WHEAT:0x9", + + //Items + "DIAMOND_BLOCK:?x1=>DIAMOND:0x9", + "GOLD_BLOCK:?x1=>GOLD_INGOT:0x9", + "IRON_BLOCK:?x1=>IRON_INGOT:0x9", + "LAPIS_BLOCK:?x1=>DYE:4x9",//Lapis Lazuli + "DANDELION:?x1=>DYE:11x2",//Dandelion Yellow + "BONE:?x1=>DYE:15x3",//Bone Meal + "DYE:0x1,DYE:14x1=>DYE:3x2",//Cocoa Beans + "DYE:0x1,DYE:1x1,DYE:11x1=>DYE:3x3",//Cocoa Beans + "DYE:1x1,DYE:15x1=>DYE:9x2",//Pink Dye + "DYE:1x1,DYE:11x1=>DYE:14x2",//Orange Dye + "DYE:2x1,DYE:15x1=>DYE:10x2",//Lime Dye + "DYE:4x1,DYE:15x1=>DYE:12x2",//Light Blue Dye + "DYE:2x1,DYE:4x1=>DYE:6x2",//Cyan Dye + "DYE:1x1,DYE:4x1=>DYE:5x2",//Purple Dye + "DYE:1x1,DYE:4x1,DYE:15x1=>DYE:13x3",//Magenta Dye + "BEETROOT:?x1=>DYE:1x2",//Rose Red + "DYE:15x1,DYE:1x2,DYE:4x1=>DYE:13x4",//Magenta Dye + "DYE:5x1,DYE:9x1=>DYE:13x2",//Magenta Dye + "DYE:0x1,DYE:15x1=>DYE:8x2",//Gray Dye + "DYE:0x1,DYE:15x2=>DYE:7x3",//Light Gray Dye + "DYE:0x1,DYE:8x1=>DYE:7x2",//Light Gray Dye + "WOOL:14x2=>CARPET:14x3", + ]; + + private static $big = [//Probably means only craftable on crafting bench. Name it better! + //Building + "WOOL:?x3,WOODEN_PLANKS:?x3=>BED:0x1", + "WOODEN_PLANKS:?x8=>CHEST:0x1", + "STICK:?x6=>FENCE:0x2", + "STICK:?x4,WOODEN_PLANKS:?x2=>FENCE_GATE:0x1", + "COBBLESTONE:?x8=>FURNACE:0x1", + "GLASS:?x6=>GLASS_PANE:0x16", + "STICK:?x7=>LADDER:0x2", + "DIAMOND:?x3,IRON_INGOT:?x6=>NETHER_REACTOR:0x1", + "WOODEN_PLANKS:?x6=>TRAPDOOR:0x2", + "WOODEN_PLANKS:?x6=>WOODEN_DOOR:0x1", + "WOODEN_PLANKS:0x6=>WOODEN_STAIRS:0x4", + "WOODEN_PLANKS:0x3=>WOOD_SLAB:0x6", + "WOODEN_PLANKS:1x6=>SPRUCE_WOOD_STAIRS:0x4", + "WOODEN_PLANKS:1x3=>WOOD_SLAB:1x6", + "WOODEN_PLANKS:2x6=>BIRCH_WOOD_STAIRS:0x4", + "WOODEN_PLANKS:2x3=>WOOD_SLAB:2x6", + //"WOODEN_PLANKS:3x6=>JUNGLE_WOOD_STAIRS:0x4", + //"WOODEN_PLANKS:3x3=>WOOD_SLAB:3x6", + + //Tools + "STICK:?x1,FEATHER:?x1,FLINT:?x1=>ARROW:0x4", + "STICK:?x3,STRING:?x3=>BOW:0x1", + "IRON_INGOT:?x3=>BUCKET:0x1", + "GOLD_INGOT:?x4,REDSTONE_DUST:?x1=>CLOCK:0x1", + "IRON_INGOT:?x4,REDSTONE_DUST:?x1=>COMPASS:0x1", + "DIAMOND:?x3,STICK:?x2=>DIAMOND_AXE:0x1", + "DIAMOND:?x2,STICK:?x2=>DIAMOND_HOE:0x1", + "DIAMOND:?x3,STICK:?x2=>DIAMOND_PICKAXE:0x1", + "DIAMOND:?x1,STICK:?x2=>DIAMOND_SHOVEL:0x1", + "DIAMOND:?x2,STICK:?x1=>DIAMOND_SWORD:0x1", + "GOLD_INGOT:?x3,STICK:?x2=>GOLDEN_AXE:0x1", + "GOLD_INGOT:?x2,STICK:?x2=>GOLDEN_HOE:0x1", + "GOLD_INGOT:?x3,STICK:?x2=>GOLDEN_PICKAXE:0x1", + "GOLD_INGOT:?x1,STICK:?x2=>GOLDEN_SHOVEL:0x1", + "GOLD_INGOT:?x2,STICK:?x1=>GOLDEN_SWORD:0x1", + "IRON_INGOT:?x3,STICK:?x2=>IRON_AXE:0x1", + "IRON_INGOT:?x2,STICK:?x2=>IRON_HOE:0x1", + "IRON_INGOT:?x3,STICK:?x2=>IRON_PICKAXE:0x1", + "IRON_INGOT:?x1,STICK:?x2=>IRON_SHOVEL:0x1", + "IRON_INGOT:?x2,STICK:?x1=>IRON_SWORD:0x1", + "COBBLESTONE:?x3,STICK:?x2=>STONE_AXE:0x1", + "COBBLESTONE:?x2,STICK:?x2=>STONE_HOE:0x1", + "COBBLESTONE:?x3,STICK:?x2=>STONE_PICKAXE:0x1", + "COBBLESTONE:?x1,STICK:?x2=>STONE_SHOVEL:0x1", + "COBBLESTONE:?x2,STICK:?x1=>STONE_SWORD:0x1", + "SAND:?x4,GUNPOWDER:?x5=>TNT:0x1", + "WOODEN_PLANKS:?x3,STICK:?x2=>WOODEN_AXE:0x1", + "WOODEN_PLANKS:?x2,STICK:?x2=>WOODEN_HOE:0x1", + "WOODEN_PLANKS:?x3,STICK:?x2=>WOODEN_PICKAXE:0x1", + "WOODEN_PLANKS:?x1,STICK:?x2=>WOODEN_SHOVEL:0x1", + "WOODEN_PLANKS:?x2,STICK:?x1=>WOODEN_SWORD:0x1", + "IRON_INGOT:?x6,STICK:?x1=>RAIL:0x16", + "GOLD_INGOT:?x6,STICK:?x1,REDSTONE:?x1=>POWERED_RAIL:0x6", + + //Food & protection + "BEETROOT:?x4,BOWL:?x1=>BEETROOT_SOUP:0x1", + "WOODEN_PLANKS:?x3=>BOWL:0x4", + "WHEAT:?x3=>BREAD:0x1", + "WHEAT:?x3,BUCKET:1x3,EGG:?x1,SUGAR:?x2=>CAKE:0x1", + "DIAMOND:?x4=>DIAMOND_BOOTS:0x1", + "DIAMOND:?x8=>DIAMOND_CHESTPLATE:0x1", + "DIAMOND:?x5=>DIAMOND_HELMET:0x1", + "DIAMOND:?x7=>DIAMOND_LEGGINGS:0x1", + "GOLD_INGOT:?x4=>GOLDEN_BOOTS:0x1", + "GOLD_INGOT:?x8=>GOLDEN_CHESTPLATE:0x1", + "GOLD_INGOT:?x5=>GOLDEN_HELMET:0x1", + "GOLD_INGOT:?x7=>GOLDEN_LEGGINGS:0x1", + "IRON_INGOT:?x4=>IRON_BOOTS:0x1", + "IRON_INGOT:?x8=>IRON_CHESTPLATE:0x1", + "IRON_INGOT:?x5=>IRON_HELMET:0x1", + "IRON_INGOT:?x7=>IRON_LEGGINGS:0x1", + "LEATHER:?x4=>LEATHER_BOOTS:0x1", + "LEATHER:?x8=>LEATHER_TUNIC:0x1", + "LEATHER:?x5=>LEATHER_CAP:0x1", + "LEATHER:?x7=>LEATHER_PANTS:0x1", + //"FIRE:?x4=>CHAIN_BOOTS:0x1", + //"FIRE:?x8=>CHAIN_CHESTPLATE:0x1", + //"FIRE:?x5=>CHAIN_HELMET:0x1", + //"FIRE:?x7=>CHAIN_LEGGINGS:0x1", + + //Items + "DIAMOND:?x9=>DIAMOND_BLOCK:0x1", + "GOLD_INGOT:?x9=>GOLD_BLOCK:0x1", + "IRON_INGOT:?x9=>IRON_BLOCK:0x1", + "IRON_INGOT:?x5=>MINECART:0x1", + "WHEAT:?x9=>HAY_BALE:0x1", + "PAPER:?x3=>BOOK:0x1", + "WOODEN_PLANKS:?x6,BOOK:?x3=>BOOKSHELF:0x1", + "DYE:4x9=>LAPIS_BLOCK:0x1", + "WOOL:?x1,STICK:?x8=>PAINTING:0x1", + "SUGARCANE:?x3=>PAPER:0x3", + "WOODEN_PLANKS:?x6,STICK:?x1=>SIGN:0x1", + "IRON_INGOT:?x6=>IRON_BARS:0x16", + "COAL:0x9=>COAL_BLOCK:0x1", + "COAL_BLOCK:?x1=>COAL:0x9", + "MELON_SLICE:?x9=>MELON_BLOCK:0x1", + ]; + + private static $stone = [ "QUARTZ:?x4=>QUARTZ_BLOCK:0x1", "BRICKS_BLOCK:?x6=>BRICK_STAIRS:0x4", "BRICK:?x4=>BRICKS_BLOCK:0x1", @@ -213,22 +195,49 @@ class CraftingRecipes{ "STONE_BRICKS:?x3=>SLAB:5x6", "STONE:?x3=>SLAB:0x6", "COBBLESTONE:?x6=>COBBLESTONE_STAIRS:0x4", - ); - - private static $recipes = array(); - + ]; + + private static $recipes = []; + + public static function init(){ + $server = ServerAPI::request(); + $id = 1; + foreach(CraftingRecipes::$small as $recipe){ + $recipe = CraftingRecipes::parseRecipe($recipe); + $recipe[3] = 0; //Type + CraftingRecipes::$recipes[$id] = $recipe; + ++$id; + } + foreach(CraftingRecipes::$big as $recipe){ + $recipe = CraftingRecipes::parseRecipe($recipe); + $recipe[3] = 1; + CraftingRecipes::$recipes[$id] = $recipe; + ++$id; + } + foreach(CraftingRecipes::$stone as $recipe){ + $recipe = CraftingRecipes::parseRecipe($recipe); + $recipe[3] = 2; + CraftingRecipes::$recipes[$id] = $recipe; + ++$id; + } + + foreach(CraftingRecipes::$recipes as $id => $recipe){ + $server->query("INSERT INTO recipes (id, type, recipe) VALUES (" . $id . ", " . $recipe[3] . ", '" . $recipe[2] . "');"); + } + } + private static function parseRecipe($recipe){ $recipe = explode("=>", $recipe); - $recipeItems = array(); + $recipeItems = []; foreach(explode(",", $recipe[0]) as $item){ $item = explode("x", $item); $id = explode(":", $item[0]); $meta = array_pop($id); $id = $id[0]; - + $it = BlockAPI::fromString($id); if(!isset($recipeItems[$it->getID()])){ - $recipeItems[$it->getID()] = array($it->getID(), $meta === "?" ? false:intval($meta)&0xFFFF, intval($item[1])); + $recipeItems[$it->getID()] = [$it->getID(), $meta === "?" ? false : intval($meta) & 0xFFFF, intval($item[1])]; }else{ if($it->getMetadata() !== $recipeItems[$it->getID()][1]){ $recipeItems[$it->getID()][1] = false; @@ -241,49 +250,20 @@ class CraftingRecipes{ $id = explode(":", $item[0]); $meta = array_pop($id); $id = $id[0]; - + $it = BlockAPI::fromString($id); - $craftItem = array($it->getID(), intval($meta)&0xFFFF, intval($item[1])); - + $craftItem = [$it->getID(), intval($meta) & 0xFFFF, intval($item[1])]; + $recipeString = ""; foreach($recipeItems as $item){ - $recipeString .= $item[0]."x".$item[2].","; - } - $recipeString = substr($recipeString, 0, -1)."=>".$craftItem[0]."x".$craftItem[2]; - - return array($recipeItems, $craftItem, $recipeString); - } - - public static function init(){ - $server = ServerAPI::request(); - $id = 1; - foreach(CraftingRecipes::$small as $recipe){ - $recipe = CraftingRecipes::parseRecipe($recipe); - $recipe[3] = 0; //Type - CraftingRecipes::$recipes[$id] = $recipe; - ++$id; - } - foreach(CraftingRecipes::$big as $recipe){ - $recipe = CraftingRecipes::parseRecipe($recipe); - $recipe[3] = 1; - CraftingRecipes::$recipes[$id] = $recipe; - ++$id; - } - foreach(CraftingRecipes::$stone as $recipe){ - $recipe = CraftingRecipes::parseRecipe($recipe); - $recipe[3] = 2; - CraftingRecipes::$recipes[$id] = $recipe; - ++$id; - } - - foreach(CraftingRecipes::$recipes as $id => $recipe){ - - $server->query("INSERT INTO recipes (id, type, recipe) VALUES (".$id.", ".$recipe[3].", '".$recipe[2]."');"); + $recipeString .= $item[0] . "x" . $item[2] . ","; } + $recipeString = substr($recipeString, 0, -1) . "=>" . $craftItem[0] . "x" . $craftItem[2]; + return [$recipeItems, $craftItem, $recipeString]; } - + public static function canCraft(array $craftItem, array $recipeItems, $type){ ksort($recipeItems); $recipeString = ""; @@ -291,11 +271,11 @@ class CraftingRecipes{ if($craftItem[0] === CAKE && $item[0] === BUCKET && $item[1] === 1){ //some dark magic with recipe happened in mcpe, pmmp restores it back to normal $item[2] = 3; } - $recipeString .= $item[0]."x".$item[2].","; + $recipeString .= $item[0] . "x" . $item[2] . ","; } - $recipeString = substr($recipeString, 0, -1)."=>".$craftItem[0]."x".$craftItem[2]; + $recipeString = substr($recipeString, 0, -1) . "=>" . $craftItem[0] . "x" . $craftItem[2]; $server = ServerAPI::request(); - $result = $server->query("SELECT id FROM recipes WHERE type == ".$type." AND recipe == '".$recipeString."';"); + $result = $server->query("SELECT id FROM recipes WHERE type == " . $type . " AND recipe == '" . $recipeString . "';"); if($result instanceof SQLite3Result){ $continue = true; while(($r = $result->fetchArray(SQLITE3_NUM)) !== false){ diff --git a/src/recipes/FuelData.php b/src/recipes/FuelData.php index c7778d24..e0c61bab 100644 --- a/src/recipes/FuelData.php +++ b/src/recipes/FuelData.php @@ -1,27 +1,8 @@ 80, COAL_BLOCK => 800, TRUNK => 15, @@ -44,7 +25,6 @@ class FuelData{ BOOKSHELF => 15, CHEST => 15, BUCKET => 1000, - - ); + ]; } \ No newline at end of file diff --git a/src/recipes/SmeltingData.php b/src/recipes/SmeltingData.php index a08b12c5..aab7c5a6 100644 --- a/src/recipes/SmeltingData.php +++ b/src/recipes/SmeltingData.php @@ -1,42 +1,21 @@ array(STONE, 0), - SAND => array(GLASS, 0), - TRUNK => array(COAL, 1), //Charcoal - GOLD_ORE => array(GOLD_INGOT, 0), - IRON_ORE => array(IRON_INGOT, 0), - NETHERRACK => array(NETHER_BRICK, 0), - RAW_PORKCHOP => array(COOKED_PORKCHOP, 0), - CLAY => array(BRICK, 0), - CACTUS => array(DYE, 2), - RED_MUSHROOM => array(DYE, 1), - RAW_BEEF => array(STEAK, 0), - RAW_CHICKEN => array(COOKED_CHICKEN, 0), - RED_MUSHROOM => array(DYE, 1), - POTATO => array(BAKED_POTATO, 0), - - ); + public static $product = [ + COBBLESTONE => [STONE, 0], + SAND => [GLASS, 0], + TRUNK => [COAL, 1], //Charcoal + GOLD_ORE => [GOLD_INGOT, 0], + IRON_ORE => [IRON_INGOT, 0], + NETHERRACK => [NETHER_BRICK, 0], + RAW_PORKCHOP => [COOKED_PORKCHOP, 0], + CLAY => [BRICK, 0], + CACTUS => [DYE, 2], + RED_MUSHROOM => [DYE, 1], + RAW_BEEF => [STEAK, 0], + RAW_CHICKEN => [COOKED_CHICKEN, 0], + RED_MUSHROOM => [DYE, 1], + POTATO => [BAKED_POTATO, 0], + ]; } \ No newline at end of file diff --git a/src/tests/ServerSuiteTest.php b/src/tests/ServerSuiteTest.php index 203a14d2..e033c274 100644 --- a/src/tests/ServerSuiteTest.php +++ b/src/tests/ServerSuiteTest.php @@ -1,60 +1,61 @@ load(); - testCase("event attached", is_integer($server->event("server.start", array($this, "hook"))), true); - $server->init(); - } - - public function hook(){ - testCase("event fired", true, true); - $server = ServerAPI::request(); - testCase("defaultgamemode", $server->getGamemode(), "survival"); - - - //Everything done! - $server->close(); - } - } +if(!class_exists("PocketMinecraftServer", false)){ + define("NO_THREADS", true); + require_once(dirname(__FILE__) . "/../dependencies.php"); + require_once(FILE_PATH . "/src/functions.php"); + require_once(FILE_PATH . "/src/dependencies.php"); + console(FORMAT_GREEN . "[TEST] Starting tests"); + testCase("dummy", dummy(), null); + $t = new ServerSuiteTest; + echo PHP_EOL; + if($testErrors === 0){ + console(FORMAT_GREEN . "[TEST] No errors. Test complete."); + exit(0); + }else{ + console(FORMAT_RED . "[TEST] Errors found."); + exit(1); + } +} + +class ServerSuiteTest{ + + public function __construct(){ + //binary things + testCase("Utils::readTriad", Utils::readTriad("\x02\x01\x03"), 131331); + testCase("Utils::readInt", Utils::readInt("\xff\x02\x01\x03"), -16645885); + testCase("Utils::readFloat", abs(Utils::readFloat("\x49\x02\x01\x03") - 532496.1875) < 0.0001, true); + testCase("Utils::readDouble", abs(Utils::readDouble("\x41\x02\x03\x04\x05\x06\x07\x08") - 147552.5024529) < 0.0001, true); + testCase("Utils::readTriad", Utils::readLong("\x41\x02\x03\x04\x05\x06\x07\x08"), "4684309878217770760"); + + //NostalgiaCore server startup + global $server; + $server = new ServerAPI(); + $server->load(); + testCase("event attached", is_integer($server->event("server.start", [$this, "hook"])), true); + $server->init(); + } + + public function hook(){ + testCase("event fired", true, true); + $server = ServerAPI::request(); + testCase("defaultgamemode", $server->getGamemode(), "survival"); + + + //Everything done! + $server->close(); + } +} /***REM_END***/ \ No newline at end of file diff --git a/src/utils/Cache.php b/src/utils/Cache.php index 3d05eee6..9091e6f5 100644 --- a/src/utils/Cache.php +++ b/src/utils/Cache.php @@ -1,47 +1,30 @@ $data){ @@ -50,5 +33,4 @@ class Cache{ } } } - } \ No newline at end of file diff --git a/src/utils/Config.php b/src/utils/Config.php index ace15d21..98433195 100644 --- a/src/utils/Config.php +++ b/src/utils/Config.php @@ -1,24 +1,5 @@ CONFIG_PROPERTIES, "cnf" => CONFIG_CNF, "conf" => CONFIG_CNF, @@ -65,50 +30,54 @@ class Config{ "sl" => CONFIG_SERIALIZED, "serialize" => CONFIG_SERIALIZED, "txt" => CONFIG_LIST, - "list" => CONFIG_LIST, - ); + "list" => CONFIG_LIST, + ]; + /** + * @var array + */ + private $config; + /** + * @var string + */ + private $file; + /** + * @var boolean + */ + private $correct; + /** + * @var integer + */ + private $type = CONFIG_DETECT; - /** - * @param string $file - * @param int $type - * @param array $default - * @param null|boolean $correct - */ - public function __construct($file, $type = CONFIG_DETECT, $default = array(), &$correct = null){ + /** + * @param string $file + * @param int $type + * @param array $default + * @param null|boolean $correct + */ + public function __construct($file, $type = CONFIG_DETECT, $default = [], &$correct = null){ $this->load($file, $type, $default); $correct = $this->check(); } - - public function reload(){ - unset($this->config); - unset($this->correct); - unset($this->type); - $this->load($this->file); - $correct = $this->check(); - } - - public function fixYAMLIndexes($str){ - return preg_replace("#^([ ]*)([a-zA-Z_]{1}[^\:]*)\:#m", "$1\"$2\":", $str); - } - /** - * @param string $file - * @param int $type - * @param array $default - * - * @return boolean - */ - public function load($file, $type = CONFIG_DETECT, $default = array()){ + /** + * @param string $file + * @param int $type + * @param array $default + * + * @return boolean + */ + public function load($file, $type = CONFIG_DETECT, $default = []){ $this->correct = true; $this->type = (int) $type; $this->file = $file; if(!is_array($default)){ - $default = array(); + $default = []; } if(!file_exists($file)){ $this->config = $default; $this->save(); - }else{ + }else{ if($this->type === CONFIG_DETECT){ $extension = explode(".", basename($this->file)); $extension = strtolower(trim(array_pop($extension))); @@ -156,17 +125,10 @@ class Config{ return true; } - /** - * @return boolean - */ - public function check(){ - return $this->correct === true; - } - - /** - * @return boolean - */ - public function save(){ + /** + * @return boolean + */ + public function save(){ if($this->correct === true){ switch($this->type){ case CONFIG_PROPERTIES: @@ -185,162 +147,34 @@ class Config{ case CONFIG_LIST: $content = implode("\r\n", array_keys($this->config)); break; - } - @file_put_contents($this->file, $content, LOCK_EX); - return true; + } + @file_put_contents($this->file, $content, LOCK_EX); + return true; }else{ return false; } } - /** - * @param $k - * - * @return boolean|mixed - */ - public function &__get($k){ - return $this->get($k); - } - - /** - * @param $k - * @param $v - */ - public function __set($k, $v){ - $this->set($k, $v); - } - - /** - * @param $k - * - * @return boolean - */ - public function __isset($k){ - return $this->exists($k); - } - - /** - * @param $k - */ - public function __unset($k){ - $this->remove($k); - } - - /** - * @param $k - * - * @return boolean|mixed - */ - public function &get($k){ - if(isset($this->correct) and ($this->correct === false or !isset($this->config[$k]))){ - $false = false; - return $false; - } - return $this->config[$k]; - } - - /** - * @param $k - * @param bool $v - */ - public function set($k, $v = true){ - $this->config[$k] = $v; - } - - /** - * @param array $v - */ - public function setAll($v){ - $this->config = $v; - } - - /** - * @param $k - * @param bool $lowercase If set, searches Config in single-case / lowercase. - * - * @return boolean - */ - public function exists($k, $lowercase = false){ - if($lowercase === true){ - $k = strtolower($k);//Convert requested key to lower - $array = array_change_key_case($this->config, CASE_LOWER);//Change all keys in array to lower - return isset($array[$k]);//Find $k in modified array - }else{ - return isset($this->config[$k]); - } - } - - /** - * @param $k - */ - public function remove($k){ - unset($this->config[$k]); - } - - /** - * @param bool $keys - * - * @return array - */ - public function getAll($keys = false){ - return ($keys === true ? array_keys($this->config):$this->config); - } - - /** - * @param $default - * @param $data - * - * @return integer - */ - private function fillDefaults($default, &$data){ - $changed = 0; - foreach($default as $k => $v){ - if(is_array($v)){ - if(!isset($data[$k]) or !is_array($data[$k])){ - $data[$k] = array(); - } - $changed += $this->fillDefaults($v, $data[$k]); - }elseif(!isset($data[$k])){ - $data[$k] = $v; - ++$changed; - } - } - return $changed; - } - - /** - * @param $content - */ - private function parseList($content){ - foreach(explode("\n", trim(str_replace("\r\n", "\n", $content))) as $v){ - $v = trim($v); - if($v == ""){ - continue; - } - $this->config[$v] = true; - } - } - - /** - * @return string - */ - private function writeProperties(){ - $content = "#Properties Config file\r\n#".date("D M j H:i:s T Y")."\r\n"; + /** + * @return string + */ + private function writeProperties(){ + $content = "#Properties Config file\r\n#" . date("D M j H:i:s T Y") . "\r\n"; foreach($this->config as $k => $v){ if(is_bool($v) === true){ - $v = $v === true ? "on":"off"; + $v = $v === true ? "on" : "off"; }elseif(is_array($v)){ - $v = implode(";", $v); + $v = implode(";", $v); } - $content .= $k."=".$v."\r\n"; + $content .= $k . "=" . $v . "\r\n"; } return $content; } - /** - * @param $content - */ - private function parseProperties($content){ + /** + * @param $content + */ + private function parseProperties($content){ if(preg_match_all('/([a-zA-Z0-9\-_\.]*)=([^\r\n]*)/u', $content, $matches) > 0){ //false or 0 matches foreach($matches[1] as $i => $k){ $v = trim($matches[2][$i]); @@ -357,11 +191,158 @@ class Config{ break; } if(isset($this->config[$k])){ - console("[NOTICE] [Config] Repeated property ".$k." on file ".$this->file, true, true, 2); + console("[NOTICE] [Config] Repeated property " . $k . " on file " . $this->file, true, true, 2); } $this->config[$k] = $v; } } } + public function fixYAMLIndexes($str){ + return preg_replace("#^([ ]*)([a-zA-Z_]{1}[^\:]*)\:#m", "$1\"$2\":", $str); + } + + /** + * @param $content + */ + private function parseList($content){ + foreach(explode("\n", trim(str_replace("\r\n", "\n", $content))) as $v){ + $v = trim($v); + if($v == ""){ + continue; + } + $this->config[$v] = true; + } + } + + /** + * @param $default + * @param $data + * + * @return integer + */ + private function fillDefaults($default, &$data){ + $changed = 0; + foreach($default as $k => $v){ + if(is_array($v)){ + if(!isset($data[$k]) or !is_array($data[$k])){ + $data[$k] = []; + } + $changed += $this->fillDefaults($v, $data[$k]); + }elseif(!isset($data[$k])){ + $data[$k] = $v; + ++$changed; + } + } + return $changed; + } + + /** + * @return boolean + */ + public function check(){ + return $this->correct === true; + } + + public function reload(){ + unset($this->config); + unset($this->correct); + unset($this->type); + $this->load($this->file); + $correct = $this->check(); + } + + /** + * @param $k + * + * @return boolean|mixed + */ + public function &__get($k){ + return $this->get($k); + } + + /** + * @param $k + * @param $v + */ + public function __set($k, $v){ + $this->set($k, $v); + } + + /** + * @param $k + * + * @return boolean|mixed + */ + public function &get($k){ + if(isset($this->correct) and ($this->correct === false or !isset($this->config[$k]))){ + $false = false; + return $false; + } + return $this->config[$k]; + } + + /** + * @param $k + * @param bool $v + */ + public function set($k, $v = true){ + $this->config[$k] = $v; + } + + /** + * @param $k + * + * @return boolean + */ + public function __isset($k){ + return $this->exists($k); + } + + /** + * @param $k + * @param bool $lowercase If set, searches Config in single-case / lowercase. + * + * @return boolean + */ + public function exists($k, $lowercase = false){ + if($lowercase === true){ + $k = strtolower($k);//Convert requested key to lower + $array = array_change_key_case($this->config, CASE_LOWER);//Change all keys in array to lower + return isset($array[$k]);//Find $k in modified array + }else{ + return isset($this->config[$k]); + } + } + + /** + * @param $k + */ + public function __unset($k){ + $this->remove($k); + } + + /** + * @param $k + */ + public function remove($k){ + unset($this->config[$k]); + } + + /** + * @param array $v + */ + public function setAll($v){ + $this->config = $v; + } + + /** + * @param bool $keys + * + * @return array + */ + public function getAll($keys = false){ + return ($keys === true ? array_keys($this->config) : $this->config); + } + } diff --git a/src/utils/Container.php b/src/utils/Container.php index 1b8a3856..0d22f2c0 100644 --- a/src/utils/Container.php +++ b/src/utils/Container.php @@ -1,26 +1,9 @@ payload = $payload; if(is_array($whitelist)){ @@ -30,11 +13,11 @@ class Container{ $this->blacklist = $blacklist; } } - + public function get(){ return $this->payload; } - + public function check($target){ $w = true; $b = false; @@ -59,8 +42,8 @@ class Container{ } return true; } - - + + public function __toString(){ return $this->payload; } diff --git a/src/utils/Java.php b/src/utils/Java.php index 268864c8..5f5fe667 100644 --- a/src/utils/Java.php +++ b/src/utils/Java.php @@ -1,26 +1,8 @@ count === 0; } - public function charAt($index){ - $index = (int) $index; - if($index < 0 or $index >= $this->count){ - trigger_error("Undefined offset $index", E_USER_WARNING); - return false; - } - return $this->value[$index]; - } - public function hashCode(){ $h = $this->hash; if($h === 0 and $this->count > 0){ @@ -63,4 +36,13 @@ class Java_String{ } return $h; } + + public function charAt($index){ + $index = (int) $index; + if($index < 0 or $index >= $this->count){ + trigger_error("Undefined offset $index", E_USER_WARNING); + return false; + } + return $this->value[$index]; + } } \ No newline at end of file diff --git a/src/utils/LightUtils.php b/src/utils/LightUtils.php index a32badee..fb826eb8 100644 --- a/src/utils/LightUtils.php +++ b/src/utils/LightUtils.php @@ -1,6 +1,7 @@ instanceof LightingBlock, $block: Block */ @@ -8,16 +9,13 @@ class LightUtils { if($source === null || $block === null){ return 0; } - $distance = sqrt(LightUtils::sqr($source->x - $block->x)+LightUtils::sqr($source->y - $block->y)+LightUtils::sqr($source->z - $block->z)); /*Distance between 2 3d objects*/ + $distance = sqrt(LightUtils::sqr($source->x - $block->x) + LightUtils::sqr($source->y - $block->y) + LightUtils::sqr($source->z - $block->z)); /*Distance between 2 3d objects*/ $result = floor($source->getMaxLightValue() - $distance); //i dont need something like 0.2192032434454... return $result <= 0 ? 0 : $result; //if result is smaller or equals 0 then return 0 else return result } - + /* Used only internally for calculating 2^(2) */ private static function sqr($val){ - return pow($val,2); + return pow($val, 2); } - -} - - +} \ No newline at end of file diff --git a/src/utils/MersenneTwister.php b/src/utils/MersenneTwister.php index ca9fef5b..955d75ae 100644 --- a/src/utils/MersenneTwister.php +++ b/src/utils/MersenneTwister.php @@ -1,4 +1,5 @@ bits32 = PHP_INT_MAX == 2147483647; - - if(func_num_args() == 1) { - $this->init_with_integer(func_get_arg(0)); - } - } - - function init_with_integer($integer_seed) { - $integer_seed = force_32_bit_int($integer_seed); - - $mt = &$this->mt; - $mti = &$this->mti; - - $mt = array_fill(0, N, 0); - - $mt[0] = $integer_seed; - - for($mti = 1; $mti < N; $mti++) { - $mt[$mti] = add_2(mul(1812433253, - ($mt[$mti - 1] ^ (($mt[$mti - 1] >> 30) & 3))), $mti); - /* - mt[mti] = - (1812433253UL * (mt[mti-1] ^ (mt[mti-1] >> 30)) + mti); - */ - } - } - - function init_with_array(array $integer_array) { - $integer_array = - array_map("force_32_bit_int", $integer_array); - - $mt = &$this->mt; - $mti = &$this->mti; - - $key_length = count($integer_array); - - $this->init_with_integer(19650218); - $i=1; $j=0; - $k = (N>$key_length ? N : $key_length); - for (; $k; $k--) { - $mt[$i] = add_3($mt[$i] ^ - mul_by_1664525($mt[$i-1] ^ (($mt[$i-1] >> 30) & 3)), - $integer_array[$j], $j); - /* - mt[i] = (mt[i] ^ ((mt[i-1] ^ (mt[i-1] >> 30)) * 1664525UL)) - + init_key[j] + j; - */ - $i++; $j++; - if ($i>=N) { $mt[0] = $mt[N-1]; $i=1; } - if ($j>=$key_length){ $j=0; } - } - for ($k=N-1; $k; $k--) { - $mt[$i] = sub($mt[$i] ^ - mul($mt[$i-1] ^ (($mt[$i-1] >> 30) & 3), 1566083941), $i); - /* - mt[i] = (mt[i] ^ ((mt[i-1] ^ (mt[i-1] >> 30)) * 1566083941UL)) - - i; - */ - $i++; - if ($i>=N) { $mt[0] = $mt[N-1]; $i=1; } - } - - $mt[0] = (1 << 31); /* MSB is 1; assuring non-zero initial array */ - } - - function init_with_string($string) { - $remainder = strlen($string) % 4; - - if($remainder > 0){ - $string .= str_repeat("\0", 4 - $remainder); - } - - $integer_array = array_values(unpack("N*", $string)); - - $this->init_with_array($integer_array); - } - - function init_with_files(array $filenames, $max_ints = -1) { - $limit_applies = $max_ints !== -1; - - if($limit_applies){ - $limit = $max_ints * 4; # 32 bits is 4 characters - } - $data = ""; - - foreach ($filenames as $filename) { - $contents = - file_get_contents($filename, FALSE, NULL, 0, - $limit_applies? $limit - strlen($data): -1); - - if($contents === FALSE) { - throw new Exception("problem reading from $filename"); - } else { - $data .= $contents; - - if($limit_applies && strlen($data) == $limit) { - break; - } - } - } - - $this->init_with_string($data); - } - - function init_with_file($filename, $max_ints = -1) { - $this->init_with_files(array($filename), $max_ints); - } - - function int32() { - static $mag01 = array(0, MATRIX_A); - - $mt = &$this->mt; - $mti = &$this->mti; - - if ($mti >= N) { /* generate N words all at once */ - for ($kk=0;$kk> 1) & MASK31) ^ $mag01[$y & 1]; - } - for (;$kk> 1) & MASK31) ^ $mag01[$y & 1]; - } - $y = ($mt[N-1]&UPPER_MASK)|($mt[0]&LOWER_MASK); - $mt[N-1] = $mt[M-1] ^ (($y >> 1) & MASK31) ^ $mag01[$y & 1]; - - $mti = 0; - } - - $y = $mt[$mti++]; - - /* Tempering */ - $y ^= ($y >> 11) & MASK21; - $y ^= ($y << 7) & ((0x9d2c << 16) | 0x5680); - $y ^= ($y << 15) & (0xefc6 << 16); - $y ^= ($y >> 18) & MASK14; - - return $y; - } - - function int31() { - return $this->int32() & MASK31; - } - - /* generates a random number on [0,1]-real-interval */ - function real_closed() { - return signed2unsigned($this->int32()) * (1.0 / 4294967295.0); - } - - /* generates a random number on [0,1)-real-interval */ - function real_halfopen() { - return signed2unsigned($this->int32()) * (1.0 / 4294967296.0); - } - - /* generates a random number on (0,1)-real-interval */ - function real_open() { - return (signed2unsigned($this->int32()) + .5) * (1.0 / 4294967296.0); - } - - /* generates a random number on [0,1) with 53-bit resolution */ - function real_halfopen2() { - return ((($this->int32() & MASK27) * 67108864.0) + - ($this->int32() & MASK26)) * - (1.0 / 9007199254740992.0); - } - - function rangeint($lower_bound, $upper_bound) { - $lower_bound = intval($lower_bound); - $upper_bound = intval($upper_bound); - - if($this->bits32) { - $pow_2_32 = pow(2, 32); - - $size_of_range = $upper_bound - $lower_bound + 1; - - $remainder = fmod($pow_2_32, $size_of_range); - - if($remainder == 0) { - return $lower_bound + - ($this->int32() & unsigned2signed($size_of_range - 1)); - } else { - $start_of_partial_range = $pow_2_32 - $remainder; - $start_as_int = unsigned2signed($start_of_partial_range); - do { - $rand = $this->int32(); - } while($rand >= $start_as_int && $rand < 0); - - $result = $lower_bound + - fmod(signed2unsigned($rand), $size_of_range); - - return intval($result); - } - } else { - if($lower_bound == -PHP_INT_MAX - 1 && $upper_bound == PHP_INT_MAX) { - return ($this->int32() << 32) & $this->int32(); - } else { - $pow_2_32 = 1 << 32; - - $size_of_range = $upper_bound - $lower_bound + 1; - - if($size_of_range > $pow_2_32) { - $size_of_range >>= 32; - $shift = 32; - $low_bits = $this->int32(); - } else { - $shift = 0; - $low_bits = 0; - } - - $remainder = $pow_2_32 % $size_of_range; - - if($remainder == 0) { - $high_bits = $this->int32() & ($size_of_range - 1); - } else { - $start_of_partial_range = $pow_2_32 - $remainder; - do { - $rand = $this->int32(); - } while($rand >= $start_of_partial_range); - - $high_bits = $rand % $size_of_range; - } - - return $lower_bound + (($high_bits << $shift) | $low_bits); - } - } - } - - /* - in each of the next 3 functions, we loop until we have a number that - meets the function's post-condition. this may be more work than - is really necessary, but i am concerned about rounding errors. - - why no rangereal_closed? because, due to the aforementioned - rounding errors, i am unable to guarantee that $upper_bound - would be a possible return value of such a function. - */ - - function rangereal_open($lower_bound, $upper_bound) { - do { - $rand = $lower_bound + - $this->real_open() * ($upper_bound - $lower_bound); - } while($rand <= $lower_bound || $rand >= $upper_bound); - - return $rand; - } - - function rangereal_halfopen($lower_bound, $upper_bound) { - do { - $rand = $lower_bound + - $this->real_halfopen() * ($upper_bound - $lower_bound); - } while($rand >= $upper_bound); - /* - $rand cannot go any lower than $lower_bound, because - $this->real_halfopen() cannot go any lower than 0 - */ - - return $rand; - } - - function rangereal_halfopen2($lower_bound, $upper_bound) { - do { - $rand = $lower_bound + - $this->real_halfopen2() * ($upper_bound - $lower_bound); - } while($rand >= $upper_bound); - - return $rand; - } } -function signed2unsigned($signed_integer) { - ## assert(is_integer($signed_integer)); - ## assert(($signed_integer & ~MASK32) === 0); - - return $signed_integer >= 0? $signed_integer: - TWO_TO_THE_32 + $signed_integer; +foreach([16, 31, 32] as $n){ + $val = pow(2, $n); + define("TWO_TO_THE_$n", $val); } -function unsigned2signed($unsigned_integer) { - ## assert($unsigned_integer >= 0); - ## assert($unsigned_integer < pow(2, 32)); - ## assert(floor($unsigned_integer) === floatval($unsigned_integer)); +$val = MASK31 | (MASK31 << 1); +define("MASK32", $val); - return intval($unsigned_integer < TWO_TO_THE_31? $unsigned_integer: - $unsigned_integer - TWO_TO_THE_32); -} -function force_32_bit_int($x) { - /* - it would be un-PHP-like to require is_integer($x), - so we have to handle cases like this: +class twister{ - $x === pow(2, 31) - $x === strval(pow(2, 31)) + const N = N; + # the class constant is not used anywhere in this namespace, + # but it makes the API cleaner. - we are also opting to do something sensible (rather than dying) - if the seed is outside the range of a 32-bit unsigned integer. - */ + function __construct(){ + $this->bits32 = PHP_INT_MAX == 2147483647; - if(is_integer($x)) { - /* - we mask in case we are on a 64-bit machine and at least one - bit is set between position 32 and position 63. - */ - return $x & MASK32; - } else { - $x = floatval($x); - - $x = $x < 0? ceil($x): floor($x); - - $x = fmod($x, TWO_TO_THE_32); - - if($x < 0){ - $x += TWO_TO_THE_32; + if(func_num_args() == 1){ + $this->init_with_integer(func_get_arg(0)); + } } - return unsigned2signed($x); - } + function init_with_integer($integer_seed){ + $integer_seed = force_32_bit_int($integer_seed); + + $mt = &$this->mt; + $mti = &$this->mti; + + $mt = array_fill(0, N, 0); + + $mt[0] = $integer_seed; + + for($mti = 1; $mti < N; $mti++){ + $mt[$mti] = add_2(mul(1812433253, + ($mt[$mti - 1] ^ (($mt[$mti - 1] >> 30) & 3))), $mti); + /* + mt[mti] = + (1812433253UL * (mt[mti-1] ^ (mt[mti-1] >> 30)) + mti); + */ + } + } + + function init_with_file($filename, $max_ints = -1){ + $this->init_with_files([$filename], $max_ints); + } + + function init_with_files(array $filenames, $max_ints = -1){ + $limit_applies = $max_ints !== -1; + + if($limit_applies){ + $limit = $max_ints * 4; # 32 bits is 4 characters + } + $data = ""; + + foreach($filenames as $filename){ + $contents = + file_get_contents($filename, false, null, 0, + $limit_applies ? $limit - strlen($data) : -1); + + if($contents === false){ + throw new Exception("problem reading from $filename"); + }else{ + $data .= $contents; + + if($limit_applies && strlen($data) == $limit){ + break; + } + } + } + + $this->init_with_string($data); + } + + function init_with_string($string){ + $remainder = strlen($string) % 4; + + if($remainder > 0){ + $string .= str_repeat("\0", 4 - $remainder); + } + + $integer_array = array_values(unpack("N*", $string)); + + $this->init_with_array($integer_array); + } + + function init_with_array(array $integer_array){ + $integer_array = + array_map("force_32_bit_int", $integer_array); + + $mt = &$this->mt; + $mti = &$this->mti; + + $key_length = count($integer_array); + + $this->init_with_integer(19650218); + $i = 1; + $j = 0; + $k = (N > $key_length ? N : $key_length); + for(; $k; $k--){ + $mt[$i] = add_3($mt[$i] ^ + mul_by_1664525($mt[$i - 1] ^ (($mt[$i - 1] >> 30) & 3)), + $integer_array[$j], $j); + /* + mt[i] = (mt[i] ^ ((mt[i-1] ^ (mt[i-1] >> 30)) * 1664525UL)) + + init_key[j] + j; + */ + $i++; + $j++; + if($i >= N){ + $mt[0] = $mt[N - 1]; + $i = 1; + } + if($j >= $key_length){ + $j = 0; + } + } + for($k = N - 1; $k; $k--){ + $mt[$i] = sub($mt[$i] ^ + mul($mt[$i - 1] ^ (($mt[$i - 1] >> 30) & 3), 1566083941), $i); + /* + mt[i] = (mt[i] ^ ((mt[i-1] ^ (mt[i-1] >> 30)) * 1566083941UL)) + - i; + */ + $i++; + if($i >= N){ + $mt[0] = $mt[N - 1]; + $i = 1; + } + } + + $mt[0] = (1 << 31); /* MSB is 1; assuring non-zero initial array */ + } + + function int31(){ + return $this->int32() & MASK31; + } + + function int32(){ + static $mag01 = [0, MATRIX_A]; + + $mt = &$this->mt; + $mti = &$this->mti; + + if($mti >= N){ /* generate N words all at once */ + for($kk = 0; $kk < N - M; $kk++){ + $y = ($mt[$kk] & UPPER_MASK) | ($mt[$kk + 1] & LOWER_MASK); + $mt[$kk] = $mt[$kk + M] ^ (($y >> 1) & MASK31) ^ $mag01[$y & 1]; + } + for(; $kk < N - 1; $kk++){ + $y = ($mt[$kk] & UPPER_MASK) | ($mt[$kk + 1] & LOWER_MASK); + $mt[$kk] = + $mt[$kk + (M - N)] ^ (($y >> 1) & MASK31) ^ $mag01[$y & 1]; + } + $y = ($mt[N - 1] & UPPER_MASK) | ($mt[0] & LOWER_MASK); + $mt[N - 1] = $mt[M - 1] ^ (($y >> 1) & MASK31) ^ $mag01[$y & 1]; + + $mti = 0; + } + + $y = $mt[$mti++]; + + /* Tempering */ + $y ^= ($y >> 11) & MASK21; + $y ^= ($y << 7) & ((0x9d2c << 16) | 0x5680); + $y ^= ($y << 15) & (0xefc6 << 16); + $y ^= ($y >> 18) & MASK14; + + return $y; + } + + /* generates a random number on [0,1]-real-interval */ + + function real_closed(){ + return signed2unsigned($this->int32()) * (1.0 / 4294967295.0); + } + + /* generates a random number on [0,1)-real-interval */ + + function rangeint($lower_bound, $upper_bound){ + $lower_bound = intval($lower_bound); + $upper_bound = intval($upper_bound); + + if($this->bits32){ + $pow_2_32 = pow(2, 32); + + $size_of_range = $upper_bound - $lower_bound + 1; + + $remainder = fmod($pow_2_32, $size_of_range); + + if($remainder == 0){ + return $lower_bound + + ($this->int32() & unsigned2signed($size_of_range - 1)); + }else{ + $start_of_partial_range = $pow_2_32 - $remainder; + $start_as_int = unsigned2signed($start_of_partial_range); + do{ + $rand = $this->int32(); + }while($rand >= $start_as_int && $rand < 0); + + $result = $lower_bound + + fmod(signed2unsigned($rand), $size_of_range); + + return intval($result); + } + }else{ + if($lower_bound == -PHP_INT_MAX - 1 && $upper_bound == PHP_INT_MAX){ + return ($this->int32() << 32) & $this->int32(); + }else{ + $pow_2_32 = 1 << 32; + + $size_of_range = $upper_bound - $lower_bound + 1; + + if($size_of_range > $pow_2_32){ + $size_of_range >>= 32; + $shift = 32; + $low_bits = $this->int32(); + }else{ + $shift = 0; + $low_bits = 0; + } + + $remainder = $pow_2_32 % $size_of_range; + + if($remainder == 0){ + $high_bits = $this->int32() & ($size_of_range - 1); + }else{ + $start_of_partial_range = $pow_2_32 - $remainder; + do{ + $rand = $this->int32(); + }while($rand >= $start_of_partial_range); + + $high_bits = $rand % $size_of_range; + } + + return $lower_bound + (($high_bits << $shift) | $low_bits); + } + } + } + + /* generates a random number on (0,1)-real-interval */ + + function rangereal_open($lower_bound, $upper_bound){ + do{ + $rand = $lower_bound + + $this->real_open() * ($upper_bound - $lower_bound); + }while($rand <= $lower_bound || $rand >= $upper_bound); + + return $rand; + } + + /* generates a random number on [0,1) with 53-bit resolution */ + + function real_open(){ + return (signed2unsigned($this->int32()) + .5) * (1.0 / 4294967296.0); + } + + function rangereal_halfopen($lower_bound, $upper_bound){ + do{ + $rand = $lower_bound + + $this->real_halfopen() * ($upper_bound - $lower_bound); + }while($rand >= $upper_bound); + /* + $rand cannot go any lower than $lower_bound, because + $this->real_halfopen() cannot go any lower than 0 + */ + + return $rand; + } + + /* + in each of the next 3 functions, we loop until we have a number that + meets the function's post-condition. this may be more work than + is really necessary, but i am concerned about rounding errors. + + why no rangereal_closed? because, due to the aforementioned + rounding errors, i am unable to guarantee that $upper_bound + would be a possible return value of such a function. + */ + + function real_halfopen(){ + return signed2unsigned($this->int32()) * (1.0 / 4294967296.0); + } + + function rangereal_halfopen2($lower_bound, $upper_bound){ + do{ + $rand = $lower_bound + + $this->real_halfopen2() * ($upper_bound - $lower_bound); + }while($rand >= $upper_bound); + + return $rand; + } + + function real_halfopen2(){ + return ((($this->int32() & MASK27) * 67108864.0) + + ($this->int32() & MASK26)) * + (1.0 / 9007199254740992.0); + } +} + +function signed2unsigned($signed_integer){ + ## assert(is_integer($signed_integer)); + ## assert(($signed_integer & ~MASK32) === 0); + + return $signed_integer >= 0 ? $signed_integer : + TWO_TO_THE_32 + $signed_integer; +} + +function unsigned2signed($unsigned_integer){ + ## assert($unsigned_integer >= 0); + ## assert($unsigned_integer < pow(2, 32)); + ## assert(floor($unsigned_integer) === floatval($unsigned_integer)); + + return intval($unsigned_integer < TWO_TO_THE_31 ? $unsigned_integer : + $unsigned_integer - TWO_TO_THE_32); +} + +function force_32_bit_int($x){ + /* + it would be un-PHP-like to require is_integer($x), + so we have to handle cases like this: + + $x === pow(2, 31) + $x === strval(pow(2, 31)) + + we are also opting to do something sensible (rather than dying) + if the seed is outside the range of a 32-bit unsigned integer. + */ + + if(is_integer($x)){ + /* + we mask in case we are on a 64-bit machine and at least one + bit is set between position 32 and position 63. + */ + return $x & MASK32; + }else{ + $x = floatval($x); + + $x = $x < 0 ? ceil($x) : floor($x); + + $x = fmod($x, TWO_TO_THE_32); + + if($x < 0){ + $x += TWO_TO_THE_32; + } + + return unsigned2signed($x); + } } /* @@ -378,13 +393,13 @@ function force_32_bit_int($x) { a slight complication is that the sum of the low half-integers may not fit into 16 bits; any "overspill" is added to the sum of the high half-integers. -*/ -function add_2($n1, $n2) { - $x = ($n1 & 0xffff) + ($n2 & 0xffff); +*/ +function add_2($n1, $n2){ + $x = ($n1 & 0xffff) + ($n2 & 0xffff); - return (((($n1 >> 16) & 0xffff) + - (($n2 >> 16) & 0xffff) + - ($x >> 16)) << 16) | ($x & 0xffff); + return (((($n1 >> 16) & 0xffff) + + (($n2 >> 16) & 0xffff) + + ($x >> 16)) << 16) | ($x & 0xffff); } # takes 2 integers, treats them as unsigned 32-bit integers, @@ -392,13 +407,13 @@ function add_2($n1, $n2) { # # for how it works, see the comment for add_2. # -function add_3($n1, $n2, $n3) { - $x = ($n1 & 0xffff) + ($n2 & 0xffff) + ($n3 & 0xffff); +function add_3($n1, $n2, $n3){ + $x = ($n1 & 0xffff) + ($n2 & 0xffff) + ($n3 & 0xffff); - return (((($n1 >> 16) & 0xffff) + - (($n2 >> 16) & 0xffff) + - (($n3 >> 16) & 0xffff) + - ($x >> 16)) << 16) | ($x & 0xffff); + return (((($n1 >> 16) & 0xffff) + + (($n2 >> 16) & 0xffff) + + (($n3 >> 16) & 0xffff) + + ($x >> 16)) << 16) | ($x & 0xffff); } # takes 2 integers, treats them as unsigned 32-bit integers, @@ -407,72 +422,72 @@ function add_3($n1, $n2, $n3) { # the explanation of why this works is too long to be # included here, so it has been moved into the file why-sub-works.txt. # -function sub($a, $b) { - return (($a & MASK31) - ($b & MASK31)) ^ - (($a ^ $b) & 0x80000000); +function sub($a, $b){ + return (($a & MASK31) - ($b & MASK31)) ^ + (($a ^ $b) & 0x80000000); } -function mul($a, $b) { - /* - a and b, considered as unsigned integers, can be expressed as follows: +function mul($a, $b){ + /* + a and b, considered as unsigned integers, can be expressed as follows: - a = 2**16 * a1 + a2, + a = 2**16 * a1 + a2, - b = 2**16 * b1 + b2, + b = 2**16 * b1 + b2, - where + where - 0 <= a2 < 2**16, - 0 <= b2 < 2**16. + 0 <= a2 < 2**16, + 0 <= b2 < 2**16. - given those 2 equations, what this function essentially does is to - use the following identity: + given those 2 equations, what this function essentially does is to + use the following identity: - a * b = 2**32 * a1 * b1 + 2**16 * a1 * b2 + 2**16 * b1 * a2 + a2 * b2 + a * b = 2**32 * a1 * b1 + 2**16 * a1 * b2 + 2**16 * b1 * a2 + a2 * b2 - note that the first term, i.e. 2**32 * a1 * b1, is unnecessary here, - so we don't compute it. + note that the first term, i.e. 2**32 * a1 * b1, is unnecessary here, + so we don't compute it. - we could make the following code clearer by using intermediate - variables, but that would probably hurt performance. - */ + we could make the following code clearer by using intermediate + variables, but that would probably hurt performance. + */ - return unsigned2signed( - fmod( - TWO_TO_THE_16 * - /* - the next line of code calculates a1 * b2, - the line after that calculates b1 * a2, - and the line after that calculates a2 * b2. - */ - ((($a >> 16) & 0xffff) * ($b & 0xffff) + - (($b >> 16) & 0xffff) * ($a & 0xffff)) + - ($a & 0xffff) * ($b & 0xffff), + return unsigned2signed( + fmod( + TWO_TO_THE_16 * + /* + the next line of code calculates a1 * b2, + the line after that calculates b1 * a2, + and the line after that calculates a2 * b2. + */ + ((($a >> 16) & 0xffff) * ($b & 0xffff) + + (($b >> 16) & 0xffff) * ($a & 0xffff)) + + ($a & 0xffff) * ($b & 0xffff), - TWO_TO_THE_32)); + TWO_TO_THE_32)); } /* mul_by_1664525($x) should be more efficient than mul(1664525, $x). */ -function mul_by_1664525($n) { - return unsigned2signed(fmod(1664525 * ($n >= 0? - $n: (TWO_TO_THE_32 + $n)), TWO_TO_THE_32)); +function mul_by_1664525($n){ + return unsigned2signed(fmod(1664525 * ($n >= 0 ? + $n : (TWO_TO_THE_32 + $n)), TWO_TO_THE_32)); } -function do_bc_op($bc_op, array $numbers) { - $modulus = pow(2, 32); +function do_bc_op($bc_op, array $numbers){ + $modulus = pow(2, 32); - $result = - call_user_func_array($bc_op, - array_map("signed2unsigned", $numbers)); + $result = + call_user_func_array($bc_op, + array_map("signed2unsigned", $numbers)); - $result = bcmod($result, $modulus); + $result = bcmod($result, $modulus); - return unsigned2signed(bccomp($result, 0) < 0? - bcadd($result, $modulus): $result); + return unsigned2signed(bccomp($result, 0) < 0 ? + bcadd($result, $modulus) : $result); } -function get_random_32bit_int() { - return rand(0, 0xffff) | (rand(0, 0xffff) << 16); +function get_random_32bit_int(){ + return rand(0, 0xffff) | (rand(0, 0xffff) << 16); } diff --git a/src/utils/NBT.php b/src/utils/NBT.php index e18ce01c..1c3dfa51 100644 --- a/src/utils/NBT.php +++ b/src/utils/NBT.php @@ -1,28 +1,6 @@ offset += $n; - return substr($this->binary, $this->offset - $n, $n); - } - - private function feof(){ - return !isset($this->binary[$this->offset]); - } - + + public $tree = []; + public $binary = b""; + private $offset = 0; + public function write($bin){ $this->binary .= $bin; } - + public function load($str){ $this->offset = 0; $this->binary = (string) $str; $this->parseTree($this->tree); } - - public function readTAG_BYTE(){ - return Utils::readByte($this->read(1)); - } - - public function readTAG_SHORT(){ - return Utils::readLShort($this->read(2)); - } - - public function readTAG_INT(){ - return Utils::readLInt($this->read(4)); - } - - public function readTAG_LONG(){ - return Utils::readLLong($this->read(8)); - } - - public function readTAG_FLOAT(){ - return Utils::readLFloat($this->read(4)); - } - - public function readTAG_DOUBLE(){ - return Utils::readLDouble($this->read(8)); - } - - public function readTAG_BYTE_ARRAY(){ - return $this->read($this->readTAG_INT()); - } - - public function readTAG_STRING(){ - return $this->read(Utils::readLShort($this->read(2), false)); - } - - public function writeTAG_BYTE($v){ - $this->binary .= chr($v); - } - - public function writeTAG_SHORT($v){ - $this->binary .= Utils::writeLShort($v); - } - - public function writeTAG_INT($v){ - $this->binary .= Utils::writeLInt($v); - } - - public function writeTAG_LONG($v){ - $this->binary .= Utils::writeLLong($v); - } - - public function writeTAG_FLOAT($v){ - $this->binary .= Utils::writeLFloar($v); - } - - public function writeTAG_DOUBLE($v){ - $this->binary .= Utils::writeLDouble($v); - } - - public function writeTAG_BYTE_ARRAY($v){ - $this->binary .= $this->writeTAG_INT(strlen($v)).$v; - } - - public function writeTAG_STRING($v){ - $this->binary .= $this->writeTAG_SHORT(strlen($v)).$v; - } - private function parseList(&$node, $tag, $cnt){ - for($i = 0; $i < $cnt and !$this->feof(); ++$i){ - switch($tag){ - case self::TAG_BYTE: - $value = $this->readTAG_BYTE(); - break; - case self::TAG_SHORT: - $value = $this->readTAG_SHORT(); - break; - case self::TAG_INT: - $value = $this->readTAG_INT(); - break; - case self::TAG_LONG: - $value = $this->readTAG_LONG(); - break; - case self::TAG_FLOAT: - $value = $this->readTAG_FLOAT(); - break; - case self::TAG_DOUBLE: - $value = $this->readTAG_DOUBLE(); - break; - case self::TAG_BYTE_ARRAY: - $value = $this->readTAG_BYTE_ARRAY(); - break; - case self::TAG_STRING: - $value = $this->readTAG_STRING(); - break; - case self::TAG_LIST: - $value = array(); - $this->parseList($value, ord($this->read(1)), Utils::readLInt($this->read(4))); - break; - case self::TAG_COMPOUND: - $value = array(); - $this->parseTree($value); - break; - default: - echo bin2hex(substr($this->binary, $this->offset - 1)).PHP_EOL.PHP_EOL; - die("Invalid NBT Tag $tag"); - break; - } - $node[] = $value; - } - } - private function parseTree(&$node){ while(($tag = ord($this->read(1))) !== self::TAG_END and !$this->feof()){ $name = $this->readTAG_STRING(); switch($tag){ - case self::TAG_BYTE: + case self::TAG_BYTE: $value = $this->readTAG_BYTE(); break; case self::TAG_SHORT: @@ -195,19 +57,139 @@ class NBT{ $value = $this->readTAG_STRING(); break; case self::TAG_LIST: - $value = array(); + $value = []; $this->parseList($value, ord($this->read(1)), Utils::readLInt($this->read(4))); break; case self::TAG_COMPOUND: - $value = array(); + $value = []; $this->parseTree($value); break; default: - echo bin2hex(substr($this->binary, $this->offset - 1)).PHP_EOL.PHP_EOL; + echo bin2hex(substr($this->binary, $this->offset - 1)) . PHP_EOL . PHP_EOL; die("Invalid NBT Tag $tag"); break; } $node[$name] = $value; } } + + public function read($n){ + if($n <= 0){ + return ""; + } + $this->offset += $n; + return substr($this->binary, $this->offset - $n, $n); + } + + private function feof(){ + return !isset($this->binary[$this->offset]); + } + + public function readTAG_STRING(){ + return $this->read(Utils::readLShort($this->read(2), false)); + } + + public function readTAG_BYTE(){ + return Utils::readByte($this->read(1)); + } + + public function readTAG_SHORT(){ + return Utils::readLShort($this->read(2)); + } + + public function readTAG_INT(){ + return Utils::readLInt($this->read(4)); + } + + public function readTAG_LONG(){ + return Utils::readLLong($this->read(8)); + } + + public function readTAG_FLOAT(){ + return Utils::readLFloat($this->read(4)); + } + + public function readTAG_DOUBLE(){ + return Utils::readLDouble($this->read(8)); + } + + public function readTAG_BYTE_ARRAY(){ + return $this->read($this->readTAG_INT()); + } + + private function parseList(&$node, $tag, $cnt){ + for($i = 0; $i < $cnt and !$this->feof(); ++$i){ + switch($tag){ + case self::TAG_BYTE: + $value = $this->readTAG_BYTE(); + break; + case self::TAG_SHORT: + $value = $this->readTAG_SHORT(); + break; + case self::TAG_INT: + $value = $this->readTAG_INT(); + break; + case self::TAG_LONG: + $value = $this->readTAG_LONG(); + break; + case self::TAG_FLOAT: + $value = $this->readTAG_FLOAT(); + break; + case self::TAG_DOUBLE: + $value = $this->readTAG_DOUBLE(); + break; + case self::TAG_BYTE_ARRAY: + $value = $this->readTAG_BYTE_ARRAY(); + break; + case self::TAG_STRING: + $value = $this->readTAG_STRING(); + break; + case self::TAG_LIST: + $value = []; + $this->parseList($value, ord($this->read(1)), Utils::readLInt($this->read(4))); + break; + case self::TAG_COMPOUND: + $value = []; + $this->parseTree($value); + break; + default: + echo bin2hex(substr($this->binary, $this->offset - 1)) . PHP_EOL . PHP_EOL; + die("Invalid NBT Tag $tag"); + break; + } + $node[] = $value; + } + } + + public function writeTAG_BYTE($v){ + $this->binary .= chr($v); + } + + public function writeTAG_LONG($v){ + $this->binary .= Utils::writeLLong($v); + } + + public function writeTAG_FLOAT($v){ + $this->binary .= Utils::writeLFloar($v); + } + + public function writeTAG_DOUBLE($v){ + $this->binary .= Utils::writeLDouble($v); + } + + public function writeTAG_BYTE_ARRAY($v){ + $this->binary .= $this->writeTAG_INT(strlen($v)) . $v; + } + + public function writeTAG_INT($v){ + $this->binary .= Utils::writeLInt($v); + } + + public function writeTAG_STRING($v){ + $this->binary .= $this->writeTAG_SHORT(strlen($v)) . $v; + } + + public function writeTAG_SHORT($v){ + $this->binary .= Utils::writeLShort($v); + } } \ No newline at end of file diff --git a/src/utils/Random.php b/src/utils/Random.php index 344c9601..85c6ae0b 100644 --- a/src/utils/Random.php +++ b/src/utils/Random.php @@ -1,37 +1,19 @@ setSeed($seed); } - + public function setSeed($seed = false){ - $seed = $seed !== false ? Utils::writeInt((int) $seed):Utils::getRandomBytes(4, false); - $state = array(); + $seed = $seed !== false ? Utils::writeInt((int) $seed) : Utils::getRandomBytes(4, false); + $state = []; for($i = 0; $i < 256; ++$i){ $state[] = $i; } @@ -44,39 +26,33 @@ class Random{ $this->state = $state; $this->i = $this->j = 0; } + public function nextGaussian(){ - if ($this->haveNextNextGaussian) { - $this->haveNextNextGaussian = false; + if($this->haveNextNextGaussian){ + $this->haveNextNextGaussian = false; return $this->nextNextGaussian; - } else { - $v1 = $v2 = $s = null; - do { - $v1 = 2 * $this->nextFloat() - 1; // between -1.0 and 1.0 - $v2 = 2 * $this->nextFloat() - 1; // between -1.0 and 1.0 - $s = $v1 * $v1 + $v2 * $v2; - } while ($s >= 1 || $s == 0); - $multiplier = sqrt(-2 * log($s)/$s); - $nextNextGaussian = $v2 * $multiplier; - $haveNextNextGaussian = true; - return $v1 * $multiplier; - } - } - public function nextInt(){ - return Utils::readInt($this->nextBytes(4)) & 0x7FFFFFFF; + }else{ + $v1 = $v2 = $s = null; + do{ + $v1 = 2 * $this->nextFloat() - 1; // between -1.0 and 1.0 + $v2 = 2 * $this->nextFloat() - 1; // between -1.0 and 1.0 + $s = $v1 * $v1 + $v2 * $v2; + }while($s >= 1 || $s == 0); + $multiplier = sqrt(-2 * log($s) / $s); + $nextNextGaussian = $v2 * $multiplier; + $haveNextNextGaussian = true; + return $v1 * $multiplier; + } } - public function nextSignedInt(){ - return Utils::readInt($this->nextBytes(4)); - } - public function nextFloat(){ return $this->nextInt() / 0x7FFFFFFF; } - public function nextSignedFloat(){ - return $this->nextSignedInt() / 0x7FFFFFFF; + public function nextInt(){ + return Utils::readInt($this->nextBytes(4)) & 0x7FFFFFFF; } - + public function nextBytes($byteCount){ $bytes = ""; for($i = 0; $i < $byteCount; ++$i){ @@ -89,11 +65,19 @@ class Random{ } return $bytes; } - + + public function nextSignedFloat(){ + return $this->nextSignedInt() / 0x7FFFFFFF; + } + + public function nextSignedInt(){ + return Utils::readInt($this->nextBytes(4)); + } + public function nextBoolean(){ return ($this->nextBytes(1) & 0x01) == 0; } - + public function nextRange($start = 0, $end = PHP_INT_MAX){ return $start + ($this->nextInt() % ($end + 1 - $start)); } diff --git a/src/utils/TextFormat.php b/src/utils/TextFormat.php index f4f56a32..d11672f5 100644 --- a/src/utils/TextFormat.php +++ b/src/utils/TextFormat.php @@ -1,24 +1,5 @@ ", $tokens); return $newString; } - + public static function toANSI($string){ if(!is_array($string)){ $string = self::tokenize($string); diff --git a/src/utils/UPnP.php b/src/utils/UPnP.php index 9e5fe2c1..93782437 100644 --- a/src/utils/UPnP.php +++ b/src/utils/UPnP.php @@ -1,24 +1,5 @@ $line){ $hex = chunk_split(chunk_split(str_pad(bin2hex($line), 32, " ", STR_PAD_RIGHT), 2, " "), 24, " "); $ascii = preg_replace('#([^\x20-\x7E])#', ".", $line); - $output .= str_pad(dechex($counter << 4), 4, "0", STR_PAD_LEFT). " " . $hex . " " . $ascii . PHP_EOL; + $output .= str_pad(dechex($counter << 4), 4, "0", STR_PAD_LEFT) . " " . $hex . " " . $ascii . PHP_EOL; } return $output; } @@ -138,17 +140,8 @@ class Utils{ return preg_replace('#([^\x20-\x7E])#', '.', $str); } - public static function readTriad($str){ - list(,$unpacked) = @unpack("N", "\x00".$str); - return $unpacked; - } - - public static function writeTriad($value){ - return substr(pack("N", $value), 1); - } - public static function getRandomUpdateTicks(){ - return -log(lcg_value())*1365.4; //Poisson distribution (1/(68.27 * 20)) + return -log(lcg_value()) * 1365.4; //Poisson distribution (1/(68.27 * 20)) } public static function writeMetadata($data){ @@ -178,7 +171,7 @@ class Utils{ $m .= Utils::writeLShort($d["value"][2]); break; case 6: - for($i=0; $i < 3; ++$i){ + for($i = 0; $i < 3; ++$i){ $m .= Utils::writeLInt($d["value"][$i]); } break; @@ -187,11 +180,46 @@ class Utils{ $m .= "\x7f"; return $m; } - - public static function writeSlot(Item $item){ - return Utils::writeShort($item->getID()).chr($item->count).Utils::writeShort($item->getMetadata()); + + public static function writeByte($c){ + if($c > 0xff){ + return false; + } + if($c < 0 and $c >= -0x80){ + $c = 0xff + $c + 1; + } + return chr($c); } - + + public static function writeLShort($value){ + if($value < 0){ + $value += 0x10000; + } + return pack("v", $value); + } + + public static function writeLInt($value){ + if($value < 0){ + $value += 0x100000000; + } + return pack("V", $value); + } + + public static function writeLFloat($value){ + return ENDIANNESS === BIG_ENDIAN ? strrev(pack("f", $value)) : pack("f", $value); + } + + public static function writeSlot(Item $item){ + return Utils::writeShort($item->getID()) . chr($item->count) . Utils::writeShort($item->getMetadata()); + } + + public static function writeShort($value){ + if($value < 0){ + $value += 0x10000; + } + return pack("n", $value); + } + public static function readSlot($ob){ $id = Utils::readShort($ob->get(2)); $cnt = ord($ob->get(1)); @@ -202,9 +230,22 @@ class Utils{ ); } + public static function readShort($str, $signed = true){ + if(strlen($str) === 0){ + return; + } + + [, $unpacked] = unpack("n", $str); + if($unpacked > 0x7fff and $signed === true){ + $unpacked -= 0x10000; // Convert unsigned short to signed short + } + + return $unpacked; + } + public static function readMetadata($value, $types = false){ $offset = 0; - $m = array(); + $m = []; $b = ord($value[$offset]); ++$offset; while($b !== 127 and isset($value[$offset])){ @@ -234,7 +275,7 @@ class Utils{ $offset += $len; break; case 5: - $r = array(); + $r = []; $r[] = Utils::readLShort(substr($value, $offset, 2)); $offset += 2; $r[] = ord($value[$offset]); @@ -243,8 +284,8 @@ class Utils{ $offset += 2; break; case 6: - $r = array(); - for($i=0; $i < 3; ++$i){ + $r = []; + for($i = 0; $i < 3; ++$i){ $r[] = Utils::readLInt(substr($value, $offset, 4)); $offset += 4; } @@ -252,7 +293,7 @@ class Utils{ } if($types === true){ - $m[$bottom] = array($r, $type); + $m[$bottom] = [$r, $type]; }else{ $m[$bottom] = $r; } @@ -262,8 +303,37 @@ class Utils{ return $m; } + public static function readByte($c, $signed = true){ + $b = ord($c[0]); + if($signed === true and ($b & 0x80) === 0x80){ //calculate Two's complement + $b = -0x80 + ($b & 0x7f); + } + return $b; + } + + public static function readLShort($str, $signed = true){ + [, $unpacked] = @unpack("v", $str); + if($unpacked > 0x7fff and $signed === true){ + $unpacked -= 0x10000; // Convert unsigned short to signed short + } + return $unpacked; + } + + public static function readLInt($str){ + [, $unpacked] = @unpack("V", $str); + if($unpacked >= 2147483648){ + $unpacked -= 4294967296; + } + return (int) $unpacked; + } + + public static function readLFloat($str){ + [, $value] = ENDIANNESS === BIG_ENDIAN ? @unpack("f", strrev($str)) : @unpack("f", $str); + return $value; + } + public static function readDataArray($str, $len = 10, &$offset = null){ - $data = array(); + $data = []; $offset = 0; for($i = 1; $i <= $len and isset($str[$offset]); ++$i){ $l = Utils::readTriad(substr($str, $offset, 3)); @@ -274,6 +344,11 @@ class Utils{ return $data; } + public static function readTriad($str){ + [, $unpacked] = @unpack("N", "\x00" . $str); + return $unpacked; + } + public static function writeDataArray($data){ $raw = ""; foreach($data as $v){ @@ -283,6 +358,10 @@ class Utils{ return $raw; } + public static function writeTriad($value){ + return substr(pack("N", $value), 1); + } + public static function getRandomBytes($length = 16, $secure = true, $raw = true, $startEntropy = "", &$rounds = 0, &$drop = 0){ static $lastRandom = ""; $output = b""; @@ -292,8 +371,8 @@ class Utils{ $drop = 0; while(!isset($output[$length - 1])){ //some entropy, but works ^^ - $weakEntropy = array( - is_array($startEntropy) ? implode($startEntropy):$startEntropy, + $weakEntropy = [ + is_array($startEntropy) ? implode($startEntropy) : $startEntropy, serialize(@stat(__FILE__)), __DIR__, PHP_OS, @@ -301,12 +380,12 @@ class Utils{ (string) lcg_value(), (string) PHP_MAXPATHLEN, PHP_SAPI, - (string) PHP_INT_MAX.".".PHP_INT_SIZE, + (string) PHP_INT_MAX . "." . PHP_INT_SIZE, serialize($_SERVER), serialize(get_defined_constants()), get_current_user(), serialize(ini_get_all()), - (string) memory_get_usage().".".memory_get_peak_usage(), + (string) memory_get_usage() . "." . memory_get_peak_usage(), php_uname(), phpversion(), //extension_loaded("gmp") ? gmp_strval(gmp_random(4)):microtime(), @@ -317,17 +396,17 @@ class Utils{ (string) getmyinode(), (string) getmygid(), (string) rand(), - function_exists("zend_thread_id") ? ((string) zend_thread_id()):microtime(), - function_exists("getrusage") ? @implode(getrusage()):microtime(), - function_exists("sys_getloadavg") ? @implode(sys_getloadavg()):microtime(), + function_exists("zend_thread_id") ? ((string) zend_thread_id()) : microtime(), + function_exists("getrusage") ? @implode(getrusage()) : microtime(), + function_exists("sys_getloadavg") ? @implode(sys_getloadavg()) : microtime(), serialize(get_loaded_extensions()), sys_get_temp_dir(), (string) disk_free_space("."), (string) disk_total_space("."), - uniqid(microtime(),true), + uniqid(microtime(), true), file_exists("/proc/cpuinfo") ? file_get_contents("/proc/cpuinfo") : microtime(), - ); - + ]; + shuffle($weakEntropy); $value = hash("sha512", implode($weakEntropy), true); $lastRandom .= $value; @@ -336,15 +415,15 @@ class Utils{ $value ^= hash("sha512", ((string) lcg_value()) . $c . microtime() . $k, true); } unset($weakEntropy); - + if($secure === true){ - $strongEntropyValues = array( - is_array($startEntropy) ? hash("sha512", $startEntropy[($rounds + $drop) % count($startEntropy)], true):hash("sha512", $startEntropy, true), //Get a random index of the startEntropy, or just read it + $strongEntropyValues = [ + is_array($startEntropy) ? hash("sha512", $startEntropy[($rounds + $drop) % count($startEntropy)], true) : hash("sha512", $startEntropy, true), //Get a random index of the startEntropy, or just read it file_exists("/dev/urandom") ? fread(fopen("/dev/urandom", "rb"), 64) : str_repeat("\x00", 64), (function_exists("openssl_random_pseudo_bytes") and version_compare(PHP_VERSION, "5.3.4", ">=")) ? openssl_random_pseudo_bytes(64) : str_repeat("\x00", 64), function_exists("mcrypt_create_iv") ? mcrypt_create_iv(64, MCRYPT_DEV_URANDOM) : str_repeat("\x00", 64), $value, - ); + ]; $strongEntropy = array_pop($strongEntropyValues); foreach($strongEntropyValues as $value){ $strongEntropy = $strongEntropy ^ $value; @@ -354,9 +433,9 @@ class Utils{ $bitcnt = 0; for($j = 0; $j < 64; ++$j){ $a = ord($strongEntropy[$j]); - for($i = 0; $i < 8; $i += 2){ - $b = ($a & (1 << $i)) > 0 ? 1:0; - if($b != (($a & (1 << ($i + 1))) > 0 ? 1:0)){ + for($i = 0; $i < 8; $i += 2){ + $b = ($a & (1 << $i)) > 0 ? 1 : 0; + if($b != (($a & (1 << ($i + 1))) > 0 ? 1 : 0)){ $secureValue = $b << $bitcnt; if($bitcnt == 7){ $value .= chr($secureValue); @@ -377,17 +456,17 @@ class Utils{ ++$rounds; } $lastRandom = hash("sha512", $lastRandom, true); - return $raw === false ? bin2hex($output):$output; + return $raw === false ? bin2hex($output) : $output; } - - public static function randomFloat(){//GameHerobrine's code - return rand()/getrandmax(); - } - + public static function chance($i){//GameHerobrine's code return self::randomFloat() <= $i / 100; } + public static function randomFloat(){//GameHerobrine's code + return rand() / getrandmax(); + } + public static function round($number){ return round($number, 0, PHP_ROUND_HALF_DOWN); } @@ -403,44 +482,24 @@ class Utils{ $Y = $pos1["y"] - $pos2["y"]; $hAngle = rad2deg(atan2($Z, $X) - M_PI_2); $vAngle = rad2deg(-atan2($Y, $dXZ)); - return array("yaw" => $hAngle, "pitch" => $vAngle); - } - - public static function curl_get($page, $timeout = 10){ - if(Utils::$online === false){ - return false; - } - - $ch = curl_init($page); - curl_setopt($ch, CURLOPT_HTTPHEADER, array("User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:12.0) Gecko/20100101 Firefox/12.0 PocketMine-MP")); - curl_setopt($ch, CURLOPT_AUTOREFERER, true); - curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); - curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2); - curl_setopt($ch, CURLOPT_FORBID_REUSE, 1); - curl_setopt($ch, CURLOPT_FRESH_CONNECT, 1); - curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); - curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); - curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, (int) $timeout); - $ret = curl_exec($ch); - curl_close($ch); - return $ret; + return ["yaw" => $hAngle, "pitch" => $vAngle]; } public static function curl_post($page, $args, $timeout = 10){ if(Utils::$online === false){ return false; } - + $ch = curl_init($page); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2); - curl_setopt($ch, CURLOPT_FORBID_REUSE, 1); - curl_setopt($ch, CURLOPT_FRESH_CONNECT, 1); + curl_setopt($ch, CURLOPT_FORBID_REUSE, 1); + curl_setopt($ch, CURLOPT_FRESH_CONNECT, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $args); curl_setopt($ch, CURLOPT_AUTOREFERER, true); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); - curl_setopt($ch, CURLOPT_HTTPHEADER, array("User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:12.0) Gecko/20100101 Firefox/12.0 PocketMine-MP")); + curl_setopt($ch, CURLOPT_HTTPHEADER, ["User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:12.0) Gecko/20100101 Firefox/12.0 PocketMine-MP"]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, (int) $timeout); $ret = curl_exec($ch); @@ -457,66 +516,23 @@ class Utils{ } public static function readBool($b){ - return Utils::readByte($b, false) === 0 ? false:true; + return Utils::readByte($b, false) === 0 ? false : true; } public static function writeBool($b){ - return Utils::writeByte($b === true ? 1:0); - } - - public static function readByte($c, $signed = true){ - $b = ord($c[0]); - if($signed === true and ($b & 0x80) === 0x80){ //calculate Two's complement - $b = -0x80 + ($b & 0x7f); - } - return $b; - } - - public static function writeByte($c){ - if($c > 0xff){ - return false; - } - if($c < 0 and $c >= -0x80){ - $c = 0xff + $c + 1; - } - return chr($c); - } - - public static function readShort($str, $signed = true){ - list(,$unpacked) = @unpack("n", $str); - if($unpacked > 0x7fff and $signed === true){ - $unpacked -= 0x10000; // Convert unsigned short to signed short - } - return $unpacked; - } - - public static function writeShort($value){ - if($value < 0){ - $value += 0x10000; - } - return pack("n", $value); - } - - public static function readLShort($str, $signed = true){ - list(,$unpacked) = @unpack("v", $str); - if($unpacked > 0x7fff and $signed === true){ - $unpacked -= 0x10000; // Convert unsigned short to signed short - } - return $unpacked; - } - - public static function writeLShort($value){ - if($value < 0){ - $value += 0x10000; - } - return pack("v", $value); + return Utils::writeByte($b === true ? 1 : 0); } public static function readInt($str){ - list(,$unpacked) = @unpack("N", $str); + if(strlen($str) === 0){ + return; + } + + [, $unpacked] = unpack("N", $str); if($unpacked >= 2147483648){ $unpacked -= 4294967296; } + return (int) $unpacked; } @@ -527,37 +543,13 @@ class Utils{ return pack("N", $value); } - public static function readLInt($str){ - list(,$unpacked) = @unpack("V", $str); - if($unpacked >= 2147483648){ - $unpacked -= 4294967296; - } - return (int) $unpacked; - } - - public static function writeLInt($value){ - if($value < 0){ - $value += 0x100000000; - } - return pack("V", $value); - } - public static function readFloat($str){ - list(,$value) = ENDIANNESS === BIG_ENDIAN ? @unpack("f", $str):@unpack("f", strrev($str)); + [, $value] = ENDIANNESS === BIG_ENDIAN ? @unpack("f", $str) : @unpack("f", strrev($str)); return $value; } public static function writeFloat($value){ - return ENDIANNESS === BIG_ENDIAN ? pack("f", $value):strrev(pack("f", $value)); - } - - public static function readLFloat($str){ - list(,$value) = ENDIANNESS === BIG_ENDIAN ? @unpack("f", strrev($str)):@unpack("f", $str); - return $value; - } - - public static function writeLFloat($value){ - return ENDIANNESS === BIG_ENDIAN ? strrev(pack("f", $value)):pack("f", $value); + return ENDIANNESS === BIG_ENDIAN ? pack("f", $value) : strrev(pack("f", $value)); } public static function printFloat($value){ @@ -565,27 +557,31 @@ class Utils{ } public static function readDouble($str){ - list(,$value) = ENDIANNESS === BIG_ENDIAN ? @unpack("d", $str):@unpack("d", strrev($str)); + [, $value] = ENDIANNESS === BIG_ENDIAN ? @unpack("d", $str) : @unpack("d", strrev($str)); return $value; } public static function writeDouble($value){ - return ENDIANNESS === BIG_ENDIAN ? pack("d", $value):strrev(pack("d", $value)); + return ENDIANNESS === BIG_ENDIAN ? pack("d", $value) : strrev(pack("d", $value)); } public static function readLDouble($str){ - list(,$value) = ENDIANNESS === BIG_ENDIAN ? @unpack("d", strrev($str)):@unpack("d", $str); + [, $value] = ENDIANNESS === BIG_ENDIAN ? @unpack("d", strrev($str)) : @unpack("d", $str); return $value; } public static function writeLDouble($value){ - return ENDIANNESS === BIG_ENDIAN ? strrev(pack("d", $value)):pack("d", $value); + return ENDIANNESS === BIG_ENDIAN ? strrev(pack("d", $value)) : pack("d", $value); + } + + public static function readLLong($str){ + return Utils::readLong(strrev($str)); } public static function readLong($x, $signed = true){ $value = "0"; if($signed === true){ - $negative = ((ord($x[0]) & 0x80) === 0x80) ? true:false; + $negative = ((ord($x[0]) & 0x80) === 0x80) ? true : false; if($negative){ $x = ~$x; } @@ -597,12 +593,16 @@ class Utils{ $value = bcmul($value, "4294967296", 0); //4294967296 == 2^32 $value = bcadd($value, 0x1000000 * ord(@$x[$i]) + ((ord(@$x[$i + 1]) << 16) | (ord(@$x[$i + 2]) << 8) | ord(@$x[$i + 3])), 0); } - return ($negative === true ? "-".$value:$value); + return ($negative === true ? "-" . $value : $value); + } + + public static function writeLLong($value){ + return strrev(Utils::writeLong($value)); } public static function writeLong($value){ $x = ""; - if(strval($value[0]) === "-"){ + if(strval($value[0] ?? '') === "-"){ $negative = true; $value = bcadd($value, "1"); if(strval($value[0]) === "-"){ @@ -618,22 +618,12 @@ class Utils{ } $x = str_pad(substr($x, 0, 8), 8, "\x00", STR_PAD_LEFT); if($negative === true){ - $x = ~$x; + $x = ~$x; } return $x; } - - public static function readLLong($str){ - return Utils::readLong(strrev($str)); - } - - public static function writeLLong($value){ - return strrev(Utils::writeLong($str)); - } - - } //if(Utils::isOnline() === false){ - //Utils::$online = false; +//Utils::$online = false; //} diff --git a/src/utils/VersionString.php b/src/utils/VersionString.php index 7fccc28b..07a5fd8d 100644 --- a/src/utils/VersionString.php +++ b/src/utils/VersionString.php @@ -1,38 +1,21 @@ 0, "a" => 0, "beta" => 1, "b" => 1, "final" => 2, "f" => 2, - ); + ]; private $stage; private $major; private $release; private $minor; private $development = false; + public function __construct($version = MAJOR_VERSION){ if(is_int($version)){ $this->minor = $version & 0x1F; @@ -45,14 +28,10 @@ class VersionString{ $this->generation = (int) $version[2]; //0-15 $this->major = (int) $version[3]; //0-15 $this->minor = (int) $version[4]; //0-31 - $this->development = $version[5] === "dev" ? true:false; + $this->development = $version[5] === "dev" ? true : false; } } - public function getNumber(){ - return (int) (VersionString::$stageOrder[$this->stage] << 13) + ($this->generation << 9) + ($this->major << 5) + $this->minor; - } - public function getStage(){ return $this->stage; } @@ -69,22 +48,22 @@ class VersionString{ return $this->minor; } - public function getRelease(){ - return $this->generation . "." . $this->major . "." . $this->minor; - } - public function isDev(){ return $this->development === true; } - - public function get(){ - return ucfirst($this->stage) . "_" . $this->getRelease() . ($this->development === true ? "dev":""); - } public function __toString(){ return $this->get(); } + public function get(){ + return ucfirst($this->stage) . "_" . $this->getRelease() . ($this->development === true ? "dev" : ""); + } + + public function getRelease(){ + return $this->generation . "." . $this->major . "." . $this->minor; + } + public function compare($target, $diff = false){ if(($target instanceof VersionString) === false){ $target = new VersionString($target); @@ -102,4 +81,8 @@ class VersionString{ return 0; //Same version } } + + public function getNumber(){ + return (int) (VersionString::$stageOrder[$this->stage] << 13) + ($this->generation << 9) + ($this->major << 5) + $this->minor; + } } \ No newline at end of file diff --git a/src/utils/pthreads.php b/src/utils/pthreads.php index a9924632..7909765f 100644 --- a/src/utils/pthreads.php +++ b/src/utils/pthreads.php @@ -1,38 +1,55 @@ input = ""; $this->output = ""; $this->stop = false; $this->start(); } - + + public function run(){ + while($this->stop === false){ + if(isset($this->input[5])){ //len 6 min + $rID = Utils::readInt($this->get(4)); + switch(Utils::readShort($this->get(2), false)){ + case ASYNC_CURL_GET: + $url = $this->get(Utils::readShort($this->get(2), false)); + $timeout = Utils::readShort($this->get(2)); + + $res = (string) Utils::curl_get($url, $timeout); + //$this->lock(); + $this->output .= Utils::writeInt($rID) . Utils::writeShort(ASYNC_CURL_GET) . Utils::writeInt(strlen($res)) . $res; + //$this->unlock(); + break; + case ASYNC_CURL_POST: + $url = $this->get(Utils::readShort($this->get(2), false)); + $timeout = Utils::readShort($this->get(2)); + $cnt = Utils::readShort($this->get(2), false); + $d = []; + for($c = 0; $c < $cnt; ++$c){ + $key = $this->get(Utils::readShort($this->get(2), false)); + $d[$key] = $this->get(Utils::readInt($this->get(4), false)); + } + $res = (string) Utils::curl_post($url, $d, $timeout); + //$this->lock(); + $this->output .= Utils::writeInt($rID) . Utils::writeShort(ASYNC_CURL_POST) . Utils::writeInt(strlen($res)) . $res; + //$this->unlock(); + break; + } + } + usleep(10000); + } + } + private function get($len){ $str = ""; if($len <= 0){ @@ -48,65 +65,32 @@ class AsyncMultipleQueue extends Thread{ $this->input = (string) substr($this->input, $offset); return $str; } - - public function run(){ - while($this->stop === false){ - if(isset($this->input[5])){ //len 6 min - $rID = Utils::readInt($this->get(4)); - switch(Utils::readShort($this->get(2), false)){ - case ASYNC_CURL_GET: - $url = $this->get(Utils::readShort($this->get(2), false)); - $timeout = Utils::readShort($this->get(2)); - - $res = (string) Utils::curl_get($url, $timeout); - //$this->lock(); - $this->output .= Utils::writeInt($rID).Utils::writeShort(ASYNC_CURL_GET).Utils::writeInt(strlen($res)).$res; - //$this->unlock(); - break; - case ASYNC_CURL_POST: - $url = $this->get(Utils::readShort($this->get(2), false)); - $timeout = Utils::readShort($this->get(2)); - $cnt = Utils::readShort($this->get(2), false); - $d = array(); - for($c = 0; $c < $cnt; ++$c){ - $key = $this->get(Utils::readShort($this->get(2), false)); - $d[$key] = $this->get(Utils::readInt($this->get(4), false)); - } - $res = (string) Utils::curl_post($url, $d, $timeout); - //$this->lock(); - $this->output .= Utils::writeInt($rID).Utils::writeShort(ASYNC_CURL_POST).Utils::writeInt(strlen($res)).$res; - //$this->unlock(); - break; - } - } - usleep(10000); - } - } } class Async extends Thread{ - public function __construct($method, $params = array()){ + + public function __construct($method, $params = []){ $this->method = $method; $this->params = $params; $this->result = null; $this->joined = false; } - public function run(){ - if(($this->result=call_user_func_array($this->method, $this->params))){ - return true; - }else{ - return false; - } - } - - public static function call($method, $params = array()){ + public static function call($method, $params = []){ $thread = new Async($method, $params); if($thread->start()){ return $thread; } } + public function run(){ + if(($this->result = call_user_func_array($this->method, $this->params))){ + return true; + }else{ + return false; + } + } + public function __toString(){ if(!$this->joined){ $this->joined = true; diff --git a/src/world/Explosion.php b/src/world/Explosion.php index 75d95a29..bc63d780 100644 --- a/src/world/Explosion.php +++ b/src/world/Explosion.php @@ -1,41 +1,24 @@ DIRT, STONE => COBBLESTONE, COAL_ORE => COAL, DIAMOND_ORE => DIAMOND, REDSTONE_ORE => REDSTONE, - ); + ]; public static $enableExplosions = true; - private $rays = 16; //Rays - public $level; + public $level; //Rays public $source; public $size; - public $affectedBlocks = array(); + public $affectedBlocks = []; public $stepLen = 0.3; + private $rays = 16; private $air; private $nullPlayer; + public function __construct(Position $center, $size){ $this->level = $center->level; $this->source = $center; @@ -43,17 +26,18 @@ class Explosion{ $this->air = BlockAPI::getItem(AIR, 0, 1); $this->nullPlayer = new PlayerNull(); } - + public function explode(){ if(!Explosion::$enableExplosions){ /*Disable Explosions*/ return; } + $server = ServerAPI::request(); - if($this->size < 0.1 or $server->api->dhandle("entity.explosion", array( - "level" => $this->level, - "source" => $this->source, - "size" => $this->size - )) === false){ + if($this->size < 0.1 or $server->api->dhandle("entity.explosion", [ + "level" => $this->level, + "source" => $this->source, + "size" => $this->size + ]) === false){ return false; } @@ -65,11 +49,11 @@ class Explosion{ $vector = new Vector3($i / $mRays * 2 - 1, $j / $mRays * 2 - 1, $k / $mRays * 2 - 1); //($i / $mRays) * 2 - 1 $vector = $vector->normalize()->multiply($this->stepLen); $pointer = clone $this->source; - + for($blastForce = $this->size * (mt_rand(700, 1300) / 1000); $blastForce > 0; $blastForce -= $this->stepLen * 0.75){ $vBlock = $pointer->floor(); $blockID = $this->level->level->getBlockID($vBlock->x, $vBlock->y, $vBlock->z); - + if($blockID > 0){ $block = BlockAPI::get($blockID, 0); $block->x = $vBlock->x; @@ -77,7 +61,7 @@ class Explosion{ $block->z = $vBlock->z; $blastForce -= ($block->getHardness() / 5 + 0.3) * $this->stepLen; if($blastForce > 0){ - $index = ($block->x << 15) + ($block->z << 7) + $block->y; + $index = ($block->x << 15) + ($block->z << 7) + $block->y; if(!isset($this->affectedBlocks[$index])){ $this->affectedBlocks[$index] = $block; } @@ -89,8 +73,8 @@ class Explosion{ } } } - - $send = array(); + + $send = []; $source = $this->source->floor(); $radius = 2 * $this->size; foreach($server->api->entity->getRadius($this->source, $radius) as $entity){ @@ -102,18 +86,18 @@ class Explosion{ foreach($this->affectedBlocks as $block){ if($block instanceof TNTBlock){ - $data = array( + $data = [ "x" => $block->x + 0.5, "y" => $block->y + 0.5, "z" => $block->z + 0.5, "power" => 4, "fuse" => mt_rand(10, 30), //0.5 to 1.5 seconds - ); + ]; $e = $server->api->entity->add($this->level, ENTITY_OBJECT, OBJECT_PRIMEDTNT, $data); $server->api->entity->spawnToAll($e); - }elseif(mt_rand(0, 10000) < ((1/$this->size) * 10000)){ + }elseif(mt_rand(0, 10000) < ((1 / $this->size) * 10000)){ foreach($block->getDrops($this->air, $this->nullPlayer) as $drop){ - $server->api->entity->drop(new Position($block->x + 0.5, $block->y, $block->z + 0.5, $this->level), BlockAPI::getItem($drop[0], $drop[1],$drop[2])); //id, meta, count + $server->api->entity->drop(new Position($block->x + 0.5, $block->y, $block->z + 0.5, $this->level), BlockAPI::getItem($drop[0], $drop[1], $drop[2])); //id, meta, count } } $this->level->level->setBlockID($block->x, $block->y, $block->z, 0); @@ -127,6 +111,5 @@ class Explosion{ $pk->radius = $this->size; $pk->records = $send; $server->api->player->broadcastPacket($this->level->players, $pk); - } } diff --git a/src/world/Level.php b/src/world/Level.php index 9df4baf5..b326e64a 100644 --- a/src/world/Level.php +++ b/src/world/Level.php @@ -1,28 +1,10 @@ server = ServerAPI::request(); $this->level = $level; @@ -34,28 +16,168 @@ class Level{ $this->nextSave = $this->startCheck = microtime(true); $this->nextSave += 90; $this->stopTime = false; - $this->server->schedule(15, array($this, "checkThings"), array(), true); - $this->server->schedule(20 * 13, array($this, "checkTime"), array(), true); + $this->server->schedule(15, [$this, "checkThings"], [], true); + $this->server->schedule(20 * 13, [$this, "checkTime"], [], true); $this->name = $name; - $this->usedChunks = array(); - $this->changedBlocks = array(); - $this->changedCount = array(); + $this->usedChunks = []; + $this->changedBlocks = []; + $this->changedCount = []; } - + public function close(){ $this->__destruct(); } - - public function useChunk($X, $Z, Player $player){ - if(!isset($this->usedChunks[$X.".".$Z])){ - $this->usedChunks[$X.".".$Z] = array(); + + public function __destruct(){ + if(isset($this->level)){ + $this->save(false, false); + $this->level->close(); + unset($this->level); } - $this->usedChunks[$X.".".$Z][$player->CID] = true; + } + + public function save($force = false, $extra = true){ + if(!isset($this->level)){ + return false; + } + if($this->server->saveEnabled === false and $force === false){ + return; + } + + if($extra !== false){ + $entities = []; + foreach($this->server->api->entity->getAll($this) as $entity){ + if($entity->class === ENTITY_MOB){ + $entities[] = [ + "id" => $entity->type, + "Color" => @$entity->data["Color"], + "Sheared" => @$entity->data["Sheared"], + "IsBaby" => @$entity->data["IsBaby"], + "Health" => $entity->health, + "Pos" => [ + 0 => $entity->x, + 1 => $entity->y, + 2 => $entity->z, + ], + "Rotation" => [ + 0 => $entity->yaw, + 1 => $entity->pitch, + ], + ]; + }elseif($entity->class === ENTITY_OBJECT){ + if($entity->type === OBJECT_PAINTING){ + $entities[] = [ + "id" => $entity->type, + "TileX" => $entity->x, + "TileY" => $entity->y, + "TileZ" => $entity->z, + "Health" => $entity->health, + "Motive" => $entity->data["Motive"], + "Pos" => [ + 0 => $entity->x, + 1 => $entity->y, + 2 => $entity->z, + ], + "Rotation" => [ + 0 => $entity->yaw, + 1 => $entity->pitch, + ], + ]; + }else{ + $entities[] = [ + "id" => $entity->type, + "Health" => $entity->health, + "Pos" => [ + 0 => $entity->x, + 1 => $entity->y, + 2 => $entity->z, + ], + "Rotation" => [ + 0 => $entity->yaw, + 1 => $entity->pitch, + ], + ]; + } + }elseif($entity->class === ENTITY_FALLING){ + $entities[] = [ + "id" => $entity->type, + "Health" => $entity->health, + "Tile" => $entity->data["Tile"], + "Pos" => [ + 0 => $entity->x, + 1 => $entity->y, + 2 => $entity->z, + ], + "Rotation" => [ + 0 => 0, + 1 => 0, + ], + ]; + }elseif($entity->class === ENTITY_ITEM){ + $entities[] = [ + "id" => 64, + "Item" => [ + "id" => $entity->type, + "Damage" => $entity->meta, + "Count" => $entity->stack, + ], + "Health" => $entity->health, + "Pos" => [ + 0 => $entity->x, + 1 => $entity->y, + 2 => $entity->z, + ], + "Rotation" => [ + 0 => 0, + 1 => 0, + ], + ]; + } + } + $this->entities->setAll($entities); + $this->entities->save(); + $tiles = []; + foreach($this->server->api->tile->getAll($this) as $tile){ + $tiles[] = $tile->data; + } + $this->tiles->setAll($tiles); + $this->tiles->save(); + + $blockUpdates = []; + $updates = $this->server->query("SELECT x,y,z,type,delay FROM blockUpdates WHERE level = '" . $this->getName() . "';"); + if($updates !== false and $updates !== true){ + $timeu = microtime(true); + while(($bupdate = $updates->fetchArray(SQLITE3_ASSOC)) !== false){ + $bupdate["delay"] = max(1, ($bupdate["delay"] - $timeu) * 20); + $blockUpdates[] = $bupdate; + } + } + + $this->blockUpdates->setAll($blockUpdates); + $this->blockUpdates->save(); + + } + + $this->level->setData("time", (int) $this->time); + $this->level->doSaveRound(); + $this->level->saveData(); + $this->nextSave = microtime(true) + 45; + } + + public function getName(){ + return $this->name;//return $this->level->getData("name"); + } + + public function useChunk($X, $Z, Player $player){ + if(!isset($this->usedChunks[$X . "." . $Z])){ + $this->usedChunks[$X . "." . $Z] = []; + } + $this->usedChunks[$X . "." . $Z][$player->CID] = true; if(isset($this->level)){ $this->level->loadChunk($X, $Z); } } - + public function freeAllChunks(Player $player){ foreach($this->usedChunks as $i => $c){ unset($this->usedChunks[$i][$player->CID]); @@ -63,39 +185,19 @@ class Level{ } public function freeChunk($X, $Z, Player $player){ - unset($this->usedChunks[$X.".".$Z][$player->CID]); + unset($this->usedChunks[$X . "." . $Z][$player->CID]); } - - public function checkTime(){ - if(!isset($this->level)){ - return false; - } - $now = microtime(true); - if($this->stopTime == true){ - }else{ - $time = $this->startTime + ($now - $this->startCheck) * 20; - } - if($this->server->api->dhandle("time.change", array("level" => $this, "time" => $time)) !== false){ - $this->time = $time; - - $pk = new SetTimePacket; - $pk->time = (int) $this->time; - $pk->started = $this->stopTime == false; - $this->server->api->player->broadcastPacket($this->players, $pk); - } - } - public function checkThings(){ if(!isset($this->level)){ return false; } $now = microtime(true); $this->players = $this->server->api->player->getAll($this); - + if(count($this->changedCount) > 0){ arsort($this->changedCount); - $resendChunks = array(); + $resendChunks = []; foreach($this->changedCount as $index => $count){ if($count < 582){//Optimal value, calculated using the relation between minichunks and single packets break; @@ -105,7 +207,7 @@ class Level{ } unset($this->changedBlocks[$index]); } - $this->changedCount = array(); + $this->changedCount = []; if(count($this->changedBlocks) > 0){ foreach($this->changedBlocks as $blocks){ @@ -119,10 +221,10 @@ class Level{ $this->server->api->player->broadcastPacket($this->players, $pk); } } - $this->changedBlocks = array(); + $this->changedBlocks = []; } } - + if($this->nextSave < $now){ foreach($this->usedChunks as $i => $c){ if(count($c) === 0){ @@ -138,156 +240,18 @@ class Level{ $this->save(false, false); } } - - public function __destruct(){ - if(isset($this->level)){ - $this->save(false, false); - $this->level->close(); - unset($this->level); - } - } - - public function save($force = false, $extra = true){ - if(!isset($this->level)){ - return false; - } - if($this->server->saveEnabled === false and $force === false){ - return; - } - - if($extra !== false){ - $entities = array(); - foreach($this->server->api->entity->getAll($this) as $entity){ - if($entity->class === ENTITY_MOB){ - $entities[] = array( - "id" => $entity->type, - "Color" => @$entity->data["Color"], - "Sheared" => @$entity->data["Sheared"], - "IsBaby" => @$entity->data["IsBaby"], - "Health" => $entity->health, - "Pos" => array( - 0 => $entity->x, - 1 => $entity->y, - 2 => $entity->z, - ), - "Rotation" => array( - 0 => $entity->yaw, - 1 => $entity->pitch, - ), - ); - }elseif($entity->class === ENTITY_OBJECT){ - if($entity->type === OBJECT_PAINTING){ - $entities[] = array( - "id" => $entity->type, - "TileX" => $entity->x, - "TileY" => $entity->y, - "TileZ" => $entity->z, - "Health" => $entity->health, - "Motive" => $entity->data["Motive"], - "Pos" => array( - 0 => $entity->x, - 1 => $entity->y, - 2 => $entity->z, - ), - "Rotation" => array( - 0 => $entity->yaw, - 1 => $entity->pitch, - ), - ); - }else{ - $entities[] = array( - "id" => $entity->type, - "Health" => $entity->health, - "Pos" => array( - 0 => $entity->x, - 1 => $entity->y, - 2 => $entity->z, - ), - "Rotation" => array( - 0 => $entity->yaw, - 1 => $entity->pitch, - ), - ); - } - }elseif($entity->class === ENTITY_FALLING){ - $entities[] = array( - "id" => $entity->type, - "Health" => $entity->health, - "Tile" => $entity->data["Tile"], - "Pos" => array( - 0 => $entity->x, - 1 => $entity->y, - 2 => $entity->z, - ), - "Rotation" => array( - 0 => 0, - 1 => 0, - ), - ); - }elseif($entity->class === ENTITY_ITEM){ - $entities[] = array( - "id" => 64, - "Item" => array( - "id" => $entity->type, - "Damage" => $entity->meta, - "Count" => $entity->stack, - ), - "Health" => $entity->health, - "Pos" => array( - 0 => $entity->x, - 1 => $entity->y, - 2 => $entity->z, - ), - "Rotation" => array( - 0 => 0, - 1 => 0, - ), - ); - } - } - $this->entities->setAll($entities); - $this->entities->save(); - $tiles = array(); - foreach($this->server->api->tile->getAll($this) as $tile){ - $tiles[] = $tile->data; - } - $this->tiles->setAll($tiles); - $this->tiles->save(); - - $blockUpdates = array(); - $updates = $this->server->query("SELECT x,y,z,type,delay FROM blockUpdates WHERE level = '".$this->getName()."';"); - if($updates !== false and $updates !== true){ - $timeu = microtime(true); - while(($bupdate = $updates->fetchArray(SQLITE3_ASSOC)) !== false){ - $bupdate["delay"] = max(1, ($bupdate["delay"] - $timeu) * 20); - $blockUpdates[] = $bupdate; - } - } - $this->blockUpdates->setAll($blockUpdates); - $this->blockUpdates->save(); - - } - - $this->level->setData("time", (int) $this->time); - $this->level->doSaveRound(); - $this->level->saveData(); - $this->nextSave = microtime(true) + 45; + public function isSpawnChunk($X, $Z){ + $spawnX = $this->level->getData("spawnX") >> 4; + $spawnZ = $this->level->getData("spawnZ") >> 4; + return abs($X - $spawnX) <= 1 and abs($Z - $spawnZ) <= 1; } - + public function getBlockRaw(Vector3 $pos){ $b = $this->level->getBlock($pos->x, $pos->y, $pos->z); return BlockAPI::get($b[0], $b[1], new Position($pos->x, $pos->y, $pos->z, $this)); } - - public function getBlock(Vector3 $pos){ - if(!isset($this->level) or ($pos instanceof Position) and $pos->level !== $this){ - return false; - } - $b = $this->level->getBlock($pos->x, $pos->y, $pos->z); - return BlockAPI::get($b[0], $b[1], new Position($pos->x, $pos->y, $pos->z, $this)); - } - + public function setBlockRaw(Vector3 $pos, Block $block, $direct = true, $send = true){ if(($ret = $this->level->setBlock($pos->x, $pos->y, $pos->z, $block->getID(), $block->getMetadata())) === true and $send !== false){ if($direct === true){ @@ -303,12 +267,12 @@ class Level{ $pos = new Position($pos->x, $pos->y, $pos->z, $this); } $block->position($pos); - $i = ($pos->x >> 4).":".($pos->y >> 4).":".($pos->z >> 4); + $i = ($pos->x >> 4) . ":" . ($pos->y >> 4) . ":" . ($pos->z >> 4); if(ADVANCED_CACHE == true){ - Cache::remove("world:{$this->name}:".($pos->x >> 4).":".($pos->z >> 4)); + Cache::remove("world:{$this->name}:" . ($pos->x >> 4) . ":" . ($pos->z >> 4)); } if(!isset($this->changedBlocks[$i])){ - $this->changedBlocks[$i] = array(); + $this->changedBlocks[$i] = []; $this->changedCount[$i] = 0; } $this->changedBlocks[$i][] = clone $block; @@ -317,7 +281,7 @@ class Level{ } return $ret; } - + public function setBlock(Vector3 $pos, Block $block, $update = true, $tiles = false, $direct = false){ if(!isset($this->level) or (($pos instanceof Position) and $pos->level !== $this) or $pos->x < 0 or $pos->y < 0 or $pos->z < 0){ return false; @@ -339,19 +303,19 @@ class Level{ $pk->meta = $block->getMetadata(); $this->server->api->player->broadcastPacket($this->players, $pk); }else{ - $i = ($pos->x >> 4).":".($pos->y >> 4).":".($pos->z >> 4); + $i = ($pos->x >> 4) . ":" . ($pos->y >> 4) . ":" . ($pos->z >> 4); if(!isset($this->changedBlocks[$i])){ - $this->changedBlocks[$i] = array(); + $this->changedBlocks[$i] = []; $this->changedCount[$i] = 0; } if(ADVANCED_CACHE == true){ - Cache::remove("world:{$this->name}:".($pos->x >> 4).":".($pos->z >> 4)); + Cache::remove("world:{$this->name}:" . ($pos->x >> 4) . ":" . ($pos->z >> 4)); } $this->changedBlocks[$i][] = clone $block; ++$this->changedCount[$i]; } - if($update === true){ + if($update === true){ $this->server->api->block->blockUpdateAround($pos, BLOCK_UPDATE_NORMAL, 1); $this->server->api->entity->updateRadius($pos, 3); } @@ -363,32 +327,32 @@ class Level{ } return $ret; } - + public function getMiniChunk($X, $Z, $Y){ if(!isset($this->level)){ return false; } return $this->level->getMiniChunk($X, $Z, $Y); } - + public function setMiniChunk($X, $Z, $Y, $data){ if(!isset($this->level)){ return false; } - $this->changedCount[$X.":".$Y.":".$Z] = 4096; + $this->changedCount[$X . ":" . $Y . ":" . $Z] = 4096; if(ADVANCED_CACHE == true){ Cache::remove("world:{$this->name}:$X:$Z"); } return $this->level->setMiniChunk($X, $Z, $Y, $data); } - + public function loadChunk($X, $Z){ if(!isset($this->level)){ return false; } return $this->level->loadChunk($X, $Z); } - + public function unloadChunk($X, $Z, $force = false){ if(!isset($this->level)){ return false; @@ -401,12 +365,6 @@ class Level{ return $this->level->unloadChunk($X, $Z, $this->server->saveEnabled); } - public function isSpawnChunk($X, $Z){ - $spawnX = $this->level->getData("spawnX") >> 4; - $spawnZ = $this->level->getData("spawnZ") >> 4; - return abs($X - $spawnX) <= 1 and abs($Z - $spawnZ) <= 1; - } - public function getOrderedChunk($X, $Z, $Yndex){ if(!isset($this->level)){ return false; @@ -417,15 +375,15 @@ class Level{ return $cache; } } - - - $raw = array(); + + + $raw = []; for($Y = 0; $Y < 8; ++$Y){ if(($Yndex & (1 << $Y)) > 0){ $raw[$Y] = $this->level->getMiniChunk($X, $Z, $Y); } } - + $ordered = ""; $flag = chr($Yndex); for($j = 0; $j < 256; ++$j){ @@ -436,7 +394,7 @@ class Level{ } if(ADVANCED_CACHE == true and $Yndex == 0xff){ Cache::add($identifier, $ordered, 60); - } + } return $ordered; } @@ -452,14 +410,7 @@ class Level{ } return $ordered; } - - public function getSpawn(){ - if(!isset($this->level)){ - return false; - } - return new Position($this->level->getData("spawnX"), $this->level->getData("spawnY"), $this->level->getData("spawnZ"), $this); - } - + public function getSafeSpawn($spawn = false){ if($spawn === false){ $spawn = $this->getSpawn(); @@ -491,7 +442,22 @@ class Level{ } return false; } - + + public function getSpawn(){ + if(!isset($this->level)){ + return false; + } + return new Position($this->level->getData("spawnX"), $this->level->getData("spawnY"), $this->level->getData("spawnZ"), $this); + } + + public function getBlock(Vector3 $pos){ + if(!isset($this->level) or ($pos instanceof Position) and $pos->level !== $this){ + return false; + } + $b = $this->level->getBlock($pos->x, $pos->y, $pos->z); + return BlockAPI::get($b[0], $b[1], new Position($pos->x, $pos->y, $pos->z, $this)); + } + public function setSpawn(Vector3 $pos){ if(!isset($this->level)){ return false; @@ -500,47 +466,63 @@ class Level{ $this->level->setData("spawnY", $pos->y); $this->level->setData("spawnZ", $pos->z); } - + public function getTime(){ return (int) ($this->time); } - - public function getName(){ - return $this->name;//return $this->level->getData("name"); - } - + public function setTime($time){ $this->startTime = $this->time = (int) $time; $this->startCheck = microtime(true); $this->checkTime(); } - + + public function checkTime(){ + if(!isset($this->level)){ + return false; + } + $now = microtime(true); + if($this->stopTime == true){ + + }else{ + $time = $this->startTime + ($now - $this->startCheck) * 20; + } + if($this->server->api->dhandle("time.change", ["level" => $this, "time" => $time]) !== false){ + $this->time = $time; + + $pk = new SetTimePacket; + $pk->time = (int) $this->time; + $pk->started = $this->stopTime == false; + $this->server->api->player->broadcastPacket($this->players, $pk); + } + } + public function stopTime(){ $this->stopTime = true; $this->startCheck = 0; $this->checkTime(); } - + public function startTime(){ $this->stopTime = false; $this->startCheck = microtime(true); $this->checkTime(); } - + public function getSeed(){ if(!isset($this->level)){ return false; } return (int) $this->level->getData("seed"); } - + public function setSeed($seed){ if(!isset($this->level)){ return false; } $this->level->setData("seed", (int) $seed); } - + public function scheduleBlockUpdate(Position $pos, $delay, $type = BLOCK_UPDATE_SCHEDULED){ if(!isset($this->level)){ return false; diff --git a/src/world/LevelImport.php b/src/world/LevelImport.php index 39676d2f..ecad737d 100644 --- a/src/world/LevelImport.php +++ b/src/world/LevelImport.php @@ -1,63 +1,46 @@ path = $path; } - + public function import(){ - if(file_exists($this->path."tileEntities.dat")){ //OldPM - $level = unserialize(file_get_contents($this->path."level.dat")); - console("[INFO] Importing OldPM level \"".$level["LevelName"]."\" to PMF format"); - $entities = new Config($this->path."entities.yml", CONFIG_YAML, unserialize(file_get_contents($this->path."entities.dat"))); + if(file_exists($this->path . "tileEntities.dat")){ //OldPM + $level = unserialize(file_get_contents($this->path . "level.dat")); + console("[INFO] Importing OldPM level \"" . $level["LevelName"] . "\" to PMF format"); + $entities = new Config($this->path . "entities.yml", CONFIG_YAML, unserialize(file_get_contents($this->path . "entities.dat"))); $entities->save(); - $tiles = new Config($this->path."tiles.yml", CONFIG_YAML, unserialize(file_get_contents($this->path."tileEntities.dat"))); + $tiles = new Config($this->path . "tiles.yml", CONFIG_YAML, unserialize(file_get_contents($this->path . "tileEntities.dat"))); $tiles->save(); - }elseif(file_exists($this->path."chunks.dat") and file_exists($this->path."level.dat")){ //Pocket + }elseif(file_exists($this->path . "chunks.dat") and file_exists($this->path . "level.dat")){ //Pocket $nbt = new NBT(); - $nbt->load(substr(file_get_contents($this->path."level.dat"), 8)); + $nbt->load(substr(file_get_contents($this->path . "level.dat"), 8)); $level = array_shift($nbt->tree); if($level["LevelName"] == ""){ - $level["LevelName"] = "world".time(); + $level["LevelName"] = "world" . time(); } - console("[INFO] Importing Pocket level \"".$level["LevelName"]."\" to PMF format"); + console("[INFO] Importing Pocket level \"" . $level["LevelName"] . "\" to PMF format"); unset($level["Player"]); - $nbt->load(substr(file_get_contents($this->path."entities.dat"), 12)); + $nbt->load(substr(file_get_contents($this->path . "entities.dat"), 12)); $entities = array_shift($nbt->tree); if(!isset($entities["TileEntities"])){ - $entities["TileEntities"] = array(); + $entities["TileEntities"] = []; } $tiles = $entities["TileEntities"]; $entities = $entities["Entities"]; - $entities = new Config($this->path."entities.yml", CONFIG_YAML, $entities); + $entities = new Config($this->path . "entities.yml", CONFIG_YAML, $entities); $entities->save(); - $tiles = new Config($this->path."tiles.yml", CONFIG_YAML, $tiles); + $tiles = new Config($this->path . "tiles.yml", CONFIG_YAML, $tiles); $tiles->save(); }else{ return false; } - - $pmf = new PMFLevel($this->path."level.pmf", array( + + $pmf = new PMFLevel($this->path . "level.pmf", [ "name" => $level["LevelName"], "seed" => $level["RandomSeed"], "time" => $level["Time"], @@ -67,13 +50,13 @@ class LevelImport{ "extra" => "", "width" => 16, "height" => 8 - )); + ]); $chunks = new PocketChunkParser(); - $chunks->loadFile($this->path."chunks.dat"); + $chunks->loadFile($this->path . "chunks.dat"); $chunks->loadMap(); for($Z = 0; $Z < 16; ++$Z){ for($X = 0; $X < 16; ++$X){ - $chunk = array( + $chunk = [ 0 => "", 1 => "", 2 => "", @@ -81,8 +64,8 @@ class LevelImport{ 4 => "", 5 => "", 6 => "", - 7 => "" - ); + 7 => "" + ]; for($z = 0; $z < 16; ++$z){ for($x = 0; $x < 16; ++$x){ $block = $chunks->getChunkColumn($X, $Z, $x, $z, 0); @@ -99,17 +82,17 @@ class LevelImport{ } $pmf->saveChunk($X, $Z); } - console("[NOTICE] Importing level ".ceil(($Z + 1)/0.16)."%"); + console("[NOTICE] Importing level " . ceil(($Z + 1) / 0.16) . "%"); } $chunks->map = null; $chunks = null; - @unlink($this->path."level.dat"); - @unlink($this->path."level.dat_old"); - @unlink($this->path."player.dat"); - @unlink($this->path."entities.dat"); - @unlink($this->path."chunks.dat"); - @unlink($this->path."chunks.dat.gz"); - @unlink($this->path."tiles.dat"); + @unlink($this->path . "level.dat"); + @unlink($this->path . "level.dat_old"); + @unlink($this->path . "player.dat"); + @unlink($this->path . "entities.dat"); + @unlink($this->path . "chunks.dat"); + @unlink($this->path . "chunks.dat.gz"); + @unlink($this->path . "tiles.dat"); unset($chunks, $level, $entities, $tiles, $nbt); return true; } diff --git a/src/world/PocketChunkParser.php b/src/world/PocketChunkParser.php index 4e5bc4a1..f9530a8a 100644 --- a/src/world/PocketChunkParser.php +++ b/src/world/PocketChunkParser.php @@ -1,56 +1,24 @@ location = array(); - console("[DEBUG] Loading Chunk Location table...", true, true, 2); - for($offset = 0; $offset < 0x1000; $offset += 4){ - $data = Utils::readLInt(substr($this->raw, $offset, 4)); - $sectors = $data & 0xff; - if($sectors === 0){ - continue; - } - $sectorLocation = $data >> 8; - $this->location[$offset >> 2] = $sectorLocation * $this->sectorLength;//$this->getOffset($X, $Z, $sectors); - } + $map = []; } public function loadFile($file){ - if(file_exists($file.".gz")){ - $this->raw = gzinflate(file_get_contents($file.".gz")); + if(file_exists($file . ".gz")){ + $this->raw = gzinflate(file_get_contents($file . ".gz")); $r = @gzinflate($this->raw); if($r !== false and $r != ""){ $this->raw = $r; } - @unlink($file.".gz"); + @unlink($file . ".gz"); file_put_contents($file, $this->raw); }elseif(!file_exists($file)){ return false; @@ -69,51 +37,14 @@ class PocketChunkParser{ return true; } - private function getOffset($X, $Z){ - return $this->location[$X + ($Z << 5)]; - } - public function getChunk($X, $Z){ $X = (int) $X; $Z = (int) $Z; return substr($this->raw, $this->getOffset($X, $Z), $this->chunkLength); } - public function writeChunk($X, $Z){ - $X = (int) $X; - $Z = (int) $Z; - if(!isset($this->map[$X][$Z])){ - return false; - } - $chunk = ""; - foreach($this->map[$X][$Z] as $section => $data){ - for($i = 0; $i < 256; ++$i){ - $chunk .= $data[$i]; - } - } - return Utils::writeLInt(strlen($chunk)).$chunk; - } - - public function parseChunk($X, $Z){ - $X = (int) $X; - $Z = (int) $Z; - $offset = $this->getOffset($X, $Z); - $len = Utils::readLInt(substr($this->raw, $offset, 4)); - $offset += 4; - $chunk = array( - 0 => array(), //Block - 1 => array(), //Data - 2 => array(), //SkyLight - 3 => array(), //BlockLight - ); - foreach($chunk as $section => &$data){ - $l = $section === 0 ? 128:64; - for($i = 0; $i < 256; ++$i){ - $data[$i] = substr($this->raw, $offset, $l); - $offset += $l; - } - } - return $chunk; + private function getOffset($X, $Z){ + return $this->location[$X + ($Z << 5)]; } public function loadMap(){ @@ -123,7 +54,7 @@ class PocketChunkParser{ $this->loadLocationTable(); console("[DEBUG] Loading chunks...", true, true, 2); for($x = 0; $x < 16; ++$x){ - $this->map[$x] = array(); + $this->map[$x] = []; for($z = 0; $z < 16; ++$z){ $this->map[$x][$z] = $this->parseChunk($x, $z); } @@ -132,6 +63,42 @@ class PocketChunkParser{ console("[DEBUG] Chunks loaded!", true, true, 2); } + private function loadLocationTable(){ + $this->location = []; + console("[DEBUG] Loading Chunk Location table...", true, true, 2); + for($offset = 0; $offset < 0x1000; $offset += 4){ + $data = Utils::readLInt(substr($this->raw, $offset, 4)); + $sectors = $data & 0xff; + if($sectors === 0){ + continue; + } + $sectorLocation = $data >> 8; + $this->location[$offset >> 2] = $sectorLocation * $this->sectorLength;//$this->getOffset($X, $Z, $sectors); + } + } + + public function parseChunk($X, $Z){ + $X = (int) $X; + $Z = (int) $Z; + $offset = $this->getOffset($X, $Z); + $len = Utils::readLInt(substr($this->raw, $offset, 4)); + $offset += 4; + $chunk = [ + 0 => [], //Block + 1 => [], //Data + 2 => [], //SkyLight + 3 => [], //BlockLight + ]; + foreach($chunk as $section => &$data){ + $l = $section === 0 ? 128 : 64; + for($i = 0; $i < 256; ++$i){ + $data[$i] = substr($this->raw, $offset, $l); + $offset += $l; + } + } + return $chunk; + } + public function saveMap($final = false){ console("[DEBUG] Saving chunks...", true, true, 2); @@ -146,14 +113,29 @@ class PocketChunkParser{ flock($fp, LOCK_UN); fclose($fp); $original = filesize($this->file); - file_put_contents($this->file .".gz", gzdeflate(gzdeflate(file_get_contents($this->file),9),9)); //Double compression for flat maps - $compressed = filesize($this->file .".gz"); - console("[DEBUG] Saved chunks.dat.gz with ".round(($compressed/$original)*100, 2)."% (".round($compressed/1024, 2)."KB) of the original size", true, true, 2); + file_put_contents($this->file . ".gz", gzdeflate(gzdeflate(file_get_contents($this->file), 9), 9)); //Double compression for flat maps + $compressed = filesize($this->file . ".gz"); + console("[DEBUG] Saved chunks.dat.gz with " . round(($compressed / $original) * 100, 2) . "% (" . round($compressed / 1024, 2) . "KB) of the original size", true, true, 2); if($final === true){ @unlink($this->file); } } + public function writeChunk($X, $Z){ + $X = (int) $X; + $Z = (int) $Z; + if(!isset($this->map[$X][$Z])){ + return false; + } + $chunk = ""; + foreach($this->map[$X][$Z] as $section => $data){ + for($i = 0; $i < 256; ++$i){ + $chunk .= $data[$i]; + } + } + return Utils::writeLInt(strlen($chunk)) . $chunk; + } + public function getFloor($x, $z){ $X = $x >> 4; $Z = $z >> 4; @@ -184,7 +166,7 @@ class PocketChunkParser{ }else{ $meta = $meta >> 4; } - return array($block, $meta); + return [$block, $meta]; } public function getChunkColumn($X, $Z, $x, $z, $type = 0){ diff --git a/src/world/Position.php b/src/world/Position.php index ee28302b..ed6725b9 100644 --- a/src/world/Position.php +++ b/src/world/Position.php @@ -1,51 +1,34 @@ __construct($x->x, $x->y, $x->z, $level); + public function __construct($x = 0, $y = 0, $z = 0, Level $level = null){ + if($x instanceof Vector3){ + parent::__construct($x->x, $x->y, $x->z); }else{ $this->x = $x; $this->y = $y; $this->z = $z; } + $this->level = $level; } - + public function getSide($side, $step = 1){ return new Position(parent::getSide($side, $step), 0, 0, $this->level); } - + public function distance($x = 0, $y = 0, $z = 0){ if(($x instanceof Position) and $x->level !== $this->level){ return PHP_INT_MAX; } + return parent::distance($x, $y, $z); } public function __toString(){ - return "Position(level=".$this->level->getName().",x=".$this->x.",y=".$this->y.",z=".$this->z.")"; + return "Position(level=" . $this->level->getName() . ",x=" . $this->x . ",y=" . $this->y . ",z=" . $this->z . ")"; } - } \ No newline at end of file diff --git a/src/world/Tile.php b/src/world/Tile.php index b7ccd428..64c8fbfe 100644 --- a/src/world/Tile.php +++ b/src/world/Tile.php @@ -1,25 +1,7 @@ server = ServerAPI::request(); $this->level = $level; $this->normal = true; @@ -49,11 +32,11 @@ class Tile extends Position{ $this->x = (int) $x; $this->y = (int) $y; $this->z = (int) $z; - $this->server->query("INSERT OR REPLACE INTO tiles (ID, level, class, x, y, z) VALUES (".$this->id.", '".$this->level->getName()."', '".$this->class."', ".$this->x.", ".$this->y.", ".$this->z.");"); + $this->server->query("INSERT OR REPLACE INTO tiles (ID, level, class, x, y, z) VALUES (" . $this->id . ", '" . $this->level->getName() . "', '" . $this->class . "', " . $this->x . ", " . $this->y . ", " . $this->z . ");"); switch($this->class){ case TILE_CHEST: case TILE_SIGN: - $this->server->query("UPDATE tiles SET spawnable = 1 WHERE ID = ".$this->id.";"); + $this->server->query("UPDATE tiles SET spawnable = 1 WHERE ID = " . $this->id . ";"); break; case TILE_FURNACE: if(!isset($this->data["BurnTime"]) or $this->data["BurnTime"] < 0){ @@ -72,165 +55,12 @@ class Tile extends Position{ break; } } - - public function isPaired(){ - if($this->class !== TILE_CHEST){ - return false; - } - if(!isset($this->data["pairx"]) or !isset($this->data["pairz"])){ - return false; - } - return true; - } - - public function getPair(){ - if($this->isPaired()){ - return $this->server->api->tile->get(new Position((int) $this->data["pairx"], $this->y, (int) $this->data["pairz"], $this->level)); - } - return false; - } - - public function pairWith(Tile $tile){ - if($this->isPaired()or $tile->isPaired()){ - return false; - } - - $this->data["pairx"] = $tile->x; - $this->data["pairz"] = $tile->z; - - $tile->data["pairx"] = $this->x; - $tile->data["pairz"] = $this->z; - - $this->server->api->tile->spawnToAll($this); - $this->server->api->tile->spawnToAll($tile); - $this->server->handle("tile.update", $this); - $this->server->handle("tile.update", $tile); - } - - public function unpair(){ - if(!$this->isPaired()){ - return false; - } - - $tile = $this->getPair(); - unset($this->data["pairx"], $this->data["pairz"], $tile->data["pairx"], $tile->data["pairz"]); - - $this->server->api->tile->spawnToAll($this); - $this->server->handle("tile.update", $this); - if($tile instanceof Tile){ - $this->server->api->tile->spawnToAll($tile); - $this->server->handle("tile.update", $tile); - } - } - - public function openInventory(Player $player){ - if($this->class === TILE_CHEST){ - $player->windowCnt++; - $player->windowCnt = $id = max(2, $player->windowCnt % 99); - if(($pair = $this->getPair()) !== false){ - if(($pair->x + ($pair->z << 13)) > ($this->x + ($this->z << 13))){ //Order them correctly - $player->windows[$id] = array( - $pair, - $this - ); - }else{ - $player->windows[$id] = array( - $this, - $pair - ); - } - }else{ - $player->windows[$id] = $this; - } - - $pk = new ContainerOpenPacket; - $pk->windowid = $id; - $pk->type = WINDOW_CHEST; - $pk->slots = is_array($player->windows[$id]) ? CHEST_SLOTS << 1:CHEST_SLOTS; - $pk->x = $this->x; - $pk->y = $this->y; - $pk->z = $this->z; - $player->dataPacket($pk); - $slots = array(); - - if(is_array($player->windows[$id])){ - $all = $this->server->api->player->getAll($this->level); - foreach($player->windows[$id] as $ob){ - $pk = new TileEventPacket; - $pk->x = $ob->x; - $pk->y = $ob->y; - $pk->z = $ob->z; - $pk->case1 = 1; - $pk->case2 = 2; - $this->server->api->player->broadcastPacket($all, $pk); - for($s = 0; $s < CHEST_SLOTS; ++$s){ - $slot = $ob->getSlot($s); - if($slot->getID() > AIR and $slot->count > 0){ - $slots[] = $slot; - }else{ - $slots[] = BlockAPI::getItem(AIR, 0, 0); - } - } - } - }else{ - $pk = new TileEventPacket; - $pk->x = $this->x; - $pk->y = $this->y; - $pk->z = $this->z; - $pk->case1 = 1; - $pk->case2 = 2; - $this->server->api->player->broadcastPacket($this->server->api->player->getAll($this->level), $pk); - for($s = 0; $s < CHEST_SLOTS; ++$s){ - $slot = $this->getSlot($s); - if($slot->getID() > AIR and $slot->count > 0){ - $slots[] = $slot; - }else{ - $slots[] = BlockAPI::getItem(AIR, 0, 0); - } - } - } - - $pk = new ContainerSetContentPacket; - $pk->windowid = $id; - $pk->slots = $slots; - $player->dataPacket($pk); - return true; - }elseif($this->class === TILE_FURNACE){ - $player->windowCnt++; - $player->windowCnt = $id = max(2, $player->windowCnt % 99); - $player->windows[$id] = $this; - - $pk = new ContainerOpenPacket; - $pk->windowid = $id; - $pk->type = WINDOW_FURNACE; - $pk->slots = FURNACE_SLOTS; - $pk->x = $this->x; - $pk->y = $this->y; - $pk->z = $this->z; - $player->dataPacket($pk); - - $slots = array(); - for($s = 0; $s < FURNACE_SLOTS; ++$s){ - $slot = $this->getSlot($s); - if($slot->getID() > AIR and $slot->count > 0){ - $slots[] = $slot; - }else{ - $slots[] = BlockAPI::getItem(AIR, 0, 0); - } - } - $pk = new ContainerSetContentPacket; - $pk->windowid = $id; - $pk->slots = $slots; - $player->dataPacket($pk); - return true; - } - } public function update(){ if($this->closed === true){ return false; - } - + } + if($this->class === TILE_FURNACE){ $fuel = $this->getSlot(1); $raw = $this->getSlot(0); @@ -274,8 +104,8 @@ class Tile extends Position{ }else{ $this->data["CookTime"] = 0; } - - $this->server->schedule(2, array($this, "update")); + + $this->server->schedule(2, [$this, "update"]); $this->scheduledUpdate = true; }else{ $current = $this->level->getBlock($this); @@ -291,7 +121,16 @@ class Tile extends Position{ $this->server->handle("tile.update", $this); $this->lastUpdate = microtime(true); } - + + public function getSlot($s){ + $i = $this->getSlotIndex($s); + if($i === false or $i < 0){ + return BlockAPI::getItem(AIR, 0, 0); + }else{ + return BlockAPI::getItem($this->data["Items"][$i]["id"], $this->data["Items"][$i]["Damage"], $this->data["Items"][$i]["Count"]); + } + } + public function getSlotIndex($s){ if($this->class !== TILE_CHEST and $this->class !== TILE_FURNACE){ return false; @@ -303,24 +142,15 @@ class Tile extends Position{ } return -1; } - - public function getSlot($s){ - $i = $this->getSlotIndex($s); - if($i === false or $i < 0){ - return BlockAPI::getItem(AIR, 0, 0); - }else{ - return BlockAPI::getItem($this->data["Items"][$i]["id"], $this->data["Items"][$i]["Damage"], $this->data["Items"][$i]["Count"]); - } - } - + public function setSlot($s, Item $item, $update = true, $offset = 0){ $i = $this->getSlotIndex($s); - $d = array( + $d = [ "Count" => $item->count, "Slot" => $s, "id" => $item->getID(), "Damage" => $item->getMetadata(), - ); + ]; if($i === false){ return false; }elseif($item->getID() === AIR or $item->count <= 0){ @@ -332,12 +162,12 @@ class Tile extends Position{ }else{ $this->data["Items"][$i] = $d; } - $this->server->api->dhandle("tile.container.slot", array( + $this->server->api->dhandle("tile.container.slot", [ "tile" => $this, "slot" => $s, "offset" => $offset, "slotdata" => $item, - )); + ]); if($update === true and $this->scheduledUpdate === false){ $this->update(); @@ -345,6 +175,159 @@ class Tile extends Position{ return true; } + public function pairWith(Tile $tile){ + if($this->isPaired() or $tile->isPaired()){ + return false; + } + + $this->data["pairx"] = $tile->x; + $this->data["pairz"] = $tile->z; + + $tile->data["pairx"] = $this->x; + $tile->data["pairz"] = $this->z; + + $this->server->api->tile->spawnToAll($this); + $this->server->api->tile->spawnToAll($tile); + $this->server->handle("tile.update", $this); + $this->server->handle("tile.update", $tile); + } + + public function isPaired(){ + if($this->class !== TILE_CHEST){ + return false; + } + if(!isset($this->data["pairx"]) or !isset($this->data["pairz"])){ + return false; + } + return true; + } + + public function unpair(){ + if(!$this->isPaired()){ + return false; + } + + $tile = $this->getPair(); + unset($this->data["pairx"], $this->data["pairz"], $tile->data["pairx"], $tile->data["pairz"]); + + $this->server->api->tile->spawnToAll($this); + $this->server->handle("tile.update", $this); + if($tile instanceof Tile){ + $this->server->api->tile->spawnToAll($tile); + $this->server->handle("tile.update", $tile); + } + } + + public function getPair(){ + if($this->isPaired()){ + return $this->server->api->tile->get(new Position((int) $this->data["pairx"], $this->y, (int) $this->data["pairz"], $this->level)); + } + return false; + } + + public function openInventory(Player $player){ + if($this->class === TILE_CHEST){ + $player->windowCnt++; + $player->windowCnt = $id = max(2, $player->windowCnt % 99); + if(($pair = $this->getPair()) !== false){ + if(($pair->x + ($pair->z << 13)) > ($this->x + ($this->z << 13))){ //Order them correctly + $player->windows[$id] = [ + $pair, + $this + ]; + }else{ + $player->windows[$id] = [ + $this, + $pair + ]; + } + }else{ + $player->windows[$id] = $this; + } + + $pk = new ContainerOpenPacket; + $pk->windowid = $id; + $pk->type = WINDOW_CHEST; + $pk->slots = is_array($player->windows[$id]) ? CHEST_SLOTS << 1 : CHEST_SLOTS; + $pk->x = $this->x; + $pk->y = $this->y; + $pk->z = $this->z; + $player->dataPacket($pk); + $slots = []; + + if(is_array($player->windows[$id])){ + $all = $this->server->api->player->getAll($this->level); + foreach($player->windows[$id] as $ob){ + $pk = new TileEventPacket; + $pk->x = $ob->x; + $pk->y = $ob->y; + $pk->z = $ob->z; + $pk->case1 = 1; + $pk->case2 = 2; + $this->server->api->player->broadcastPacket($all, $pk); + for($s = 0; $s < CHEST_SLOTS; ++$s){ + $slot = $ob->getSlot($s); + if($slot->getID() > AIR and $slot->count > 0){ + $slots[] = $slot; + }else{ + $slots[] = BlockAPI::getItem(AIR, 0, 0); + } + } + } + }else{ + $pk = new TileEventPacket; + $pk->x = $this->x; + $pk->y = $this->y; + $pk->z = $this->z; + $pk->case1 = 1; + $pk->case2 = 2; + $this->server->api->player->broadcastPacket($this->server->api->player->getAll($this->level), $pk); + for($s = 0; $s < CHEST_SLOTS; ++$s){ + $slot = $this->getSlot($s); + if($slot->getID() > AIR and $slot->count > 0){ + $slots[] = $slot; + }else{ + $slots[] = BlockAPI::getItem(AIR, 0, 0); + } + } + } + + $pk = new ContainerSetContentPacket; + $pk->windowid = $id; + $pk->slots = $slots; + $player->dataPacket($pk); + return true; + }elseif($this->class === TILE_FURNACE){ + $player->windowCnt++; + $player->windowCnt = $id = max(2, $player->windowCnt % 99); + $player->windows[$id] = $this; + + $pk = new ContainerOpenPacket; + $pk->windowid = $id; + $pk->type = WINDOW_FURNACE; + $pk->slots = FURNACE_SLOTS; + $pk->x = $this->x; + $pk->y = $this->y; + $pk->z = $this->z; + $player->dataPacket($pk); + + $slots = []; + for($s = 0; $s < FURNACE_SLOTS; ++$s){ + $slot = $this->getSlot($s); + if($slot->getID() > AIR and $slot->count > 0){ + $slots[] = $slot; + }else{ + $slots[] = BlockAPI::getItem(AIR, 0, 0); + } + } + $pk = new ContainerSetContentPacket; + $pk->windowid = $id; + $pk->slots = $slots; + $player->dataPacket($pk); + return true; + } + } + public function spawn($player){ if($this->closed){ return false; @@ -355,36 +338,36 @@ class Tile extends Position{ switch($this->class){ case TILE_CHEST: $nbt = new NBT(); - $nbt->write(chr(NBT::TAG_COMPOUND)."\x00\x00"); - + $nbt->write(chr(NBT::TAG_COMPOUND) . "\x00\x00"); + $nbt->write(chr(NBT::TAG_STRING)); $nbt->writeTAG_String("id"); $nbt->writeTAG_String($this->class); - + $nbt->write(chr(NBT::TAG_INT)); $nbt->writeTAG_String("x"); $nbt->writeTAG_Int((int) $this->x); - + $nbt->write(chr(NBT::TAG_INT)); $nbt->writeTAG_String("y"); $nbt->writeTAG_Int((int) $this->y); - + $nbt->write(chr(NBT::TAG_INT)); $nbt->writeTAG_String("z"); $nbt->writeTAG_Int((int) $this->z); - + if($this->isPaired()){ $nbt->write(chr(NBT::TAG_INT)); $nbt->writeTAG_String("pairx"); $nbt->writeTAG_Int((int) $this->data["pairx"]); - + $nbt->write(chr(NBT::TAG_INT)); $nbt->writeTAG_String("pairz"); $nbt->writeTAG_Int((int) $this->data["pairz"]); } - - $nbt->write(chr(NBT::TAG_END)); - + + $nbt->write(chr(NBT::TAG_END)); + $pk = new EntityDataPacket; $pk->x = $this->x; $pk->y = $this->y; @@ -394,42 +377,42 @@ class Tile extends Position{ break; case TILE_SIGN: $nbt = new NBT(); - $nbt->write(chr(NBT::TAG_COMPOUND)."\x00\x00"); - + $nbt->write(chr(NBT::TAG_COMPOUND) . "\x00\x00"); + $nbt->write(chr(NBT::TAG_STRING)); $nbt->writeTAG_String("Text1"); $nbt->writeTAG_String($this->data["Text1"]); - + $nbt->write(chr(NBT::TAG_STRING)); $nbt->writeTAG_String("Text2"); $nbt->writeTAG_String($this->data["Text2"]); - + $nbt->write(chr(NBT::TAG_STRING)); $nbt->writeTAG_String("Text3"); $nbt->writeTAG_String($this->data["Text3"]); - + $nbt->write(chr(NBT::TAG_STRING)); $nbt->writeTAG_String("Text4"); $nbt->writeTAG_String($this->data["Text4"]); - + $nbt->write(chr(NBT::TAG_STRING)); $nbt->writeTAG_String("id"); $nbt->writeTAG_String($this->class); - + $nbt->write(chr(NBT::TAG_INT)); $nbt->writeTAG_String("x"); $nbt->writeTAG_Int((int) $this->x); - + $nbt->write(chr(NBT::TAG_INT)); $nbt->writeTAG_String("y"); $nbt->writeTAG_Int((int) $this->y); - + $nbt->write(chr(NBT::TAG_INT)); $nbt->writeTAG_String("z"); $nbt->writeTAG_Int((int) $this->z); - - $nbt->write(chr(NBT::TAG_END)); - + + $nbt->write(chr(NBT::TAG_END)); + $pk = new EntityDataPacket; $pk->x = $this->x; $pk->y = $this->y; @@ -439,7 +422,7 @@ class Tile extends Position{ break; } } - + public function setText($line1 = "", $line2 = "", $line3 = "", $line4 = ""){ if($this->class !== TILE_SIGN){ return false; @@ -448,18 +431,22 @@ class Tile extends Position{ $this->data["Text2"] = $line2; $this->data["Text3"] = $line3; $this->data["Text4"] = $line4; - $this->server->api->tile->spawnToAll($this); + $this->server->api->tile->spawnToAll($this); $this->server->handle("tile.update", $this); return true; } - + public function getText(){ - return array( + return [ $this->data["Text1"], $this->data["Text2"], $this->data["Text3"], $this->data["Text4"] - ); + ]; + } + + public function __destruct(){ + $this->close(); } public function close(){ @@ -469,10 +456,6 @@ class Tile extends Position{ } } - public function __destruct(){ - $this->close(); - } - public function getName(){ return $this->name; } @@ -481,12 +464,11 @@ class Tile extends Position{ public function setPosition(Vector3 $pos){ if($pos instanceof Position){ $this->level = $pos->level; - $this->server->query("UPDATE tiles SET level = '".$this->level->getName()."' WHERE ID = ".$this->id.";"); + $this->server->query("UPDATE tiles SET level = '" . $this->level->getName() . "' WHERE ID = " . $this->id . ";"); } $this->x = (int) $pos->x; $this->y = (int) $pos->y; $this->z = (int) $pos->z; - $this->server->query("UPDATE tiles SET x = ".$this->x.", y = ".$this->y.", z = ".$this->z." WHERE ID = ".$this->id.";"); + $this->server->query("UPDATE tiles SET x = " . $this->x . ", y = " . $this->y . ", z = " . $this->z . " WHERE ID = " . $this->id . ";"); } - } diff --git a/src/world/generator/LevelGenerator.php b/src/world/generator/LevelGenerator.php index 5da98645..a018deea 100644 --- a/src/world/generator/LevelGenerator.php +++ b/src/world/generator/LevelGenerator.php @@ -1,34 +1,16 @@ preset = "2;7,59x1,3x3,2;1;spawn(radius=10 block=89),decoration(treecount=80 grasscount=45)"; $this->options = $options; if(isset($options["preset"])){ @@ -36,50 +18,50 @@ class SuperflatGenerator implements LevelGenerator{ } if(isset($this->options["decoration"])){ $ores = new OrePopulator(); - $ores->setOreTypes(array( + $ores->setOreTypes([ new OreType(new CoalOreBlock(), 20, 16, 0, 128), - new OreType(New IronOreBlock(), 20, 8, 0, 64), + new OreType(new IronOreBlock(), 20, 8, 0, 64), new OreType(new RedstoneOreBlock(), 8, 7, 0, 16), new OreType(new LapisOreBlock(), 1, 6, 0, 32), new OreType(new GoldOreBlock(), 2, 8, 0, 32), new OreType(new DiamondOreBlock(), 1, 7, 0, 16), new OreType(new DirtBlock(), 20, 32, 0, 128), new OreType(new GravelBlock(), 10, 16, 0, 128), - )); - $this->populators[] = $ores; + ]); + $this->populators[] = $ores; } - + /*if(isset($this->options["mineshaft"])){ $this->populators[] = new MineshaftPopulator(isset($this->options["mineshaft"]["chance"]) ? floatval($this->options["mineshaft"]["chance"]) : 0.01); }*/ } - + public function parsePreset($preset){ $this->preset = $preset; $preset = explode(";", $preset); $version = (int) $preset[0]; $blocks = @$preset[1]; - $biome = isset($preset[2]) ? $preset[2]:1; - $options = isset($preset[3]) ? $preset[3]:""; + $biome = isset($preset[2]) ? $preset[2] : 1; + $options = isset($preset[3]) ? $preset[3] : ""; preg_match_all('#(([0-9]{0,})x?([0-9]{1,3}:?[0-9]{0,2})),?#', $blocks, $matches); $y = 0; - $this->structure = array(); - $this->chunks = array(); + $this->structure = []; + $this->chunks = []; foreach($matches[3] as $i => $b){ $b = BlockAPI::fromString($b); - $cnt = $matches[2][$i] === "" ? 1:intval($matches[2][$i]); + $cnt = $matches[2][$i] === "" ? 1 : intval($matches[2][$i]); for($cY = $y, $y += $cnt; $cY < $y; ++$cY){ $this->structure[$cY] = $b; } } - + $this->floorLevel = $y; - - for(;$y < 0xFF; ++$y){ + + for(; $y < 0xFF; ++$y){ $this->structure[$y] = new AirBlock(); } - - + + for($Y = 0; $Y < 8; ++$Y){ $this->chunks[$Y] = ""; $startY = $Y << 4; @@ -92,16 +74,16 @@ class SuperflatGenerator implements LevelGenerator{ $blocks .= chr($this->structure[$y]->getID()); $metas .= substr(dechex($this->structure[$y]->getMetadata()), -1); } - $this->chunks[$Y] .= $blocks.hex2bin($metas)."\x00\x00\x00\x00\x00\x00\x00\x00"; + $this->chunks[$Y] .= $blocks . hex2bin($metas) . "\x00\x00\x00\x00\x00\x00\x00\x00"; } } } - + preg_match_all('#(([0-9a-z_]{1,})\(?([0-9a-z_ =:]{0,})\)?),?#', $options, $matches); foreach($matches[2] as $i => $option){ $params = true; if($matches[3][$i] !== ""){ - $params = array(); + $params = []; $p = explode(" ", $matches[3][$i]); foreach($p as $k){ $k = explode("=", $k); @@ -113,29 +95,29 @@ class SuperflatGenerator implements LevelGenerator{ $this->options[$option] = $params; } } - + public function init(Level $level, Random $random){ $this->level = $level; $this->random = $random; } - + public function generateChunk($chunkX, $chunkZ){ for($Y = 0; $Y < 8; ++$Y){ $this->level->setMiniChunk($chunkX, $chunkZ, $Y, $this->chunks[$Y]); } } - - public function populateChunk($chunkX, $chunkZ){ + + public function populateChunk($chunkX, $chunkZ){ foreach($this->populators as $populator){ $this->random->setSeed((int) ($chunkX * 0xdead + $chunkZ * 0xbeef) ^ $this->level->getSeed()); $populator->populate($this->level, $chunkX, $chunkZ, $this->random); } } - + public function populateLevel(){ $this->random->setSeed($this->level->getSeed()); if(isset($this->options["spawn"])){ - $spawn = array(10, new SandstoneBlock()); + $spawn = [10, new SandstoneBlock()]; if(isset($this->options["spawn"]["radius"])){ $spawn[0] = intval($this->options["spawn"]["radius"]); } @@ -156,7 +138,7 @@ class SuperflatGenerator implements LevelGenerator{ } } } - + if(isset($this->options["decoration"])){ $treecount = 80; $grasscount = 120; @@ -171,7 +153,7 @@ class SuperflatGenerator implements LevelGenerator{ $centerZ = $this->random->nextRange(0, 255); $down = $this->level->level->getBlockID($centerX, $this->floorLevel - 1, $centerZ); if($down === DIRT or $down === GRASS or $down === FARMLAND){ - TreeObject::growTree($this->level, new Vector3($centerX, $this->floorLevel, $centerZ), $this->random, $this->random->nextRange(0,3)); + TreeObject::growTree($this->level, new Vector3($centerX, $this->floorLevel, $centerZ), $this->random, $this->random->nextRange(0, 3)); } } for($t = 0; $t < $grasscount; ++$t){ @@ -184,7 +166,7 @@ class SuperflatGenerator implements LevelGenerator{ } } } - + public function getSpawn(){ return new Vector3(128, $this->floorLevel, 128); } diff --git a/src/world/generator/TemporalGenerator.php b/src/world/generator/TemporalGenerator.php index d03fde3d..ae45ac04 100644 --- a/src/world/generator/TemporalGenerator.php +++ b/src/world/generator/TemporalGenerator.php @@ -1,63 +1,47 @@ level = $level; $this->random = $random; $this->index = mt_rand(0, count(TemporalGenerator::$levels) - 1); $this->world = new PocketChunkParser(); - $this->world->loadRaw(gzinflate(gzinflate(base64_decode(TemporalGenerator::$levels[$this->index][4]))), ""); + $this->world->loadRaw(gzinflate(gzinflate(base64_decode(TemporalGenerator::$levels[$this->index][4]))), ""); $this->world->loadMap(); $this->level->setSeed(TemporalGenerator::$levels[$this->index][0]); } - + public function generateChunk($chunkX, $chunkZ){ } - + public function populateChunk($chunkX, $chunkZ){ } - + public function populateLevel(){ for($Z = 0; $Z < 16; ++$Z){ for($X = 0; $X < 16; ++$X){ - $chunk = array( + $chunk = [ 0 => "", 1 => "", 2 => "", @@ -65,8 +49,8 @@ class TemporalGenerator implements LevelGenerator{ 4 => "", 5 => "", 6 => "", - 7 => "" - ); + 7 => "" + ]; for($z = 0; $z < 16; ++$z){ for($x = 0; $x < 16; ++$x){ $block = $this->world->getChunkColumn($X, $Z, $x, $z, 0); @@ -82,13 +66,13 @@ class TemporalGenerator implements LevelGenerator{ $this->level->setMiniChunk($X, $Z, $Y, $data); } } - console("[NOTICE] Importing level ".ceil(($Z + 1)/0.16)."%"); + console("[NOTICE] Importing level " . ceil(($Z + 1) / 0.16) . "%"); } $this->level->save(true, true); $this->world->map = null; $this->world = null; } - + public function getSpawn(){ return new Vector3(TemporalGenerator::$levels[$this->index][1], TemporalGenerator::$levels[$this->index][2], TemporalGenerator::$levels[$this->index][3]); } diff --git a/src/world/generator/WorldGenerator.php b/src/world/generator/WorldGenerator.php index 4b79bf8f..21a81754 100644 --- a/src/world/generator/WorldGenerator.php +++ b/src/world/generator/WorldGenerator.php @@ -1,34 +1,17 @@ seed = $seed !== false ? (int) $seed:Utils::readInt(Utils::getRandomBytes(4, false)); + $this->seed = $seed !== false ? (int) $seed : Utils::readInt(Utils::getRandomBytes(4, false)); $this->random = new Random($this->seed); $this->width = (int) $width; $this->height = (int) $height; - $this->path = DATA_PATH."worlds/".$name."/"; + $this->path = DATA_PATH . "worlds/" . $name . "/"; $this->generator = $generator; - $level = new PMFLevel($this->path."level.pmf", array( + $level = new PMFLevel($this->path . "level.pmf", [ "name" => $name, "seed" => $this->seed, "time" => 0, @@ -38,20 +21,20 @@ class WorldGenerator{ "extra" => "", "width" => $this->width, "height" => $this->height - )); - $entities = new Config($this->path."entities.yml", CONFIG_YAML); - $tiles = new Config($this->path."tiles.yml", CONFIG_YAML); - $blockUpdates = new Config($this->path."bupdates.yml", CONFIG_YAML); + ]); + $entities = new Config($this->path . "entities.yml", CONFIG_YAML); + $tiles = new Config($this->path . "tiles.yml", CONFIG_YAML); + $blockUpdates = new Config($this->path . "bupdates.yml", CONFIG_YAML); $this->level = new Level($level, $entities, $tiles, $blockUpdates, $name); } - + public function generate(){ $this->generator->init($this->level, $this->random); for($Z = 0; $Z < $this->width; ++$Z){ for($X = 0; $X < $this->width; ++$X){ $this->generator->generateChunk($X, $Z); } - console("[NOTICE] Generating level ".ceil((($Z + 1)/$this->width) * 100)."%"); + console("[NOTICE] Generating level " . ceil((($Z + 1) / $this->width) * 100) . "%"); } console("[NOTICE] Populating level"); $this->generator->populateLevel(); @@ -59,13 +42,13 @@ class WorldGenerator{ for($X = 0; $X < $this->width; ++$X){ $this->generator->populateChunk($X, $Z); } - console("[NOTICE] Populating level ".ceil((($Z + 1)/$this->width) * 100)."%"); + console("[NOTICE] Populating level " . ceil((($Z + 1) / $this->width) * 100) . "%"); } - + $this->level->setSpawn($this->generator->getSpawn()); $this->level->save(true, true); } - + public function close(){ $this->level->close(); } diff --git a/src/world/generator/noise/NoiseGenerator.php b/src/world/generator/noise/NoiseGenerator.php index b6d24472..227a6693 100644 --- a/src/world/generator/noise/NoiseGenerator.php +++ b/src/world/generator/noise/NoiseGenerator.php @@ -1,24 +1,5 @@ permutations[$i] = $i; } - + for($i = 0; $i < 256; ++$i){ $j = $random->nextRange(0, 256 - $i) + $i; $k = $this->permutations[$i]; @@ -49,29 +31,9 @@ class NoiseGeneratorPerlin extends NoiseGenerator{ $this->permutations[$j] = $k; $this->permutations[$i + 256] = $this->permutations[$i]; } - + } - - public final function curve($par1, $par2, $par3){ - return $par2 + $par1 * ($par3 - $par2); - } - - public function grad2D($int, $par1, $par2){ - $i = $int & 0x0F; - $d1 = (1 - (($i & 0x08) >> 3)) * $par1; - $d2 = ($i === 12 or $i === 14) ? $par1:($i < 4 ? 0:$par2); - - return (($i & 0x01) === 0 ? $d1:-$d1) + (($i & 0x02) === 0 ? $d2:-$d2); - } - - public function grad3D($int, $par1, $par2, $par3){ - $i = $int & 0x0F; - $d1 = $i < 8 ? $par1 : $par2; - $d2 = ($i === 12 or $i === 14) ? $par1:($i < 4 ? $par2:$par3); - - return (($i & 0x01) === 0 ? $d1:-$d1) + (($i & 0x02) === 0 ? $d2:-$d2); - } - + public function populateNoiseArray(&$floats, $par1, $par2, $par3, $int1, $int2, $int3, $par4, $par5, $par6, $par7){ if($int2 === 1){ $n = 0; @@ -85,7 +47,7 @@ class NoiseGeneratorPerlin extends NoiseGenerator{ $i3 = $i2 & 0xFF; $d4 -= $i2; $d5 = $d4 * $d4 * $d4 * ($d4 * ($d4 * 6 - 15) + 10); - + for($i4 = 0; $i4 < $int3; ++$i4){ $d6 = $par3 + $i4 * $par6 + $this->zCoord; $i5 = (int) $d6; @@ -95,14 +57,14 @@ class NoiseGeneratorPerlin extends NoiseGenerator{ $i6 = $i5 & 0xFF; $d6 -= $i5; $d7 = $d6 * $d6 * $d6 * ($d6 * ($d6 * 6 - 15) + 10); - + $i = $this->permutations[$i3]; $j = $this->permutations[$i] + $i6; $k = $this->permutations[$i3 + 1]; $m = $this->permutations[$k] + $i6; $d1 = $this->curve($d5, $this->grad2D($this->permutations[$j], $d4, $d6), $this->grad3D($this->permutations[$m], $d4 - 1, 0, $d6)); $d2 = $this->curve($d5, $this->grad3D($this->permutations[$j + 1], $d4, 0, $d6 - 1), $this->grad3D($this->permutations[$m + 1], $d4 - 1, 0, $d6 - 1)); - + $d8 = $this->curve($d7, $d1, $d2); $floats[$n++] += $d8 * $d3; } @@ -114,7 +76,7 @@ class NoiseGeneratorPerlin extends NoiseGenerator{ $m = -1; $n = 0; $i = 0; - + for($i4 = 0; $i4 < $int1; ++$i4){ $d6 = $par1 + $i4 * $par4 + $this->xCoord; $i5 = (int) $d6; @@ -124,7 +86,7 @@ class NoiseGeneratorPerlin extends NoiseGenerator{ $i6 = $i5 & 0xFF; $d6 -= $i5; $d7 = $d6 * $d6 * $d6 * ($d6 * ($d6 * 6 - 15) + 10); - + for($i12 = 0; $i12 < $int3; ++$i12){ $d12 = $par3 + $i12 * $par6 + $this->zCoord; $i13 = (int) $d12; @@ -134,7 +96,7 @@ class NoiseGeneratorPerlin extends NoiseGenerator{ $i14 = $i13 & 0xFF; $d12 -= $i13; $d13 = $d12 * $d12 * $d12 * ($d12 * ($d12 * 6 - 15) + 10); - + for($i15 = 0; $i15 < $int2; ++$i15){ $d14 = $par2 + $i15 * $par5 + $this->yCoord; $i16 = (int) $d14; @@ -157,7 +119,7 @@ class NoiseGeneratorPerlin extends NoiseGenerator{ $d11 = $this->curve($d7, $this->grad3D($this->permutations[$i8 + 1], $d6, $d14, $d12 - 1), $this->grad3D($this->permutations[$n + 1], $d6 - 1, $d14, $d12 - 1)); $d5 = $this->curve($d7, $this->grad3D($this->permutations[$i9 + 1], $d6, $d14 - 1, $d12 - 1), $this->grad3D($this->permutations[$i11 + 1], $d6 - 1, $d14 - 1, $d12 - 1)); } - + $d16 = $this->curve($d15, $d10, $d4); $d17 = $this->curve($d15, $d11, $d5); $d18 = $this->curve($d13, $d16, $d17); @@ -166,4 +128,24 @@ class NoiseGeneratorPerlin extends NoiseGenerator{ } } } + + public final function curve($par1, $par2, $par3){ + return $par2 + $par1 * ($par3 - $par2); + } + + public function grad2D($int, $par1, $par2){ + $i = $int & 0x0F; + $d1 = (1 - (($i & 0x08) >> 3)) * $par1; + $d2 = ($i === 12 or $i === 14) ? $par1 : ($i < 4 ? 0 : $par2); + + return (($i & 0x01) === 0 ? $d1 : -$d1) + (($i & 0x02) === 0 ? $d2 : -$d2); + } + + public function grad3D($int, $par1, $par2, $par3){ + $i = $int & 0x0F; + $d1 = $i < 8 ? $par1 : $par2; + $d2 = ($i === 12 or $i === 14) ? $par1 : ($i < 4 ? $par2 : $par3); + + return (($i & 0x01) === 0 ? $d1 : -$d1) + (($i & 0x02) === 0 ? $d2 : -$d2); + } } \ No newline at end of file diff --git a/src/world/generator/object/NetherReactorStructure.php b/src/world/generator/object/NetherReactorStructure.php index 031a905c..484f606c 100644 --- a/src/world/generator/object/NetherReactorStructure.php +++ b/src/world/generator/object/NetherReactorStructure.php @@ -1,5 +1,7 @@ [ @@ -174,23 +176,23 @@ class NetherReactorStructure{ "NNNNNNNNNNNNNNNNN", ], 7 => [ //spaces are required - "NNNNNNNNNNNNNNNNN", - "N N", - "N N", - "N NNNNNNNNNNN N", - "N N N N", - "N N N N", - "N N N N", - "N N N N", - "N N N N", - "N N N N", - "N N N N", - "N N N N", - "N N N N", - "N NNNNNNNNNNN N", - "N NN", - "N NNN", - "NNNNNNNNNNNNNNNN ", + "NNNNNNNNNNNNNNNNN", + "N N", + "N N", + "N NNNNNNNNNNN N", + "N N N N", + "N N N N", + "N N N N", + "N N N N", + "N N N N", + "N N N N", + "N N N N", + "N N N N", + "N N N N", + "N NNNNNNNNNNN N", + "N NN", + "N NNN", + "NNNNNNNNNNNNNNNN ", ], 8 => [ "NNNNNNNNNNNNNNNNN", @@ -589,6 +591,7 @@ class NetherReactorStructure{ " N ", ], ]; + public static function buildReactor($level, $x, $y, $z){ /*use CENTER positions*/ $offsetX = 0; $offsetZ = 0; diff --git a/src/world/generator/object/OreObject.php b/src/world/generator/object/OreObject.php index 7d6c6785..2bb05326 100644 --- a/src/world/generator/object/OreObject.php +++ b/src/world/generator/object/OreObject.php @@ -1,41 +1,23 @@ type = $type; $this->random = $random; } - + public function getType(){ return $this->type; } - + public function canPlaceObject(Level $level, $x, $y, $z){ return ($level->level->getBlockID($x, $y, $z) != AIR); } - + public function placeObject(Level $level, Vector3 $pos){ $clusterSize = (int) $this->type->clusterSize; $angle = $this->random->nextFloat() * M_PI; @@ -51,14 +33,14 @@ class OreObject{ $seedY = $y1 + ($y2 - $y1) * $count / $clusterSize; $seedZ = $z1 + ($z2 - $z1) * $count / $clusterSize; $size = ((sin($count * (M_PI / $clusterSize)) + 1) * $this->random->nextFloat() * $clusterSize / 16 + 1) / 2; - + $startX = (int) ($seedX - $size); $startY = (int) ($seedY - $size); $startZ = (int) ($seedZ - $size); $endX = (int) ($seedX + $size); $endY = (int) ($seedY + $size); $endZ = (int) ($seedZ + $size); - + for($x = $startX; $x <= $endX; ++$x){ $sizeX = ($x + 0.5 - $seedX) / $size; $sizeX *= $sizeX; diff --git a/src/world/generator/object/OreType.php b/src/world/generator/object/OreType.php index 8ff13676..27f98a75 100644 --- a/src/world/generator/object/OreType.php +++ b/src/world/generator/object/OreType.php @@ -1,27 +1,9 @@ material = $material; $this->clusterCount = (int) $clusterCount; diff --git a/src/world/generator/object/PondObject.php b/src/world/generator/object/PondObject.php index 828cf1e5..69f75bcb 100644 --- a/src/world/generator/object/PondObject.php +++ b/src/world/generator/object/PondObject.php @@ -1,37 +1,18 @@ type = $type; $this->random = $random; } - + public function canPlaceObject(Level $level, Vector3 $pos){ } - + public function placeObject(Level $level, Vector3 $pos){ } - } \ No newline at end of file diff --git a/src/world/generator/object/grass/TallGrassObject.php b/src/world/generator/object/grass/TallGrassObject.php index 18053fd6..527a6373 100644 --- a/src/world/generator/object/grass/TallGrassObject.php +++ b/src/world/generator/object/grass/TallGrassObject.php @@ -1,35 +1,16 @@ nextRange($pos->x - $radius, $pos->x + $radius); diff --git a/src/world/generator/object/tree/BigTreeObject.php b/src/world/generator/object/tree/BigTreeObject.php index d7ceb7a5..a4a34e21 100644 --- a/src/world/generator/object/tree/BigTreeObject.php +++ b/src/world/generator/object/tree/BigTreeObject.php @@ -1,39 +1,20 @@ getBlockX(); $groupY = $leafGrou->getBlockY(); $groupZ = $leafGroup->getBlockZ(); - for ($yy = $groupY; $yy < $groupY + $this->leafDistanceLimit; ++$yy) { + for($yy = $groupY; $yy < $groupY + $this->leafDistanceLimit; ++$yy){ $this->generateGroupLayer($level, $groupX, $yy, $groupZ, $this->getLeafGroupLayerSize($yy - $groupY)); } } diff --git a/src/world/generator/object/tree/PineTreeObject.php b/src/world/generator/object/tree/PineTreeObject.php index eb78dd98..91642259 100644 --- a/src/world/generator/object/tree/PineTreeObject.php +++ b/src/world/generator/object/tree/PineTreeObject.php @@ -1,29 +1,11 @@ findRandomLeavesSize($random); $checkRadius = 0; - for($yy = 0; $yy < $this->totalHeight; ++$yy) { - if($yy === $this->leavesSizeY) { + for($yy = 0; $yy < $this->totalHeight; ++$yy){ + if($yy === $this->leavesSizeY){ $checkRadius = $this->leavesAbsoluteMaxRadius; } for($xx = -$checkRadius; $xx < ($checkRadius + 1); ++$xx){ @@ -54,7 +36,7 @@ class PineTreeObject extends TreeObject{ } public function placeObject(Level $level, Vector3 $pos, Random $random){ - if($this->leavesSizeY === -1 or $this->leavesAbsoluteMaxRadius === -1) { + if($this->leavesSizeY === -1 or $this->leavesAbsoluteMaxRadius === -1){ $this->findRandomLeavesSize($random); } $level->setBlockRaw(new Vector3($pos->x, $pos->y - 1, $pos->z), new DirtBlock()); @@ -62,19 +44,19 @@ class PineTreeObject extends TreeObject{ $leavesMaxRadius = 1; $leavesBottomY = $this->totalHeight - $this->leavesSizeY; $firstMaxedRadius = false; - for($leavesY = 0; $leavesY <= $leavesBottomY; ++$leavesY) { + for($leavesY = 0; $leavesY <= $leavesBottomY; ++$leavesY){ $yy = $this->totalHeight - $leavesY; - for($xx = -$leavesRadius; $xx <= $leavesRadius; ++$xx) { - for($zz = -$leavesRadius; $zz <= $leavesRadius; ++$zz) { - if(abs($xx) != $leavesRadius or abs($zz) != $leavesRadius or $leavesRadius <= 0) { + for($xx = -$leavesRadius; $xx <= $leavesRadius; ++$xx){ + for($zz = -$leavesRadius; $zz <= $leavesRadius; ++$zz){ + if(abs($xx) != $leavesRadius or abs($zz) != $leavesRadius or $leavesRadius <= 0){ $level->setBlockRaw(new Vector3($pos->x + $xx, $pos->y + $yy, $pos->z + $zz), new LeavesBlock($this->type)); } } } - if($leavesRadius >= $leavesMaxRadius) { + if($leavesRadius >= $leavesMaxRadius){ $leavesRadius = $firstMaxedRadius ? 1 : 0; $firstMaxedRadius = true; - if(++$leavesMaxRadius > $this->leavesAbsoluteMaxRadius) { + if(++$leavesMaxRadius > $this->leavesAbsoluteMaxRadius){ $leavesMaxRadius = $this->leavesAbsoluteMaxRadius; } }else{ diff --git a/src/world/generator/object/tree/SmallTreeObject.php b/src/world/generator/object/tree/SmallTreeObject.php index 475b85ce..65db4aa3 100644 --- a/src/world/generator/object/tree/SmallTreeObject.php +++ b/src/world/generator/object/tree/SmallTreeObject.php @@ -1,42 +1,24 @@ trunkHeight + 3; ++$yy) { - if($yy == 1 or $yy === $this->trunkHeight) { + for($yy = 0; $yy < $this->trunkHeight + 3; ++$yy){ + if($yy == 1 or $yy === $this->trunkHeight){ ++$radiusToCheck; } for($xx = -$radiusToCheck; $xx < ($radiusToCheck + 1); ++$xx){ @@ -49,27 +31,13 @@ class SmallTreeObject extends TreeObject{ } return true; } - - protected function placeTrunk(Level $level, $x, $y, $z, Random $random, $trunkHeight){ - // The base dirt block - $dirtpos = new Vector3($x, $y - 1, $z); - $level->setBlockRaw($dirtpos, new DirtBlock()); - for($yy = 0; $yy < $this->treeHeight; ++$yy){ - $blockId = $level->getBlock(new Vector3($x, $y + $yy, $z))->getID(); - if(isset($this->overridable[$blockId])){ - $trunkpos = new Vector3($x, $y + $yy, $z); - $level->setBlockRaw($trunkpos, new WoodBlock($this->type)); - } - } - } - public function placeObject(Level $level, Vector3 $pos, Random $random){ $this->treeHeight = mt_rand(0, 3) + 4; //randomized tree height $x = $pos->getX(); $y = $pos->getY(); $z = $pos->getZ(); - + for($yy = $y - 3 + $this->treeHeight; $yy <= $y + $this->treeHeight; ++$yy){ $yOff = $yy - ($y + $this->treeHeight); $mid = (int) (1 - $yOff / 2); @@ -90,5 +58,19 @@ class SmallTreeObject extends TreeObject{ $this->placeTrunk($level, $x, $y, $z, $random, $this->treeHeight - 1); } - + + protected function placeTrunk(Level $level, $x, $y, $z, Random $random, $trunkHeight){ + // The base dirt block + $dirtpos = new Vector3($x, $y - 1, $z); + $level->setBlockRaw($dirtpos, new DirtBlock()); + + for($yy = 0; $yy < $this->treeHeight; ++$yy){ + $blockId = $level->getBlock(new Vector3($x, $y + $yy, $z))->getID(); + if(isset($this->overridable[$blockId])){ + $trunkpos = new Vector3($x, $y + $yy, $z); + $level->setBlockRaw($trunkpos, new WoodBlock($this->type)); + } + } + } + } \ No newline at end of file diff --git a/src/world/generator/object/tree/SpruceTreeObject.php b/src/world/generator/object/tree/SpruceTreeObject.php index e705764d..b496454b 100644 --- a/src/world/generator/object/tree/SpruceTreeObject.php +++ b/src/world/generator/object/tree/SpruceTreeObject.php @@ -1,29 +1,11 @@ findRandomLeavesSize($random); $checkRadius = 0; - for($yy = 0; $yy < $this->totalHeight + 2; ++$yy) { - if($yy === $this->leavesBottomY) { + for($yy = 0; $yy < $this->totalHeight + 2; ++$yy){ + if($yy === $this->leavesBottomY){ $checkRadius = $this->leavesMaxRadius; } for($xx = -$checkRadius; $xx < ($checkRadius + 1); ++$xx){ @@ -54,20 +36,20 @@ class SpruceTreeObject extends TreeObject{ } public function placeObject(Level $level, Vector3 $pos, Random $random){ - if($this->leavesBottomY === -1 or $this->leavesMaxRadius === -1) { + if($this->leavesBottomY === -1 or $this->leavesMaxRadius === -1){ $this->findRandomLeavesSize(); } $level->setBlockRaw(new Vector3($pos->x, $pos->y - 1, $pos->z), new DirtBlock()); $leavesRadius = 0; for($yy = $this->totalHeight; $yy >= $this->leavesBottomY; --$yy){ - for($xx = -$leavesRadius; $xx <= $leavesRadius; ++$xx) { - for($zz = -$leavesRadius; $zz <= $leavesRadius; ++$zz) { - if(abs($xx) != $leavesRadius or abs($zz) != $leavesRadius or $leavesRadius <= 0) { + for($xx = -$leavesRadius; $xx <= $leavesRadius; ++$xx){ + for($zz = -$leavesRadius; $zz <= $leavesRadius; ++$zz){ + if(abs($xx) != $leavesRadius or abs($zz) != $leavesRadius or $leavesRadius <= 0){ $level->setBlockRaw(new Vector3($pos->x + $xx, $pos->y + $yy, $pos->z + $zz), new LeavesBlock($this->type)); } } } - if($leavesRadius > 0 and $yy === ($pos->y + $this->leavesBottomY + 1)) { + if($leavesRadius > 0 and $yy === ($pos->y + $this->leavesBottomY + 1)){ --$leavesRadius; }elseif($leavesRadius < $this->leavesMaxRadius){ ++$leavesRadius; diff --git a/src/world/generator/object/tree/TreeObject.php b/src/world/generator/object/tree/TreeObject.php index fc8bbc30..c8811bd4 100644 --- a/src/world/generator/object/tree/TreeObject.php +++ b/src/world/generator/object/tree/TreeObject.php @@ -1,31 +1,12 @@ true, 6 => true, 18 => true, - ); + ]; public static function growTree(Level $level, Vector3 $pos, Random $random, $type = 0){ switch($type & 0x03){ @@ -49,7 +30,7 @@ class TreeObject{ /*if($random->nextRange(0, 9) === 0){ $tree = new BigTreeObject(); }else{*/ - $tree = new SmallTreeObject(); + $tree = new SmallTreeObject(); //} break; } diff --git a/src/world/generator/populator/MineshaftPopulator.php b/src/world/generator/populator/MineshaftPopulator.php index b4bb29a5..e731a552 100644 --- a/src/world/generator/populator/MineshaftPopulator.php +++ b/src/world/generator/populator/MineshaftPopulator.php @@ -1,35 +1,17 @@ nextRange(0, MineshaftPopulator::$ODD) === 0){ $mineshaft = new Mineshaft($random); } } - + } \ No newline at end of file diff --git a/src/world/generator/populator/OrePopulator.php b/src/world/generator/populator/OrePopulator.php index 390cbcba..4b2893c3 100644 --- a/src/world/generator/populator/OrePopulator.php +++ b/src/world/generator/populator/OrePopulator.php @@ -1,26 +1,9 @@ oreTypes as $type){ $ore = new OreObject($random, $type); @@ -34,7 +17,7 @@ class OrePopulator extends Populator{ } } } - + public function setOreTypes(array $types){ $this->oreTypes = $types; } diff --git a/src/world/generator/populator/PondPopulator.php b/src/world/generator/populator/PondPopulator.php index d57480bf..d928e185 100644 --- a/src/world/generator/populator/PondPopulator.php +++ b/src/world/generator/populator/PondPopulator.php @@ -1,28 +1,11 @@ nextRange(0, $this->waterOdd) === 0){ $v = new Vector3( @@ -36,7 +19,7 @@ class PondPopulator extends Populator{ } } } - + public function setWaterOdd($waterOdd){ $this->waterOdd = $waterOdd; }