From 61ec6aaaa512a55ea8eecebdec7ea9d121ee28c0 Mon Sep 17 00:00:00 2001 From: tracer Date: Tue, 27 Sep 2022 19:13:28 +0200 Subject: [PATCH] refactored command registration --- src/Controller/CLIController.php | 3010 ++++++++++++++++-------------- 1 file changed, 1623 insertions(+), 1387 deletions(-) diff --git a/src/Controller/CLIController.php b/src/Controller/CLIController.php index 3df74dc..732d11e 100644 --- a/src/Controller/CLIController.php +++ b/src/Controller/CLIController.php @@ -11,8 +11,13 @@ define(constant_name: 'COLOR_BLUE', value: "\033[34m"); define(constant_name: 'COLOR_WHITE', value: "\033[37m"); define(constant_name: 'COLOR_DEFAULT', value: "\033[39m"); +use App\Controller\Commands\Command; +use App\Controller\Commands\CommandGroup; +use App\Controller\Commands\CommandGroupContainer; +use App\Entity\Apikey; use App\Entity\Domain; use App\Entity\DynDNS; +use App\Entity\KeyHelp\KeyHelpDomain; use App\Entity\Nameserver; use App\Entity\Panel; use App\Repository\ApikeyRepository; @@ -22,10 +27,13 @@ use App\Repository\NameserverRepository; use App\Repository\PanelRepository; use Arubacao\TldChecker\Validator; use Exception; +use JsonMapper; +use JsonMapper_Exception; use LucidFrame\Console\ConsoleTable; +use SodiumException; if (php_sapi_name() !== 'cli') { - exit; + exit; } @@ -35,1534 +43,1762 @@ if (php_sapi_name() !== 'cli') { class CLIController { private array $arguments; + private CommandGroupContainer $commandGroupContainer; - /** - * @throws Exception - */ - public function __construct( - private readonly ApiController $apiController, - private readonly ApikeyRepository $apikeyRepository, - private readonly DomainController $domainController, - private readonly DomainRepository $domainRepository, - private readonly DynDNSRepository $dynDNSRepository, - private readonly NameserverRepository $nameserverRepository, - private readonly PanelRepository $panelRepository, - private readonly ConfigController $configController, - private $logger) - { - $this->checkSetup(); - } + /** + * @throws Exception + */ + public function __construct( + private readonly ApiController $apiController, + private readonly ApikeyRepository $apikeyRepository, + private readonly DomainController $domainController, + private readonly DomainRepository $domainRepository, + private readonly DynDNSRepository $dynDNSRepository, + private readonly NameserverRepository $nameserverRepository, + private readonly PanelRepository $panelRepository, + private readonly ConfigController $configController, + private readonly EncryptionController $encryptionController, + private $logger) + { + $this->checkSetup(); - function checkSetup(): void - { - if (!$this->domainController->checkPermissions(disableVerbose: true)) { - echo 'You need to setup the bindAPI first.' . PHP_EOL; - exit(1); - } + $this->commandGroupContainer = (new CommandGroupContainer()) + ->add(commandGroup: (new CommandGroup(name: 'check', description: 'health checks the system can perform')) + ->addCommand(command: new Command( + name: 'permissions', + callback: function () { + $this->handleCheckPermissions(); + }, + description: 'health checks the system can perform')) + ->addCommand(command: new Command( + name: 'panels', + callback: function () { + $this->handleCheckPanels(); + }, + optionalParameters: ['ID', 'fix=xes'])) + ->addCommand(command: new Command( + name: 'domains', + callback: function () { + $this->handleCheckDomains(); + })) + ->addCommand(command: new Command( + name: 'showincludes', + callback: function () { + $this->handleCheckShowIncludes(); + }, + description: 'Shows needed setting on panels')) + ->addCommand(command: new Command( + name: 'generatekey', + callback: function () { + $this->handleCheckGenerateKey(); + }, + description: 'Generates a a new key for encryption')) + ->addCommand(command: new Command( + name: 'setup', + callback: function () { + $this->handleCheckSetup(); + }, + mandatoryParameters: ['username'], + description: 'Adapt filesystem permissions (requires elaborated permissions)')) + ->addCommand(command: new Command( + name: 'version', + callback: function () { + $this->handleChecksVersion(); + }, + optionalParameters: ['major:minor:patch'], + description: 'Read or set the bindApi version in the database'))) + ->add(commandGroup: (new CommandGroup(name: 'panels', description: 'all KeyHelp systems configured')) + ->addCommand(command: new Command( + name: 'list', + callback: function () { + $this->handlePanelsList(); + })) + ->addCommand(command: new Command( + name: 'create', + callback: function () { + $this->handlePanelsCreate(); + }, + mandatoryParameters: ['name'], + optionalParameters: ['A=', 'AAAA=', 'apikey='])) + ->addCommand(command: new Command( + name: 'update', + callback: function () { + $this->handlePanelsUpdate(); + }, + mandatoryParameters: ['ID'], + optionalParameters: ['name=', 'A=', 'AAAA=', 'apikey='])) + ->addCommand(command: new Command( + name: 'delete', + callback: function () { + $this->handlePanelsDelete(); + }, + mandatoryParameters: ['ID'])) + ->addCommand(command: new Command( + name: 'apiping', + callback: function () { + $this->handleApiPing(); + }, + optionalParameters: ['ID']))) + ->add(commandGroup: (new CommandGroup(name: 'nameservers', description: 'available nameservers')) + ->addCommand(command: new Command( + name: 'list', + callback: function () { + $this->handleNameserversList(); + })) + ->addCommand(command: new Command( + name: 'create', + callback: function () { + $this->handleNameserversCreate(); + }, + mandatoryParameters: ['name'], + optionalParameters: ['A=', 'AAAA=', 'apikey='])) + ->addCommand(command: new Command( + name: 'update', + callback: function () { + $this->handleNameserversUpdate(); + }, + mandatoryParameters: ['ID'], + optionalParameters: ['name=', 'A=', 'AAAA=', 'apikey='])) + ->addCommand(command: new Command( + name: 'delete', + callback: function () { + $this->handleNameserversDelete(); + }, + mandatoryParameters: ['ID'])) + ->addCommand(command: new Command( + name: 'apiping', + callback: function () { + $this->handleApiPing(); + }, + optionalParameters: ['ID']))) + ->add(commandGroup: (new CommandGroup(name: 'domains', description: 'configured domains')) + ->addCommand(command: new Command( + name: 'list', + callback: function () { + $this->handleDomainsList(); + })) + ->addCommand(command: new Command( + name: 'refresh', + callback: function () { + $this->handleDomainsRefresh(); + }, + mandatoryParameters: ['name'], + optionalParameters: ['A=', 'AAAA=', 'apikey=']))) + ->add(commandGroup: (new CommandGroup(name: 'dyndns', description: 'handle DynDNS entries')) + ->addCommand(command: new Command( + name: 'list', + callback: function () { + $this->handleDynDnsList(); + })) + ->addCommand(command: new Command( + name: 'create', + callback: function () { + $this->handlePanelsCreate(); + }, + mandatoryParameters: ['hostname.example.com', 'password'], + description: 'FQDN within a domain where this server is master')) + ->addCommand(command: new Command( + name: 'update', + callback: function () { + $this->handlePanelsUpdate(); + }, + mandatoryParameters: ['ID'], + optionalParameters: ['name=', 'A=', 'AAAA=', 'apikey='])) + ->addCommand(command: new Command( + name: 'delete', + callback: function () { + $this->handlePanelsDelete(); + }, + mandatoryParameters: ['ID']))); + } - $self = $this->panelRepository->findSelf(); + function checkSetup(): void + { + if (!$this->domainController->checkPermissions(disableVerbose: true)) { + echo 'You need to setup the bindAPI first.' . PHP_EOL; + exit(1); + } - $c = count($self); + $self = $this->panelRepository->findSelf(); - if ($c != 1) { - if ($c == 0) { - echo 'No panel marked as this server.' . PHP_EOL; - echo 'Use ' . COLOR_YELLOW . 'panels:update self=1 ' . COLOR_DEFAULT . 'to mark this panel.' . PHP_EOL; - } else { - echo 'Only one panel can be marked as self.' . PHP_EOL; - echo 'Use ' . COLOR_YELLOW . 'panels:update self=0 ' . COLOR_DEFAULT . 'to remove the stale panel' . PHP_EOL; - } - } - } + $c = count($self); + + if ($c != 1) { + if ($c == 0) { + echo 'No panel marked as this server.' . PHP_EOL; + echo 'Use ' . COLOR_YELLOW . 'panels:update self=1 ' . COLOR_DEFAULT . 'to mark this panel.' . PHP_EOL; + } else { + echo 'Only one panel can be marked as self.' . PHP_EOL; + echo 'Use ' . COLOR_YELLOW . 'panels:update self=0 ' . COLOR_DEFAULT . 'to remove the stale panel' . PHP_EOL; + } + } + } - // TODO encrypt the password in the config file, key in config - - function runCommand(array $arguments): void - { + function runCommand(array $arguments): void + { if (count($arguments) < 1) { $this->showUsage(); exit(0); } - $this->logger->debug(message: "runCommand()"); + $this->logger->debug(message: "runCommand()"); - if (str_contains(haystack: $arguments[0], needle: ':')) { - [$command, $subcommand] = explode(separator: ':', string: $arguments[0]); - } else { - $command = $arguments[0]; - $subcommand = ''; - } + if (str_contains(haystack: $arguments[0], needle: ':')) { + [$command, $subcommand] = explode(separator: ':', string: $arguments[0]); + } else { + $command = $arguments[0]; + $subcommand = ''; + } $this->arguments = $this->parseArguments(arguments: $arguments); - - match ($command) { - 'check' => $this->handleChecks(subcommand: $subcommand), - 'panels' => $this->handlePanels(subcommand: $subcommand), - 'apikeys' => $this->handleApiKeys(subcommand: $subcommand), - 'domains' => $this->handleDomains(subcommand: $subcommand), - 'dyndns' => $this->handleDynDns(subcommand: $subcommand), - 'nameservers' => $this->handleNameservers(subcommand: $subcommand), - default => $this->unknownCommand(command: $command) - }; - } + $this->commandGroupContainer->run(command: $command, subcommand: $subcommand); + } - /** - * @return void - */ - function showUsage(): void - { - $this->logger->debug(message: "showUsage()"); + /** + * @return void + */ + function showUsage(): void + { + $this->logger->debug(message: "showUsage()"); - echo COLOR_YELLOW . 'Usage:' . PHP_EOL; - echo COLOR_DEFAULT . "\t./bin/console {options} {arguments}" . PHP_EOL . PHP_EOL; + $debug = $this->configController->getConfig(configKey: 'debug'); + echo 'bindAPI version: todo (env: todo) '; + if ($debug) { + echo 'true'; + } else { + echo 'false'; + } + echo COLOR_DEFAULT . ')' . PHP_EOL; - echo COLOR_YELLOW . 'Options:' . PHP_EOL; - echo COLOR_GREEN . "\t-v, --version\t\t" . COLOR_DEFAULT . "Display the version of the API" . PHP_EOL; - echo COLOR_GREEN . "\t-V, --verbose\t\t" . COLOR_DEFAULT . "All :lists command are auto-verbose" . PHP_EOL . PHP_EOL; + echo COLOR_YELLOW . 'Usage:' . PHP_EOL; + echo COLOR_DEFAULT . "\t./bin/console {options} {arguments}" . PHP_EOL . PHP_EOL; - echo COLOR_YELLOW . 'Arguments:' . PHP_EOL; - echo COLOR_YELLOW . "check" . COLOR_WHITE . "\t health checks the system can perform" . PHP_EOL; - echo COLOR_GREEN . "\t check:permissions" . PHP_EOL; - echo COLOR_GREEN . "\t check:panels {ID} {fix=yes}" . PHP_EOL; - echo COLOR_GREEN . "\t check:domains" . PHP_EOL; - echo COLOR_GREEN . "\t check:showincludes" . COLOR_WHITE . " Shows needed setting on panels" . PHP_EOL; - echo COLOR_GREEN . "\t check:generatekey" . COLOR_WHITE . " Generates a key for encryption" . PHP_EOL; - echo COLOR_GREEN . "\t check:setup " . COLOR_WHITE . " Adapt filesystem permissions (requires elaborated permissions)" . PHP_EOL; + echo COLOR_YELLOW . 'Options:' . PHP_EOL; + echo COLOR_GREEN . "\t-v, --version\t\t" . COLOR_DEFAULT . "Display the version of the API" . PHP_EOL; + echo COLOR_GREEN . "\t-V, --verbose\t\t" . COLOR_DEFAULT . "All :lists command are auto-verbose" . PHP_EOL . PHP_EOL; + echo COLOR_YELLOW . 'Arguments: ' . COLOR_WHITE . ' {optional}' . PHP_EOL; - echo COLOR_YELLOW . "panels" . COLOR_WHITE . "\t all KeyHelp systems configured" . PHP_EOL; - echo COLOR_GREEN . "\t panels:list" . PHP_EOL; - echo COLOR_GREEN . "\t panels:create {A=} {AAAA=} {apikey=}" . PHP_EOL; - echo COLOR_GREEN . "\t panels:update {name=} {A=} {AAAA=} {apikey=}" . PHP_EOL; - echo COLOR_GREEN . "\t panels:delete " . PHP_EOL; - echo COLOR_GREEN . "\t panels:apiping {}" . PHP_EOL; + $this->commandGroupContainer->printCommands(); - echo COLOR_YELLOW . "nameservers" . COLOR_WHITE . " available nameservers" . PHP_EOL; - echo COLOR_GREEN . "\t nameservers:list" . PHP_EOL; - echo COLOR_GREEN . "\t nameservers:create {A=} {AAAA=} {apikey=}" . PHP_EOL; - echo COLOR_GREEN . "\t nameservers:update {name=} {A=} {AAAA=} {apikey=}" . PHP_EOL; - echo COLOR_GREEN . "\t nameservers:delete " . PHP_EOL; - echo COLOR_GREEN . "\t nameservers:apiping {}" . PHP_EOL; + echo COLOR_YELLOW . "dyndns" . COLOR_WHITE . " handle dyndns entries" . PHP_EOL; + echo COLOR_GREEN . "\t dyndns:list" . PHP_EOL; + echo COLOR_GREEN . "\t dyndns:create " . COLOR_DEFAULT . " FQDN within a domain where this server is master" . PHP_EOL; + echo COLOR_GREEN . "\t dyndns:update {A=} {AAAA=}" . PHP_EOL; + echo COLOR_GREEN . "\t dyndns:delete " . PHP_EOL; - echo COLOR_YELLOW . "domains" . COLOR_WHITE . " configured domains" . PHP_EOL; - echo COLOR_GREEN . "\t domains:list" . PHP_EOL; - echo COLOR_GREEN . "\t domains:refresh" . PHP_EOL; + echo COLOR_YELLOW . "apikeys" . COLOR_WHITE . "\t API keys to access this server" . PHP_EOL; + echo COLOR_GREEN . "\t apikeys:list" . PHP_EOL; + echo COLOR_GREEN . "\t apikeys:create {name=}" . PHP_EOL; + echo COLOR_GREEN . "\t apikeys:update {name=}" . PHP_EOL; + echo COLOR_GREEN . "\t apikeys:delete " . PHP_EOL; - echo COLOR_YELLOW . "dyndns" . COLOR_WHITE . " handle dyndns entries" . PHP_EOL; - echo COLOR_GREEN . "\t dyndns:list" . PHP_EOL; - echo COLOR_GREEN . "\t dyndns:create " . COLOR_DEFAULT . " FQDN within a domain where this server is master" . PHP_EOL; - echo COLOR_GREEN . "\t dyndns:update {A=} {AAAA=}" . PHP_EOL; - echo COLOR_GREEN . "\t dyndns:delete " . PHP_EOL; - - echo COLOR_YELLOW . "apikeys" . COLOR_WHITE . "\t API keys to access this server" . PHP_EOL; - echo COLOR_GREEN . "\t apikeys:list" . PHP_EOL; - echo COLOR_GREEN . "\t apikeys:create {name=}" . PHP_EOL; - echo COLOR_GREEN . "\t apikeys:update {name=}" . PHP_EOL; - echo COLOR_GREEN . "\t apikeys:delete " . PHP_EOL; - - echo PHP_EOL . "\033[39me.g. ./bin/console apikeys:list" . PHP_EOL; - } - - function handleChecks(string $subcommand): void - { - $this->logger->debug(message: "handleChecks()"); - - match ($subcommand) { - 'permissions' => $this->handleCheckPermissions(), - 'panels' => $this->handleCheckPanels(), - 'domains' => $this->handleCheckDomains(), - 'showincludes' => $this->handleCheckShowIncludes(), - 'generatekey' => $this->handleCheckGenerateKey(), - 'setup' => $this->handleCheckSetup(), - default => $this->unknownSubcommand(subcommand: $subcommand) - }; - } + echo PHP_EOL . "\033[39me.g. ./bin/console apikeys:list" . PHP_EOL; + } function unknownCommand(string $command): void { - echo COLOR_DEFAULT . 'Unknown command: ' . COLOR_YELLOW . $command . COLOR_DEFAULT . PHP_EOL; + echo COLOR_DEFAULT . 'Unknown command: ' . COLOR_YELLOW . $command . COLOR_DEFAULT . PHP_EOL; } - function unknownSubcommand(string $subcommand): void - { - if ($subcommand) { - echo COLOR_DEFAULT . 'Unknown argument: ' . COLOR_YELLOW . $subcommand . COLOR_DEFAULT . PHP_EOL; - } else { - echo COLOR_DEFAULT . 'You need to supply a subcommand after a colon.' . COLOR_DEFAULT . PHP_EOL; - } - } + function unknownSubcommand(string $subcommand): void + { + if ($subcommand) { + echo COLOR_DEFAULT . 'Unknown argument: ' . COLOR_YELLOW . $subcommand . COLOR_DEFAULT . PHP_EOL; + } else { + echo COLOR_DEFAULT . 'You need to supply a subcommand after a colon.' . COLOR_DEFAULT . PHP_EOL; + } + } - /** - */ - function handleCheckPermissions(): void - { - $this->logger->debug(message: "handleCheckPermissions()"); + /** + */ + public function handleCheckPermissions(): void + { + $this->logger->debug(message: "handleCheckPermissions()"); - if (!$this->domainController->checkPermissions()) { - if ($this->configController->getConfig(configKey: 'verbose')) { - echo PHP_EOL . COLOR_DEFAULT; - echo 'Missing permissions, please run ' . COLOR_YELLOW . './bin/console check:setup' . COLOR_DEFAULT . ' as root or with sudo.' . PHP_EOL; - } - exit(1); - } else { - exit(0); - } - } + if (!$this->domainController->checkPermissions()) { + if ($this->configController->getConfig(configKey: 'verbose')) { + echo PHP_EOL . COLOR_DEFAULT; + echo 'Missing permissions, please run ' . COLOR_YELLOW . './bin/console check:setup' . COLOR_DEFAULT . ' as root or with sudo.' . PHP_EOL; + } + exit(1); + } else { + exit(0); + } + } - function handleCheckSetup(): void - { - if (count($this->arguments) < 2) { - echo 'You need to supply a username.' . PHP_EOL; - exit(1); - } - $username = $this->arguments[1]; - $uid = posix_getuid(); - if ($uid != 0) { - echo 'You need to run this as root or with sudo.' . PHP_EOL; - exit(1); - } + /* + public function handleCheckPermissions(): void + { + $this->logger->debug(message: "handleCheckPermissions()"); - // deluser tracer bind - // adduser tracer bind + if (!$this->domainController->checkPermissions()) { + if ($this->configController->getConfig(configKey: 'verbose')) { + echo PHP_EOL . COLOR_DEFAULT; + echo 'Missing permissions, please run ' . COLOR_YELLOW . './bin/console check:setup' . COLOR_DEFAULT . ' as root or with sudo.' . PHP_EOL; + } + exit(1); + } else { + exit(0); + } + } +*/ - // add user to group bind - exec(command: "adduser $username bind", output: $output, result_code: $return); - if ($return != 0) { - echo 'Could not add user to bind group.' . PHP_EOL; - exit(1); - } + function handleCheckSetup(): void + { + if (count($this->arguments) < 2) { + echo 'You need to supply a username.' . PHP_EOL; + exit(1); + } + $username = $this->arguments[1]; + $uid = posix_getuid(); + if ($uid != 0) { + echo 'You need to run this as root or with sudo.' . PHP_EOL; + exit(1); + } - // for /etc/bind/local.zones file - if (!file_exists(filename: $this->domainController->localZoneFile)) { - echo 'Could not find ' . COLOR_YELLOW . $this->domainController->localZoneFile . COLOR_DEFAULT . '.' . PHP_EOL; - echo 'Creating …'; - touch(filename: $this->domainController->localZoneFile); - if (!file_exists(filename: $this->domainController->localZoneFile)) { - echo 'Could not create ' . $this->domainController->localZoneFile . '.' . PHP_EOL; - exit(1); - } else { - echo ' done.' . PHP_EOL; - echo 'Setting owner …'; - if (chown(filename: $this->domainController->localZoneFile, user: 'bind')) { - echo " done." . PHP_EOL; - } - echo 'Setting permissions …'; - if (chmod(filename: $this->domainController->localZoneFile, permissions: 0664)) { - echo " done." . PHP_EOL; - } - } - } + // deluser tracer bind + // adduser tracer bind - // /etc/bind/local.zones file must be included in /etc/bind/named.conf.local - $namedConfLocal = file_get_contents(filename: $this->domainController->namedConfLocalFile); - if (str_contains(haystack: $namedConfLocal, needle: $this->domainController->localZoneFile)) { - echo 'Found ' . COLOR_YELLOW . $this->domainController->localZoneFile . COLOR_DEFAULT . ' in ' . COLOR_YELLOW . $this->domainController->namedConfLocalFile . COLOR_DEFAULT . '.' . PHP_EOL; - } else { - echo 'Could not find ' . COLOR_YELLOW . $this->domainController->localZoneFile . COLOR_DEFAULT . ' in ' . COLOR_YELLOW . $this->domainController->namedConfLocalFile . COLOR_DEFAULT . '.' . PHP_EOL; - echo 'Adding …'; - $namedConfLocal .= PHP_EOL . 'include "' . $this->domainController->localZoneFile . '";' . PHP_EOL; - file_put_contents(filename: $this->domainController->namedConfLocalFile, data: $namedConfLocal); - if (str_contains(haystack: $namedConfLocal, needle: $this->domainController->localZoneFile)) { - echo ' done.' . PHP_EOL; - } else { - echo 'Could not add ' . COLOR_YELLOW . $this->domainController->localZoneFile . COLOR_DEFAULT . ' to ' . COLOR_YELLOW . $this->domainController->namedConfLocalFile . COLOR_DEFAULT . '.' . PHP_EOL; - exit(1); - } - } + // add user to group bind + exec(command: "adduser $username bind", output: $output, result_code: $return); + if ($return != 0) { + echo 'Could not add user to bind group.' . PHP_EOL; + exit(1); + } - // check /etc/bind/zones exists - echo 'Check for ' . COLOR_YELLOW . $this->domainController->localZonesDir . COLOR_DEFAULT . ' …'; - if (is_dir(filename: $this->domainController->localZonesDir)) { - echo " done." . PHP_EOL; - } else { - echo ' Could not find ' . COLOR_YELLOW . $this->domainController->localZonesDir . COLOR_DEFAULT . '.' . PHP_EOL; - echo 'Creating …'; - mkdir(directory: $this->domainController->localZonesDir, permissions: 0775, recursive: true); - echo ' done.' . PHP_EOL; - echo 'Setting owner …'; - if (chown(filename: $this->domainController->localZonesDir, user: 'bind')) { - echo " done." . PHP_EOL; - } - echo 'Setting permissions …'; - if (chmod(filename: $this->domainController->localZonesDir, permissions: 0774)) { - echo " done." . PHP_EOL; - } - } - } + // for /etc/bind/local.zones file + if (!file_exists(filename: $this->domainController->localZoneFile)) { + echo 'Could not find ' . COLOR_YELLOW . $this->domainController->localZoneFile . COLOR_DEFAULT . '.' . PHP_EOL; + echo 'Creating …'; + touch(filename: $this->domainController->localZoneFile); + if (!file_exists(filename: $this->domainController->localZoneFile)) { + echo 'Could not create ' . $this->domainController->localZoneFile . '.' . PHP_EOL; + exit(1); + } else { + echo ' done.' . PHP_EOL; + echo 'Setting owner …'; + if (chown(filename: $this->domainController->localZoneFile, user: 'bind')) { + echo " done." . PHP_EOL; + } + echo 'Setting permissions …'; + if (chmod(filename: $this->domainController->localZoneFile, permissions: 0664)) { + echo " done." . PHP_EOL; + } + } + } + + // /etc/bind/local.zones file must be included in /etc/bind/named.conf.local + $namedConfLocal = file_get_contents(filename: $this->domainController->namedConfLocalFile); + if (str_contains(haystack: $namedConfLocal, needle: $this->domainController->localZoneFile)) { + echo 'Found ' . COLOR_YELLOW . $this->domainController->localZoneFile . COLOR_DEFAULT . ' in ' . COLOR_YELLOW . $this->domainController->namedConfLocalFile . COLOR_DEFAULT . '.' . PHP_EOL; + } else { + echo 'Could not find ' . COLOR_YELLOW . $this->domainController->localZoneFile . COLOR_DEFAULT . ' in ' . COLOR_YELLOW . $this->domainController->namedConfLocalFile . COLOR_DEFAULT . '.' . PHP_EOL; + echo 'Adding …'; + $namedConfLocal .= PHP_EOL . 'include "' . $this->domainController->localZoneFile . '";' . PHP_EOL; + file_put_contents(filename: $this->domainController->namedConfLocalFile, data: $namedConfLocal); + if (str_contains(haystack: $namedConfLocal, needle: $this->domainController->localZoneFile)) { + echo ' done.' . PHP_EOL; + } else { + echo 'Could not add ' . COLOR_YELLOW . $this->domainController->localZoneFile . COLOR_DEFAULT . ' to ' . COLOR_YELLOW . $this->domainController->namedConfLocalFile . COLOR_DEFAULT . '.' . PHP_EOL; + exit(1); + } + } + + // check /etc/bind/zones exists + echo 'Check for ' . COLOR_YELLOW . $this->domainController->localZonesDir . COLOR_DEFAULT . ' …'; + if (is_dir(filename: $this->domainController->localZonesDir)) { + echo " done." . PHP_EOL; + } else { + echo ' Could not find ' . COLOR_YELLOW . $this->domainController->localZonesDir . COLOR_DEFAULT . '.' . PHP_EOL; + echo 'Creating …'; + mkdir(directory: $this->domainController->localZonesDir, permissions: 0775, recursive: true); + echo ' done.' . PHP_EOL; + echo 'Setting owner …'; + if (chown(filename: $this->domainController->localZonesDir, user: 'bind')) { + echo " done." . PHP_EOL; + } + echo 'Setting permissions …'; + if (chmod(filename: $this->domainController->localZonesDir, permissions: 0774)) { + echo " done." . PHP_EOL; + } + } + } - /** - */ - function handleCheckPanels(): void - { - $this->logger->debug(message: "handleCheckPanels()"); + /** + */ + function handleCheckPanels(): void + { + $this->logger->debug(message: "handleCheckPanels()"); - $id = intval(value: $this->arguments[1] ?? 0); + $id = intval(value: $this->arguments[1] ?? 0); - if ($id != 0) { - if ($panel = $this->panelRepository->findByID(id: $id)) { - $this->checkSinglePanel(panel: $panel); - } else { - echo "Unknown panel ID $id" . PHP_EOL; - } - } else { - echo "check all …" . PHP_EOL; - $panels = $this->panelRepository->findAll(); - foreach ($panels as $panel) { - $this->checkSinglePanel(panel: $panel); - } - } - } + if ($id != 0) { + if ($panel = $this->panelRepository->findByID(id: $id)) { + $this->checkSinglePanel(panel: $panel); + } else { + echo "Unknown panel ID $id" . PHP_EOL; + } + } else { + echo "check all …" . PHP_EOL; + $panels = $this->panelRepository->findAll(); + foreach ($panels as $panel) { + $this->checkSinglePanel(panel: $panel); + } + } + } - /** - * @param \App\Entity\Panel $panel - * - * @return void - */ - public function checkSinglePanel(Panel $panel): void - { - $this->logger->debug(message: "checkSinglePanel()"); + /** + * @param Panel $panel + * + * @return void + */ + public function checkSinglePanel(Panel $panel): void + { + $this->logger->debug(message: "checkSinglePanel()"); - echo COLOR_DEFAULT . 'KeyHelp-Panel: ' . COLOR_YELLOW . $panel->getName(); + echo COLOR_DEFAULT . 'KeyHelp-Panel: ' . COLOR_YELLOW . $panel->getName() . COLOR_DEFAULT; - if ($this->configController->getConfig(configKey: 'verbose')) { - if (empty($panel->getA())) { - $panelRequest = $this->apiController->sendCommand( - requestType: 'GET', - serverName: $panel->getName(), - versionIP: 6, - apiKey: $panel->getApikey(), - command: '/server', - serverType: 'panel'); - } else { - $panelRequest = $this->apiController->sendCommand( - requestType: 'GET', - serverName: $panel->getName(), - versionIP: 4, - apiKey: $panel->getApikey(), - command: '/server', - serverType: 'panel'); - } - $panelData = json_decode(json: $panelRequest['data']); - if (!empty($panelData)) { - $panelVersion = $panelData->meta->panel_version; - $responseTime = sprintf("%0.3f", $panelRequest['responseTime']); - } else { - $panelVersion = 'n/a'; - $responseTime = 'n/a'; - } - echo COLOR_DEFAULT . ' KeyHelp version: ' . $panelVersion . " ($responseTime seconds)" . PHP_EOL; - } else { - echo PHP_EOL; - } + $encryptionKey = $this->configController->getConfig(configKey: 'encryptionKey'); + $decryptedKey = $this->encryptionController->safeDecrypt(encrypted: $panel->getApikey(), key: $encryptionKey); - if (empty($panel->getA())) { - $result = $this->apiController->sendCommand( - requestType: 'GET', - serverName: $panel->getName(), - versionIP: 6, - apiKey: $panel->getApikey(), - command: 'domains?sort=domain', - serverType: 'panel' - ); - } else { - $result = $this->apiController->sendCommand( - requestType: 'GET', - serverName: $panel->getName(), - versionIP: 4, - apiKey: $panel->getApikey(), - command: 'domains?sort=domain', - serverType: 'panel'); - } + if ($this->configController->getConfig(configKey: 'verbose')) { + if (empty($panel->getA())) { + $panelRequest = $this->apiController->sendCommand( + requestType: 'GET', + serverName: $panel->getName(), + versionIP: 6, + apiKey: $decryptedKey, + command: '/server', + serverType: 'panel'); + } else { + $panelRequest = $this->apiController->sendCommand( + requestType: 'GET', + serverName: $panel->getName(), + versionIP: 4, + apiKey: $decryptedKey, + command: '/server', + serverType: 'panel'); + } + $panelData = json_decode(json: $panelRequest['data']); + if (!empty($panelData)) { + $panelVersion = $panelData->meta->panel_version; + $responseTime = sprintf("%0.3f", $panelRequest['responseTime']); + } else { + $panelVersion = 'n/a'; + $responseTime = 'n/a'; + } + echo COLOR_DEFAULT . ' KeyHelp version: ' . $panelVersion . " ($responseTime seconds)" . PHP_EOL; + } else { + echo PHP_EOL; + } - if (!empty($result['error'])) { - echo $result['data'] . PHP_EOL; - exit(1); - } - if (!empty($result['data'])) { - $domains = json_decode(json: $result['data']); - } else { - echo 'No domains found' . PHP_EOL; - exit(1); - } + if (empty($panel->getA())) { + $result = $this->apiController->sendCommand( + requestType: 'GET', + serverName: $panel->getName(), + versionIP: 6, + apiKey: $decryptedKey, + command: 'domains?sort=domain&subdomains=false', + serverType: 'panel' + ); + } else { + $result = $this->apiController->sendCommand( + requestType: 'GET', + serverName: $panel->getName(), + versionIP: 4, + apiKey: $decryptedKey, + command: 'domains?sort=domain&subdomains=false', + serverType: 'panel'); + } - $maxDomainNameLength = 0; - $tmpDomainlist = []; - if (count($domains) > 0) { - foreach ($domains as $domain) { - if ($this->isValidSecondLevelDomain(domainName: $domain->domain, panel: $panel->getName(), parent: $domain->id_parent_domain)) { - $tmpDomainlist[] = $domain; - if (strlen(string: $domain->domain) > $maxDomainNameLength) { - $maxDomainNameLength = strlen(string: $domain->domain); - } - } - } - } + if (!empty($result['error'])) { + echo $result['data'] . PHP_EOL; + exit(1); + } + if (!empty($result['data'])) { + $domains = json_decode(json: $result['data']); + } else { + echo 'No domains found' . PHP_EOL; + exit(1); + } - $domainCount = 0; - foreach ($tmpDomainlist as $domain) { - echo COLOR_DEFAULT . " Domain: " . COLOR_YELLOW . str_pad(string: $domain->domain, length: $maxDomainNameLength); - $this->checkNS(domainName: $domain->domain, panel: $panel); - $domainCount++; - } + $maxDomainNameLength = 0; + $tmpDomainList = []; - if ($domainCount == 0) { - echo 'No second level domains found.' . COLOR_DEFAULT . PHP_EOL; - } - echo PHP_EOL; - } + $mapper = new JsonMapper(); - function isValidSecondLevelDomain(string $domainName, string $panel, int $parent): bool - { - $this->logger->debug(message: "isValidSecondLevelDomain()"); + if (count($domains) > 0) { + foreach ($domains as $domain) { + $mapper->bExceptionOnUndefinedProperty = true; + $mapper->bStrictNullTypes = false; + try { + $domainObject = $mapper->map(json: $domain, object: new KeyHelpDomain()); + } catch (JsonMapper_Exception $e) { + die($e->getMessage() . PHP_EOL); + } + $tmpDomainList[] = $domainObject; + if (strlen(string: $domain->domain) > $maxDomainNameLength) { + $maxDomainNameLength = strlen(string: $domain->domain); + } + } + } - // subdomain - if ($parent != 0) { - return false; - } + $domainCount = 0; + foreach ($tmpDomainList as $domain) { + echo COLOR_DEFAULT . " Domain: " . COLOR_YELLOW . str_pad(string: $domain->getDomain(), length: $maxDomainNameLength); + if (!$domain->isSubdomain()) { + $this->checkNS(domainName: $domain->getDomain(), panel: $panel); + $domainCount++; + } + } - // system domain - if (str_contains(haystack: $domainName, needle: $panel)) { - return false; - } + if ($domainCount == 0) { + echo 'No second level domains found.' . COLOR_DEFAULT . PHP_EOL; + } + echo PHP_EOL; - // valid second level domain - if (!Validator::endsWithTld(value: $domainName)) { - return false; - } + try { + sodium_memzero(string: $decryptedKey); + } catch (SodiumException $e) { + die($e->getMessage() . PHP_EOL); + } + } - // no second level domain - if (substr_count(haystack: $domainName, needle: '.') > 1) { - return false; - } + function isSubDomain(Domain $domain): bool + { + $this->logger->debug(message: "isSubDomain()"); - return true; - } + // valid second level domain + if (!Validator::endsWithTld(value: $domain)) { + return false; + } + + $domainParts = explode(separator: '.', string: $domain->getName()); + $reversedParts = array_reverse(array: $domainParts); + $testDomain = ''; + $foundDomain = ''; + foreach ($reversedParts as $part) { + if ($testDomain) { + $testDomain = $part . '.' . $testDomain; + } else { + $testDomain = $part; + } + if ($this->domainRepository->findByName(name: $testDomain)) { + $foundDomain = $testDomain; + echo $part . PHP_EOL; + } + } + + echo "fould domain ***" . $foundDomain . PHP_EOL; + + /* + // system domain + if (str_contains(haystack: $domainName, needle: $panel)) { + return false; + } - /** - * @param String $domainName - * @param \App\Entity\Panel $panel - * - * @return void - */ - function checkNS(string $domainName, Panel $panel): void - { - $this->logger->debug(message: "checkNS()"); + // no second level domain + if (substr_count(haystack: $domainName, needle: '.') > 1) { + return false; + } +*/ + return true; + } - $nameServers = $this->nameserverRepository->findAll(); - foreach ($nameServers as $nameServer) { - echo COLOR_YELLOW . ' ' . $nameServer->getName(); - if (!empty($nameServer->getName())) { - $result = $this->apiController->sendCommand( - requestType: 'GET', - serverName: $nameServer->getName(), - versionIP: 6, - apiKey: $nameServer->getApikey(), - command: 'domains/name/' . $domainName, - serverType: 'nameserver'); - } else { - $result = $this->apiController->sendCommand( - requestType: 'GET', - serverName: $nameServer->getName(), - versionIP: 4, - apiKey: $nameServer->getApikey(), - command: 'domains/name/', - serverType: 'nameserver' . $domainName); - } - switch ($result['header']) { - case 200: - echo COLOR_GREEN . ' OK'; - break; - case 404: - echo COLOR_RED . ' ' . $result['header'] . COLOR_DEFAULT; - if (!empty($this->arguments['fix']) && $this->arguments['fix'] == 'yes') { - echo ' trying to fix …'; - $body = [ - 'name' => $domainName, - 'panel' => $panel->getName(), - ]; - if (!empty($nameServer->getAaaa())) { - $create = $this->apiController->sendCommand( - requestType: 'POST', - serverName: $nameServer->getName(), - versionIP: 6, - apiKey: $nameServer->getApikey(), - command: 'domains', - serverType: 'nameserver', - body: $body); - } else { - $create = $this->apiController->sendCommand( - requestType: 'POST', - serverName: $nameServer->getName(), - versionIP: 4, - apiKey: $nameServer->getAPikey(), - command: 'domains', - serverType: 'nameserver', - body: $body); - } - if ($create['header'] != 201) { - print_r(value: $create); - die("make error handling"); - } else { - echo COLOR_GREEN . 'OK' . COLOR_DEFAULT; - } - } - break; - default: - echo 'Server error' . PHP_EOL; - exit(1); - } - } - echo PHP_EOL; - } + function isValidSecondLevelDomain(string $domainName, string $panel, int $parent): bool + { + $this->logger->debug(message: "isValidSecondLevelDomain()"); + + // subdomain + if ($parent != 0) { + return false; + } + + // system domain + if (str_contains(haystack: $domainName, needle: $panel)) { + return false; + } + + // valid second level domain + if (!Validator::endsWithTld(value: $domainName)) { + return false; + } + + // no second level domain + if (substr_count(haystack: $domainName, needle: '.') > 1) { + return false; + } + + return true; + } + + + /** + * @param String $domainName + * @param Panel $panel + * + * @return void + */ + function checkNS(string $domainName, Panel $panel): void + { + $this->logger->debug(message: "checkNS()"); + + $nameServers = $this->nameserverRepository->findAll(); + foreach ($nameServers as $nameServer) { + echo COLOR_YELLOW . ' ' . $nameServer->getName(); + if (!empty($nameServer->getName())) { + $result = $this->apiController->sendCommand( + requestType: 'GET', + serverName: $nameServer->getName(), + versionIP: 6, + apiKey: $nameServer->getApikey(), + command: 'domains/name/' . $domainName, + serverType: 'nameserver'); + } else { + $result = $this->apiController->sendCommand( + requestType: 'GET', + serverName: $nameServer->getName(), + versionIP: 4, + apiKey: $nameServer->getApikey(), + command: 'domains/name/', + serverType: 'nameserver' . $domainName); + } + + switch ($result['header']) { + case 200: + echo COLOR_GREEN . ' OK'; + break; + case 404: + echo COLOR_RED . ' ' . $result['header'] . COLOR_DEFAULT; + if (!empty($this->arguments['fix']) && $this->arguments['fix'] == 'yes') { + echo ' trying to fix …'; + $body = [ + 'name' => $domainName, + 'panel' => $panel->getName(), + ]; + if (!empty($nameServer->getAaaa())) { + $create = $this->apiController->sendCommand( + requestType: 'POST', + serverName: $nameServer->getName(), + versionIP: 6, + apiKey: $nameServer->getApikey(), + command: 'domains', + serverType: 'nameserver', + body: $body); + } else { + $create = $this->apiController->sendCommand( + requestType: 'POST', + serverName: $nameServer->getName(), + versionIP: 4, + apiKey: $nameServer->getAPikey(), + command: 'domains', + serverType: 'nameserver', + body: $body); + } + if ($create['header'] != 201) { + print_r(value: $create); + die("make error handling"); + } else { + echo COLOR_GREEN . 'OK' . COLOR_DEFAULT; + } + } + break; + default: + echo 'Server error' . PHP_EOL; + exit(1); + } + } + echo PHP_EOL; + } /** * @param array $arguments * @return array */ - public function parseArguments(array $arguments): array - { - $this->logger->debug(message: "parseArguments()"); + public function parseArguments(array $arguments): array + { + $this->logger->debug(message: "parseArguments()"); - $parsedArguments = []; + $parsedArguments = []; $parseCount = 0; - foreach ($arguments as $argument) { - if (str_contains(haystack: $argument, needle: '=')) { - [$key, $value] = explode(separator: '=', string: $argument); - $parsedArguments[strtolower(string: $key)] = $value; + foreach ($arguments as $argument) { + if (str_contains(haystack: $argument, needle: '=')) { + [$key, $value] = explode(separator: '=', string: $argument); + $parsedArguments[strtolower(string: $key)] = $value; $parsedArguments[$parseCount++] = $value; - } else { - $parsedArguments[strtolower(string: $argument)] = $argument; + } else { + $parsedArguments[strtolower(string: $argument)] = $argument; $parsedArguments[$parseCount++] = $argument; - } - } - return $parsedArguments; - } + } + } + return $parsedArguments; + } - /** - * @param string $subcommand - * - * @return void - */ - public function handlePanels(string $subcommand): void - { - $this->logger->debug(message: "handlePanels()"); + /** + * @param string $subcommand + * + * @return void + */ + public function handlePanels(string $subcommand): void + { + $this->logger->debug(message: "handlePanels()"); - match ($subcommand) { - 'create' => $this->handlePanelsCreate(), - 'list' => $this->handlePanelsList(), - 'update' => $this->handlePanelsUpdate(), - 'delete' => $this->handlePanelsDelete(), - 'apiping' => $this->handleAPIPing(type: 'panel'), - default => $this->unknownSubcommand(subcommand: $subcommand) - }; - } + match ($subcommand) { + 'create' => $this->handlePanelsCreate(), + 'list' => $this->handlePanelsList(), + 'update' => $this->handlePanelsUpdate(), + 'delete' => $this->handlePanelsDelete(), + 'apiping' => $this->handleApiPing(type: 'panel'), + default => $this->unknownSubcommand(subcommand: $subcommand) + }; + } - /** - * @return void - */ - function handlePanelsCreate(): void - { - $this->logger->debug(message: "handlePanelsCreate()"); + /** + * @return void + */ + function handlePanelsCreate(): void + { + $this->logger->debug(message: "handlePanelsCreate()"); - $name = $this->arguments[1] ?? ''; - if (empty($name)) { - echo 'You need to supply the panel name.' . PHP_EOL; - exit(1); - } + $name = $this->arguments[1] ?? ''; + if (empty($name)) { + echo 'You need to supply the panel name.' . PHP_EOL; + exit(1); + } - $filteredName = filter_var(value: $name, filter: FILTER_VALIDATE_DOMAIN, options: FILTER_FLAG_HOSTNAME); - if (!empty($filteredName) && str_contains(haystack: $filteredName, needle: '.')) { - $name = $filteredName; - } else { - echo "$name is no valid DNS domain name." . PHP_EOL; - exit(1); - } + $filteredName = filter_var(value: $name, filter: FILTER_VALIDATE_DOMAIN, options: FILTER_FLAG_HOSTNAME); + if (!empty($filteredName) && str_contains(haystack: $filteredName, needle: '.')) { + $name = $filteredName; + } else { + echo "$name is no valid DNS domain name." . PHP_EOL; + exit(1); + } - $a = $this->arguments['a'] ?? ''; - $aaaa = $this->arguments['aaaa'] ?? ''; - if (empty($a) && empty($aaaa)) { - echo 'At least one IP address is required.' . PHP_EOL; - exit(0); - } - $apikey = $this->arguments['apikey'] ?? ''; - $self = intval(value: $this->arguments['self'] ?? 0); + $a = $this->arguments['a'] ?? ''; + $aaaa = $this->arguments['aaaa'] ?? ''; + if (empty($a) && empty($aaaa)) { + echo 'At least one IP address is required.' . PHP_EOL; + exit(0); + } + $apikey = $this->arguments['apikey'] ?? ''; + $self = $this->arguments['self'] ?? 'no'; - if ($this->panelRepository->findByName(name: $name)) { - echo "Panel: $name already exists." . PHP_EOL; - exit(1); - } else { - $result = $this->panelRepository->insert(name: $name, a: $a, aaaa: $aaaa, apikey: $apikey, self: $self); - echo "Panel $name has been created with id $result" . PHP_EOL; - exit(0); - } - } + if ($this->panelRepository->findByName(name: $name)) { + echo "Panel: $name already exists." . PHP_EOL; + exit(1); + } else { + $panel = new Panel(name: $name, a: $a, aaaa: $aaaa, passphrase: $apikey, self: $self); + $result = $this->panelRepository->insert(panel: $panel); + echo "Panel $name has been created with id $result" . PHP_EOL; + exit(0); + } + } - /** - * @return void - */ - function handlePanelsList(): void - { - $this->logger->debug(message: "handlePanelsList()"); + /** + * @return void + */ + function handlePanelsList(): void + { + $this->logger->debug(message: "handlePanelsList()"); - $panels = $this->panelRepository->findAll(); - if (!empty($panels)) { - echo 'All available panels:' . PHP_EOL; - $table = new ConsoleTable(); - $table->setHeaders(content: ['ID', 'Name', 'A', 'AAAA', 'API Key (Prefix)', 'This Panel']); - foreach ($panels as $panel) { - $row = []; - $token = strtok(string: $panel->getApikey(), token: '.'); - $row[] = $panel->getID(); - $row[] = $panel->getName(); - $row[] = $panel->getA(); - $row[] = $panel->getAaaa(); - $row[] = $token; - if ($panel->getSelf() == 1) { - $row[] = 'Yes'; - } else { - $row[] = 'No'; + $panels = $this->panelRepository->findAll(); + if (!empty($panels)) { + echo 'All available panels:' . PHP_EOL; + $table = new ConsoleTable(); + $table->setHeaders(content: ['ID', 'Name', 'A', 'AAAA', 'API Key (Prefix)', 'This Panel']); - } - $table->addRow(data: $row); - } - $table->setPadding(value: 2); - $table->display(); - } else { - echo 'No panels found.' . PHP_EOL; - exit(1); - } - exit(0); - } + foreach ($panels as $panel) { + $row = []; + $row[] = $panel->getID(); + $row[] = $panel->getName(); + $row[] = $panel->getA(); + $row[] = $panel->getAaaa(); + $row[] = $panel->getApikeyPrefix(); + $row[] = ucfirst(string: $panel->getSelf()); + $table->addRow(data: $row); + } + $table->setPadding(value: 2); + $table->display(); + } else { + echo 'No panels found.' . PHP_EOL; + exit(1); + } + exit(0); + } - /** - */ - function handlePanelsUpdate(): void - { - $this->logger->debug(message: "handlePanelsUpdate()"); + /** + */ + function handlePanelsUpdate(): void + { + $this->logger->debug(message: "handlePanelsUpdate()"); - $id = intval(value: $this->arguments[1] ?? 0); - $name = $this->arguments['name'] ?? ''; - $a = $this->arguments['a'] ?? ''; - $aaaa = $this->arguments['aaaa'] ?? ''; - $apikey = $this->arguments['apikey'] ?? ''; - $self = intval(value: $this->arguments['self'] ?? 0); + $id = intval(value: $this->arguments[1] ?? 0); + $name = $this->arguments['name'] ?? ''; + $a = $this->arguments['a'] ?? ''; + $aaaa = $this->arguments['aaaa'] ?? ''; + $apikey = $this->arguments['apikey'] ?? ''; + $self = $this->arguments['self'] ?? ''; - // a workaround for 0 being equal to false … - if ($self == 0) { - $self = -1; - } + if ($id == 0) { + echo 'An ID is required' . PHP_EOL; + exit(1); + } + if (!$this->panelRepository->findByID(id: $id)) { + echo "Panel with ID : $id doesn't exist." . PHP_EOL; + exit(1); + } + if ($apikey) { + $panel = new Panel(name: $name, id: $id, a: $a, aaaa: $aaaa, passphrase: $apikey, self: $self); + } else { + $panel = new Panel(name: $name, id: $id, a: $a, aaaa: $aaaa, self: $self); + } + if ($this->panelRepository->update(panel: $panel) !== false) { + echo 'Panel ' . COLOR_YELLOW . $id . COLOR_DEFAULT . ' has been updated' . PHP_EOL; + } else { + echo 'Error while updating domain server.' . PHP_EOL; + } + } - if ($id == 0) { - echo 'An ID is required' . PHP_EOL; - exit(1); - } - if (!$this->panelRepository->findByID(id: $id)) { - echo "Panel with ID : $id doesn't exist." . PHP_EOL; - exit(1); - } - if ($this->panelRepository->update(id: $id, name: $name, a: $a, aaaa: $aaaa, apikey: $apikey, self: $self) !== false) { - echo 'Panel has been updated' . PHP_EOL; - } else { - echo 'Error while updating domain server.' . PHP_EOL; - } - } + /** + */ + function handlePanelsDelete(): void + { + $this->logger->debug(message: "handlePanelsDelete()"); - /** - */ - function handlePanelsDelete(): void - { - $this->logger->debug(message: "handlePanelsDelete()"); + if (empty($this->arguments[1])) { + echo "You need to supply an ID." . PHP_EOL; + exit(1); + } - if (empty($this->arguments[1])) { - echo "You need to supply an ID." . PHP_EOL; - exit(1); - } + $id = intval(value: $this->arguments[1]) ?? 0; + if ($id == 0) { + echo "Panel with ID $id not found." . PHP_EOL; + exit(1); + } + if (!$this->panelRepository->findByID(id: $id)) { + echo "There is no panel with ID $id." . PHP_EOL; + exit(1); + } + $this->panelRepository->delete(id: $id); + echo "The panel with ID $id has been deleted." . PHP_EOL; + } - $id = intval(value: $this->arguments[1]) ?? 0; - if ($id == 0) { - echo "Panel with ID $id not found." . PHP_EOL; - exit(1); - } - if (!$this->panelRepository->findByID(id: $id)) { - echo "There is no panel with ID $id." . PHP_EOL; - exit(1); - } - $this->panelRepository->delete(id: $id); - echo "The panel with ID $id has been deleted." . PHP_EOL; - } + /** + */ + function handleApiPing(string $type): void + { + $this->logger->debug(message: "handleApiPing()"); - /** - */ - function handleAPIPing(string $type): void - { - $this->logger->debug(message: "handleApiPing()"); + $error = false; - $error = false; + $id = $this->getId(); - $id = $this->getId(); + if ($id != 0) { + if ($type == 'panel') { + $server = $this->panelRepository->findByID(id: $id); + } else { + $server = $this->nameserverRepository->findByID(id: $id); + } - if ($id != 0) { - if ($type == 'panel') { - $server = $this->panelRepository->findByID(id: $id); - } else { - $server = $this->nameserverRepository->findByID(id: $id); - } + if ($server) { + if (!$this->checkPing(server: $server, type: $type)) { + $error = true; + } + } else { + if (!$this->configController->getConfig(configKey: 'quiet')) { + echo "Unknown $type ID $id" . PHP_EOL; + } + $error = true; + } + } else { + if ($type == 'panel') { + $servers = $this->panelRepository->findAll(); + } else { + $servers = $this->nameserverRepository->findAll(); + } + foreach ($servers as $server) { + if (!$this->checkPing(server: $server, type: $type)) { + $error = true; + } + } + } + if (!$this->configController->getConfig(configKey: 'quiet')) { + echo PHP_EOL; + } + if ($error) { + if (!$this->configController->getConfig(configKey: 'verbose')) { + echo 'There were errors, run command with -V (or -verbose) to see the errors.' . PHP_EOL; + } + exit(1); + } else { + exit(0); + } + } - if ($server) { - if (!$this->checkPing(server: $server, type: $type)) { - $error = true; - } - } else { - if ($this->configController->getConfig(configKey: 'verbose')) { - echo "Unknown $type ID $id" . PHP_EOL; - } - $error = true; - } - } else { - if ($type == 'panel') { - $servers = $this->panelRepository->findAll(); - } else { - $servers = $this->nameserverRepository->findAll(); - } - foreach ($servers as $server) { - if (!$this->checkPing(server: $server, type: $type)) { - $error = true; - } - } - } - if ($this->configController->getConfig(configKey: 'verbose')) { - echo PHP_EOL; - } - if ($error) { - exit(1); - } else { - exit(0); - } - } + /** + * @return int|void + */ + public function getId() + { + if (!empty($this->arguments[1])) { + $id = intval(value: $this->arguments[1] ?? 0); - /** - * @return int|void - */ - public function getId() - { - if (!empty($this->arguments[1])) { - $id = intval(value: $this->arguments[1] ?? 0); + if ($id != $this->arguments[1]) { + echo 'ID has to be a number.' . PHP_EOL; + exit(1); + } + } else { + $id = 0; + } + return $id; + } - if ($id != $this->arguments[1]) { - echo 'ID has to be a number.' . PHP_EOL; - exit(1); - } - } else { - $id = 0; - } - return $id; - } + /** + * @param Panel|Nameserver $server + * @param String $type + * + * @return bool + */ + public function checkPing(Panel|Nameserver $server, string $type): bool + { + $this->logger->debug(message: "handleApiPing() - server, type: " . $server->getName() . ', ' . $type); - /** - * @param \App\Entity\Panel|\App\Entity\Nameserver $server - * @param String $type - * - * @return bool - */ - public function checkPing(Panel|Nameserver $server, string $type): bool - { - $error = false; + $error = false; - if ($type == 'nameserver') { - $maxName = $this->nameserverRepository->getLongestEntry(field: 'name'); - $maxA = $this->nameserverRepository->getLongestEntry(field: 'a'); - $maxAAAA = $this->nameserverRepository->getLongestEntry(field: 'aaaa'); - } else { - $maxName = $this->panelRepository->getLongestEntry(field: 'name'); - $maxA = $this->panelRepository->getLongestEntry(field: 'a'); - $maxAAAA = $this->panelRepository->getLongestEntry(field: 'aaaa'); - } + if ($type == 'nameserver') { + $maxName = $this->nameserverRepository->getLongestEntry(field: 'name'); + $maxA = $this->nameserverRepository->getLongestEntry(field: 'a'); + $maxAAAA = $this->nameserverRepository->getLongestEntry(field: 'aaaa'); + } else { + $maxName = $this->panelRepository->getLongestEntry(field: 'name'); + $maxA = $this->panelRepository->getLongestEntry(field: 'a'); + $maxAAAA = $this->panelRepository->getLongestEntry(field: 'aaaa'); + } - if ($this->configController->getConfig(configKey: 'verbose')) { - echo COLOR_YELLOW . str_pad(string: $server->getName(), length: $maxName); - } + if (!$this->configController->getConfig(configKey: 'quiet')) { + echo COLOR_YELLOW . str_pad(string: $server->getName(), length: $maxName); + } - $a = $server->getA() ?? ''; - if (!empty($a)) { - if ($this->configController->getConfig(configKey: 'verbose')) { - echo COLOR_DEFAULT . ' ' . str_pad(string: $a, length: $maxA, pad_type: STR_PAD_LEFT) . ' '; - } - if ($result = $this->apiController->sendCommand( - requestType: 'GET', - serverName: $server->getName(), - versionIP: 4, - apiKey: $server->getApikey(), - command: 'ping', - serverType: $type)) { - if ($this->configController->getConfig(configKey: 'verbose')) { - if ($result['data'] == 'pong') { - echo COLOR_GREEN . $result['data']; - } else { - echo COLOR_BLUE . 'skip'; - } - } - } else { - $error = true; - } - } - $aaaa = $server->getAaaa() ?? ''; - if (!empty($aaaa)) { - if ($this->configController->getConfig(configKey: 'verbose')) { - echo COLOR_DEFAULT . ' ' . str_pad(string: $aaaa, length: $maxAAAA, pad_type: STR_PAD_LEFT) . ' '; - } - if ($result = $this->apiController->sendCommand( - requestType: 'GET', - serverName: $server->getName(), - versionIP: 6, - apiKey: $server->getApikey(), - command: 'ping', - serverType: $type)) { - if ($this->configController->getConfig(configKey: 'verbose')) { - if ($result['data'] == 'pong') { - echo COLOR_GREEN . $result['data']; - } else { - echo COLOR_BLUE . $result['data']; // TODO 'skip'; - } - } - } else { - $error = true; - } - } - if ($this->configController->getConfig(configKey: 'verbose')) { - echo PHP_EOL; - } - return $error; - } + $encryptionKey = $this->configController->getConfig(configKey: 'encryptionKey'); + $decryptedKey = $this->encryptionController->safeDecrypt(encrypted: $server->getApikey(), key: $encryptionKey); - /** - * @param string $subcommand - * - * @return void - */ - public function handleApiKeys(string $subcommand): void - { - match ($subcommand) { - 'create' => $this->handleApikeysCreate(), - 'list' => $this->handleApikeysList(), - 'update' => $this->handleApikeysUpdate(), - 'delete' => $this->handleApikeysDelete(), - default => $this->unknownSubcommand(subcommand: $subcommand) - }; - } + $a = $server->getA() ?? ''; + if (!empty($a)) { + $this->logger->debug("check a"); + if ($this->configController->getConfig(configKey: 'verbose')) { + echo COLOR_DEFAULT . ' ' . str_pad(string: $a, length: $maxA, pad_type: STR_PAD_LEFT) . ' '; + } + if ($result = $this->apiController->sendCommand( + requestType: 'GET', + serverName: $server->getName(), + versionIP: 4, + apiKey: $decryptedKey, + command: 'ping', + serverType: $type)) { + if (!$this->configController->getConfig(configKey: 'quiet')) { + if ($result['data'] == 'pong') { + echo ' ' . COLOR_GREEN . $result['data']; + } else { + echo COLOR_BLUE . ' skip' . COLOR_DEFAULT; + if ($this->configController->getConfig(configKey: 'verbose')) { + echo ' ' . $result['data']; + } + } + } + } else { + $error = true; + } + } + $aaaa = $server->getAaaa() ?? ''; + if (!empty($aaaa)) { + $this->logger->debug("check aaaa"); + if ($this->configController->getConfig(configKey: 'verbose')) { + echo COLOR_DEFAULT . ' ' . str_pad(string: $aaaa, length: $maxAAAA, pad_type: STR_PAD_LEFT) . ' '; + } + if ($result = $this->apiController->sendCommand( + requestType: 'GET', + serverName: $server->getName(), + versionIP: 6, + apiKey: $decryptedKey, + command: 'ping', + serverType: $type)) { + if (!$this->configController->getConfig(configKey: 'quiet')) { + if ($result['data'] == 'pong') { + echo ' ' . COLOR_GREEN . $result['data']; + } else { + echo COLOR_BLUE . ' skip' . COLOR_DEFAULT; + if ($this->configController->getConfig(configKey: 'verbose')) { + echo ' ' . $result['data']; + } + } + } + } else { + $error = true; + } + } + try { + sodium_memzero(string: $decryptedKey); + } catch (SodiumException $e) { + die($e->getMessage() . PHP_EOL); + } - /** - * @return void - */ - function handleApikeysCreate(): void - { - $name = $this->arguments['name'] ?? ''; + if (!$this->configController->getConfig(configKey: 'quiet')) { + echo COLOR_DEFAULT . PHP_EOL; + } + return !$error; + } - $result = $this->apikeyRepository->create(name: $name); - echo 'API key ' . COLOR_YELLOW . $result['row'] . COLOR_DEFAULT . ' has been generated. Store it in a save place, it cannot be recovered.' . PHP_EOL; - echo "\033[32m\t" . $result['tokenPrefix'] . '.' . $result['key'] . PHP_EOL; - exit(0); - } + /** + * @param string $subcommand + * + * @return void + */ + public function handleApiKeys(string $subcommand): void + { + match ($subcommand) { + 'create' => $this->handleApikeysCreate(), + 'list' => $this->handleApikeysList(), + 'update' => $this->handleApikeysUpdate(), + 'delete' => $this->handleApikeysDelete(), + default => $this->unknownSubcommand(subcommand: $subcommand) + }; + } - /** - * @return void - */ - function handleApikeysList(): void - { - $keys = $this->apikeyRepository->findAll(); - if (!empty($keys)) { - echo 'All valid API keys:' . PHP_EOL; - $table = new ConsoleTable(); - $table->setHeaders(content: ['ID', 'Name', 'API key prefix']); - foreach ($keys as $key) { - $row = []; - $row[] = $key->getID(); - $row[] = $key->getName(); - $row[] = $key->getApiTokenPrefix(); - $table->addRow(data: $row); - } - $table->setPadding(value: 2); - $table->display(); - } else { - echo 'No keys found.' . PHP_EOL; - } - exit(0); - } + /** + * @return void + */ + function handleApikeysCreate(): void + { + $name = $this->arguments['name'] ?? ''; + + $apiKeyPrefix = uniqid(); + try { + $apikeyRand = bin2hex(string: random_bytes(length: 24)); + } catch (Exception $e) { + die($e->getMessage() . PHP_EOL); + } + + $passphrase = password_hash(password: $apiKeyPrefix . '.' . $apikeyRand, algo: PASSWORD_ARGON2ID); + + $apikey = new Apikey(name: $name, apikeyPrefix: $apiKeyPrefix, passphrase: $passphrase); + + $result = $this->apikeyRepository->insert(apikey: $apikey); + + if ($name) { + echo 'API key ' . COLOR_YELLOW . $name . COLOR_DEFAULT; + } else { + echo 'Unnamed API key '; + } + + echo ' with ID ' . COLOR_YELLOW . $result . COLOR_DEFAULT . ' has been generated. Store it in a safe place, it cannot be recovered.' . PHP_EOL; + echo COLOR_YELLOW . $apiKeyPrefix . '.' . $apikeyRand . COLOR_DEFAULT . PHP_EOL; + exit(0); + } + + /** + * @return void + */ + function handleApikeysList(): void + { + $keys = $this->apikeyRepository->findAll(); + if (!empty($keys)) { + echo 'All valid API keys:' . PHP_EOL; + $table = new ConsoleTable(); + $table->setHeaders(content: ['ID', 'Name', 'API key prefix']); + foreach ($keys as $key) { + $row = []; + $row[] = $key->getID(); + $row[] = $key->getName(); + $row[] = $key->getApikeyPrefix(); + $table->addRow(data: $row); + } + $table->setPadding(value: 2); + $table->display(); + } else { + echo 'No keys found.' . PHP_EOL; + } + exit(0); + } - /** - */ - function handleApikeysUpdate(): void - { + /** + */ + function handleApikeysUpdate(): void + { + $id = intval(value: $this->arguments[1]) ?? 0; + $name = $this->arguments['name'] ?? ''; - // TODO check for use of id instead of number, mind for all occurences - $id = $this->arguments[1] ?? 0; - $name = $this->arguments['name'] ?? ''; + if ($id == 0) { + echo 'An ID is required' . PHP_EOL; + exit(1); + } + if (!$this->apikeyRepository->findByID(id: intval(value: $id))) { + echo "Apikeys with ID : $id doesn't exist." . PHP_EOL; + exit(1); + } + if (!$name) { + echo 'You need tu supply a name.' . PHP_EOL; + exit(1); + } - if ($id == 0) { - echo 'An ID is required' . PHP_EOL; - exit(1); - } - if (empty($name)) { - echo 'You need to supply the new name.' . PHP_EOL; - exit(1); - } - if (!$this->apikeyRepository->findByID(id: intval(value: $id))) { - echo "Apikeys with ID : $id doesn't exist." . PHP_EOL; - exit(1); - } - if ($this->apikeyRepository->update(id: intval(value: $id), name: $name) !== false) { - echo 'Apikey has been updated' . PHP_EOL; - } else { - echo 'Error while updating apikey.' . PHP_EOL; - } - } + $apikey = new Apikey(id: $id, name: $name); + if ($this->apikeyRepository->update(apikey: $apikey) !== false) { + echo 'Apikey has been updated' . PHP_EOL; + } else { + echo 'Error while updating apikey.' . PHP_EOL; + } + } - /** - * @return void - */ - function handleApikeysDelete(): void - { - $id = intval(value: $this->arguments[1] ?? 0); - if ($id == 0) { - echo 'You need to add the ID of the API key.' . PHP_EOL; - exit(1); - } - if ($this->apikeyRepository->findByID(id: $id)) { - $this->apikeyRepository->delete(id: $id); - echo 'API key ' . COLOR_YELLOW . $id . COLOR_DEFAULT . ' has been deleted.' . PHP_EOL; - exit(0); - } else { - echo 'Unknown ID ' . COLOR_YELLOW . $id . '.' . PHP_EOL; - exit(1); - } - } + /** + * @return void + */ + function handleApikeysDelete(): void + { + $id = intval(value: $this->arguments[1] ?? 0); + if ($id == 0) { + echo 'You need to add the ID of the API key.' . PHP_EOL; + exit(1); + } + if ($this->apikeyRepository->findByID(id: $id)) { + $this->apikeyRepository->delete(id: $id); + echo 'API key ' . COLOR_YELLOW . $id . COLOR_DEFAULT . ' has been deleted.' . PHP_EOL; + exit(0); + } else { + echo 'Unknown ID ' . COLOR_YELLOW . $id . '.' . PHP_EOL; + exit(1); + } + } - /** - * @param string $subcommand - * - * @return void - */ - public function handleDomains(string $subcommand): void - { - match ($subcommand) { - 'list' => $this->handleDomainsList(), - 'refresh' => $this->handleDomainsRefresh(), - 'delete' => $this->handleDomainsDelete(), - default => $this->unknownSubcommand(subcommand: $subcommand) - }; - } + /** + * @param string $subcommand + * + * @return void + */ + public function handleDomains(string $subcommand): void + { + match ($subcommand) { + 'list' => $this->handleDomainsList(), + 'refresh' => $this->handleDomainsRefresh(), + 'update' => $this->handleDomainsUpdate(), + 'delete' => $this->handleDomainsDelete(), + default => $this->unknownSubcommand(subcommand: $subcommand) + }; + } - /** - * @return void - */ - function handleDomainsList(): void - { - $domains = $this->domainRepository->findAll(); - if (!empty($domains)) { - echo 'All available domains:' . PHP_EOL; - $table = new ConsoleTable(); - $table->setHeaders(content: ['ID', 'Name', 'Panel', 'Type']); - /** @var Domain $domain */ - foreach ($domains as $domain) { - $row = []; - $row[] = $domain->getId(); - $row[] = $domain->getName(); - $row[] = $domain->getPanel(); - $row[] = $this->domainController->isMasterZone(domain: $domain) ? 'MASTER' : 'SLAVE'; - $table->addRow(data: $row); - } - $table->setPadding(value: 2); - $table->display(); - } else { - echo 'No domains found.' . PHP_EOL; - } - exit(0); - } + /** + * @return void + */ + function handleDomainsList(): void + { + $domains = $this->domainRepository->findAll(); + if (!empty($domains)) { + echo 'All available domains:' . PHP_EOL; + $table = new ConsoleTable(); + $table->setHeaders(content: ['ID', 'Name', 'Panel', 'Type']); + /** @var Domain $domain */ + foreach ($domains as $domain) { + $row = []; + $row[] = $domain->getId(); + $row[] = $domain->getName(); + $row[] = $domain->getPanel(); + $row[] = $this->domainController->isMasterZone(domain: $domain) ? 'MASTER' : 'SLAVE'; + $table->addRow(data: $row); + } + $table->setPadding(value: 2); + $table->display(); + } else { + echo 'No domains found.' . PHP_EOL; + } + exit(0); + } - /** - * @return void - */ - function handleDynDnsList(): void - { - $dyndns = $this->dynDNSRepository->findAll(); - if (!empty($dyndns)) { - echo 'All available DynDNS hosts:' . PHP_EOL; - $table = new ConsoleTable(); - $table->setHeaders(content: ['ID', 'Name', 'Panel', 'Type']); - /** @var \App\Entity\DynDNS $dyndnsHost */ - foreach ($dyndns as $dyndnsHost) { - $row = []; - $row[] = $dyndnsHost->getId(); - $row[] = $dyndnsHost->getName(); - $table->addRow(data: $row); - } - $table->setPadding(value: 2); - $table->display(); - } else { - echo 'No DynDNS hosts found.' . PHP_EOL; - } - exit(0); - } + /** + * @return void + */ + function handleDynDnsList(): void + { + $dyndns = $this->dynDNSRepository->findAll(); + if (!empty($dyndns)) { + echo 'All available DynDNS hosts:' . PHP_EOL; + $table = new ConsoleTable(); + $table->setHeaders(content: ['ID', 'Name', 'Panel', 'Type']); + /** @var \App\Entity\DynDNS $dyndnsHost */ + foreach ($dyndns as $dyndnsHost) { + $row = []; + $row[] = $dyndnsHost->getId(); + $row[] = $dyndnsHost->getName(); + $table->addRow(data: $row); + } + $table->setPadding(value: 2); + $table->display(); + } else { + echo 'No DynDNS hosts found.' . PHP_EOL; + } + exit(0); + } - /** - * @return void - */ - function handleDynDnsCreate(): void - { - $name = $this->arguments[1] ?? ''; - if (empty($name)) { - echo 'You need to supply the FQDN (hostname).' . PHP_EOL; - exit(1); - } + /** + * @return void + */ + function handleDynDnsCreate(): void + { + $name = $this->arguments[1] ?? ''; + if (empty($name)) { + echo 'You need to supply the FQDN (hostname).' . PHP_EOL; + exit(1); + } - $filteredName = filter_var(value: $name, filter: FILTER_VALIDATE_DOMAIN, options: FILTER_FLAG_HOSTNAME); - if (!empty($filteredName) && str_contains(haystack: $filteredName, needle: '.')) { - $name = $filteredName; - } else { - echo "$name is no valid DNS domain name." . PHP_EOL; - exit(1); - } + $filteredName = filter_var(value: $name, filter: FILTER_VALIDATE_DOMAIN, options: FILTER_FLAG_HOSTNAME); + if (!empty($filteredName) && str_contains(haystack: $filteredName, needle: '.')) { + $name = $filteredName; + } else { + echo "$name is no valid DNS domain name." . PHP_EOL; + exit(1); + } $password = $this->arguments[2] ?? ''; var_dump($this->arguments); die(); - $domainParts = explode(separator: '.', string: $name); - $reversedParts = array_reverse(array: $domainParts); - $testDomain = ''; - $foundDomain = ''; - foreach ($reversedParts as $part) { - if ($testDomain) { - $testDomain = $part . '.' . $testDomain; - } else { - $testDomain = $part; - } - if ($this->domainRepository->findByName(name: $testDomain)) { - $foundDomain = $testDomain; - echo $part . PHP_EOL; - } - } - if (!$foundDomain) { - echo 'No matching domain found for this panel.' . PHP_EOL; - exit(1); + $domainParts = explode(separator: '.', string: $name); + $reversedParts = array_reverse(array: $domainParts); + $testDomain = ''; + $foundDomain = ''; + foreach ($reversedParts as $part) { + if ($testDomain) { + $testDomain = $part . '.' . $testDomain; + } else { + $testDomain = $part; + } + if ($this->domainRepository->findByName(name: $testDomain)) { + $foundDomain = $testDomain; + echo $part . PHP_EOL; + } + } + if (!$foundDomain) { + echo 'No matching domain found for this panel.' . PHP_EOL; + exit(1); - } + } if ($this->configController->getConfig(configKey: 'verbose')) { echo "Found domain: " . COLOR_YELLOW . $foundDomain . COLOR_DEFAULT . PHP_EOL; } - // get host + // get host if ($this->dynDNSRepository->findByName(name: $name)) { if ($this->configController->getConfig(configKey: 'verbose')) { - echo "DynDNS host " . COLOR_YELLOW . $name . COLOR_DEFAULT . "already exists.". PHP_EOL; + echo "DynDNS host " . COLOR_YELLOW . $name . COLOR_DEFAULT . "already exists." . PHP_EOL; exit(0); } } else { if ($this->configController->getConfig(configKey: 'verbose')) { - echo "DynDNS host " . COLOR_YELLOW . $name . COLOR_DEFAULT . "will be created.". PHP_EOL; + echo "DynDNS host " . COLOR_YELLOW . $name . COLOR_DEFAULT . "will be created." . PHP_EOL; // insert in db - $dyndnsHost = new DynDNS(); + $dyndnsHost = new DynDNS(name: $name); $dyndnsHost->setName($name); } } - // check on NS - // => add if missing - - - if ($this->domainRepository->findByName(name: $name)) { - echo "Domain: $name already exists." . PHP_EOL; - exit(1); - } else { - if (!$this->panelRepository->findByName(name: $panel)) { - echo 'Unknown panel: ' . COLOR_YELLOW . $panel . COLOR_DEFAULT . '.' . PHP_EOL; - exit(1); - } - $domain = new Domain(name: $name, panel: $panel); - $result = $this->domainRepository->insert(domain: $domain); - echo 'Domain' . COLOR_YELLOW . $name . COLOR_DEFAULT . ' has been created with id ' . COLOR_YELLOW . $result . COLOR_DEFAULT . '.' . PHP_EOL; - $this->domainController->createSlaveZoneFile(domain: $domain); - exit(0); - } - } - - function handleDomainsCreate(): void - { - // check if we're correctly setup - if (!$this->domainController->checkPermissions()) { - echo 'You need to setup the bindAPI first.' . PHP_EOL; - exit(1); - } - - $name = $this->arguments[1] ?? ""; - if (empty($name)) { - echo 'You need to supply the domain name.' . PHP_EOL; - exit(1); - } - - $filteredName = filter_var(value: $name, filter: FILTER_VALIDATE_DOMAIN, options: FILTER_FLAG_HOSTNAME); - if (!empty($filteredName) && str_contains(haystack: $filteredName, needle: '.')) { - $name = $filteredName; - } else { - echo "$name is no valid DNS domain name." . PHP_EOL; - exit(1); - } - - $arguments = $this->parseArguments(); - $panel = $arguments['panel'] ?? ''; - - if (empty($panel)) { - echo 'You need to supply the panel name.' . PHP_EOL; - exit(1); - } - - if ($this->domainRepository->findByName(name: $name)) { - echo "Domain: $name already exists." . PHP_EOL; - exit(1); - } else { - if (!$this->panelRepository->findByName(name: $panel)) { - echo 'Unknown panel: ' . COLOR_YELLOW . $panel . COLOR_DEFAULT . '.' . PHP_EOL; - exit(1); - } - $domain = new Domain(name: $name, panel: $panel); - $result = $this->domainRepository->insert(domain: $domain); - echo 'Domain' . COLOR_YELLOW . $name . COLOR_DEFAULT . ' has been created with id ' . COLOR_YELLOW . $result . COLOR_DEFAULT . '.' . PHP_EOL; - $this->domainController->createSlaveZoneFile(domain: $domain); - exit(0); - } - } - - /** - */ - function handleDomainsUpdate(): void - { - // check if we're correctly setup - if (!$this->domainController->checkPermissions()) { - echo 'You need to setup the bindAPI first.' . PHP_EOL; - exit(1); - } - - $arguments = $this->parseArguments(); - - $id = intval(value: $this->arguments[1] ?? 0); - $name = $arguments['name'] ?? ''; - $panelName = $arguments['panel'] ?? ''; - - if ($id == 0) { - echo 'An ID is required' . PHP_EOL; - exit(1); - } - if (!$domain = $this->domainRepository->findByID(id: $id)) { - echo "Domain with ID : $id doesn't exist." . PHP_EOL; - exit(1); - } - - if (!empty($panelName)) { - $panel = $this->panelRepository->findByName(name: $panelName); - } - - if (empty($name) && empty($panel)) { - echo COLOR_DEFAULT . 'No name or panel given, just recreate the config file' . PHP_EOL; - $this->domainController->updateSlaveZones(); - exit(1); - } - $newDomain = new Domain(name: $name, panel: $panelName, id: $domain->getId()); - - if ($this->domainRepository->update(domain: $newDomain) !== false) { - echo 'Domain server has been updated' . PHP_EOL; - $this->domainController->updateSlaveZones(); - } else { - echo 'Error while updating domain server.' . PHP_EOL; - } - } - - - /** - */ - function handleDomainsDelete(): void - { - if (empty($this->arguments[1])) { - echo "You need to supply an ID." . PHP_EOL; - exit(1); - } - - $id = intval(value: $this->arguments[1]) ?? 0; - if ($id == 0) { - echo "Domain with ID $id not found." . PHP_EOL; - exit(1); - } - if (!$domain = $this->domainRepository->findByID(id: $id)) { - echo "There is no domain with ID $id." . PHP_EOL; - exit(1); - } - $this->domainRepository->delete(domain: $domain); - $this->domainController->deleteZone(domain: $domain); - echo "The domain with ID $id has been deleted." . PHP_EOL; - } - - /** - * @param string $subcommand - * - * @return void - */ - public - function handleDynDns(string $subcommand): void - { - match ($subcommand) { - 'list' => $this->handleDynDnsList(), - 'create' => $this->handleDynDnsCreate(), - 'update' => $this->handleDynDnsUpdate(), - 'delete' => $this->handleDynDnsDelete(), - 'push' => $this->handleDynDnsPush(), - default => $this->unknownSubcommand(subcommand: $subcommand) - }; - } - - /** - * @param string $subcommand - * - * @return void - */ - public - function handleNameservers(string $subcommand): void - { - match ($subcommand) { - 'create' => $this->handleNameserversCreate(), - 'list' => $this->handleNameserversList(), - 'update' => $this->handleNameserversUpdate(), - 'delete' => $this->handleNameserversDelete(), - 'apiping' => $this->handleAPIPing(type: 'nameserver'), - default => $this->unknownSubcommand(subcommand: $subcommand) - }; - } - - - /** - * @return void - */ - function handleNameserversCreate(): void - { - $name = $this->arguments[1] ?? ''; - if (empty($name)) { - echo 'You need to supply the nameserver name.' . PHP_EOL; - exit(1); - } - - $filteredName = filter_var(value: $name, filter: FILTER_VALIDATE_DOMAIN); - if (!empty($filteredName) && str_contains(haystack: $filteredName, needle: '.')) { - $name = $filteredName; - } else { - echo "$name is no valid nameserver name." . PHP_EOL; - exit(1); - } - - $arguments = $this->parseArguments(); - - $a = $arguments['a'] ?? ''; - $aaaa = $arguments['aaaa'] ?? ''; - if (empty($a) && empty($aaaa)) { - echo 'At least one IP address is required.' . PHP_EOL; - exit(0); - } - $apikey = $arguments['apikey'] ?? ''; - - if ($this->nameserverRepository->findByName(name: $name)) { - echo "Nameserver: $name already exists." . PHP_EOL; - exit(1); - } else { - $nameserver = new Nameserver(name: $name, a: $a, aaaa: $aaaa, apikey: $apikey); - $result = $this->nameserverRepository->insert(nameserver: $nameserver); - echo "Nameserver $name has been created with id $result" . PHP_EOL; - exit(0); - } - } - - - /** - * @return void - */ - function handleNameserversList(): void - { - $nameservers = $this->nameserverRepository->findAll(); - if (!empty($nameservers)) { - echo 'All available nameservers:' . PHP_EOL; - $table = new ConsoleTable(); - $table->setHeaders(content: ['ID', 'Name', 'A', 'AAAA', 'API Key']); - foreach ($nameservers as $nameserver) { - $row = []; - $token = strtok(string: $nameserver->getApiKey(), token: '.'); - $row[] = $nameserver->getId(); - $row[] = $nameserver->getName(); - $row[] = $nameserver->getA(); - $row[] = $nameserver->getAaaa(); - $row[] = $token; - $table->addRow(data: $row); - } - $table->setPadding(value: 2); - $table->display(); - } else { - echo 'No nameservers found.' . PHP_EOL; - exit(1); - } - exit(0); - } - - - /** - */ - function handleNameserversUpdate(): void - { - $arguments = $this->parseArguments(); - - $id = $this->arguments[1] ?? 0; - $name = $arguments['name'] ?? ''; - $a = $arguments['a'] ?? ''; - $aaaa = $arguments['aaaa'] ?? ''; - $apikey = $arguments['apikey'] ?? ''; - - if ($id == 0) { - echo 'An ID is required.' . PHP_EOL; - exit(1); - } - if (!$this->nameserverRepository->findByID(id: intval(value: $id))) { - echo 'Nameserver with ID ' . COLOR_YELLOW . $id . COLOR_DEFAULT . " doesn't exist." . PHP_EOL; - exit(1); - } - if ($this->nameserverRepository->update(id: intval(value: $id), name: $name, a: $a, aaaa: $aaaa, apikey: $apikey) !== false) { - echo 'Nameserver ' . COLOR_YELLOW . $id . COLOR_DEFAULT . ' has been updated.' . PHP_EOL; - } else { - echo 'Error while updating nameserver ' . COLOR_YELLOW . $id . '.' . PHP_EOL; - } - } - - - /** - */ - function handleNameserversDelete(): void - { - if (empty($this->arguments[1])) { - echo "You need to supply an ID." . PHP_EOL; - exit(1); - } - - $id = intval(value: $this->arguments[1] ?? 0); - if ($id == 0) { - echo 'Nameserver with ID ' . COLOR_YELLOW . $id . COLOR_DEFAULT . ' not found.' . PHP_EOL; - exit(1); - } - if (!$this->nameserverRepository->findByID(id: $id)) { - echo 'There is no nameserver with ID ' . COLOR_YELLOW . $id . COLOR_DEFAULT . '.' . PHP_EOL; - exit(1); - } - $this->nameserverRepository->delete(id: $id); - echo 'The nameserver with ID ' . COLOR_YELLOW . $id . COLOR_DEFAULT . ' has been deleted.' . PHP_EOL; - } - - - /** - */ - function handleCheckShowIncludes(): void - { - $nameservers = $this->nameserverRepository->findAll(); - - if (count($nameservers) === 0) { - echo 'No nameservers found.' . PHP_EOL; - echo 'You first need to setup the system.' . PHP_EOL; - exit(1); - } - - - echo COLOR_DEFAULT . 'You need to add these lines to ' . COLOR_YELLOW . '/etc/bind/local.bindapi.options' . COLOR_DEFAULT . ' on every panel and make sure' . PHP_EOL; - echo 'that ' . COLOR_YELLOW . 'include "/etc/bind/local.bindapi.options";' . COLOR_DEFAULT . ' exists in ' . COLOR_YELLOW . '/etc/bind/named.conf.options' . COLOR_DEFAULT . '.' . PHP_EOL; - $ip = []; - foreach ($nameservers as $nameserver) { - if (!empty($nameserver->getA())) { - $ip[] = $nameserver->getA(); - } - if (!empty($nameserver->getAaaa())) { - $ip[] = $nameserver->getAaaa(); - } - } - echo PHP_EOL . 'allow-transfer {' . PHP_EOL; - foreach ($ip as $currentIp) - echo "\t$currentIp;" . PHP_EOL; - echo '};'; - echo PHP_EOL . 'also-notify {' . PHP_EOL; - foreach ($ip as $currentIp) - echo "\t$currentIp;" . PHP_EOL; - echo '};' . PHP_EOL; - echo PHP_EOL . 'After the modification feel free to run ' . COLOR_YELLOW . 'named-checkconf' . COLOR_DEFAULT . ' to ensure there were no errors.' . PHP_EOL; - echo PHP_EOL . 'Run ' . COLOR_YELLOW . 'rndc reload' . COLOR_DEFAULT . ' to activate the changes.' . PHP_EOL; - - - } - - /** - */ - function handleCheckDomains(): void - { - $this->domainController->checkDomains(); - } - - - /** - */ - private - function handleDynDnsPush(): void - { - $hostName = $this->arguments[1] ?? ''; - - if (empty($hostName)) { - echo 'You need to supply at least the hostname' . PHP_EOL; - exit(1); - } - - if ($this->configController->getConfig(configKey: 'verbose')) { - echo "Updating DynDNS host: $hostName" . PHP_EOL; - } - - echo 'here'; - $domain = $this->domainRepository->findByHost(host: $hostName); - print_r(value: $domain); - echo 'there'; - // we need the panel who is master for zone - $panel = $this->panelRepository->findByName(name: $domain->getPanel()); - - // which NS belongs to that panel - - - if (!empty($panel->getAaaa())) { - $result = $this->apiController->sendCommand( - requestType: 'POST', - serverName: $panel->getName(), - versionIP: 6, - apiKey: $panel->getApikey(), - command: 'dyndns/' . $hostName, - serverType: 'nameserver'); - } else { - $result = $this->apiController->sendCommand( - requestType: 'POST', - serverName: $panel->getName(), - versionIP: 4, - apiKey: $panel->getApikey(), - command: 'dyndns/' . $hostName, - serverType: 'nameserver'); - } - - if ($result['header'] == 200) { - if ($this->configController->getConfig(configKey: 'verbose')) { - $data = $result['data']; - $decodedData = json_decode(json: $data, associative: true); - echo $decodedData['message'] . PHP_EOL; - } - } else { - echo 'Something went wrong:' . PHP_EOL; - print_r(value: $result); - exit(1); - } - exit(0); - } - - private - function handleCheckGenerateKey(): void - { - echo 'This generates a fresh encryption key.' . PHP_EOL; - echo 'Copy it to config.json.' . PHP_EOL; - echo 'Note: You must update all API-Keys for panels and nameservers after changing the key!' . PHP_EOL; - - $cStrong = false; - $bytes = null; - while (!$cStrong) { - $bytes = openssl_random_pseudo_bytes(length: 18, strong_result: $cStrong); - } - $hex = bin2hex(string: $bytes); - - echo 'Suggested new key : ' . COLOR_YELLOW . $hex . COLOR_DEFAULT . '.' . PHP_EOL; - echo PHP_EOL; - } - - private - function handleDomainsRefresh(): void - { - - // TODO check for self in check:permissions - - $this->logger->debug(message: "handleDomainsRefresh()"); - - // TODO create getSelf() - $panel = $this->panelRepository->findByName(name: 'keyhelp.lab.24unix.net'); - - if (empty($panel->getA())) { - $result = $this->apiController->sendCommand( - requestType: 'GET', - serverName: $panel->getName(), - versionIP: 6, - apiKey: $panel->getApikey(), - command: 'domains?sort=domain', - serverType: 'panel' - ); - } else { - $result = $this->apiController->sendCommand( - requestType: 'GET', - serverName: $panel->getName(), - versionIP: 4, - apiKey: $panel->getApikey(), - command: 'domains?sort=domain', - serverType: 'panel'); - } - - if (!empty($result['error'])) { - echo $result['data'] . PHP_EOL; - exit(1); - } - if (!empty($result['data'])) { - $domains = json_decode(json: $result['data']); - } else { - echo 'No domains found' . PHP_EOL; - exit(1); - } - - // TODO remove stale domains - - $domainCount = 0; - if (count($domains) > 0) { - foreach ($domains as $domain) { - if ($this->isValidSecondLevelDomain(domainName: $domain->domain, panel: $panel->getName(), parent: $domain->id_parent_domain)) { - $domainCount++; - echo COLOR_YELLOW . $domain->domain; - if ($this->domainRepository->findByName(name: $domain->domain)) { - echo COLOR_GREEN . ' OK'; - } else { - $newDomain = new Domain(name: $domain->domain, panel: $panel->getName()); - $result = $this->domainRepository->insert(domain: $newDomain); - echo COLOR_DEFAULT . ' has been created with id ' . COLOR_YELLOW . $result . COLOR_DEFAULT . '.' . PHP_EOL; - } - echo PHP_EOL; - } - } - } - - if ($domainCount == 0) { - echo 'No second level domains found.' . COLOR_DEFAULT . PHP_EOL; - } - echo PHP_EOL; - - } + // check on NS + // => add if missing + + + if ($this->domainRepository->findByName(name: $name)) { + echo "Domain: $name already exists." . PHP_EOL; + exit(1); + } else { + if (!$this->panelRepository->findByName(name: $panel)) { + echo 'Unknown panel: ' . COLOR_YELLOW . $panel . COLOR_DEFAULT . '.' . PHP_EOL; + exit(1); + } + $domain = new Domain(name: $name, panel: $panel); + $result = $this->domainRepository->insert(domain: $domain); + echo 'Domain' . COLOR_YELLOW . $name . COLOR_DEFAULT . ' has been created with id ' . COLOR_YELLOW . $result . COLOR_DEFAULT . '.' . PHP_EOL; + $this->domainController->createSlaveZoneFile(domain: $domain); + exit(0); + } + } + + function handleDomainsCreate(): void + { + // check if we're correctly setup + if (!$this->domainController->checkPermissions()) { + echo 'You need to setup the bindAPI first.' . PHP_EOL; + exit(1); + } + + $name = $this->arguments[1] ?? ""; + if (empty($name)) { + echo 'You need to supply the domain name.' . PHP_EOL; + exit(1); + } + + $filteredName = filter_var(value: $name, filter: FILTER_VALIDATE_DOMAIN, options: FILTER_FLAG_HOSTNAME); + if (!empty($filteredName) && str_contains(haystack: $filteredName, needle: '.')) { + $name = $filteredName; + } else { + echo "$name is no valid DNS domain name." . PHP_EOL; + exit(1); + } + + $panel = $this->arguments['panel'] ?? ''; + + if (empty($panel)) { + echo 'You need to supply the panel name.' . PHP_EOL; + exit(1); + } + + if ($this->domainRepository->findByName(name: $name)) { + echo "Domain: $name already exists." . PHP_EOL; + exit(1); + } else { + if (!$this->panelRepository->findByName(name: $panel)) { + echo 'Unknown panel: ' . COLOR_YELLOW . $panel . COLOR_DEFAULT . '.' . PHP_EOL; + exit(1); + } + $domain = new Domain(name: $name, panel: $panel); + $result = $this->domainRepository->insert(domain: $domain); + echo 'Domain' . COLOR_YELLOW . $name . COLOR_DEFAULT . ' has been created with id ' . COLOR_YELLOW . $result . COLOR_DEFAULT . '.' . PHP_EOL; + $this->domainController->createSlaveZoneFile(domain: $domain); + exit(0); + } + } + + /** + */ + function handleDomainsUpdate(): void + { + // check if we're correctly setup + if (!$this->domainController->checkPermissions()) { + echo 'You need to setup the bindAPI first.' . PHP_EOL; + exit(1); + } + + $id = intval(value: $this->arguments[1] ?? 0); + $name = $this->arguments['name'] ?? ''; + $panelName = $this->arguments['panel'] ?? ''; + + if ($id == 0) { + echo 'An ID is required' . PHP_EOL; + exit(1); + } + if (!$domain = $this->domainRepository->findByID(id: $id)) { + echo "Domain with ID : $id doesn't exist." . PHP_EOL; + exit(1); + } + + if (!empty($panelName)) { + $panel = $this->panelRepository->findByName(name: $panelName); + } + + if (empty($name) && empty($panel)) { + echo COLOR_DEFAULT . 'No name or panel given, just recreate the config file' . PHP_EOL; + $this->domainController->updateSlaveZones(); + exit(1); + } + $newDomain = new Domain(name: $name, panel: $panelName, id: $domain->getId()); + + if ($this->domainRepository->update(domain: $newDomain) !== false) { + echo 'Domain server has been updated' . PHP_EOL; + $this->domainController->updateSlaveZones(); + } else { + echo 'Error while updating domain server.' . PHP_EOL; + } + } + + + /** + */ + function handleDomainsDelete(): void + { + if (empty($this->arguments[1])) { + echo "You need to supply an ID." . PHP_EOL; + exit(1); + } + + $id = intval(value: $this->arguments[1]) ?? 0; + if ($id == 0) { + echo "Domain with ID $id not found." . PHP_EOL; + exit(1); + } + if (!$domain = $this->domainRepository->findByID(id: $id)) { + echo "There is no domain with ID $id." . PHP_EOL; + exit(1); + } + $this->domainRepository->delete(domain: $domain); + $this->domainController->deleteZone(domain: $domain); + echo "The domain with ID $id has been deleted." . PHP_EOL; + } + + /** + * @param string $subcommand + * + * @return void + */ + public + function handleDynDns(string $subcommand): void + { + match ($subcommand) { + 'list' => $this->handleDynDnsList(), + 'create' => $this->handleDynDnsCreate(), + 'update' => $this->handleDynDnsUpdate(), + 'delete' => $this->handleDynDnsDelete(), + 'push' => $this->handleDynDnsPush(), + default => $this->unknownSubcommand(subcommand: $subcommand) + }; + } + + /** + * @param string $subcommand + * + * @return void + */ + public + function handleNameservers(string $subcommand): void + { + match ($subcommand) { + 'create' => $this->handleNameserversCreate(), + 'list' => $this->handleNameserversList(), + 'update' => $this->handleNameserversUpdate(), + 'delete' => $this->handleNameserversDelete(), + 'apiping' => $this->handleAPIPing(type: 'nameserver'), + default => $this->unknownSubcommand(subcommand: $subcommand) + }; + } + + + /** + * @return void + */ + function handleNameserversCreate(): void + { + $name = $this->arguments[1] ?? ''; + if (empty($name)) { + echo 'You need to supply the nameserver name.' . PHP_EOL; + exit(1); + } + + $filteredName = filter_var(value: $name, filter: FILTER_VALIDATE_DOMAIN); + if (!empty($filteredName) && str_contains(haystack: $filteredName, needle: '.')) { + $name = $filteredName; + } else { + echo "$name is no valid nameserver name." . PHP_EOL; + exit(1); + } + + + $a = $this->arguments['a'] ?? ''; + $aaaa = $this->arguments['aaaa'] ?? ''; + if (empty($a) && empty($aaaa)) { + echo 'At least one IP address is required.' . PHP_EOL; + exit(0); + } + $apikey = $this->arguments['apikey'] ?? ''; + + if (empty($apikey)) { + echo 'An API key is required.' . PHP_EOL; + exit(0); + } + + if ($this->nameserverRepository->findByName(name: $name)) { + echo "Nameserver: $name already exists." . PHP_EOL; + exit(1); + } else { + $nameserver = new Nameserver(name: $name, a: $a, aaaa: $aaaa, passphrase: $apikey); + $result = $this->nameserverRepository->insert(nameserver: $nameserver); + echo 'Nameserver ' . COLOR_YELLOW . $name . COLOR_DEFAULT . ' has been created with id ' . COLOR_YELLOW . $result . COLOR_DEFAULT . PHP_EOL; + exit(0); + } + } + + + /** + * @return void + */ + function handleNameserversList(): void + { + $nameservers = $this->nameserverRepository->findAll(); + if (!empty($nameservers)) { + echo 'All available nameservers:' . PHP_EOL; + $table = new ConsoleTable(); + $table->setHeaders(content: ['ID', 'Name', 'A', 'AAAA', 'API Key']); + foreach ($nameservers as $nameserver) { + $row = []; + $row[] = $nameserver->getId(); + $row[] = $nameserver->getName(); + $row[] = $nameserver->getA(); + $row[] = $nameserver->getAaaa(); + $row[] = $nameserver->getApikeyPrefix(); + $table->addRow(data: $row); + } + $table->setPadding(value: 2); + $table->display(); + } else { + echo 'No nameservers found.' . PHP_EOL; + exit(1); + } + exit(0); + } + + + /** + */ + function handleNameserversUpdate(): void + { + $id = $this->arguments[1] ?? 0; + $name = $this->arguments['name'] ?? ''; + $a = $this->arguments['a'] ?? ''; + $aaaa = $this->arguments['aaaa'] ?? ''; + $apikey = $this->arguments['apikey'] ?? ''; + + if ($id == 0) { + echo 'An ID is required.' . PHP_EOL; + exit(1); + } + if (!$this->nameserverRepository->findByID(id: intval(value: $id))) { + echo 'Nameserver with ID ' . COLOR_YELLOW . $id . COLOR_DEFAULT . " doesn't exist." . PHP_EOL; + exit(1); + } + + if ($apikey) { + $nameserver = new Nameserver(name: $name, id: intval(value: $id), a: $a, aaaa: $aaaa, passphrase: $apikey); + } else { + $nameserver = new Nameserver(name: $name, id: intval(value: $id), a: $a, aaaa: $aaaa); + } + + if ($this->nameserverRepository->update(nameserver: $nameserver) !== false) { + echo 'Nameserver ' . COLOR_YELLOW . $id . COLOR_DEFAULT . ' has been updated.' . PHP_EOL; + } else { + echo 'Error while updating nameserver ' . COLOR_YELLOW . $id . '.' . PHP_EOL; + } + } + + + /** + */ + function handleNameserversDelete(): void + { + if (empty($this->arguments[1])) { + echo "You need to supply an ID." . PHP_EOL; + exit(1); + } + + $id = intval(value: $this->arguments[1] ?? 0); + if ($id == 0) { + echo 'Nameserver with ID ' . COLOR_YELLOW . $id . COLOR_DEFAULT . ' not found.' . PHP_EOL; + exit(1); + } + if (!$this->nameserverRepository->findByID(id: $id)) { + echo 'There is no nameserver with ID ' . COLOR_YELLOW . $id . COLOR_DEFAULT . '.' . PHP_EOL; + exit(1); + } + $this->nameserverRepository->delete(id: $id); + echo 'The nameserver with ID ' . COLOR_YELLOW . $id . COLOR_DEFAULT . ' has been deleted.' . PHP_EOL; + } + + + /** + */ + function handleCheckShowIncludes(): void + { + $nameservers = $this->nameserverRepository->findAll(); + + if (count($nameservers) === 0) { + echo 'No nameservers found.' . PHP_EOL; + echo 'You first need to setup the system.' . PHP_EOL; + exit(1); + } + + + echo COLOR_DEFAULT . 'You need to add these lines to ' . COLOR_YELLOW . '/etc/bind/local.bindapi.options' . COLOR_DEFAULT . ' on every panel and make sure' . PHP_EOL; + echo 'that ' . COLOR_YELLOW . 'include "/etc/bind/local.bindapi.options";' . COLOR_DEFAULT . ' exists in ' . COLOR_YELLOW . '/etc/bind/named.conf.options' . COLOR_DEFAULT . '.' . PHP_EOL; + $ip = []; + foreach ($nameservers as $nameserver) { + if (!empty($nameserver->getA())) { + $ip[] = $nameserver->getA(); + } + if (!empty($nameserver->getAaaa())) { + $ip[] = $nameserver->getAaaa(); + } + } + echo PHP_EOL . 'allow-transfer {' . PHP_EOL; + foreach ($ip as $currentIp) + echo "\t$currentIp;" . PHP_EOL; + echo '};'; + echo PHP_EOL . 'also-notify {' . PHP_EOL; + foreach ($ip as $currentIp) + echo "\t$currentIp;" . PHP_EOL; + echo '};' . PHP_EOL; + echo PHP_EOL . 'After the modification feel free to run ' . COLOR_YELLOW . 'named-checkconf' . COLOR_DEFAULT . ' to ensure there were no errors.' . PHP_EOL; + echo PHP_EOL . 'Run ' . COLOR_YELLOW . 'rndc reload' . COLOR_DEFAULT . ' to activate the changes.' . PHP_EOL; + + + } + + /** + */ + function handleCheckDomains(): void + { + $this->domainController->checkDomains(); + } + + + /** + */ + private + function handleDynDnsPush(): void + { + $hostName = $this->arguments[1] ?? ''; + + if (empty($hostName)) { + echo 'You need to supply at least the hostname' . PHP_EOL; + exit(1); + } + + if ($this->configController->getConfig(configKey: 'verbose')) { + echo "Updating DynDNS host: $hostName" . PHP_EOL; + } + + echo 'here'; + $domain = $this->domainRepository->findByHost(host: $hostName); + print_r(value: $domain); + echo 'there'; + // we need the panel who is master for zone + $panel = $this->panelRepository->findByName(name: $domain->getPanel()); + + // which NS belongs to that panel + + + if (!empty($panel->getAaaa())) { + $result = $this->apiController->sendCommand( + requestType: 'POST', + serverName: $panel->getName(), + versionIP: 6, + apiKey: $panel->getApikey(), + command: 'dyndns/' . $hostName, + serverType: 'nameserver'); + } else { + $result = $this->apiController->sendCommand( + requestType: 'POST', + serverName: $panel->getName(), + versionIP: 4, + apiKey: $panel->getApikey(), + command: 'dyndns/' . $hostName, + serverType: 'nameserver'); + } + + if ($result['header'] == 200) { + if ($this->configController->getConfig(configKey: 'verbose')) { + $data = $result['data']; + $decodedData = json_decode(json: $data, associative: true); + echo $decodedData['message'] . PHP_EOL; + } + } else { + echo 'Something went wrong:' . PHP_EOL; + print_r(value: $result); + exit(1); + } + exit(0); + } + + /** + */ + private function handleCheckGenerateKey(): void + { + echo 'This generates a fresh encryption key.' . PHP_EOL; + echo 'Copy it to config.json.' . PHP_EOL; + echo 'Note: You must update all API-Keys for panels and nameservers after changing the key!' . PHP_EOL; + + try { + $key = sodium_bin2hex(string: sodium_crypto_secretbox_keygen()); + echo 'Suggested new key : "' . COLOR_YELLOW . $key . COLOR_DEFAULT . '".' . PHP_EOL; + echo PHP_EOL; + exit(0); + } catch (SodiumException $e) { + die($e->getMessage() . PHP_EOL); + } + + } + + + private function handleDomainsRefresh(): void + { + + // TODO check for self in check:permissions + + $this->logger->debug(message: "handleDomainsRefresh()"); + + // TODO create getSelf() + $panels = $this->panelRepository->findAll(); + + foreach ($panels as $panel) { + echo COLOR_DEFAULT . 'Checking panel ' . COLOR_YELLOW . $panel->getName() . COLOR_DEFAULT . PHP_EOL; + if (empty($panel->getA())) { + $result = $this->apiController->sendCommand( + requestType: 'GET', + serverName: $panel->getName(), + versionIP: 6, + apiKey: $panel->getApikey(), + command: 'domains?sort=domain&subdomains=false', + serverType: 'panel' + ); + } else { + $result = $this->apiController->sendCommand( + requestType: 'GET', + serverName: $panel->getName(), + versionIP: 4, + apiKey: $panel->getApikey(), + command: 'domains?sort=domain&subdomains=false', + serverType: 'panel'); + } + + if (!empty($result['error'])) { + echo $result['data'] . PHP_EOL; + exit(1); + } + if (!empty($result['data'])) { + $domains = json_decode(json: $result['data']); + } else { + echo 'No domains found' . PHP_EOL; + exit(1); + } + + $domainCount = 0; + if (count($domains) > 0) { + foreach ($domains as $domain) { + $domainCount++; + echo COLOR_YELLOW . ' ' . $domain->domain; + if ($this->domainRepository->findByName(name: $domain->domain)) { + echo COLOR_GREEN . ' OK' . COLOR_DEFAULT . PHP_EOL; + } else { + $newDomain = new Domain(name: $domain->domain, panel: $panel->getName()); + $result = $this->domainRepository->insert(domain: $newDomain); + echo COLOR_DEFAULT . ' has been created with id ' . COLOR_YELLOW . $result . COLOR_DEFAULT . '.' . PHP_EOL; + } + } + } + if ($domainCount == 0) { + echo 'No second level domains found.' . COLOR_DEFAULT . PHP_EOL; + } + } + $this->domainController->updateSlaveZones(); + } }