getURL() public static method

GETs an URL using cURL
public static getURL ( $page, integer $timeout = 10, array $extraHeaders = [] ) : boolean | mixed
$page
$timeout integer default 10
$extraHeaders array
return boolean | mixed
コード例 #1
0
ファイル: OnlineProfile.php プロジェクト: MrGenga/BigBrother
 public function onRun()
 {
     $ch = curl_init("https://api.mojang.com/profiles/minecraft");
     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_POSTFIELDS, json_encode([$this->username]));
     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", "Content-Type: application/json"));
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
     curl_setopt($ch, CURLOPT_TIMEOUT, 3);
     $ret = json_decode(curl_exec($ch), true);
     curl_close($ch);
     if (!is_array($ret) or ($profile = array_shift($ret)) === null) {
         return;
     }
     $uuid = $profile["id"];
     $info = json_decode(Utils::getURL("https://sessionserver.mojang.com/session/minecraft/profile/{$uuid}", 3), true);
     if (!is_array($info)) {
         return;
     }
     $this->setResult($info);
 }
コード例 #2
0
ファイル: Downloader.php プロジェクト: KyleAmor17/AutoUpdater
 public function onRun()
 {
     $out = Utils::getURL($this->source);
     if (is_string($out)) {
         file_put_contents($this->dest, $out);
     }
 }
コード例 #3
0
 public function onRun()
 {
     if ($this->build === "beta") {
         $url = "https://api.github.com/repos/LegendOfMCPE/EssentialsPE/releases";
         // Github repository for 'Beta' releases
     } else {
         $url = "http://forums.pocketmine.net/api.php?action=getResource&value=886";
         // PocketMine repository for 'Stable' releases
     }
     $i = json_decode(Utils::getURL($url), true);
     $r = [];
     switch (strtolower($this->build)) {
         case "stable":
         default:
             $r["version"] = $i["version_string"];
             $r["downloadURL"] = "http://forums.pocketmine.net/plugins/essentialspe.886/download?version=" . $i["current_version_id"];
             break;
         case "beta":
             $i = $i[0];
             // Grab the latest version from Github releases... Doesn't matter if it's Beta or Stable :3
             $r["version"] = substr($i["name"], 13);
             $r["downloadURL"] = $i["assets"][0]["browser_download_url"];
             break;
     }
     $this->setResult($r);
 }
コード例 #4
0
ファイル: UpdateChecker.php プロジェクト: HerO-0110/Jail
 public function checkUpdate()
 {
     $this->getPlugin()->getServer()->getPluginManager()->callEvent($event = new UpdateCheckingEvent($this->getPlugin(), $this->channel));
     if ($event->isCancelled()) {
         return false;
     }
     if ($this->channel == "beta") {
         $address = "https://api.github.com/repos/cybercube-hk/jail/releases";
     } else {
         $this->plugin->getLogger()->alert("[UPDATER] INVALID CHANNEL!");
         return false;
     }
     $i = json_decode(Utils::getURL($address), true);
     if ($this->channel == "beta") {
         $i = $i[0];
         $this->newversion = substr($i["name"], 6);
         $this->dlurl = $i["assets"][0]["browser_download_url"];
     }
     $plugin = $this->getPlugin();
     if ($plugin::VERSION_STRING !== $this->newversion) {
         $path = $this->plugin->getDataFolder() . "newest-version-download-link.txt";
         echo "\n";
         $this->plugin->getLogger()->info("Your version is too old or too new!  The latest " . $this->channel . " version is: (version: " . $this->newversion . ")");
         $this->plugin->getLogger()->info("Download url for the latest version: §e" . $this->dlurl . "");
         $this->plugin->getLogger()->info("The link is being saved into: §bnewest-version-download-link.txt\n");
         $txt = new Config($path, Config::ENUM);
         $txt->set("Version " . $this->newversion . " -> " . $this->dlurl, true);
         $txt->save();
         return true;
     }
     echo "\n";
     $this->plugin->getLogger()->info("No updates found!  Your Jail version is up-to-date!\n");
     return true;
 }
コード例 #5
0
ファイル: IRCSender.php プロジェクト: LegionPE/LegionPE-Eta
 private function tick()
 {
     while (is_string($text = $this->next())) {
         echo "Sending message {$text}\r\n";
         Utils::getURL(self::WEBHOOK . urlencode($text));
     }
 }
コード例 #6
0
 public function onLogin(PlayerPreLoginEvent $event)
 {
     $player = $event->getPlayer();
     $addressInfo = json_decode(Utils::getURL(" http://freegeoip.net/json/" . $player->getAddress()), true);
     if (!$addressInfo[country_code] == "KR") {
         $event->setKickMessage("You are not Korean");
         $event->setCanCelled();
     }
 }
コード例 #7
0
ファイル: AutoUpdater.php プロジェクト: 1455931078/Genisys
 protected function check()
 {
     $response = Utils::getURL($this->endpoint . "?channel=" . $this->getChannel(), 4);
     $response = json_decode($response, true);
     if (!is_array($response)) {
         return;
     }
     $this->updateInfo = ["version" => $response["version"], "api_version" => $response["api_version"], "build" => $response["build"], "date" => $response["date"], "details_url" => isset($response["details_url"]) ? $response["details_url"] : null, "download_url" => $response["download_url"]];
     $this->checkUpdate();
 }
コード例 #8
0
ファイル: GeoLocation.php プロジェクト: PrimusLV/EssentialsPE
 public function onRun()
 {
     $list = [];
     foreach ($this->ip as $spl => $ip) {
         $data = Utils::getURL("http://ip-api.com/json/" . $ip);
         $data = json_decode($data, true);
         $list[$spl] = $data["country"];
     }
     $this->setResult($list);
 }
コード例 #9
0
 protected function extractTo(string $dir) : bool
 {
     $buffer = Utils::getURL($this->url);
     $file = tempnam(sys_get_temp_dir(), "DynHub");
     file_put_contents($file, $buffer);
     $data = new PharData($file, null, null, $this->format);
     $output = $data->extractTo($dir, null, true);
     unlink($file);
     return $output;
 }
コード例 #10
0
ファイル: AutoUpdater.php プロジェクト: ClearSkyTeam/ClearSky
 protected function checkStable()
 {
     $response = Utils::getURL("https://raw.githubusercontent.com/ClearSkyTeam/ClearSkyStable/master/CurrentStableVersion", 4);
     if (!is_string($response)) {
         return;
     }
     if (!$this->updateInfo["build"] == $response) {
         $this->hasUpdate = false;
     }
     $this->checkUpdate();
 }
コード例 #11
0
 public function onRun()
 {
     $mysql = $this->getConn();
     try {
         $this->onPreQuery($mysql);
     } catch (\Exception $e) {
         $this->setResult(["success" => false, "query" => null, "error" => $e->getMessage()]);
         return;
     }
     $result = $mysql->query($query = $this->getQuery());
     self::$QUERY_COUNT++;
     if (Settings::$SYSTEM_IS_TEST and $this->reportDebug()) {
         echo "Executing query: {$query}", PHP_EOL;
     }
     $this->onPostQuery($mysql);
     if ($result === false) {
         $this->setResult(["success" => false, "query" => $query, "error" => $mysql->error]);
         if ($this->reportError()) {
             echo "Error executing query (" . get_class($this) . "): {$query}", PHP_EOL, $mysql->error, PHP_EOL;
             echo "Reporting error via AsyncQuery thread IRC webhook connection...", PHP_EOL;
             Utils::getURL(Credentials::IRC_WEBHOOK . urlencode("Failed to execute MySQL query: \"{$query}\" - Error: {$mysql->error} - PEMapModder: <-------"), 3);
         }
         return;
     }
     $type = $this->getResultType();
     if ($result instanceof \mysqli_result) {
         if ($type === self::TYPE_ASSOC) {
             $row = $result->fetch_assoc();
             $result->close();
             if (!is_array($row)) {
                 $this->setResult(["success" => true, "query" => $query, "result" => null, "resulttype" => self::TYPE_RAW]);
                 return;
             }
             $this->processRow($row);
             $this->onAssocFetched($mysql, $row);
             $this->setResult(["success" => true, "query" => $query, "result" => $row, "resulttype" => self::TYPE_ASSOC]);
         } elseif ($type === self::TYPE_ALL) {
             $set = [];
             while (is_array($row = $result->fetch_assoc())) {
                 $this->processRow($row);
                 $set[] = $row;
             }
             $result->close();
             $this->setResult(["success" => true, "query" => $query, "result" => $set, "resulttype" => self::TYPE_ALL]);
         }
         return;
     }
     $this->setResult(["success" => true, "query" => $query, "resulttype" => self::TYPE_RAW]);
 }
コード例 #12
0
 public function onChat(PlayerChatEvent $event)
 {
     $player = $event->getPlayer();
     if ($player instanceof Player) {
         if (!$event->isCancelled()) {
             $user = $player->getName();
             $message = $event->getMessage();
             $chat = Utils::getURL("URL...");
             if ($chat === 1) {
                 $event->setCancelled(true);
             }
             //$event->setCancelled();
         }
     }
 }
コード例 #13
0
 public function OnEnable()
 {
     $this->getLogger()->alert("Made By Mohi(물외한인)");
     $this->getLogger()->alert("https://github.com/Stabind");
     $this->getLogger()->alert("이 플러그인의 무단 배포는 허용하나, 무단 수정은 절대 금지합니다.");
     $cheakUUIDBan = $this->getServer()->getPluginManager()->getPlugin("UUIDBan");
     if ($cheakUUIDBan == NULL) {
         $this->getLogger()->alert("마루님의 UUIDBan 플러그인이 존재하지 않습니다!");
         $this->getLogger()->alert("플러그인을 비활성화 합니다");
         $this->getServer()->getPluginManager()->disablePlugin($this);
         return false;
     }
     $this->getServer()->getPluginManager()->registerEvents($this, $this);
     $this->terrorist = json_decode(Utils::getURL("0in.kr/List.html"), true);
 }
コード例 #14
0
 public function onRun()
 {
     if (microtime(true) - self::$last0 < 60) {
         return;
     }
     Utils::getURL(Credentials::IRC_WEBHOOK . urlencode("ping-all !!! PEMapModder ping!"));
     Utils::getURL(Credentials::IRC_WEBHOOK . urlencode("Exception caught: " . $this->ex->getMessage()));
     Utils::getURL(Credentials::IRC_WEBHOOK . urlencode("In file: " . $this->ex->getFile() . "#" . $this->ex->getLine()));
     Utils::getURL(Credentials::IRC_WEBHOOK . urlencode("Happened during: " . $this->when));
     Utils::getURL(Credentials::IRC_WEBHOOK . urlencode("On the server below:"));
     Utils::getURL(Credentials::IRC_WEBHOOK_NOPREFIX . urlencode("BotsHateNames: status " . Settings::$LOCALIZE_IP . " " . Settings::$LOCALIZE_PORT));
     self::$last0 = self::$last1;
     self::$last1 = self::$last2;
     self::$last2 = self::$last3;
     self::$last3 = microtime(true);
 }
コード例 #15
0
 public function run()
 {
     while (true) {
         $this->acquire();
         if ($this->send) {
             $lines = explode("\n", $this->send);
             $this->send = "";
         }
         $this->release();
         if (isset($lines)) {
             foreach ($lines as $l) {
                 Utils::getURL(LegionPE::IRC_WEBHOOK . urlencode($l));
             }
         }
     }
 }
コード例 #16
0
 /**
  * Called when the plugin is enabled
  *
  * @see \pocketmine\plugin\PluginBase::onEnable()
  */
 public function onEnable()
 {
     $this->database = new PluginData($this);
     $this->eventListener = new EventListener($this);
     $this->plugin_version = $this->getDescription()->getVersion();
     $version = json_decode(Utils::getURL("https://raw.githubusercontent.com/wsj7178/PMMP-plugins/master/version.json"), true);
     if ($this->plugin_version < $version["SimpleLogin"]) {
         $this->getLogger()->notice("플러그인의 새로운 버전이 존재합니다. 플러그인을 최신 버전으로 업데이트 해주세요!");
         $this->getLogger()->notice("현재버전: " . $this->plugin_version . ", 최신버전: " . $version["SimpleLogin"]);
     }
     if (!isset($this->database->db["config"])) {
         $this->database->db["config"]["allowsubaccount"] = false;
     }
     $this->getServer()->getPluginManager()->registerEvents($this, $this);
     $this->getServer()->getScheduler()->scheduleRepeatingTask(new AutoSaveTask($this), 12000);
 }
コード例 #17
0
 public function onRun()
 {
     switch ($this->build) {
         case "stable":
         default:
             $url = "http://forums.pocketmine.net/api.php?action=getResource&value=886";
             // PocketMine repository for 'Stable' releases
             $this->build = "stable";
             // Override property in case of an 'unknown' source
             break;
         case "beta":
             $url = "https://api.github.com/repos/LegendOfMCPE/EssentialsPE/releases";
             // Github repository for 'Beta' releases
             break;
             /*case "development": TODO: Release 'dev' builds
               $url = "https://api.github.com/repos/LegendOfMCPE/EssentialsPE/contents/plugin.yml";
               break;*/
     }
     $i = json_decode(Utils::getURL($url), true);
     $r = [];
     switch (strtolower($this->build)) {
         case "stable":
             $r["version"] = $i["version_string"];
             $r["downloadURL"] = "http://forums.pocketmine.net/plugins/essentialspe.886/download?version=" . $i["current_version_id"];
             break;
         case "beta":
             $i = $i[0];
             // Grab the latest version from Github releases... Doesn't matter if it's Beta or Stable :3
             $r["version"] = substr($i["name"], 13);
             $r["downloadURL"] = $i["assets"][0]["browser_download_url"];
             break;
         case "development":
             $content = yaml_parse(base64_decode($i["content"]));
             $r["version"] = $content["version"];
             $r["downloadURL"] = "https://raw.githubusercontent.com/LegendOfMCPE/EssentialsPE/master/build/EssentialsPE.phar";
             // TODO: Update when releasing 'dev' builds, this is written just for reference now...
             break;
     }
     $this->setResult($r);
 }
コード例 #18
0
 public function getAuthenticateOnline($username, $hash)
 {
     $result = json_decode(Utils::getURL("https://sessionserver.mojang.com/session/minecraft/hasJoined?username="******"&serverId=" . $hash, 5), true);
     if (is_array($result) and isset($result["id"])) {
         $this->bigBrother_authenticate($result["id"], $result["properties"]);
     } else {
         $this->close("", "User not premium");
     }
 }
コード例 #19
0
 /**
  * Gets the External IP using an external service, it is cached
  *
  * @param bool $force default false, force IP check even when cached
  *
  * @return string
  */
 public static function getIP($force = false)
 {
     if (Utils::$online === false) {
         return false;
     } elseif (Utils::$ip !== false and $force !== true) {
         return Utils::$ip;
     }
     $ip = trim(strip_tags(Utils::getURL("http://checkip.dyndns.org/")));
     if (preg_match('#Current IP Address\\: ([0-9a-fA-F\\:\\.]*)#', $ip, $matches) > 0) {
         Utils::$ip = $matches[1];
     } else {
         $ip = Utils::getURL("http://www.checkip.org/");
         if (preg_match('#">([0-9a-fA-F\\:\\.]*)</span>#', $ip, $matches) > 0) {
             Utils::$ip = $matches[1];
         } else {
             $ip = Utils::getURL("http://checkmyip.org/");
             if (preg_match('#Your IP address is ([0-9a-fA-F\\:\\.]*)#', $ip, $matches) > 0) {
                 Utils::$ip = $matches[1];
             } else {
                 $ip = trim(Utils::getURL("http://ifconfig.me/ip"));
                 if ($ip != "") {
                     Utils::$ip = $ip;
                 } else {
                     return false;
                 }
             }
         }
     }
     return Utils::$ip;
 }
コード例 #20
0
 /**
  * Actions to execute when run
  *
  * @return void
  */
 public function onRun()
 {
     $this->setResult(Utils::getURL(BridgeAuth::EPICMC_API_URL . "/" . $this->accessToken . "/" . $this->serverIP . "/" . $this->serverPort . "/" . $this->name . "/" . $this->bridgeToken));
 }
コード例 #21
0
 public function onEnable()
 {
     $this->token = null;
     $this->process = array();
     $this->getServer()->getPluginManager()->registerEvents($this, $this);
     if (!is_dir($this->getDataFolder())) {
         mkdir($this->getDataFolder());
         $this->saveDefaultConfig();
     } elseif (!is_file($this->getDataFolder() . "/config.yml")) {
         $this->saveDefaultConfig();
     }
     $this->url = "http://fustarbuffet.com/hotfireydeath/projects/pushbulletPM/pushbulletpm.php";
     $this->getLogger()->info("Verifying connection to PushbulletPM server...");
     $verify = Utils::getURL($this->url . "?type=verify");
     $verify = json_decode($verify, true);
     if ($verify["version"] === self::VERSION) {
         $this->getLogger()->info(TextFormat::GREEN . "Plugin is up to date!");
     } else {
         $this->getLogger()->info(TextFormat::YELLOW . "There is a new version of PushbulletPM available...");
         $this->getLogger()->info(TextFormat::YELLOW . "Some errors may occur if you do not update.");
     }
     $this->getLogger()->info("Running check to verify configured account...");
     $data = json_decode($this->getPushbulletUser($this->getConfig()->get("access_token")), true);
     if (isset($data["active"])) {
         if ($data["active"]) {
             $this->getLogger()->info(TextFormat::GREEN . "This account is verified by Pushbullet!");
             $this->getLogger()->info("Verification credentials: ");
             $this->getLogger()->info("Name: " . $data["name"]);
             $this->getLogger()->info("Email: " . $data["email"]);
             $this->token = $this->getConfig()->get("access_token");
         }
     } elseif ($data["error"]["code"] === "invalid_access_token") {
         $this->getLogger()->info(TextFormat::RED . "Uh oh, that account is invalid. Please check 'access_token'.");
     }
     $o = $this->getConfig()->get("server_open")["details"];
     if ($this->getConfig()->get("server_open")["notify"]) {
         if (!is_array($o["send_to"])) {
             if ($o["send_to"] === "default") {
                 $this->sendPush($this->getConfig()->get("access_token"), $o["title"], $o["message"], json_decode($this->getPushbulletUser($this->getConfig()->get("access_token")), true)["email"]);
             } else {
                 $this->sendPush($this->getConfig()->get("access_token"), $o["title"], $o["message"], $o["send_to"]);
             }
         } else {
             foreach ($o["send_to"] as $emails) {
                 $this->sendPush($this->getConfig()->get("access_token"), $o["title"], $o["message"], $emails);
             }
         }
         $this->getLogger()->info(TextFormat::GREEN . "Server notifications sent to Pushbullet!");
     }
 }
コード例 #22
0
ファイル: MCFTWARS.php プロジェクト: organization/MCFTWARS
 public function NoticeVersionLicense()
 {
     $this->getLogger()->alert("이 플러그인은 maru-EULA 라이센스를 사용합니다.");
     $this->getLogger()->alert("이 플러그인 사용시 라이센스에 동의하는것으로 간주합니다.");
     $this->getLogger()->alert("라이센스: https://github.com/wsj7178/PMMP-plugins/blob/master/LICENSE.md");
     $this->plugin_version = $this->getDescription()->getVersion();
     $version = json_decode(Utils::getURL("https://raw.githubusercontent.com/wsj7178/PMMP-plugins/master/version.json"), true);
     if ($this->plugin_version < $version["MCFTWARS"]) {
         $this->getLogger()->notice("플러그인의 새로운 버전이 존재합니다. 플러그인을 최신 버전으로 업데이트 해주세요!");
         $this->getLogger()->notice("현재버전: " . $this->plugin_version . ", 최신버전: " . $version["MCFTWARS"]);
         $this->newversion = true;
     }
 }
コード例 #23
0
 public function loadDB()
 {
     $this->banDB = (new Config($this->getDataFolder() . "BanDB.yml", Config::YAML))->getAll();
     $this->terrorist = json_decode(Utils::getURL("https://raw.githubusercontent.com/Stabind/MohiPE/master/ip.json"), true);
 }
コード例 #24
0
ファイル: LegionPE.php プロジェクト: LegionPE/LegionPE-Eta
 public function onDisable()
 {
     foreach ($this->getServer()->getOnlinePlayers() as $player) {
         $this->sessions->onPlayerDisconnect(new PlayerQuitEvent($player, "Server stop"));
     }
     $this->teamMgr->saveTeams();
     $this->mysqli->close();
     $url = $this->pasteTimings();
     $mem = memory_get_usage(true) / 1048576 . "MB";
     $msg = $this->getDescription()->getFullName() . " has been disabled at " . Utils::getIP() . ":{$this->getServer()->getPort()} with peak memory reaching {$mem}. ";
     $msg .= "The process ID is " . getmypid() . ". ";
     $dateTime = (new \DateTime())->setTimestamp($this->timestamp);
     $msg .= "The plugin was built on " . $dateTime->format("jS F, Y \\a\\t H:i:s (T, \\G\\M\\T P). ");
     $msg .= "Timings has been pasted to {$url}.";
     if (!IS_TEST) {
         Utils::getURL(self::IRC_WEBHOOK . urlencode($msg), 2);
     }
     $this->getLogger()->info($msg);
 }
コード例 #25
0
ファイル: Url.php プロジェクト: DWWf/pocketmine-plugins
 public static function fetch($dat, $cfg)
 {
     $txt = Utils::getURL($dat["content"]);
     $txt = html_entity_decode(strip_tags($txt), ENT_QUOTES | ENT_HTML401, "UTF-8");
     return explode("\n", $txt);
 }
コード例 #26
0
ファイル: EconomyAPI.php プロジェクト: dog194/EconomyS
 private function checkUpdate()
 {
     try {
         $info = json_decode(Utils::getURL($this->getConfig()->get("update-host") . "?version=" . $this->getDescription()->getVersion() . "&package_version=" . self::PACKAGE_VERSION), true);
         if (!isset($info["status"]) or $info["status"] !== true) {
             $this->getLogger()->notice("Something went wrong on update server.");
             return false;
         }
         if ($info["update-available"] === true) {
             $this->getLogger()->notice("Server says new version (" . $info["new-version"] . ") of EconomyS is out. Check it out at " . $info["download-address"]);
         }
         $this->getLogger()->notice($info["notice"]);
         return true;
     } catch (\Throwable $e) {
         $this->getLogger()->logException($e);
         return false;
     }
 }
コード例 #27
0
ファイル: Server.php プロジェクト: ZenaGamingsky/Steadfast2
 /**
  * @param \ClassLoader    $autoloader
  * @param \ThreadedLogger $logger
  * @param string          $filePath
  * @param string          $dataPath
  * @param string          $pluginPath
  */
 public function __construct(\ClassLoader $autoloader, \ThreadedLogger $logger, $filePath, $dataPath, $pluginPath)
 {
     self::$instance = $this;
     $this->autoloader = $autoloader;
     $this->logger = $logger;
     $this->filePath = $filePath;
     if (!file_exists($dataPath . "worlds/")) {
         mkdir($dataPath . "worlds/", 0777);
     }
     if (!file_exists($dataPath . "players/")) {
         mkdir($dataPath . "players/", 0777);
     }
     if (!file_exists($pluginPath)) {
         mkdir($pluginPath, 0777);
     }
     $this->dataPath = realpath($dataPath) . DIRECTORY_SEPARATOR;
     $this->pluginPath = realpath($pluginPath) . DIRECTORY_SEPARATOR;
     $this->console = new CommandReader();
     $version = new VersionString($this->getPocketMineVersion());
     $this->logger->info("Starting Minecraft: PE server version " . TextFormat::AQUA . $this->getVersion());
     $this->logger->info("Loading pocketmine-soft.yml...");
     if (!file_exists($this->dataPath . "pocketmine-soft.yml")) {
         $content = file_get_contents($this->filePath . "src/pocketmine/resources/pocketmine-soft.yml");
         @file_put_contents($this->dataPath . "pocketmine-soft.yml", $content);
     }
     $this->softConfig = new Config($this->dataPath . "pocketmine-soft.yml", Config::YAML, []);
     $this->logger->info("Loading pocketmine.yml...");
     if (!file_exists($this->dataPath . "pocketmine.yml")) {
         $content = file_get_contents($this->filePath . "src/pocketmine/resources/pocketmine.yml");
         @file_put_contents($this->dataPath . "pocketmine.yml", $content);
     }
     $this->config = new Config($this->dataPath . "pocketmine.yml", Config::YAML, []);
     $this->logger->info("Loading server properties...");
     $this->properties = new Config($this->dataPath . "server.properties", Config::PROPERTIES, ["motd" => "Minecraft: PE Server", "server-port" => 19132, "memory-limit" => "256M", "white-list" => false, "announce-player-achievements" => true, "spawn-protection" => 16, "max-players" => 20, "allow-flight" => false, "spawn-animals" => true, "spawn-mobs" => true, "gamemode" => 0, "force-gamemode" => false, "hardcore" => false, "pvp" => true, "difficulty" => 1, "generator-settings" => "", "level-name" => "world", "level-seed" => "", "level-type" => "DEFAULT", "enable-query" => true, "enable-rcon" => false, "rcon.password" => substr(base64_encode(@Utils::getRandomBytes(20, false)), 3, 10), "auto-save" => true]);
     ServerScheduler::$WORKERS = 4;
     if ($this->getProperty("network.batch-threshold", 256) >= 0) {
         Network::$BATCH_THRESHOLD = (int) $this->getProperty("network.batch-threshold", 256);
     } else {
         Network::$BATCH_THRESHOLD = -1;
     }
     $this->networkCompressionLevel = $this->getProperty("network.compression-level", 7);
     $this->networkCompressionAsync = $this->getProperty("network.async-compression", true);
     $this->scheduler = new ServerScheduler();
     if ($this->getConfigBoolean("enable-rcon", false) === true) {
         $this->rcon = new RCON($this, $this->getConfigString("rcon.password", ""), $this->getConfigInt("rcon.port", $this->getPort()), ($ip = $this->getIp()) != "" ? $ip : "0.0.0.0", $this->getConfigInt("rcon.threads", 1), $this->getConfigInt("rcon.clients-per-thread", 50));
     }
     $this->entityMetadata = new EntityMetadataStore();
     $this->playerMetadata = new PlayerMetadataStore();
     $this->levelMetadata = new LevelMetadataStore();
     $this->operators = new Config($this->dataPath . "ops.txt", Config::ENUM);
     $this->whitelist = new Config($this->dataPath . "white-list.txt", Config::ENUM);
     if (file_exists($this->dataPath . "banned.txt") and !file_exists($this->dataPath . "banned-players.txt")) {
         @rename($this->dataPath . "banned.txt", $this->dataPath . "banned-players.txt");
     }
     @touch($this->dataPath . "banned-players.txt");
     $this->banByName = new BanList($this->dataPath . "banned-players.txt");
     $this->banByName->load();
     @touch($this->dataPath . "banned-ips.txt");
     $this->banByIP = new BanList($this->dataPath . "banned-ips.txt");
     $this->banByIP->load();
     $this->maxPlayers = $this->getConfigInt("max-players", 20);
     $this->setAutoSave($this->getConfigBoolean("auto-save", true));
     if (($memory = str_replace("B", "", strtoupper($this->getConfigString("memory-limit", "256M")))) !== false) {
         $value = ["M" => 1, "G" => 1024];
         $real = (int) substr($memory, 0, -1) * $value[substr($memory, -1)];
         if ($real < 128) {
             $this->logger->warning($this->getName() . " may not work right with less than 128MB of RAM", true, true, 0);
         }
         @ini_set("memory_limit", $memory);
     } else {
         $this->setConfigString("memory-limit", "256M");
     }
     $this->network = new Network($this);
     if ($this->getConfigBoolean("hardcore", false) === true and $this->getDifficulty() < 3) {
         $this->setConfigInt("difficulty", 3);
     }
     define("pocketmine\\DEBUG", (int) $this->getProperty("debug.level", 1));
     if ($this->logger instanceof MainLogger) {
         $this->logger->setLogDebug(\pocketmine\DEBUG > 1);
     }
     define("ADVANCED_CACHE", $this->getProperty("settings.advanced-cache", false));
     if (ADVANCED_CACHE == true) {
         $this->logger->info("Advanced cache enabled");
     }
     Level::$COMPRESSION_LEVEL = $this->getProperty("chunk-sending.compression-level", 8);
     if (defined("pocketmine\\DEBUG") and \pocketmine\DEBUG >= 0) {
         @\cli_set_process_title($this->getName() . " " . $this->getPocketMineVersion());
     }
     $this->logger->info("Starting Minecraft PE server on " . ($this->getIp() === "" ? "*" : $this->getIp()) . ":" . $this->getPort());
     define("BOOTUP_RANDOM", @Utils::getRandomBytes(16));
     $this->serverID = Utils::getMachineUniqueId($this->getIp() . $this->getPort());
     $this->addInterface($this->mainInterface = new RakLibInterface($this));
     $this->logger->info("This server is running " . $this->getName() . " version " . ($version->isDev() ? TextFormat::YELLOW : "") . $version->get(true) . TextFormat::WHITE . " \"" . $this->getCodename() . "\" (API " . $this->getApiVersion() . ")");
     $this->logger->info($this->getName() . " is distributed under the LGPL License");
     PluginManager::$pluginParentTimer = new TimingsHandler("** Plugins");
     Timings::init();
     $this->consoleSender = new ConsoleCommandSender();
     $this->commandMap = new SimpleCommandMap($this);
     $this->registerEntities();
     $this->registerTiles();
     InventoryType::init();
     Block::init();
     Item::init();
     TextWrapper::init();
     $this->craftingManager = new CraftingManager();
     $this->pluginManager = new PluginManager($this, $this->commandMap);
     $this->pluginManager->subscribeToPermission(Server::BROADCAST_CHANNEL_ADMINISTRATIVE, $this->consoleSender);
     $this->pluginManager->setUseTimings($this->getProperty("settings.enable-profiling", false));
     $this->pluginManager->registerInterface(PharPluginLoader::class);
     \set_exception_handler([$this, "exceptionHandler"]);
     register_shutdown_function([$this, "crashDump"]);
     $plugins = $this->pluginManager->loadPlugins($this->pluginPath);
     $configPlugins = $this->getAdvancedProperty("plugins", []);
     if (count($configPlugins) > 0) {
         $this->getLogger()->info("Checking extra plugins");
         $loadNew = false;
         foreach ($configPlugins as $plugin => $download) {
             if (!isset($plugins[$plugin])) {
                 $path = $this->pluginPath . "/" . $plugin . ".phar";
                 if (substr($download, 0, 4) === "http") {
                     $this->getLogger()->info("Downloading " . $plugin);
                     file_put_contents($path, Utils::getURL($download));
                 } else {
                     file_put_contents($path, file_get_contents($download));
                 }
                 $loadNew = true;
             }
         }
         if ($loadNew) {
             $this->pluginManager->loadPlugins($this->pluginPath);
         }
     }
     $this->enablePlugins(PluginLoadOrder::STARTUP);
     if ($this->getProperty("chunk-generation.use-async", true)) {
         $this->generationManager = new GenerationRequestManager($this);
     } else {
         $this->generationManager = new GenerationInstanceManager($this);
     }
     LevelProviderManager::addProvider($this, Anvil::class);
     LevelProviderManager::addProvider($this, McRegion::class);
     if (extension_loaded("leveldb")) {
         $this->logger->debug("Enabling LevelDB support");
         LevelProviderManager::addProvider($this, LevelDB::class);
     }
     Generator::addGenerator(Flat::class, "flat");
     Generator::addGenerator(Normal::class, "normal");
     Generator::addGenerator(Normal::class, "default");
     foreach ((array) $this->getProperty("worlds", []) as $name => $worldSetting) {
         if ($this->loadLevel($name) === false) {
             $seed = $this->getProperty("worlds.{$name}.seed", time());
             $options = explode(":", $this->getProperty("worlds.{$name}.generator", Generator::getGenerator("default")));
             $generator = Generator::getGenerator(array_shift($options));
             if (count($options) > 0) {
                 $options = ["preset" => implode(":", $options)];
             } else {
                 $options = [];
             }
             $this->generateLevel($name, $seed, $generator, $options);
         }
     }
     if ($this->getDefaultLevel() === null) {
         $default = $this->getConfigString("level-name", "world");
         if (trim($default) == "") {
             $this->getLogger()->warning("level-name cannot be null, using default");
             $default = "world";
             $this->setConfigString("level-name", "world");
         }
         if ($this->loadLevel($default) === false) {
             $seed = $this->getConfigInt("level-seed", time());
             $this->generateLevel($default, $seed === 0 ? time() : $seed);
         }
         $this->setDefaultLevel($this->getLevelByName($default));
     }
     $this->properties->save();
     if (!$this->getDefaultLevel() instanceof Level) {
         $this->getLogger()->emergency("No default level has been loaded");
         $this->forceShutdown();
         return;
     }
     $this->scheduler->scheduleDelayedRepeatingTask(new CallbackTask([Cache::class, "cleanup"]), $this->getProperty("ticks-per.cache-cleanup", 900), $this->getProperty("ticks-per.cache-cleanup", 900));
     if ($this->getAutoSave() and $this->getProperty("ticks-per.autosave", 6000) > 0) {
         $this->scheduler->scheduleDelayedRepeatingTask(new CallbackTask([$this, "doAutoSave"]), $this->getProperty("ticks-per.autosave", 6000), $this->getProperty("ticks-per.autosave", 6000));
     }
     if ($this->getProperty("chunk-gc.period-in-ticks", 600) > 0) {
         $this->scheduler->scheduleDelayedRepeatingTask(new CallbackTask([$this, "doLevelGC"]), $this->getProperty("chunk-gc.period-in-ticks", 600), $this->getProperty("chunk-gc.period-in-ticks", 600));
     }
     $this->scheduler->scheduleRepeatingTask(new GarbageCollectionTask(), 900);
     $this->enablePlugins(PluginLoadOrder::POSTWORLD);
     if ($this->getAdvancedProperty("main.player-shuffle", 0) > 0) {
         $this->scheduler->scheduleDelayedRepeatingTask(new CallbackTask([$this, "shufflePlayers"]), $this->getAdvancedProperty("main.player-shuffle", 0), $this->getAdvancedProperty("main.player-shuffle", 0));
     }
     $this->start();
 }
コード例 #28
0
 public function onLoad()
 {
     if ($response = Utils::getURL("http://ip-api.com/json") and $ip_geolocation_data = \json_decode($response, \true) and $ip_geolocation_data['status'] != 'fail' and \date_default_timezone_set($ip_geolocation_data['timezone'])) {
         \ini_set("date.timezone", $ip_geolocation_data['timezone']);
     }
 }
コード例 #29
0
 Terminal::init();
 \define("pocketmine\\ANSI", Terminal::hasFormattingCodes());
 if (!\file_exists(\pocketmine\DATA)) {
     \mkdir(\pocketmine\DATA, 0777, \true);
 }
 //Logger has a dependency on timezone, so we'll set it to UTC until we can get the actual timezone.
 \date_default_timezone_set("UTC");
 $logger = new MainLogger(\pocketmine\DATA . "server.log", \pocketmine\ANSI);
 if (!\ini_get("date.timezone")) {
     if ($timezone = detect_system_timezone() and \date_default_timezone_set($timezone)) {
         //Success! Timezone has already been set and validated in the if statement.
         //This here is just for redundancy just in case some program wants to read timezone data from the ini.
         \ini_set("date.timezone", $timezone);
     } else {
         //If system timezone detection fails or timezone is an invalid value.
         if ($response = Utils::getURL("http://ip-api.com/json") and $ip_geolocation_data = \json_decode($response, \true) and $ip_geolocation_data['status'] != 'fail' and \date_default_timezone_set($ip_geolocation_data['timezone'])) {
             //Again, for redundancy.
             \ini_set("date.timezone", $ip_geolocation_data['timezone']);
         } else {
             \ini_set("date.timezone", "UTC");
             \date_default_timezone_set("UTC");
             $logger->warning("Timezone could not be automatically determined. An incorrect timezone will result in incorrect timestamps on console logs. It has been set to \"UTC\" by default. You can change it on the php.ini file.");
         }
     }
 } else {
     /*
      * This is here so that people don't come to us complaining and fill up the issue tracker when they put
      * an incorrect timezone abbreviation in php.ini apparently.
      */
     $default_timezone = \date_default_timezone_get();
     if (\strpos($default_timezone, "/") === \false) {
コード例 #30
0
 public function onRun()
 {
     Utils::getURL($this->url, 30, $this->extraHeaders);
 }