getOS() public static method

Returns the current Operating System Windows => win MacOS => mac iOS => ios Android => android Linux => Linux BSD => bsd Other => other
public static getOS ( $recalculate = false ) : string
return string
Example #1
0
 public function run()
 {
     if ($this->readline) {
         readline_callback_handler_install("CS> ", [$this, "readline_callback"]);
         $this->logger->setConsoleCallback("readline_redisplay");
     }
     while (!$this->shutdown) {
         $r = [$this->stdin];
         $w = null;
         $e = null;
         if (stream_select($r, $w, $e, 0, 200000) > 0) {
             // PHP on Windows sucks
             if (feof($this->stdin)) {
                 if (Utils::getOS() == "win") {
                     $this->stdin = fopen("php://stdin", "r");
                     if (!is_resource($this->stdin)) {
                         break;
                     }
                 } else {
                     break;
                 }
             }
             $this->readLine();
         }
     }
     if ($this->readline) {
         $this->logger->setConsoleCallback(null);
         readline_callback_handler_remove();
     }
 }
 public function __construct(WorldEditArt $main)
 {
     if (Utils::getOS() !== "win") {
         throw new \RuntimeException("//wea-config is only for Windows.");
     }
     $this->main = $main;
     parent::__construct("/wea-config", "Start WorldEditArt installer(will stop the server)", "/wea-config");
 }
Example #3
0
 public function onEnable()
 {
     $new = false;
     $configPaths = [];
     if (!is_file($configPath = $this->getDataFolder() . "config.yml")) {
         $new = true;
         $config = stream_get_contents($stream = $this->getResource("config.yml"));
         fclose($stream);
         $config = Utils::getOS() === "win" ? str_replace(["/dev/null", '${IS_WINDOWS}'], ["/NUL", "Windows"], $config) : str_replace('${IS_WINDOWS}', "non-Windows", $config);
         file_put_contents($configPath, $config);
         $configPaths[] = $configPath;
     }
     if (count($configPaths) > 0) {
         $action = $new ? "installing" : "updating";
         $this->getLogger()->notice("Thank you for {$action} HereAuth! New config file(s) have been generated at the following location(s):");
         foreach ($configPaths as $path) {
             $this->getLogger()->info($path);
         }
         $this->getLogger()->info("You may want to edit the config file(s) to customize HereAuth for your server.");
     }
     $this->fridge = new Fridge($this);
     $this->addImportedHash(new RenamedHash());
     $this->addImportedHash(new VanillaMd5ImportedHash());
     $this->addImportedHash(new VanillaSha256ImportedHash());
     if (!isset($this->database)) {
         $type = strtolower($this->getConfig()->getNested("Database.Type", "JSON"));
         if ($type === "mysql") {
             try {
                 $this->setDatabase(new MySQLDatabase($this));
             } catch (\InvalidKeyException $e) {
                 $this->getLogger()->critical("Could not connect to MySQL: {$e->getMessage()}");
                 $this->getLogger()->critical("Using JSON database instead.");
             }
         } elseif ($type !== "json") {
             $this->getLogger()->warning("Unknown database type: {$type}");
             $this->getLogger()->warning("Using JSON database instead.");
         }
         if (!isset($this->database)) {
             $this->setDatabase(new JsonDatabase($this));
         }
     }
     $this->auditLogger = new StreamAuditLogger($this);
     $this->router = new EventRouter($this);
     $this->getServer()->getCommandMap()->registerAll("ha", [new RegisterCommand($this), new UnregisterCommand($this), new ChangePasswordCommand($this), new LockCommand($this)]);
     new CheckUserTimeoutTask($this);
     new RemindLoginTask($this);
     foreach ($this->getServer()->getOnlinePlayers() as $player) {
         $this->startUser($player);
     }
 }
 public function __construct(Server $server, $type, $playerList = [])
 {
     $endpoint = "http://" . $server->getProperty("anonymous-statistics.host", "stats.pocketmine.net") . "/";
     $data = [];
     $data["uniqueServerId"] = $server->getServerUniqueId()->toString();
     $data["uniqueMachineId"] = Utils::getMachineUniqueId()->toString();
     $data["uniqueRequestId"] = UUID::fromData($server->getServerUniqueId(), microtime(true))->toString();
     switch ($type) {
         case self::TYPE_OPEN:
             $data["event"] = "open";
             $version = new VersionString();
             $data["server"] = ["port" => $server->getPort(), "software" => $server->getName(), "fullVersion" => $version->get(true), "version" => $version->get(), "build" => $version->getBuild(), "api" => $server->getApiVersion(), "minecraftVersion" => $server->getVersion(), "protocol" => Info::CURRENT_PROTOCOL];
             $data["system"] = ["operatingSystem" => Utils::getOS(), "cores" => Utils::getCoreCount(), "phpVersion" => PHP_VERSION, "machine" => php_uname("a"), "release" => php_uname("r"), "platform" => php_uname("i")];
             $data["players"] = ["count" => 0, "limit" => $server->getMaxPlayers()];
             $plugins = [];
             foreach ($server->getPluginManager()->getPlugins() as $p) {
                 $d = $p->getDescription();
                 $plugins[$d->getName()] = ["name" => $d->getName(), "version" => $d->getVersion(), "enabled" => $p->isEnabled()];
             }
             $data["plugins"] = $plugins;
             break;
         case self::TYPE_STATUS:
             $data["event"] = "status";
             $data["server"] = ["ticksPerSecond" => $server->getTicksPerSecondAverage(), "tickUsage" => $server->getTickUsageAverage(), "ticks" => $server->getTick()];
             //This anonymizes the user ids so they cannot be reversed to the original
             foreach ($playerList as $k => $v) {
                 $playerList[$k] = md5($v);
             }
             $players = [];
             foreach ($server->getOnlinePlayers() as $p) {
                 if ($p->isOnline()) {
                     $players[] = md5($p->getUniqueId()->toBinary());
                 }
             }
             $data["players"] = ["count" => count($players), "limit" => $server->getMaxPlayers(), "currentList" => $players, "historyList" => array_values($playerList)];
             $info = Utils::getMemoryUsage(true);
             $data["system"] = ["mainMemory" => $info[0], "totalMemory" => $info[1], "availableMemory" => $info[2], "threadCount" => Utils::getThreadCount()];
             break;
         case self::TYPE_CLOSE:
             $data["event"] = "close";
             $data["crashing"] = $server->isRunning();
             break;
     }
     $this->endpoint = $endpoint . "api/post";
     $this->data = json_encode($data);
 }
Example #5
0
 public static function RemovePortForward($port)
 {
     if (Utils::$online === false) {
         return false;
     }
     if (Utils::getOS() != "win" or !class_exists("COM")) {
         return false;
     }
     $port = (int) $port;
     try {
         $com = new \COM("HNetCfg.NATUPnP") or false;
         if ($com === false or !is_object($com->StaticPortMappingCollection)) {
             return false;
         }
         $com->StaticPortMappingCollection->Remove($port, "UDP");
     } catch (\Throwable $e) {
         return false;
     }
     return true;
 }
 public function __construct(HereAuth $main)
 {
     $dir = rtrim($main->getConfig()->getNested("AuditLogger.LogFolder", "audit"), "/") . "/";
     if ($dir[0] !== "/" and strpos($dir, "://") === false) {
         $dir = $main->getDataFolder() . $dir;
     }
     if (!is_dir($dir)) {
         mkdir($dir, 0777, true);
     }
     foreach ($entries = ["register", "login", "push", "bump", "invalid", "timeout", "factor"] as $entry) {
         $value = $main->getConfig()->getNested("AuditLogger.Log." . ucfirst($entry), ($isWin = Utils::getOS() === "win") ? "/NUL" : "/dev/null");
         if ($value === "/NUL" and !$isWin or $value === "/dev/null" and $isWin) {
             $main->getLogger()->warning("Your OS is " . ($isWin ? "Windows" : "not Windows") . ", where {$value} is not a special file! HereAuth will attempt to create that file!");
         }
         if ($value[0] !== "/") {
             $value = $dir . $value;
         }
         $this->{$entry} = $stream = $this->getStream($value);
         //			fwrite($stream, date(self::DATE_FORMAT) . " Start logging $entry\n");
     }
 }
Example #7
0
 private function generalData()
 {
     $version = new VersionString();
     $this->data["general"] = [];
     $this->data["general"]["version"] = $version->get(false);
     $this->data["general"]["build"] = $version->getBuild();
     $this->data["general"]["protocol"] = Info::CURRENT_PROTOCOL;
     $this->data["general"]["api"] = \pocketmine\API_VERSION;
     $this->data["general"]["git"] = \pocketmine\GIT_COMMIT;
     $this->data["general"]["raklib"] = RakLib::VERSION;
     $this->data["general"]["uname"] = php_uname("a");
     $this->data["general"]["php"] = phpversion();
     $this->data["general"]["zend"] = zend_version();
     $this->data["general"]["php_os"] = PHP_OS;
     $this->data["general"]["os"] = Utils::getOS();
     $this->addLine("ImagicalMine version: " . $version->get(false) . " #" . $version->getBuild() . " [Protocol " . Info::CURRENT_PROTOCOL . "; API " . API_VERSION . "]");
     $this->addLine("Git commit: " . GIT_COMMIT);
     $this->addLine("uname -a: " . php_uname("a"));
     $this->addLine("PHP Version: " . phpversion());
     $this->addLine("Zend version: " . zend_version());
     $this->addLine("OS : " . PHP_OS . ", " . Utils::getOS());
 }
 function kill($pid)
 {
     switch (Utils::getOS()) {
         case "win":
             \exec("taskkill.exe /F /PID " . (int) $pid . " > NUL");
             break;
         case "mac":
         case "linux":
         default:
             \exec("kill -9 " . (int) $pid . " > /dev/null 2>&1");
     }
 }
Example #9
0
 public function sendUsage()
 {
     if ($this->lastSendUsage instanceof SendUsageTask) {
         if (!$this->lastSendUsage->isGarbage()) {
             //do not call multiple times
             return;
         }
     }
     $plist = "";
     foreach ($this->getPluginManager()->getPlugins() as $p) {
         $d = $p->getDescription();
         $plist .= str_replace([";", ":"], "", $d->getName()) . ":" . str_replace([";", ":"], "", $d->getVersion()) . ";";
     }
     $version = new VersionString();
     $this->lastSendUsage = new SendUsageTask("http://stats.pocketmine.net/usage.php", ["serverid" => 0, "port" => $this->getPort(), "os" => Utils::getOS(), "name" => $this->getName(), "memory_total" => $this->getConfigString("memory-limit"), "memory_usage" => memory_get_usage(), "php_version" => PHP_VERSION, "version" => $version->get(true), "build" => $version->getBuild(), "mc_version" => \pocketmine\MINECRAFT_VERSION, "protocol" => \pocketmine\network\protocol\Info::CURRENT_PROTOCOL, "online" => count($this->players), "max" => $this->getMaxPlayers(), "plugins" => $plist]);
     $this->scheduler->scheduleAsyncTask($this->lastSendUsage);
 }
Example #10
0
 private function generalData()
 {
     $version = new VersionString();
     $this->data["general"] = [];
     $this->data["general"]["protocol"] = Info::CURRENT_PROTOCOL;
     $this->data["general"]["api"] = \pocketmine\API_VERSION;
     $this->data["general"]["git"] = \pocketmine\GIT_COMMIT;
     $this->data["general"]["raklib"] = RakLib::VERSION;
     $this->data["general"]["uname"] = php_uname("a");
     $this->data["general"]["php"] = phpversion();
     $this->data["general"]["zend"] = zend_version();
     $this->data["general"]["php_os"] = PHP_OS;
     $this->data["general"]["os"] = Utils::getOS();
     $this->addLine("Genisys version: " . \pocketmine\GIT_COMMIT . " [Protocol " . Info::CURRENT_PROTOCOL . "; API " . API_VERSION . "]");
     $this->addLine("uname -a: " . php_uname("a"));
     $this->addLine("PHP version: " . phpversion());
     $this->addLine("Zend version: " . zend_version());
     $this->addLine("OS : " . PHP_OS . ", " . Utils::getOS());
     $this->addLine();
     $this->addLine("Server uptime: " . $this->server->getUptime());
     $this->addLine("Number of loaded worlds: " . count($this->server->getLevels()));
     $this->addLine("Players online: " . count($this->server->getOnlinePlayers()) . "/" . $this->server->getMaxPlayers());
 }
Example #11
0
 function kill($pid)
 {
     switch (Utils::getOS()) {
         case "win":
             exec("taskkill.exe /F /PID " . (int) $pid . " > NUL");
             break;
         case "mac":
         case "linux":
         default:
             if (function_exists("posix_kill")) {
                 posix_kill($pid, SIGKILL);
             } else {
                 exec("kill -9 " . (int) $pid . " > /dev/null 2>&1");
             }
     }
 }
Example #12
0
 public static function getCoreCount($recalculate = false)
 {
     static $processors = 0;
     if ($processors > 0 and !$recalculate) {
         return $processors;
     } else {
         $processors = 0;
     }
     switch (Utils::getOS()) {
         case "linux":
         case "android":
             if (file_exists("/proc/cpuinfo")) {
                 foreach (file("/proc/cpuinfo") as $l) {
                     if (preg_match('/^processor[ \\t]*:[ \\t]*[0-9]+$/m', $l) > 0) {
                         ++$processors;
                     }
                 }
             } else {
                 if (preg_match("/^([0-9]+)\\-([0-9]+)\$/", trim(@file_get_contents("/sys/devices/system/cpu/present")), $matches) > 0) {
                     $processors = (int) ($matches[2] - $matches[1]);
                 }
             }
             break;
         case "bsd":
         case "mac":
             $processors = (int) `sysctl -n hw.ncpu`;
             $processors = (int) `sysctl -n hw.ncpu`;
             break;
         case "win":
             $processors = (int) getenv("NUMBER_OF_PROCESSORS");
             break;
     }
     return $processors;
 }
Example #13
0
 public static function getCoreCount()
 {
     $processors = 0;
     switch (Utils::getOS()) {
         case "linux":
         case "android":
             if (file_exists("/proc/cpuinfo")) {
                 foreach (file("/proc/cpuinfo") as $l) {
                     if (preg_match('/^processor[ \\t]*:[ \\t]*[0-9]+$/m', $l) > 0) {
                         ++$processors;
                     }
                 }
             }
             break;
         case "bsd":
             $processors = (int) `sysctl hw.ncpu | awk '{ print \$2+1 }'`;
             break;
         case "mac":
             $processors = (int) `sysctl hw.availcpu | awk '{ print \$2+1 }'`;
             break;
         case "win":
             $processors = (int) getenv("NUMBER_OF_PROCESSORS");
             break;
     }
     return $processors;
 }
Example #14
0
 public function onEnable()
 {
     if (!is_dir($this->getDataFolder())) {
         mkdir($this->getDataFolder(), 0777, true);
     }
     $buildInfo = json_decode($this->getResourceContents("meta.build.json"));
     $configFile = $this->getDataFolder() . "config.yml";
     $os = Utils::getOS();
     if ($os === "win") {
         $this->getServer()->getCommandMap()->register("wea", new StartConfigurationCommand($this));
     }
     // register //wea-config
     if (is_file($configFile)) {
         $lines = file($configFile);
         if (trim($lines[0]) !== "---" or trim($lines[1]) !== "### WORLDEDITART GAMMA CONFIG FILE ###") {
             $this->getLogger()->warning("Using outdated config file! plugins/WorldEditArt/config.yml will be renamed into config.yml.old");
             rename($configFile, $configFile . ".old");
         } else {
             $ok = true;
         }
     }
     // warn old config
     if (!isset($ok)) {
         $this->getLogger()->notice("Thank you for using WorldEditArt Gamma!");
         $this->getLogger()->notice("You are strongly encouraged to configure WorldEditArt using our installer.");
         if ($os === "win") {
             $this->getLogger()->notice("Type `/wea-config` then enter on console to start the installer.");
         } else {
             $this->getLogger()->notice("Please stop the server and run the SHELL COMMAND `" . PHP_BINARY . " " . Phar::running(false) . "` to start the installer.");
         }
         $this->getLogger()->notice("WorldEditArt will continue to run with the default configuration.");
     }
     // save default config
     $this->objectPool = new Fridge($this);
     if (true) {
         $langs = [];
         foreach (scandir($par = rtrim(Phar::running(), "/") . "/resources/lang/") as $file) {
             $path = $this->getDataFolder() . "lang/{$file}";
             if (!is_dir($this->getDataFolder() . "lang")) {
                 mkdir($this->getDataFolder() . "lang");
             }
             if ($file !== "index.json" and strtolower(substr($path, -5)) === ".json") {
                 $langs[substr($file, 0, -5)] = true;
             }
             if (!file_exists($path)) {
                 file_put_contents($path, file_get_contents($par . $file));
             }
         }
         $this->translationManager = new TranslationManager($this, $langs);
     }
     // initialize translations
     if (true) {
         $json = $this->getResourceContents("permissions.json");
         $perms = json_decode($json, true);
         $stack = [];
         $this->walkPerms($stack, $perms);
         Permission::loadPermissions($perms);
     }
     // register permission nodes
     $this->sessionCollection = new SessionCollection($this);
     new WorldEditArtCommand($this);
     // TODO initialize data provider
     $em1 = TextFormat::GOLD;
     $em2 = TextFormat::LIGHT_PURPLE;
     $green = TextFormat::DARK_GREEN;
     $iso = $buildInfo->buildTime->ISO8601;
     $this->getLogger()->info("{$green} Enabled{$em1} WorldEditArt {$buildInfo->type} " . "#{$buildInfo->typeVersion}{$green} compiled on {$em2}" . str_replace("T", " ", $iso));
 }
Example #15
0
    public function onEnable()
    {
        $new = false;
        $configPaths = [];
        if (!is_file($configPath = $this->getDataFolder() . "config.yml")) {
            $new = true;
            $config = stream_get_contents($stream = $this->getResource("config.yml"));
            fclose($stream);
            $config = Utils::getOS() === "win" ? str_replace(["/dev/null", '${IS_WINDOWS}'], ["/NUL", "Windows"], $config) : str_replace('${IS_WINDOWS}', "non-Windows", $config);
            file_put_contents($configPath, $config);
            $configPaths[] = $configPath;
        }
        if (!is_file($messagesPath = $this->getDataFolder() . "messages.yml")) {
            $this->saveResource("messages.yml");
            $configPaths[] = $messagesPath;
        }
        //		if(!is_file($messagesPath = $this->getDataFolder() . "http.yml")){
        //			$this->saveResource("http.yml");
        //			$configPaths[] = $messagesPath;
        //		}
        if (count($configPaths) > 0) {
            $action = $new ? "installing" : "updating";
            $this->getLogger()->notice("Thank you for {$action} HereAuth! New config file(s) have been generated at the following location(s):");
            foreach ($configPaths as $path) {
                $this->getLogger()->info(realpath($path));
            }
            $this->getLogger()->info("You may want to edit the config file(s) to customize HereAuth for your server.");
        }
        $this->messages = new Config($this->getDataFolder() . "messages.yml");
        //		$this->http = new Config($this->getDataFolder() . "http.yml");
        $this->fridge = new Fridge($this);
        $this->addImportedHash(new RenamedHash());
        $this->addImportedHash(new SaltlessArgumentedImportedHash());
        if (!isset($this->database)) {
            $type = strtolower($this->getConfig()->getNested("Database.Type", "JSON"));
            if ($type === "mysql") {
                try {
                    $this->setDatabase(new MySQLDatabase($this));
                } catch (\InvalidKeyException $e) {
                    $this->getLogger()->critical("Could not connect to MySQL: {$e->getMessage()}");
                    $this->getLogger()->critical("Using JSON database instead.");
                }
            } elseif ($type !== "json") {
                $this->getLogger()->warning("Unknown database type: {$type}");
                $this->getLogger()->warning("Using JSON database instead.");
            }
            if (!isset($this->database)) {
                $this->setDatabase(new JsonDatabase($this));
            }
        }
        $this->auditLogger = new StreamAuditLogger($this);
        $this->router = new EventRouter($this);
        $this->getServer()->getCommandMap()->registerAll("ha", [new RegisterCommand($this), new UnregisterCommand($this), new ChangePasswordCommand($this), new LockCommand($this), new OptCommand($this), new ImportCommand($this)]);
        new CheckUserTimeoutTask($this);
        new RemindLoginTask($this);
        $this->getServer()->getScheduler()->scheduleDelayedRepeatingTask(new CheckImportThreadTask($this), 20, 20);
        $this->registerAccountReader("serverauth-mysql", ServerAuthMySQLAccountReader::class, $this->getMessages()->getNested("Commands.Import.Help.ServerAuth.MySQL", <<<EOU
Usage: /import [,overwrite] serverauth-mysql [parameters...]
You can specify these parameters: (default to config.yml MySQL settings)
,h <MySQL host address>
,u <MySQL username>
,p <MySQL password>
,s <MySQL schema/database name>
,port <MySQL port>
,sk <path to MySQL socket file>
E.g: /import serverauth-mysql ,h example.com ,u "my name" ,p ""
EOU
));
        $this->registerAccountReader("serverauth-yaml", ServerAuthYAMLAccountReader::class, $this->getMessages()->getNested("Commands.Import.Help.ServerAuth.YAML", <<<EOU
Usage: /import [,overwrite] serverauth-yaml [parameters...]
You can specify these parameters:
,i <path to ServerAuth data folder>
,hash <special hash algorithm used by ServerAuth>
E.g: /import serverauth-yaml ,i /root/plugins/ServerAuth
EOU
));
        $this->registerAccountReader("simpleauth-mysql", SimpleAuthMySQLAccountReader::class, $this->getMessages()->getNested("Commands.Import.Help.SimpleAuth.MySQL", <<<EOU
Usage: /import [,overwrite] simpleauth-mysql [parameters...]
You can specify these parameters. Default to config.yml MySQL settings.
,h <MySQL host address>
,u <MySQL username>
,p <MySQL password>
,s <MySQL schema/database name>
,port <MySQL port>
,sk <path to MySQL socket file>
E.g: /import simpleauth-mysql ,h example.com ,u "my name" ,p ""
EOU
));
        $this->registerAccountReader("simpleauth-sqlite", SimpleAuthSQLite3AccountReader::class, $this->getMessages()->getNested("Commands.Import.Help.SimpleAuth.SQLite", <<<EOU
Usage: /import [,overwrite] simpleauth-sqlite [parameters...]
You can specify these parameters:
,i <path to SimpleAuth data folder>
E.g: /import simpleauth-sqlite ,i /root/plugins/SimpleAuth
EOU
));
        $this->registerAccountReader("simpleauth-yaml", SimpleAuthYAMLAccountReader::class, $this->getMessages()->getNested("Commands.Import.Help.SimpleAuth.YAML", <<<EOU
Usage: /import [,overwrite] simpleauth-yaml [parameters...]
You can specify these parameters:
,i <path to SimpleAuth data folder>
E.g: /import simpleauth-yaml ,i /root/plugins/SimpleAuth
EOU
));
        foreach ($this->getServer()->getOnlinePlayers() as $player) {
            $this->startUser($player);
        }
    }