2020-06-07 19:04:43 +03:00
|
|
|
<?php declare(strict_types=1);
|
|
|
|
namespace openvk\Web\Util\Shell;
|
|
|
|
|
|
|
|
class Shell
|
|
|
|
{
|
|
|
|
static function shellAvailable(): bool
|
|
|
|
{
|
|
|
|
if(ini_get("safe_mode"))
|
|
|
|
return FALSE;
|
|
|
|
|
|
|
|
$functions = array_map(function($x) {
|
|
|
|
return trim($x);
|
|
|
|
}, explode(" ", ini_get("disable_functions")));
|
2022-03-20 18:37:52 +03:00
|
|
|
if(in_array("system", $functions))
|
|
|
|
return FALSE;
|
|
|
|
|
|
|
|
if(Shell::isPowershell()) {
|
|
|
|
exec("WHERE powershell", $_x, $_c);
|
|
|
|
unset($_x);
|
|
|
|
|
|
|
|
return $_c === 0;
|
|
|
|
}
|
|
|
|
|
|
|
|
return TRUE;
|
|
|
|
}
|
|
|
|
|
|
|
|
static function isPowershell(): bool
|
|
|
|
{
|
|
|
|
return strncasecmp(PHP_OS, 'WIN', 3) === 0;
|
2020-06-07 19:04:43 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
static function commandAvailable(string $name): bool
|
|
|
|
{
|
2021-10-15 12:34:59 +03:00
|
|
|
if(!Shell::shellAvailable())
|
|
|
|
throw new Exceptions\ShellUnavailableException;
|
2022-03-20 18:37:52 +03:00
|
|
|
|
|
|
|
if(Shell::isPowershell()) {
|
|
|
|
exec("WHERE $name", $_x, $_c);
|
|
|
|
unset($_x);
|
|
|
|
|
|
|
|
return $_c === 0;
|
|
|
|
}
|
|
|
|
|
2020-06-07 19:04:43 +03:00
|
|
|
return !is_null(`command -v $name`);
|
|
|
|
}
|
2022-03-20 18:37:52 +03:00
|
|
|
|
2020-06-07 19:04:43 +03:00
|
|
|
static function __callStatic(string $name, array $arguments): object
|
|
|
|
{
|
2021-10-15 12:34:59 +03:00
|
|
|
if(!Shell::commandAvailable($name))
|
|
|
|
throw new Exceptions\UnknownCommandException($name);
|
2020-06-07 19:04:43 +03:00
|
|
|
|
|
|
|
$command = implode(" ", array_merge([$name], $arguments));
|
|
|
|
|
|
|
|
return new class($command)
|
|
|
|
{
|
|
|
|
private $command;
|
|
|
|
|
|
|
|
function __construct(string $cmd)
|
|
|
|
{
|
|
|
|
$this->command = $cmd;
|
|
|
|
}
|
|
|
|
|
2021-10-15 12:34:59 +03:00
|
|
|
function execute(?int &$result = nullptr): string
|
2020-06-07 19:04:43 +03:00
|
|
|
{
|
2021-10-15 12:34:59 +03:00
|
|
|
$stdout = [];
|
2022-03-20 18:37:52 +03:00
|
|
|
|
|
|
|
if(Shell::isPowershell()) {
|
|
|
|
$cmd = escapeshellarg($this->command);
|
|
|
|
exec("powershell -Command $this->command", $stdout, $result);
|
|
|
|
} else {
|
|
|
|
exec($this->command, $stdout, $result);
|
|
|
|
}
|
2021-10-15 12:34:59 +03:00
|
|
|
|
|
|
|
return implode(PHP_EOL, $stdout);
|
2020-06-07 19:04:43 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
function start(): string
|
|
|
|
{
|
2022-03-20 18:37:52 +03:00
|
|
|
if(Shell::isPowershell()) {
|
|
|
|
$cmd = escapeshellarg($this->command);
|
|
|
|
pclose(popen("start /b powershell -Command $this->command", "r"));
|
|
|
|
} else {
|
|
|
|
system("nohup " . $this->command . " > /dev/null 2>/dev/null &");
|
|
|
|
}
|
2020-06-07 19:04:43 +03:00
|
|
|
|
|
|
|
return $this->command;
|
|
|
|
}
|
|
|
|
};
|
|
|
|
}
|
|
|
|
}
|